<% /*
    $Revision$
    $Id$

    File:           model_reportsx.inc

    Description:    rapport model voor het *definieren* van rapporten.
                    Zal rapporten niet uitvoeren dus. Daar is model_reports voor
    Parameters:
    Context:

    Notes:
*/
%>
<!-- #include file="./model_reportcolumns.inc" -->
<%

function model_reportsx(usrrap_key, rapparams)
{
    rapparams = rapparams || {};
    this.table = "fac_usrrap";
    this.primary = "fac_usrrap_key";
    this.records_name = "reports";
    this.record_name = "report";
    this.records_title = L("lcl_menu_fac_reports");
    this.record_title = L("lcl_usrrap_report");

    this.fields = { "id"           : {  dbs: "fac_usrrap_key",           typ: "key",      label: "Key",                    filter: "exact", required: true },
                    "name"         : {  dbs: "fac_usrrap_omschrijving",  typ: "varchar",  label: L("lcl_usrrap_report"),   filter: "like", translate: true, len : 60, required: true},
                    "description"  : {  dbs: "fac_usrrap_info",          typ: "varchar",  label: L("lcl_usrrap_info"),     filter: "like", translate: true },
                    "viewname"     : {  dbs: "fac_usrrap_view_name",     typ: "varchar",  label: L("lcl_usrrap_viewname"), filter: "like", required: true },
                    "authorization": {  dbs: "fac_functie_key",          typ: "key",      label: L("lcl_usrrap_functie"),  foreign: "fac_functie"},
                    "group"        : {  dbs: "fac_usrrap_groep",         typ: "varchar",  label: L("lcl_usrrap_groep"),    filter: "like" },
                    "styling"      : {  dbs: "fac_usrrap_functie",       typ: "key", label: L("lcl_usrrap_styling"),
                                          LOV: L("lcl_usrrap_stylingLOV") }, // 0;on-gestylede;1;gestylede;2;procedure;3;procedure gestyled;8;Via tabelizer;16;mobile;32;UDR Template

                    "urllink"      : {  dbs: "fac_usrrap_urllink",       typ: "varchar",  label: L("lcl_usrrap_urllink")},
                    "autorefresh"  : {  dbs: "fac_usrrap_autorefresh",   typ: "check",    label: L("lcl_usrrap_autorefresh")},
                    "count"        : {  dbs: "fac_usrrap_count",         typ: "number",   label: L("lcl_usrrap_showcount"),
                                            required: true, defaultvalue: 1, LOV: L("lcl_usrrap_showcountLOV")}, // 0;Uit, verborgen;1;Uit, kiesbaar;2;Aan, verborgen;3;Aan, kiesbaar
                    "ratio"        : {  dbs: "fac_usrrap_ratio",         typ: "number",   label: L("lcl_usrrap_showratio"),
                                            required: true, defaultvalue: 1, LOV: L("lcl_usrrap_showcountLOV")}, // 0;Uit, verborgen;1;Uit, kiesbaar;2;Aan, verborgen;3;Aan, kiesbaar
                    "pivot"        : {  dbs: "fac_usrrap_pivot",         typ: "number",   label: L("lcl_usrrap_showpivot"),
                                            required: true, defaultvalue: 0, LOV: L("lcl_usrrap_showcountLOV")},
                    "graph"        : {  dbs: "fac_usrrap_graph",         typ: "number",   label: L("lcl_usrrap_showgraph"),
                                            required: true, defaultvalue: 0, LOV: L("lcl_usrrap_showcountLOV")},
                    "graph_type"   : {  dbs: "fac_usrrap_graph_type",    typ: "number",   label: L("lcl_usrrap_graphtype"), LOV: L("lcl_usrrap_graphtypeLOV"), emptyoption: null},
                    "lastrefresh"  : {  dbs: "fac_usrrap_col_refresh",   typ: "datetime", label: "Columns last refreshed", readonly: true },
                    "graph_options": {  dbs: "fac_usrrap_graph_options", typ: "memo", label: "Graph Options" }
                  };

    this.list = { columns: ["id", "name", "description"] };
    this.search = { autosearch: true,
                    filters: ["id", "name", "description"]
                  };

    this.includes = {"columns": { model: new model_reportcolumns(usrrap_key, { internal: rapparams.internal }),
                                         joinfield: "fac_usrrap_key",
                                         enable_update: true
                                }
              };

    var hasFACFAC = user.has("WEB_FACFAC"); // Die mag ook tabellen doen
    this.is_safe_view = function(viewname)
    {
        if (hasFACFAC)
            return true; // die mag alles

        if (rapparams.internal)
            return true; // cloning

        if (viewname)
        {
            if (viewname.substr(0, 4).toUpperCase() == customerId)
                return true;

            var regexp = S("fac_usrrap_safe_view_regexp"); //"^(AAXX|PCHX)"

            if (regexp && new RegExp(regexp, 'i').test(viewname))
                return true;

            __Log("Viewname '{0}' is unsafe for {1}".format(viewname, user.oslogin()));
            return false;
        }
        else
            return true;
    };

    this._check_authorization = function(params, method)
        {
            params.message = "";
            var autfunction = "WEB_UDRMAN";
            params.authparams = user.checkAutorisation(autfunction); // pessimistisch
        };

    if (!hasFACFAC)
    {
        this.fields.lastrefresh.hidden_fld = true;
        this.fields.authorization.foreign =
            {
              "tbl": "fac_functie",
              "key": "fac_functie_key",
              "desc": "lcl.l(fac_functie_omschrijving, 1) || ' (' || fac_functie_code || ')'",
              "where": "fac_functie_code NOT IN ('WEB_FACFAC', 'WEB_FACTAB')"
            }
    }

    this._analyze_fields = function (dbfields, params, jsondata) /* analyseer inkomende data, common voor PUT en POST */
        {
            // viewname zit alleen in dbfields als het een insert is. In edit-mode is dit veld readonly, dus niet in dbfields.
            if ("viewname" in dbfields)
                user.auth_required_or_abort(this.is_safe_view(jsondata.viewname));
        };

    this.hook_pre_edit = function (obj)
    {
        this.fields.styling.LOV = api2.filterLOV(L("lcl_usrrap_stylingLOV"), "0,1,2,3,8,16"); // De meesten mogen L(ike) niet
        this.fields.graph_type.LOV = api2.filterLOV(this.fields.graph_type.LOV, "0,1,3,4"); // dashboard nu nog even niet.

        if (obj.graph.id > 0)
        {
            this.fields.graph_type.LOV = this.fields.graph_type.LOV.substring(3);
            this.fields.graph_type.LOV = api2.filterLOV(this.fields.graph_type.LOV, "1,3,4"); // dashboard nu nog even niet.
        }
    };

    this.REST_GET = function _reportsx_GET(params, jsondata)
        {
            var query = api2.sqlfields(params, this);

            var wheres = api2.sqlfilter(params, this);
            query.wheres = query.wheres.concat(wheres);

            var authparams = user.checkAutorisation("WEB_UDRMAN", true);
            var whereor = ["fac_functie_key IS NULL"]
            whereor.push("fac_functie_key IN"
                             + " (SELECT w.fac_functie_key"
                             + "    FROM fac_v_webgebruiker W"
                             + "   WHERE w.prs_perslid_key = " + user_key + ")");
            if (user.has("WEB_UDRMAN")) // Met UDRMAN hoef je er geen rechten op te hebben
            {                           // Uitzondeing: FACFAC en FACTAB, daar moet je altijd rechten op hebben
                whereor.push("fac_functie_key NOT IN"
                             + "    (SELECT fac_functie_key"
                             + "       FROM fac_functie"
                             + "      WHERE fac_functie_code IN ('WEB_FACFAC', 'WEB_FACTAB'))");
            }
            query.wheres.push("(" + whereor.join(" OR ") +")");
            if (S("fac_usrrap_mode") != 1 || rapparams.forview) // Als je niet mag clonen heb je niets aan UDR template rapporten
            {
                query.wheres.push("BITAND(COALESCE(fac_usrrap_functie, 0), 32) = 0");
            }
            var sql = "SELECT " + query.selects.join(", ")
                    + "  FROM " + query.tables.join(", ")
                    + (query.wheres.length ? " WHERE " + query.wheres.join(" AND " ) : "")
                    + " ORDER BY 2";

            if (params.include && params.include.length)
                sql += ", fac_usrrap_cols_volgnr";

            var json = api2.sql2json (params, sql, this);
            if (json.length == 1)
            {
                var rap_data = json[0];
                if (params.include && inArray("columns", params.include))
                {
                    this.includes["columns"].model._view2columns(params.filter.id, rap_data.lastrefresh, rap_data.columns);
                    var json = api2.sql2json (params, sql, this ); // En nu opnieuw ophalen
                }
                   if ("viewname" in rap_data && !this.is_safe_view(rap_data.viewname))
                    this.fields["viewname"].readonly = true;

                if (rap_data.styling && rap_data.styling.id & 32) // UDR Template
                {
                    this.REST_PUT = false; // Niets te updaten, alleen clonen
                }
            }

            return json;
        };

    this.REST_PUT = function _reportsx_REST_PUT(params, jsondata, the_key) /* update report */
        {
            this._check_authorization(params, "PUT");

            var sql = "SELECT fac_usrrap_view_name"
                    + "  FROM fac_usrrap"
                    + " WHERE fac_usrrap_key = " + the_key;
            var oRs = Oracle.Execute(sql);
            var old_view = oRs("fac_usrrap_view_name").Value;
            oRs.Close();

            var dbfields = api2.update_fields(params, this, jsondata); // Build updater
            this._analyze_fields(dbfields, params, jsondata);

            var wheres = [" fac_usrrap_key = " + the_key];
            var roomUpd = buildTrackingUpdate("fac_usrrap", wheres.join(" AND " ), dbfields, { noValidateToken: true });

            var err = Oracle.Execute(roomUpd.sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

            var beztrack = api2.process_includes(params, this, jsondata, the_key);

            if ("viewname" in jsondata && old_view.toUpperCase() != jsondata.viewname.toUpperCase())
            {   // Verwijder alle kolommen als er een nieuwe view is ingevuld, maar laat de expressies staan.
                var sql = "DELETE fac_usrrap_cols"
                        + " WHERE fac_usrrap_cols_expression IS NULL"
                        + "   AND fac_usrrap_key = " + the_key;
                var err = Oracle.Execute(sql, true);
                if (err.friendlyMsg)
                    abort_with_warning(err.friendlyMsg);
                // Voeg de kolommen van de nieuwe view weer toe.
                this.includes["columns"].model._view2columns(the_key, null, []);
            }

            return { key: the_key, warning: "" };
        };

    this.REST_POST = function _reportsx_REST_POST(params, jsondata) /* new report */
        {
            this._check_authorization(params, "POST");

            var dbfields = api2.update_fields(params, this, jsondata); // Build updater
            this._analyze_fields(dbfields, params, jsondata);

            dbfields["xxx"] = {dbs: "fac_usrrap_key", typ: "key", seq: "fac_s_fac_usrrap_key" };
            var rapIns = buildInsert("fac_usrrap", dbfields, { noValidateToken: true });
            var rap_key = rapIns.sequences["fac_usrrap_key"];

            var err = Oracle.Execute(rapIns.sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

            var beztrack = api2.process_includes(params, this, jsondata, rap_key);

            return { key: rap_key, warning: "" };
        };

    this.REST_DELETE = function (params, the_key) /* delete report */
        {
            this._check_authorization(params, "DELETE");
            var sql = "DELETE FROM fac_usrrap"
                    + " WHERE fac_usrrap_key = " + the_key;

            var err = Oracle.Execute(sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

            return { key: the_key, warning: "" };
        };

    if (!rapparams.internal)
    {
        if (hasFACFAC)
            settings.overrule_setting("fac_usrrap_mode", 1); // _FACILITOR mag alles
        else
        {
            // ooit iets als this.fields["viewname"].foreignsql = "SELECT object_name FROM user_objects WHERE objecttype = 'VIEW' AND <<safe>>";
            // scaffolding.inc / scf_RWFIELDTR moet dan wel foreignsql gaan ondersteunen
        }
        if (S("fac_usrrap_mode") != 1)
        {
            this.fields["count"].readonly = true;
            this.fields["ratio"].readonly = true;  // denk ik dan
            this.fields["pivot"].readonly = true;
            this.fields["graph"].readonly = true;
        }
        if (!user.checkAutorisation("WEB_UDRMAN", true))
        {   // Dit heeft betrekking op de zoekvelden van appl/fac/fac_reportx_show.asp?mode=search
            // Omdat wij standaard linken naar mode=list speelt dit zelden.
            for (var fld in this.fields)
            {
                if (fld != "id" && fld != "name" && fld != "description")
                    this.fields[fld].hidden = true;
            }
            this.list.columns = ["name", "description"];
            this.fields["id"].filter = false;
        }
    }

    if (usrrap_key > 0)
    {
        rapparams.filter = { "id" : usrrap_key };
        this.data = this.REST_GET(rapparams)[0];
    }

}
%>