<% /*
    $Revision$
    $Id$

    File:           model_reportcolumns.inc

    Description:    rapport model voor de kolommen van rapporten.

    Parameters:
    Context:

    Notes:
*/

// model_reportcolumns is uitsluitend beschikbaar onder model_reports(x) die de autorisatie dan ook doet
// TODO: neen, security lek FSN#33869
function model_reportcolumns(usrrap_key, params)
{
    var rap_key = getQParamInt("fac_usrrap_key", -1); // JGL: Lelijk

    params = params || {};
    this.records_name = "columns";
    this.record_name = "column";
    this.table = "fac_usrrap_cols";
    this.primary = "fac_usrrap_cols_key";
    this.records_title = L("lcl_rap_columns");
    this.record_title = L("lcl_rap_column");
    this.autfunction = "WEB_UDRMAN",  // Minstens UDRMAN rechten, met FACTAB kan ook sql-expressie zelf worden ingevuld.
    this.defaultIcon = "fa-table-cells-large";
    this.edit = {
        modal: true,
        requires: {
            js: ["../fac/fac_reportx.js"]
        }
    };

    var hasFACFAC = !!user.has("WEB_FACFAC");
    var hasFACTAB = !!user.has("WEB_FACTAB");
    var hasUDRMAN = !!user.has("WEB_UDRMAN");

    this.fields = {
        "id": {
            dbs: "fac_usrrap_cols_key",
            typ: "key",
            label: L("lcl_key"),
            seq: "fac_s_fac_usrrap_cols_key"
        },
        "name": {
            dbs: "fac_usrrap_cols_column_name",
            typ: "varchar",
            label: L("lcl_rap_column"),
            required: true,
            insertonly: true
        },
        "datatype": {
            dbs: "fac_usrrap_cols_datatype",
            typ: "varchar",
            label: L("lcl_rap_datatype"),
            required: true,
            LOV: L("lcl_rap_datatypeLOV") // "varchar;Tekst;date;Datum;datetime;Datumtijd;time;Tijd;float;Float;currency;Bedrag;number;Getal;check0;Checkbox;html;Html"
        },
        "sequence": {
            dbs: "fac_usrrap_cols_volgnr",
            typ: "number",
            label: L("lcl_rap_sequence"),
            required: true
        },
        "caption": {
            dbs: "fac_usrrap_cols_caption",
            typ: "varchar",
            label: L("lcl_rap_caption"),
            required: true,
            translate: true
        },
        "sorting": {
            dbs: "fac_usrrap_cols_sorting",
            typ: "number",
            label: L("lcl_usrrap_sorting"),
            LOV: L("lcl_usrrap_sortingLOV"),
            required: true,
            defaultvalue: 3,
            multiedit: true
        },
        "filter": {
            dbs: "fac_usrrap_cols_filter",
            typ: "varchar",
            label: L("lcl_rap_filter"),
            LOV: L("lcl_rap_filterLOV"), //  "A;Automatisch"
            multiedit: true
        },
        "filterdefault": {
            dbs: "fac_usrrap_cols_filterdefault",
            typ: "varchar",
            label: L("lcl_rap_filterdefault")
        },
        "urllink": {
            dbs: "fac_usrrap_cols_urllink",
            typ: "memo",
            label: L("lcl_usrrap_cols_urllink")
        },
        "visible": {
            dbs: "fac_usrrap_cols_visible",
            typ: "varchar",
            label: L("lcl_rap_visible"),
            required: true,
            LOV: L("lcl_rap_visibleLOV"), // "V;Visible;I;Invisible;H;hidden;S;Suppress repetitions"
            emptyoption: null,
            multiedit: true
        },
        "group": {
            dbs: "fac_usrrap_cols_group",
            typ: "varchar",
            label: L("lcl_rap_groupby"),
            required: true,
            LOV: L("lcl_rap_groupbyLOV"),
            emptyoption: null
        },
        "fac_usrrap_key": {
            dbs: "fac_usrrap_key",
            typ: "key",
            hidden_fld: true
        },
        "expression": {
            dbs: "fac_usrrap_cols_expression",
            typ: "memo",
            label: L("lcl_rap_expression"),
            labelaction: {
                icon: "fa-wand-sparkles",
                hint: L("lcl_usrrap_property_wizard"),
                action: "kenmerkkolom()"
            },
            required: true,
            readonly: true
        }
    };

    this.fnrowClass = function _fnrowClass(oRs)
    {
        return "report_" + oRs.Fields("visible").Value.id;
    }

    this.list = {
        columns: [
            "sequence",
            "name",
            "caption",
            "sorting",
            "datatype",
            "visible",
            "filter",
            "filterdefault",
            "group"
        ],
        rowClass: this.fnrowClass
    };

    this.hook_pre_edit = function (obj, fld)
    {
        function getOrgDatatype(p_usrrap_key, p_column_name)
        {
            var datatype = null;
            var sql = "SELECT CASE WHEN REGEXP_SUBSTR(UPPER(c.column_name), '^FCLT_C_') IS NOT NULL THEN 'currency'"
                    + "            WHEN REGEXP_SUBSTR(UPPER(c.column_name), '^HTML_')   IS NOT NULL THEN 'html'"
                    + "            WHEN data_type = 'NUMBER' AND data_scale > 0 THEN 'float'"
                    + "            WHEN data_type = 'NUMBER' THEN 'number'"
                    + "            WHEN data_type = 'DATE'  THEN 'date'"
                    + "            ELSE 'varchar'"
                    + "       END column_datatype"
                    + "  FROM user_tab_columns c"
                    + "     , fac_usrrap r"
                    + " WHERE c.table_name = UPPER(r.fac_usrrap_view_name)"
                    + "   AND c.column_name = " + safe.quoted_sql_upper(p_column_name)
                    + "   AND r.fac_usrrap_key = " + p_usrrap_key;
            var oRs = Oracle.Execute(sql);
            if (!oRs.eof)
                datatype = oRs("column_datatype").Value;
            oRs.Close();
            return datatype;
        }

        this.fields.filter.LOV = api2.filterLOV(L("lcl_rap_filterLOV"), "A,E,R,RR,P"); // De meesten mogen L(ike) niet
        if ((obj.datatype && !obj.expression))
        {
            var orgDatatype = getOrgDatatype(obj.fac_usrrap_key, obj.name);
            var datatype_id = (obj.datatype.id == "varchar" && orgDatatype == "number" ? "number" : obj.datatype.id);
            switch (datatype_id)
            {
                case "date":
                case "datetime":
                    this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,D,W,M,Q,Y,H");
                    this.fields.datatype.LOV = api2.filterLOV(L("lcl_rap_datatypeLOV"), "date,datetime,time");
                    break;
                case "time":
                    this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,H");
                    this.fields.datatype.LOV = api2.filterLOV(L("lcl_rap_datatypeLOV"), "date,datetime,time");
                    break;
                case "varchar":
                    if (orgDatatype == "number" || orgDatatype == "float" || orgDatatype == "currency") {
                        this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,S,C,A");
                        this.fields.datatype.readonly = false;
                        this.fields.datatype.LOV = api2.filterLOV(L("lcl_rap_datatypeLOV"), "varchar,number,float,currency");
                    } else {
                        this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G");
                        this.fields.datatype.readonly = true;
                        this.fields.filter.LOV = L("lcl_rap_filterLOV"); // die mag alle filters
                    }
                    break;
                case "html":
                    this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G");
                    this.fields.datatype.readonly = true;
                    this.fields.filter.LOV = L("lcl_rap_filterLOV");
                    break;
                case "check0":
                case "float":
                case "number":
                case "currency":
                    this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,S,C,A");
                    this.fields.datatype.LOV = api2.filterLOV(L("lcl_rap_datatypeLOV"), "float,currency,number,varchar");
                    break;
                default:
                    this.fields.group.LOV = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G");
            }
        }

        if ((obj.filter && obj.filter.id == "P" || obj.expression || !obj.id))
        {
            this.fields.expression.readonly = false;
            this.fields.name.insertonly = false;

            if ( obj.expression || (obj.filter && obj.filter.id == "P") )
            {   // Een door gebruiker toegevoegd veld mag verwijderd worden, mits UDRMAN of FACTAB rechten.
                this.REST_DELETE = generic_REST_DELETE(this);
            }
            if (!hasFACTAB && obj.id)
            {   // Een UDRMAN hoeft deze velden niet te zien bij wijzigen.
                delete this.fields.name;
                delete this.fields.expression;
                // .. maar wel handig om te weten dat er een sql-expressie bestaat.
                if (obj.expression && obj.expression.length > 0)
                {
                    this.fields.hasexpression = {"dbs": "",
                                                 "label": L("lcl_rap_expression"),
                                                 "typ": "varchar",
                                                 "readonly": true
                                                };
                    obj.hasexpression = L("lcl_inserted0").format("");
                }
            }
        }
        var x_id = getQParamInt("id", -1);
%>
<script>
    var params_js = { model: "columns"
                    , id: <%=x_id%>
                    , hasfactab: (<%=(hasFACTAB?1:0)%>==1)
                    , hasudrman: (<%=(hasUDRMAN?1:0)%>==1)
                    };
</script>
<%
    };

    this.hook_pre_post = function (params, obj)
    {
        if (obj.id == -1)
            this.fields.expression.readonly = false;
    };

    this.hook_pre_delete = function (params, columns_key)
    {   // Alleen een parameter of sql-expressie mag door een gebruiker verwijderd worden.
        var sql = "SELECT 1"
                + "  FROM fac_usrrap_cols"
                + " WHERE (  fac_usrrap_cols_expression IS NOT NULL"
                + "       OR fac_usrrap_cols_filter = 'P'"
                + "       )"
                + "   AND fac_usrrap_cols_key = " + columns_key;
        var oRs = Oracle.Execute(sql, true);

        if (oRs.eof)
            abort_with_warning(L("lcl_cnt_Del_Fails_Auth"));

        oRs.Close();
        user.checkAutorisation(["WEB_FACTAB","WEB_UDRMAN"]);
        this.REST_DELETE = generic_REST_DELETE(this);
    };

    // Maakt de default fac_usrrap_cols records aan aan de hand van de view of werk ze bij
    this._view2columns = function (usrrap_key, lastrefresh, oldcols)
        {
            var sql_date = ", TO_DATE('" + toDateTimeString(lastrefresh, true, true) + "','dd-mm-yyyy hh24:mi:ss')";
            var sql = "BEGIN"
                    + "  fac.view2columns(" + usrrap_key + (lastrefresh ? sql_date : "") + ");"
                    + "  END;";
            var err  = Oracle.Execute(sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);
        }

    this.REST_GET = function _GET(params)
        {
            // De modal detail popup gebruikt dit echter nog wel.
            var query = api2.sqlfields(params, this );
            var wheres = api2.sqlfilter(params, this);
            query.wheres = query.wheres.concat(wheres);

            var sql = "SELECT " + query.selects.join(", ")
                    + "  FROM " + query.tables.join(", ")
                    + " WHERE " + query.wheres.join(" AND " )
                    + " ORDER BY fac_usrrap_cols_volgnr";

            var json = api2.sql2json (params, sql, this );
            if (!json.length)
            {
                INTERNAL_ERROR_MISSING_COLUMNS;
            }

            return json;
        }

    this.REST_PUT = function (params, jsondata, the_key) /* update columns */
        {
            var valid_char = /^[_0-9a-zA-Z]+$/; // Alleen deze tekens zijn geldig!
            if (!valid_char.test(jsondata.name))
                abort_with_warning(L("lcl_rap_column_invalid"));

            if (hasFACTAB && (jsondata.expression || !jsondata.id))
            {
                this.fields.expression.readonly = false;
                this.fields.name.insertonly = false;
            }

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

            var sql = buildUpdate("fac_usrrap_cols", dbfields, { noValidateToken: true }) + " fac_usrrap_cols_key = " + the_key;
            var err = Oracle.Execute(sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

            return { key: the_key };
        }

    this._REST_PUT = this.REST_PUT; // Interne is er altijd

    // Only internally used by report_clone and _view2columns
    this._REST_POST = function (params, jsondata, parent_key) /* insert columns */
        {
            params.isNew = true;
            if (hasFACTAB && !jsondata.id || params.cloning)
                this.fields.expression.readonly = false;

            var valid_char = /^[_0-9a-zA-Z]+$/;
            if (!valid_char.test(jsondata.name))
                abort_with_warning(L("lcl_rap_column_invalid"));

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

            dbfields["id"] = this.fields["id"];
            if (parent_key && !jsondata.fac_usrrap_key)
                dbfields["xxx"] = { dbs: "fac_usrrap_key", typ: "key", val: parent_key };

            var rapIns = buildInsert("fac_usrrap_cols", dbfields, { noValidateToken: true });
            var col_key = rapIns.sequences["fac_usrrap_col_key"];
            var err = Oracle.Execute(rapIns.sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

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

    if (params.internal || hasFACTAB || hasUDRMAN)
    {
        this.REST_POST = this._REST_POST;
    }

    if (rap_key > 0)
    {
        // var rap_data = model_reportsx(rap_key); te veel recursie
        var sql = "SELECT fac_usrrap_functie"
                + "  FROM fac_usrrap"
                + " WHERE fac_usrrap_key = " + rap_key;
        var oRs = Oracle.Execute(sql);
        var functie = oRs("fac_usrrap_functie").Value || 0;
        oRs.Close();
        if (functie & 32) { // template
            this.REST_PUT = false;
            this.REST_POST = false;
        }
    }
}

%>
