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

LET OP: Oude stijl rapportage alleen voor procedure en gestylde varianten.
        'Gewone' rapportages gaan via fac_rapport.asp

    File:               fac_usrrap_list.asp
    Description:        Actually create the user report as selected in usrreport.asp
                        and additionally filtered by values in usrreport_filter.asp
    Parameters:
        usrrap_key      Key in the FAC_USRRAP table
        standAlone      ---
                        Also implies nohtml=1 (to remain compatible with previous behaviour)
        nohtml          Do not add html tags. All formatting is provided by the outcome of the stylesheet
        bodyclass       optional. className to be added to the body to allow specific styling

                        TODO: Deze via api/api_fetchXML.asp implementeren?

    Context:            When report is executed
    Notes:              session_user_key en session_customerId zijn voor sessie-bescherming vanuit
                        fac_usrrap_infobord.asp die 24/7 moet kunnen aanstaan, incl. de nachtelijke recycle
                        (maar worden ook nog misbruikt voor WELK XML API)
*/

var standAlone = getQParamInt("standAlone", 0) == 1;
var nohtml = getQParamInt("nohtml", 0) == 1;
var nobuttons = getQParamInt("nobuttons", 0) == 1;
var bodyclass = getQParam("bodyclass", "");  // Een optioneel ID tbv CSS
var outputmode = getQParamInt("outputmode", 0); //  0 = screen, 1 = print, 2 = excel etc

if (standAlone) {
    nohtml = true;
    DOCTYPE_Disable = 1;
}

var fclt_key = getQParamInt("fclt_key",  -1); // Optioneel vanuit custom aanroepen
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/adovbs.inc"-->
<!-- #include file="../Shared/iface.inc"-->
<!-- #include file="../Shared/xml_converter.inc" -->
<!-- #include file="./fac_usrrap.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->

<%
    FCLTHeader.Requires({plugins: ["jQuery"],
                              js: ["sorttable.js", "jQuery-ui.js"]});


// Let op: in de database is er ook nog bitje '8' welke tabelized aangeeft
function rapport_xmlxsl_mode (p_function_key) {
    return (p_function_key & 1) == 1;
}

function rapport_plain_mode (p_function_key) {
    return !rapport_xmlxsl_mode (p_function_key);
}

function rapport_view (p_function_key) {
    return (p_function_key & 2) == 0;
}

function rapport_proc (p_function_key) {
    return (p_function_key & 2) == 2;
}

    if (Server.ScriptTimeout<600) Server.ScriptTimeout=600;

    var usrrap_key   = getQParamInt("key", -1);// bij hoge uitzondering backward compatible. Gebruik usrrap_key!
    if (usrrap_key == -1)
        usrrap_key = getQParamInt("usrrap_key");
    var fac_usrrap = usrrap.fac_usrrap_info(usrrap_key);
    var p_tableName  = fac_usrrap.view_name;

    func_mode = fac_usrrap.functie;

    //
    //  ATTENTIE - OPZETJE - COMPATIBLE - CREATE VIEW rechten vereist voor de job-user
    //
    //  Voor FAC_USRRAP_FUNCTIE & 8 is er de nachtelijke job rap_compressor die
    //  de view tabelliseert, waardoor dat veel sneller uitvoert. Hier kijken we
    //  of dat bij deze het geval is, en dan leggen de de naam om. De getabelliseerde
    //  view heeft een voorgedefinieerde afgeleide naam
    //
    p_tableName_org = p_tableName;

    if (func_mode&8) {
        p_tableName = usrrap.tabelizedViewname(p_tableName);
        func_mode = func_mode - 8;  // bitje verbruikt
    }

    var sqlWhere3D = usrrap.create3Dclause(p_tableName.split(".").pop(), fac_usrrap.fac_functie_key);

