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

    File            fac_report.asp
    Description:    Voer een rapport uit (toon het zoekblok/list body)

    Parameters:     usrrap_key van een rapport (voorkeur)
                    of rapcode, de (unieke) fac_usrrap_code een rapport.
                    of rap_name, de naam van de view van een rapport (geen voorkeur). Deze moet dan wel uniek zijn

                    mode=list optioneel, toon het rapport direct zonder zoekblok

    Note:           Dit is de hoofdingang voor rapportage, vervolgens deze flow
                    - rapport.styling & 2: Procedure-gegenereerde rapporten gaan via de (oude) fac_usrrap_search.asp
                    en dan de rest via overrule van default scaffolding_list()
                    - rapport.styling & 1: XSL-gestylde rapporten gaan via XML+XSL
                    en dan de rest
                    - rapport.graph_type.id & 6: Kaart via leaflet
                    - rapport.graph_type.id > 0: Grafiek via jqPlot
                    en de rest (rapport.graph_type.id = 0)
                    - standaard, via de resultsettable
*/

CSP_EXTRADATA = 1; // eventuele S("csp_header_extradata") ook toestaan voor tilemap
%>
<!-- #include file="../scf/scaffolding.inc" -->
<!-- #include file="../api2/model_reports.inc" -->
<!-- #include file="../Shared/xml_converter.inc" -->
<!-- #include file="./fac_report_graph.inc" -->
<!-- #include file="./fac_report_lfmap.inc" -->
<%
    var usrrap_key = getQParamInt("usrrap_key", -1);
    var widget_height = getQParamInt("widget_height", null);

    if (usrrap_key == -1) // Dan kan rapcode meegegeven zijn
    {
        var usrrap_code = getQParam("rapcode", "");
        if (usrrap_code)
        {
            var sql = "SELECT fac_usrrap_key"
                    + "  FROM fac_usrrap"
                    + " WHERE fac_usrrap_code = " + safe.quoted_sql(usrrap_code);
            var oRs = Oracle.Execute(sql);
            if (oRs.EOF)
            {
                abort_with_warning("Report '{0}' not found".format(usrrap_code), 404);
            }
            usrrap_key = oRs("fac_usrrap_key").Value;
            oRs.Close();
        }
    }

    if (usrrap_key == -1) // Dan moet rap_name meegegeven zijn
    {
        var rap_name = getQParam("rap_name"); // Gebruiker liever de usrrap_key versie maar vooruit.
        var sql = "SELECT fac_usrrap_key"
                + "  FROM fac_usrrap"
                + " WHERE UPPER(fac_usrrap_view_name) = " + safe.quoted_sql_upper(rap_name);
        var oRs = Oracle.Execute(sql);
        var usrrap_key = oRs("fac_usrrap_key").Value;
        oRs.MoveNext()
        if (!oRs.Eof)
            INTERNAL_ERROR_RAPNAME_NOT_UNIQUE; // gebruik dan maar usrrap_key
        oRs.Close();
    }

    // Mocht het rapport niet meer bestaan, dan geeft "model_reports" netjes de melding "Dit tabblad is niet meer aanwezig. Klik op de kleine pin om het tabblad te verwijderen."
    var rapport = model_reports(usrrap_key);

    var usrrap_maxresults = rapport.maxrows; // Rapport "Max. aantal regels".

    if (mode == "list" && Server.ScriptTimeout < 600)
        Server.ScriptTimeout=600; // extra tijd

    if (mode == "search" && rapport.autorefresh > 0)
    {
        var refreshThisUrl = "/appl/fac/fac_report.asp?mode=list" + transitQS();
        if ((rapport.list.autoGraph & 2) && rapport.graph_type.id == 7) {
            refreshThisUrl += "&worker=calendar";
        }
        var theURL = "../shared/refresher.asp?url=" + Server.URLencode(refreshThisUrl) + "&refreshrate=" + S("usrrap_refreshrate");
        if (widget_height)
            theURL += "&widget_height=" + widget_height;
        Response.Redirect(theURL);
    }

    rapport.list.canGroup = (S("fac_usrrap_mode") == 1);

    if (rapport.styling && (rapport.styling & 2)) // view proc doen we "old style"
            Response.Redirect("fac_usrrap_search.asp?usrrap_key=" + usrrap_key);

    var params = { transit: { "usrrap_key": usrrap_key, "viewname": rapport.table }, // viewname uitsluitend ter (logging)informatie
                   search: { requires: { js: ["./fac_report.js"] }, keepfilter: "report"}
                 };

    if ("estimated_rows" in rapport && rapport.estimated_rows < 250)
        params.search.autosearch = true;
    params.search.keepfilters = getQParamInt("keepfilters", 0) == 1;

    Oracle.Execute("ALTER SESSION SET optimizer_features_enable = '12.1.0.1'"); // BLCC#71903 anders te vaak ORA-04023

    if (rapport.styling && (rapport.styling & 1)) // XSL proc doen we niet via resultsettable
    {
        // Overrule scaffolding_list
        scaffolding_list = function _styled_report_scaffolding_list(model, scf_params)
        {
            var xxx_params = { filter : scf_params.filter || shared.qs2json(rapport) };

            // Zet de extra parameters in een aparte lijst
            // en verwijder ze uit het filter.
            var xxx_extra_param = [];
            if (xxx_params.filter && xxx_params.filter.columns)
            {
                var param_arr = usrrap.isParamFilterCol(usrrap_key);
                var param_col_arr = xxx_params.filter.columns.split(",");
                for (var i=0; i<param_col_arr.length; i++)
                {
                    for (var j=0; j<param_arr.length; j++)
                    {
                        var fld = param_col_arr[i];
                        if (param_arr[j].column_name.toLowerCase() == fld.toLowerCase())
                        {
                            var param_value = xxx_params.filter[fld] || "";
                            if (param_arr[j].datatype == "check0")
                            {
                                param_value = (param_value == "" ? 0 : 1);
                                delete xxx_params.filter["has_"+fld];
                            }
                            xxx_extra_param.push( {name: fld.toLowerCase(), value: param_value} );
                            delete xxx_params.filter[fld];
                        }
                    }
                }
            }

            rapport.addfixedfilters(xxx_params.filter);
            var wheres = api2.sqlfilter(xxx_params, rapport);
            rapport.add3d(wheres);

            var sql_where = null;
            if (wheres.length)
                sql_where = "WHERE " + wheres.join(" AND " );

            var outputmode = getQParamInt("outputmode", 0);
            var nobuttons = getQParamInt("nobuttons", 0) == 1;
            var noheader = getQParamInt("noheader", 0) == 1;

            var rmode = "";
            if (outputmode==2) rmode = "excel";
            if (outputmode==1) rmode = "print";

            var nohtml = getQParamInt("nohtml", 0) == 1;
            if (nohtml) // Die is simpel
            {
                Response.Clear();
                FCLT2XMLResponse ({xmlnode: ((rapport.styling & 4) == 4? "sysrapport" : "rapport"), key: usrrap_key, mode: rmode, where: sql_where, extraparams: xxx_extra_param });
                Response.End;
            }

            // Zelf niet nodig maar sommige XSL-rapportages (ARAI KPI) doen modal popup
            FCLTHeader.Requires({js: ["jquery-ui.js"]});

            %><html>
                  <head>
                <%  FCLTHeader.Generate({ outputmode: outputmode, forceInlineExcel: true }); %>
                    <% if (outputmode == 0) {%>
                      <script type="text/javascript">
                        function rap_print()
                        {
                            FcltMgr.windowopen("fac_report.asp?outputmode=1<%=safe.jsstring(transitQS())%>");
                        }
                        function rap_excel()
                        {
                            FcltMgr.windowopen("fac_report.asp?outputmode=2<%=safe.jsstring(transitQS())%>");
                        }
                      </script>
                    <% } %>
                  </head>
                  <body id="listbody" <%= (outputmode == 1? "onload='window.print()'" : "")%>>
                <%
                    if (outputmode==0)
                    {
                        var buttons = [];
                        if(!nobuttons)
                        {
                            var buttons = [ { icon: "fa-fclt-refresh", title: L("lcl_refresh"), action: "FcltMgr.reload()" },
                                            { icon: "fa-print",  title: L("lcl_print_table"), action: "rap_print()" },
                                            { icon: "fa-table", title: L("lcl_export_to_excel"), action: "rap_excel()" }
                                          ];
                        }
                        if (!noheader)
                            IFRAMER_HEADER(model.records_title, buttons);
                    }
                    FCLT2XMLResponse ({xmlnode: ((rapport.styling & 4) == 4? "sysrapport" : "rapport"), key: usrrap_key, mode: rmode, where: sql_where, extraparams: xxx_extra_param});
                %>
                  </body>
                </html>
            <%
        }
    }
    else
    {
        var graph = (rapport.list.autoGraph & 2) == 2;
        var graph_type = getQParamInt("scf_graph_type", graph ? rapport.graph_type.id : null);
        if (mode == "list" && graph_type == 6)
        {
            FCLTHeader.Requires({ plugins: ["jQuery"],
                                  js: [ "./leaflet/leaflet.js"],
                                  css: ["./leaflet/leaflet.css"]});
            // Overrule scaffolding_list
            scaffolding_list = fac_usrrap_list_map;
        }
        else if (mode == "list" && graph_type == 7) {
            Server.Transfer("../Shared/fullcalendar.asp");
        }
        else if (mode == "list" && graph_type >= 1)
        {
            FCLTHeader.Requires({plugins: ["jQuery"],
                                 js: ["../Localscripts/jqPlot/dist/excanvas.js",
                                      "../Localscripts/jqPlot/dist/jquery.jqplot.min.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasTextRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasAxisLabelRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasAxisTickRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.categoryAxisRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.barRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.meterGaugeRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.pieRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.highlighter.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasOverlay.js"
                                     ],
                                 css: ["../Localscripts/jqPlot/dist/jquery.jqplot.css"]
                                 });
            // Overrule scaffolding_list
            scaffolding_list = fac_usrrap_list_graph;
        }
        if (mode == "list" && (graph_type == 1 || graph_type == 4))
        {
            // Alleen bij barchart (1) en linechart (4) dit script voor label-points, bij gaugemeter NIET(!) om runtime error te voorkomen (en voegt daar niets toe).
            // "axes[...]._ticks.0.formatter is null or not an object" krijg je namelijk
            // https://bitbucket.org/cleonello/jqplot/issue/201/highlighter-plugin-causes-error-on-hover meldt min of meer hetzelfde
            FCLTHeader.Requires({  js: ["../Localscripts/jqPlot/dist/plugins/jqplot.pointLabels.js"]});
        }
    }

    if (mode == "list")
        shared.registeraction("report", {refkey: usrrap_key, daily: 2});  // future: analoog aan fac_gui_counter_menu_daily een fac_gui_counter_report_daily te gebruiken

    params.list = params.list || {};
    params.list.columns = params.list.columns || [];
    params.list.groupby = params.list.groupby || [];

    if (rapport.has_bijlagen)
    {
        params.list.buttons = [ { icon: "fa-file-zip", title: L("lcl_zip_bijlagen"), action: "doOutput(7)" } ];
    }

    var cols = getQParamArray("columns", []);
    if (cols.length && cols[0])
        params.list.columns = cols;


    var grps = getQParamArray("groupby", []);
    if (grps.length)
        params.list.groupby = grps;

    if (!params.list.columns.length && "list" in rapport)
    {
        params.list.columns = rapport.list.columns;
        params.list.groupby = rapport.list.groupby;
    }

    var urllink_index = -1;
    var urllink_col;
    var urllink;
    for (var u = 0; u < params.list.columns.length; u++)
    {
      if (rapport.fields[params.list.columns[u]] && rapport.fields[params.list.columns[u]].urllink)
      {
        if (graph_type == 0)
        {
          // Als scf_pivot = 0 (Geen pivot) dan per regel klikbaar maken. Maar dan moet het keyfield een field met de naam "id" zijn.
          var obj_click_ref = rapport.fields[params.list.columns[u]];
          var obj_click_clone = JSON.parse(JSON.stringify(obj_click_ref)); // Clone Object without reference (Het object met de klikactie).
          rapport.fields["id"] = obj_click_clone;
        }
        urllink_index = u;
        urllink_col = params.list.columns[u];
        urllink = rapport.fields[params.list.columns[u]].urllink
        break;
      }
    }

    params.urllink = {index: urllink_index, col: urllink_col, link: urllink};

    scaffolding(rapport, params);
%>

<% ASPPAGE_END(); %>
