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

    File:           fin_search_list_xd.asp
    Description:    Show a readonly list of invoices from multiple environments (crossdomain xd)
                    using the invoices-API
                    providing a means to access these in their native environment by a single click
    Parameters:     -
    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="../Shared/xd.inc" -->
<!-- #include file="../fin/fin.inc" -->
<%
var outputmode = getQParamInt("outputmode", 0); //  0 = screen, 1 = print, 2 = excel etc
var showall    = getQParamInt("showall", 0) == 1;
var urole      = getQParamSafe("urole", "bo");

var finnum     = getQParam("finnum", null,true); // Factuurnummer (string) of factuur_key

var findate_from = getQParamDate("findate_from", null);
var findate_to   = getQParamDate("findate_to", null);

var fin_type   = getQParam("fintype", -1); // Factuurtype (O,C of B)
//var opdrnr     = getQParam("opdrnr", ""); // Opdrachtnummer
var finstatus  = getQParamInt("finstatus", -1); // Factuurstatus
var debtor     = getQParam("debtor", ""); // Eigen debiteurnummer
var sumover    = getQParamFloat("sumover", ""); // Factuurbedrag boven
var sumbelow   = getQParamFloat("sumbelow", ""); // Factuurbedrag boven
var fin_actual = (getQParam("fin_actual", "off") == "on"); // Actuele facturen
var fin_deleted = (getQParam("fin_deleted", "off") == "on"); // Verwijderde facturen
var goedkeurdertekst = getQParam("goedkeurdertekst", "");

var params = {name: finnum,
              start_invoicedate: findate_from,
              end_invoicedate: findate_to,
              referencetype: fin_type,
              finstatus: finstatus,
              debiteur_nr: debtor,
              start_total: sumover,
              end_total: sumbelow,
              fin_actual: fin_actual,
              fin_deleted: fin_deleted,
              goedkeur: goedkeurdertekst}

FCLTHeader.Requires({ plugins: ["jQuery"], js: ["jquery-ui.js"]});
FCLTHeader.Title(L("lcl_xd_invoices"));
%>
<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/fin/fin_factuur.asp?fin_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 = "";
for (var cid in xd.SecundaryDomains) {
    url = xd.SecundaryDomains[cid].apiurl + "api2/invoices.json?scope="+urole;

    // Condities toevoegen (komen van fin_search.asp)
    if (finnum)            url += "&name="+ finnum;

    // Datumfilter werkt op fin_factuur_datum
    if (findate_from) url += "&start_invoicedate="+findate_from.toISOString();
    if (findate_to)   url += "&end_invoicedate="+findate_to.toISOString();
    if (finstatus>-1) url += "&finstatus="+ safe.url(finstatus);
    if (debtor)       url += "&debiteur_nr="+ safe.url(debtor);
    if (sumover)      url += "&start_total="+safe.url(sumover);
    if (sumbelow)     url += "&end_total="+safe.url(sumbelow);
    if (fin_type!=-1) url += "&referencetype="+safe.url(fin_type);
    if (goedkeurdertekst) url += "&goedkeur=~" + safe.url(goedkeurdertekst);
//    if (fin_actual)   url += ??
//    if (fin_deleted)  url += ??

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

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

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

// Merge these result objects into one list for the resultset to process.
// 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 = [];
__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,
                      factuurnr_intern: thisdata.name,
                      factuur_datum: thisdata.invoicedate,
                      creditor: thisdata.creditor?thisdata.creditor.name:"",
                      referencetype: (thisdata.referencetype == 'O' ? L("lcl_fin_mld_opdr")
                                    : (thisdata.referencetype == 'C' ? L("lcl_fin_cnt_contract")
                                      : (thisdata.referencetype == 'B' ? L("lcl_fin_bestelling") : ""))),
                      factuurnr_extern: thisdata.name,
                      opdrachtnr: (thisdata.contract ? thisdata.contract.name
                                 : (thisdata.order ? thisdata.order.name
                                   : (thisdata.besorder ? thisdata.besorder.name : null))),
                      bedrag_excl_BTW: thisdata.total,
                      vat: thisdata.vat,
                      bedrag_incl_BTW: thisdata.total+thisdata.vat,
                      fin_factuur_opmerking: thisdata.remark,
                      finstatus: thisdata.finstatus.name
                   });
    }
}
dataset.sort(function (a, b) { return (a.factuur_datum <= b.factuur_datum? -1: 1) });

function fnrowClass(oRs)
{
    var resclass ="";
    if (oRs.Fields("finstatus").Value == 3)
        resclass += ' outsidemargin';  // niet echt
    return resclass;
}


var rst = new ResultsetTable({ dataset: dataset,
                               keyColumn: "id",
                               rowData: xd.fnRowData,
                               ID: "multi-invoices-table",
                               title: L("lcl_xd_invoices"),
                               filterParams: params,
                               outputmode: outputmode,
                               showAll: showall
                              });

  rst.addColumn(new Column({caption: L("lcl_fin_nr"), content: xd.fnCustName }));
  rst.addColumn(new Column({caption: L("lcl_fin_date"), content: "factuur_datum", datatype: "date"}));
  rst.addColumn(new Column({caption: L("lcl_handler"), content: "creditor"}));
  rst.addColumn(new Column({caption: L("lcl_fin_invoice_nr_extern"), content: "name"}));
  rst.addColumn(new Column({caption: L("lcl_fin_type"), content: "referencetype"}));
  rst.addColumn(new Column({caption: L("lcl_fin_opdrachtnr"), content: "opdrachtnr"}));
  rst.addColumn(new Column({caption: L("lcl_fin_total_sum_exBTW"), content: "bedrag_excl_BTW", datatype: "currency"}));
  rst.addColumn(new Column({caption: L("lcl_fin_total_sum"), content: "bedrag_incl_BTW", datatype: "currency", combine:true}));
  rst.addColumn(new Column({caption: L("lcl_fin_fin_status"), content: "finstatus"}));
  rst.addColumn(new Column({caption: L("lcl_fin_remark"), content: "fin_factuur_opmerking"}));
  rst.addColumn(new Column({caption: L("lcl_xd_custid"), content:"custid", purpose: PRINTING_ONLY }));

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

rst.processResultset();

%>