if (!nohtml) {
%>
 <html>
  <head>
    <%  FCLTHeader.Generate({ outputmode: outputmode, forceInlineExcel: rapport_xmlxsl_mode (func_mode) }) %>
<% if (outputmode == 0) {%>
  <script type="text/javascript">
    function rap_print()
    {
        FcltMgr.windowopen("fac_usrrap_list.asp?outputmode=1<%=safe.jsstring(transitQS())%>");
    }
    function rap_excel()
    {
        FcltMgr.windowopen("fac_usrrap_list.asp?outputmode=2<%=safe.jsstring(transitQS())%>");
    }
  </script>
<% } %>
  </head>

<body id="listbody" <%=bodyclass != "" ? "class='"+safe.htmlattr(bodyclass)+"'": ""%> <%= (outputmode == 1 && rapport_xmlxsl_mode (func_mode)? "onload='window.print()'" : "")%>>
<%
       }

      var sql,sql1,sql_where,sql_order, sql_rep;
      var oRs, oRs2;
      var xxx_extra_param = [];

      var safeShowFilter = ""; // Build string to show actual filter values
                               // Print/Excel only

      var ora_date_fld = getQParam("datum_field", ""); // TODO Zelf bepalen!

     //Period from start-time until end-time
     var ora_date1P = getQParamDate("s_date", null);
     if (ora_date1P)
         safeShowFilter += "<tr><td class='formheader'>"+L("lcl_from")+"</td><td>" + toDateString(ora_date1P) + "</td></tr>";
     var ora_date2P = getQParamDate("e_date", null);
     if (ora_date2P)
        safeShowFilter += "<tr><td class='formheader'>"+L("lcl_to")+"</td><td>" + toDateString(ora_date2P) + "</td></tr>";

    // sql_where bevat straks de filtering op filtervelden uit het scherm
    //      of op waarden vanuit fac_usrrap_infobord
    sql_where = "";
    sql_cond = " WHERE ";
    sql_column = "";
    var i = 1;
    while (getQParam("fclt_f_colname" + i, "") != "")
    {
        var p_col_name = getQParam("fclt_f_colname" + i);

        if (usrrap.isParamFilterCol(fac_usrrap, p_col_name))
        {
            var p_col_value = getQParam("fclt_f_colvalue" + i, "");
            var p_col_data = usrrap.getColumndataByValue(fac_usrrap.columns, "column_name", p_col_name);
            if (p_col_data.datatype == "check0")
                p_col_value = (p_col_value == "" ? 0 : 1);
            xxx_extra_param.push( {name: p_col_name.toLowerCase(), value: p_col_value} );
        }
        else
        {
            usrrap.requireFilterCol(p_tableName, p_col_name); // Safety check

            // Multiselect
            // En als de listbox niet gevuld is moeten we misschien de textveld waarde gebruiken
            var p_col_value_arr = getQParamArray("fclt_f_colvalue" + i + "_l", []);
            if (!p_col_value_arr.length)
                p_col_value_arr.push(getQParam("fclt_f_colvalue" + i, ""));

            sql_column = "";
            for (j=0; j<p_col_value_arr.length; j++)
            {
                var p_col_value = "" + p_col_value_arr[j];

                if (p_col_value != "")
                {
                    if (p_col_value == "null")
                        sql_column += (j > 0 ? " OR " : "") + p_col_name + " IS NULL";
                    else if (p_col_name.match(/_key$/i))
                        sql_column += (j > 0 ? " OR " : "") + p_col_name + "=" + parseInt(p_col_value, 10);
                    else
                        sql_column += (j > 0 ? " OR " : "") + "UPPER(" + p_col_name + ") like " + safe.quoted_sql_wild(p_col_value);
                    safeShowFilter += "<tr><td class='formheader'>" + safe.html(p_col_name.substring(7)) + "</td>"
                                    + "<td>" + safe.html(p_col_value) + "</td></tr>";
                }
            }
            sql_where = sql_where + (sql_column != "" ? sql_cond + "(" + sql_column + ")" : "");
            sql_cond = (sql_where == "" ? sql_cond : " and ");
        }
        i++;
    }

    if (ora_date1P && ora_date_fld != ""){
        usrrap.requireFilterCol(p_tableName, ora_date_fld); // Safety check
        sql_where = sql_where + sql_cond + "TO_DATE(" + ora_date_fld + ",'dd-mm-yyyy') >= " + ora_date1P.toSQL();
        sql_cond = " and ";
    }
    if (ora_date2P && ora_date_fld != ""){
        sql_where = sql_where + sql_cond + "TO_DATE(" + ora_date_fld + ",'dd-mm-yyyy') < " + ora_date2P.endToSQL();
        sql_cond = " and ";
    }
    if (fclt_key > 0)
    {
       sql_where +=  sql_cond  + " FCLT_KEY=" + fclt_key;
       sql_cond = " AND ";
    }

if (outputmode == 0)
{
     if (rapport_xmlxsl_mode (func_mode)) // bij XML wordt hij niet uitgeschakeld na laden
     {
        Response.Flush(); // wel direct vorige wissen
     }
}

