<% /*
    $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" -->
<!-- #include file="./model_fac_notificatie_job.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",
                                        required: true
                                     },
                    "name"         : {  dbs: "fac_usrrap_omschrijving",
                                        typ: "varchar",
                                        label: L("lcl_usrrap_report"),
                                        filter: "like",
                                        translate: true,
                                        len : 60, required: true
                                     },
                    "viewname"     : {  dbs: "fac_usrrap_view_name",
                                        typ: "varchar",
                                        label: L("lcl_usrrap_viewname"),
                                        filter: "like",
                                        required: true
                                     },
                    "description"  : {  dbs: "fac_usrrap_info",
                                        typ: "memo",
                                        label: L("lcl_usrrap_info"),
                                        filter: "like",
                                        translate: true
                                     },
                    "sequence"     : {  dbs: "fac_usrrap_volgnr",
                                        typ: "number",
                                        label:  L("lcl_rap_sequence"),
                                        multiedit: true
                                     },
                    "group"        : {  dbs: "fac_usrrap_groep",
                                        typ: "varchar",
                                        label: L("lcl_usrrap_groep"),
                                        filter: "like",
                                        multiedit: true },
                    "authorization": {  dbs: "fac_functie_key",
                                        typ: "key",
                                        label: L("lcl_usrrap_functie"),
                                        foreign: "fac_functie",
                                        multiedit: true
                                     },
                    "condition"    : {  dbs: "fac_usrrap_cond",
                                        typ: "number",
                                        label: L("lcl_usrrap_showcondition"),
                                        required: true,
                                        defaultvalue: 0,
                                        LOV: L("lcl_usrrap_showconditionLOV")
                                     },
                    "styling"      : {  dbs: "fac_usrrap_functie",   // LET OP: Hier gebeurt elders (hook_pre_edit) iets raars mee, dat eens elimineren?
                                        typ: "number",
                                       "label": L("lcl_usrrap_styling"),
                                        defaultvalue: 0,
                                        required: true,
                                        // We onderkennen bij rapportages de volgende bit settingen voor fac_usrrap_functie:
                                        // 0:   desktop-query (view).
                                        // &1:  gestyled (ipv plat resultaat).
                                        // &2:  procedure (ipv view).
                                        // &4:  systeem rapport (xmlnode "sysrapport").
                                        // &8:  tabelized (snapshot).
                                        // &16: mobiel beschikbaar.
                                        // &32: templaterapportage (core/system setting).
                                        "bits": [
                                            {
                                                "name": "fac_usrrap_functie1",
                                                "typ": "radio",
                                                "label": L("lcl_fac_usrrap_functie1"),
                                                "mask": 1,
                                                "defaultvalue": 0,
                                                "radios": [
                                                    {
                                                        "label": L("lcl_fac_usrrap_functie1_stylesheetoff"),
                                                        "mask": 0
                                                    },
                                                    {
                                                        "label": L("lcl_fac_usrrap_functie1_stylesheeton"),
                                                        "mask": 1
                                                    }
                                                ]
                                            },
                                            {
                                                "typ": "check",
                                                "label": L("lcl_fac_usrrap_functie4"),
                                                "mask": 4,
                                                "readonly": true,
                                                "radios": [
                                                    {
                                                        "name": "fac_usrrap_functie4",
                                                        "label": L("lcl_fac_usrrap_functie4_system"),
                                                        "mask": 4,
                                                        "defaultvalue": 0
                                                    }
                                                ]
                                            },
                                            {
                                                "name": "fac_usrrap_functie2",
                                                "typ": "radio",
                                                "label": L("lcl_fac_usrrap_functie2"),
                                                "mask": 2,
                                                "defaultvalue": 0,
                                                "radios": [
                                                    {
                                                        "label": L("lcl_fac_usrrap_functie2_procedureoff"),
                                                        "mask": 0
                                                    },
                                                    {
                                                        "label": L("lcl_fac_usrrap_functie2_procedureon"),
                                                        "mask": 2
                                                    }
                                                ]
                                            },
                                            {
                                                "typ": "check",
                                                "label": L("lcl_fac_usrrap_functie8"),
                                                "mask": 8,
                                                "radios": [
                                                    {
                                                        "name": "fac_usrrap_functie8",
                                                        "label": L("lcl_fac_usrrap_functie8_snapshoton"),
                                                        "mask": 8,
                                                        "defaultvalue": 0
                                                    }
                                                ]
                                            },
                                            {
                                                "typ": "check",
                                                "label": L("lcl_fac_usrrap_functie16"),
                                                "mask": 16,
                                                "radios": [
                                                    {
                                                        "name": "fac_usrrap_functie16",
                                                        "label": L("lcl_fac_usrrap_functie16_mobielon"),
                                                        "mask": 16,
                                                        "defaultvalue": 0
                                                    }
                                                ]
                                            }
                                            // &32 wordt gebruikt voor templaterapportages  (core/system setting).
                                            ]
                                       },
                    "sort"         : {  dbs: "fac_usrrap_sort",
                                        typ: "number",
                                        label: L("lcl_usrrap_sort"),
                                        required: true,
                                        defaultvalue: 0,
                                        LOV: L("lcl_usrrap_sortLOV"),
                                        multiedit: true
                                     },
                    "maxrows"      : {  dbs: "fac_usrrap_maxrows",
                                        typ: "number",
                                        label: L("lcl_usrrap_maxrows"),
                                        multiedit: true
                                     },
                    "urllink"      : {  dbs: "fac_usrrap_urllink",
                                        typ: "varchar",
                                        label: L("lcl_usrrap_urllink")},
                    "autorefresh"  : {  dbs: "fac_usrrap_autorefresh",
                                        typ: "check",
                                        label: L("lcl_usrrap_autorefresh"),
                                        multiedit: true
                                     },
                    "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
                                        multiedit: true
                                     },
                    "ratio"        : {  dbs: "fac_usrrap_ratio",
                                        typ: "number",
                                        label: L("lcl_usrrap_showratio"),
                                        required: true, defaultvalue: 1,
                                        LOV: L("lcl_usrrap_showratioLOV"), // 0;Uit, verborgen;1;Uit, kiesbaar;2;Aan, verborgen;3;Aan, kiesbaar
                                        multiedit: true
                                     },
                    "pivot"        : {  dbs: "fac_usrrap_pivot",
                                        typ: "number",
                                        label: L("lcl_usrrap_showpivot"),
                                        required: true, defaultvalue: 0,
                                        LOV: L("lcl_usrrap_showpivotLOV"),
                                        multiedit: true
                                     },
                    "graph"        : {  dbs: "fac_usrrap_graph",
                                        typ: "number",
                                        label: L("lcl_usrrap_showgraph"),
                                        required: true, defaultvalue: 0,
                                        LOV: L("lcl_usrrap_showgraphLOV"),
                                        multiedit: true
                                     },
                    "graph_type"   : {  dbs: "fac_usrrap_graph_type",
                                        typ: "number",
                                        label: L("lcl_usrrap_graphtype"),
                                        LOV: L("lcl_usrrap_graphtypeLOV"),
                                        emptyoption: null,
                                        multiedit: true
                                     },
                    "limit0":        { dbs: "fac_usrrap_limiet0",
                                       label: L("lcl_usrrap_limiet0"),
                                       typ: "number"
                                     },
                    "limit1":        { dbs: "fac_usrrap_limiet1",
                                       label: L("lcl_usrrap_limiet1"),
                                       typ: "number"
                                     },
                    "limit2":        { dbs: "fac_usrrap_limiet2",
                                       label: L("lcl_usrrap_limiet2"),
                                       typ: "number"
                                     },
                    "limit3":        { dbs: "fac_usrrap_limiet3",
                                       label: L("lcl_usrrap_limiet3"),
                                       typ: "number"
                                     },
                    "lastrefresh"  : {  dbs: "fac_usrrap_col_refresh",
                                        typ: "datetime",
                                        label: L("lcl_usrrap_lastrefresh"),
                                        readonly: true
                                     },
                    "graph_options": {  dbs: "fac_usrrap_graph_options",
                                        typ: "memo",
                                        label: L("lcl_usrrap_graphoptions")
                                     },
                    "code"         : {  dbs: "fac_usrrap_code",
                                        typ: "varchar",
                                        label: L("lcl_usrrap_code"),
                                        filter: "exact",
                                        len : 60
                                     },
                    "parameters"   : {  dbs: "fac_usrrap_parameters",
                                        typ: "varchar",
                                        label: L("lcl_usrrap_parameters"),
                                        multiedit: true
                                     },
                    "created"       : { "dbs": "fac_usrrap_aanmaak",
                                        "label": L("lcl_usrrap_aanmaak"),
                                        "typ": "datetime",
                                        "clone": false,
                                        "readonly": true
                                     }
                  };

    var sqlteller = "(SELECT (SELECT TO_CHAR(COALESCE(SUM (fac_gui_counter_count), 0)) "
                  + "          FROM fac_gui_counter "
                  +"         WHERE fac_gui_counter_group = 'report' AND fac_gui_counter_refkey = fac_usrrap.fac_usrrap_key "
                  + "           AND fac_gui_counter_date > SYSDATE - 7) "
                  + "       || '/' || "
                  + "       (SELECT TO_CHAR(COALESCE(SUM (fac_gui_counter_count), 0)) "
                  + "          FROM fac_gui_counter "
                  + "         WHERE fac_gui_counter_group = 'report' AND fac_gui_counter_refkey = fac_usrrap.fac_usrrap_key "
                  + "           AND fac_gui_counter_date > SYSDATE - 30) "
                  + "       || '/' || "
                  + "       (SELECT TO_CHAR(COALESCE(SUM (fac_gui_counter_count), 0)) "
                  + "          FROM fac_gui_counter "
                  + "         WHERE fac_gui_counter_group = 'report' AND fac_gui_counter_refkey = fac_usrrap.fac_usrrap_key "
                  + "           AND fac_gui_counter_date > SYSDATE - 365) "
                  + "  FROM DUAL) "

    // if (user.has("WEB_FACFAC"))
    {
        this.fields["usage"] = {
            "dbs": "dummy",
            "label": L("fac_usrrap_usage"),
            typ: "varchar",
            sql: sqlteller
        }
    }

    this.list = { columns: ["id", "sequence", "group", "name", "description", "graph_type", "code", "authorization","usage"] };
    this.search = { autosearch: true,
                    filters: ["name", "code", "group", "description"]
                  };

    this.includes = {
        "columns": {
            "model": new model_reportcolumns(usrrap_key, { internal: rapparams.internal }),
            "joinfield": "fac_usrrap_key",
            "enable_update": true
        },
        "notificationjobs": {
            "model": new model_fac_notificatie_job({ niveau: "S"}),
            "joinfield": "fac_usrrap_key",
            "enable_update": true,
            "label": L("lcl_schedule_frm_report"),
            "notransport": true // te ingewikkeld, ook geen cloning
        }
    };

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

        if (params.cloning)
            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;

            var oRs = Oracle.Execute("SELECT fac_version_group FROM fac_version");
            if (!oRs.Eof && viewname.substr(0, 4).toUpperCase() == oRs("fac_version_group").Value)
            {
              return true;
            }

            __Log("Viewname '{0}' is unsafe for {1}".format(viewname, user.oslogin() || user.prs_perslid_email()));
            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')",
              "selectorforeign": "fac_functie"
            }
    }

    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, params));
        };

    this.hook_pre_edit = function (obj)
    {
    };

    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 (!rapparams.forview &&   // Kun je er wel iets wijzigen?
                user.has("WEB_UDRMAN")) // Met UDRMAN hoef je er geen rechten op te hebben
            {                           // Uitzondering: 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 fac_usrrap_volgnr NULLS LAST, fac_usrrap_omschrijving";

            // Srikt op volgnr sluit niet aan bij de functionaliteit, de onzichtbaren mogen onderaan
            // "V;Visible;I;Invisible;H;hidden;S;Suppress repetitions"
            if (params.include && params.include.length && inArray("columns", params.include))
                sql += ", DECODE(fac_usrrap_cols_visible,'H',9, 'I', 5, 1), 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 (!params.internal && "viewname" in rap_data && !this.is_safe_view(rap_data.viewname, {}))
                  this.fields["viewname"].readonly = true;

                if (!params.cloning && rap_data.styling && rap_data.styling & 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 */
        {
            params.isNew = true; // negeer eventuele bestaande keys
            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);
            if (params.cloning)
                this.includes.columns.model.REST_POST = this.includes.columns.model._REST_POST; // Voor de clone van de kolommen
            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;
            this.fields["condition"].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];
    }

}
%>