if (rapport_view(func_mode)) // Normal view (2024.2 JGL: Komen wie hier ooit nog?)
{
      //sql = "SELECT fac.usrrap_query(" + safe.quoted_sql(p_tableName) + ") FROM dual";
      //oRs = Oracle.Execute(sql);
      //sql1 = oRs.Fields(0).Value;
      sql1 = "SELECT * FROM " + p_tableName;

      sql = "SELECT fac.usrrap_orderby(" + safe.quoted_sql(p_tableName) + ") FROM dual";
      oRs = Oracle.Execute(sql);
      sql_order = oRs.Fields(0).Value;
      oRs.close();

    if (sqlWhere3D != "")
    {
        sql_where +=  sql_cond  + sqlWhere3D
        sql_cond = " AND ";
    }

    sql_rep = sql1 + sql_where + sql_order;

    // for formatted reports we perform the query later on.
    if (rapport_plain_mode(func_mode)){ // VIEW-mode voor Plain Rapportage
        oRs = Oracle.Execute(sql_rep);
    }
}
else
{ // Stored Procedure
    // de raportages verwachten formaat 'DD-MM-YYYY')
    __Log("sql_where=" +sql_where);
    var dt1 = "";
    var dt2 = "";
    if (ora_date1P) // Is er een begindatum meegegeven (was begindatum aanwezig)
      dt1 = padout(ora_date1P.getDate()) + "-" + padout(ora_date1P.getMonth() + 1) + "-" + padout(ora_date1P.getFullYear());
    if (ora_date2P) // Is er een einddatum meegegeven (was einddatum aanwezig)
      dt2 = padout(ora_date2P.getDate()) + "-" + padout(ora_date2P.getMonth() + 1) + "-" + padout(ora_date2P.getFullYear());
    if (rapport_plain_mode(func_mode)){ // Stored Procedure voor Plain rapportage (2024.2: bijvoorbeeld BONS/Factuur A) Per beschikking in periode)
        // JGL: Intrigerende compacte syntax maar werkt niet bij ORAOLEDB: ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'UWVA_RAP_ONDERSTEUNING' ORA-06550: line 1, column 7: PL/SQL: Statement ignored
        //oRs = Oracle.Execute("{ call " + p_tableName +"("+user_key+", '"+dt1+"', '"+dt2+"') } ")
        var stmt = new ActiveXObject("ADODB.Command")

        if (sql_where == ""){
            // Stored proc zonder filter-view
            stmt.CommandText  = "{ call " + p_tableName +"(?, ?, ?) } ";
        }
        else {
            // Stored proc MET filter-view
            stmt.CommandText  = "{ call " + p_tableName +"(?, ?, ?, ?) } ";
        }
        __Log(stmt.CommandText);

        stmt.CommandType  = adCmdText;
        stmt.ActiveConnection = Oracle.RealConnection;
        try { stmt.Properties("PLSQLRSet") = true; } catch (e) { /* nodig voor OLEDB, error bij MSDAORA */ };
        var p_user = stmt.CreateParameter("p1", adUnsignedBigInt, adParamInput, 0, user_key);
        var p_dt1 = stmt.CreateParameter("p2", adVarChar, adParamInput, 1000, dt1);
        var p_dt2 = stmt.CreateParameter("p3", adVarChar, adParamInput, 1000, dt2);
        stmt.Parameters.Append(p_user);
        stmt.Parameters.Append(p_dt1);
        stmt.Parameters.Append(p_dt2);
        if (sql_where != ""){
            var p_where = stmt.CreateParameter("p4", adVarChar, adParamInput, 1000, sql_where);
            stmt.Parameters.Append(p_where);
        }

        oRs = stmt.Execute();
        try { stmt.Properties("PLSQLRSet") = false; } catch (e) { /* nodig voor OLEDB, error bij MSDAORA */ };
    }
    else { // Stored Procedure voor XML/XSL rapportage, (2024.2: bijvoorbeeld TWYN/BREG_RUB)
        if (sqlWhere3D)
        {
            sql_where += sql_cond + sqlWhere3D;
        }

        sql_where = user_key + "#" + dt1 + "#" + dt2 + (sql_where?"#" + sql_where:"")// GEEN echte where-clause, maar om door te geven in make_xml (fac_pacx.src) en daar te parsen
    }
}

if (rapport_view(func_mode) && rapport_plain_mode(func_mode) && oRs.eof){ // Indien VIEW PLAIN een LEGE recordset oplevert...
  %>
  <div align="center">
  <p><b><%=L("lcl_empty_rstable")%></b></p>
  </div>
<% }
else { // In alle andere gevallen, dus normaliter (bij gevulde oRs) zijn dat nog alle gevallen...

        if (rapport_xmlxsl_mode (func_mode)) // Rapportage via XML/XSL: deze transformeren via xmlxsl
        {
            if(outputmode==0 && !nohtml)
            {
               buttons = [ { icon: "fa-print",  title: L("lcl_print_table"), action: 'rap_print()' },
                           { icon: "fa-table", title: L("lcl_export_to_excel"), action: 'rap_excel()' }
                         ];
               IFRAMER_HEADER(fac_usrrap.omschrijving, buttons);
            }

            mode = '';
            if (outputmode==2) mode = 'excel';
            if (outputmode==1) mode = 'print';
            if(!nohtml) {%><div><%}
            FCLT2XMLResponse ({xmlnode: "rapport", key: usrrap_key, mode: mode, where: sql_where, extraparams: xxx_extra_param});
            if(!nohtml) {%></div><%}
        }
        else  // plain rapportage, dus NIET via xml/xsl
        {
             if  (safeShowFilter != "" && (outputmode==1 || outputmode==2)) {
                %><table width="100%">
            <tr>
                <td><table><%=safeShowFilter%></table></td>
            </tr></table><%
            }

            var rst = new ResultsetTable({ sql: "dummy",
                                           pRs: oRs, // oRs is al eerder bepaald
                                           ID: "facusrdatatable",
                                           showAll: true, //showall,
                                           outputmode: outputmode,
                                           canCSV: !nobuttons,
                                           noLoading: true, // Hebben we zelf al gedaan
                                           title: fac_usrrap.omschrijving,
                                           totalShow: fntotalShow,
                                           noPrint: nobuttons,
                                           noExcel: nobuttons,
                                           buttons: [] // print en excel komen vanzelf
                                         });

            function fnfnmyFloat(kolom)
            {
                return function (oRs)
                {
                    var v = oRs(kolom).Value;
                    return safe.displayfloat(v, 2, true); // true voor trimZeros, we weten helemaal niet of die 2 zo bedoeld was
                }
            }

            function fnfnmyVal(kolom)
            {
                return function (oRs)
                {
                    return oRs(kolom).Value;
                }
            }

            function fntotalShow(column, nrlines)
            {
                if (column.datatype == 'currency')
                    return safe.curr(column.totalsum)
                else
                    return safe.displayfloat(column.totalsum, 2, true)
            }

           for (i= 0; i < oRs.Fields.Count; i++)
           {
                var kolomnaam = oRs.Fields(i).Name;
                var colpar = {caption: kolomnaam,
                              content: kolomnaam,
                              datatype: null,
                              total: false,
                              align: null
                             }
                var kolomtype = oRs.Fields(i).Type;

                if (  kolomnaam.substring(0,7).toUpperCase() == "HIDE_F_"
                    ||kolomnaam.substring(0,7).toUpperCase() == "FCLT_X_"
                    ||kolomnaam.substring(0,8).toUpperCase() == "FCLT_3D_"
                    ||kolomnaam == "FCLT_KEY")
                {
                    continue; // niet tonen, gewone FCLT_F_ .... blijven
                }
                __Log("Kolom:" + kolomnaam + " " + kolomtype
                           + " NumericScale: " + oRs.Fields(i).NumericScale
                           + " DefinedSize: " + oRs.Fields(i).DefinedSize
                           + " Precision: " + oRs.Fields(i).Precision );

                if (kolomtype == adInteger || kolomtype == adDecimal)
                {
                   colpar.datatype = 'number';
                   colpar.total = true;
                }
                else if (kolomnaam.substring(0,7).toUpperCase() == "FCLT_C_") // Currency
                {
                   colpar.datatype = 'currency';
                   colpar.content = kolomnaam;
                   colpar.amount = fnfnmyVal(kolomnaam); // voor optellen
                   colpar.total = true;
                   kolomnaam = kolomnaam.substring(7);
                }
                else if (kolomtype == adCurrency || kolomtype == adNumeric || kolomtype == adVarNumeric || kolomtype == adDouble)
                {
                   //colpar.datatype = 'float'; // autodetect 'currency' is veel te onbetrouwbaar==>gebruik FCLT_C_
                   colpar.align = "right"
                   colpar.content = fnfnmyFloat(kolomnaam);
                   colpar.amount = fnfnmyVal(kolomnaam); // voor optellen
                   colpar.total = true;
                }
                else if (kolomtype == adDBTimeStamp)
                {
                   colpar.datatype = 'date'; // ??
                }
                __Log("datatype:" + colpar.datatype);
                if (  kolomnaam.substring(0,5).toUpperCase() == "HTML_" )
                {
                  colpar.content = fnfnmyVal(kolomnaam);
                }
                if (kolomnaam.substring(0,5).toUpperCase() == "HTML_")
                    kolomnaam = kolomnaam.substring(5);

                if (kolomnaam.substring(0,7).toUpperCase() == "FCLT_F_" ||
                    kolomnaam.substring(0,7).toUpperCase() == "FCLT_D_")
                {
                    kolomnaam = kolomnaam.substring(7);
                }
                //kolomnaam = kolomnaam.replace(/\_/g, " ");
                colpar.caption = kolomnaam;
                rst.addColumn(new Column(colpar));
            }

            var cnt = rst.processResultset();
        // ========================================================================================================================
        } // Einde else: plain rapportage, dus NIET via xml/xsl

if (!nohtml) {
   %>
</body>
</html>
<% }
} // End else: In alle andere gevallen...
%><% ASPPAGE_END(); %>
