<% /*
     $Revision$
     $Id$


    File:               fac_usrrap.inc (voorheen Where3d.inc)
    Description:        Handige functies voor de usrrap's
                        defines function for Build WHERE-clause for the report to apply 3D autorization
    Globals:
        p_tableName     The selected FAC_USR_REPORT name
    Result:             returns where3D clause
    Context:
    Note:               When FAC_FUNCTIE.FAC_FUNCTIE_DISCIPLINE==1 column FCLT_3D_DISCIPLINE_KEY
                                will be filtered in the view (when [present)
                        When '8'-bit set in FAC_FUNCTIE.FAC_FUNCTIE_MIN_LEVEL then
                                column FCLT_3D_LOCATIE_KEY will be filtered in the view (when [present)
                        When '4'-bit set in FAC_FUNCTIE.FAC_FUNCTIE_MIN_LEVEL then
                                column FCLT_3D_AFDELING_KEY will be filtered in the view (when [present)
                        So care must be taken in selecting the appropriate FAC_FUNCTIE!
                        Independent from bitsettings allow filtering on FCLT_3D_USER_KEY
*/

usrrap = {
    create3Dclause: function (ptableName, fac_functie_key)
    {
        if (!fac_functie_key)
            return "";

        var sql;

        sql  = "SELECT FAC_FUNCTIE_CODE, FAC_FUNCTIE_MIN_LEVEL, FAC_FUNCTIE_DISCIPLINE"
        sql += "  FROM FAC_FUNCTIE F "
        sql += " WHERE F.FAC_FUNCTIE_KEY = " + fac_functie_key;
        var oRs = Oracle.Execute(sql)

        var where3D = "" // Default no autorization

        var autfunction    = oRs("FAC_FUNCTIE_CODE").Value;
        var bMetALGAuth    = (oRs("FAC_FUNCTIE_MIN_LEVEL") & 8) == 8;
        var bMetPRSAuth    = (oRs("FAC_FUNCTIE_MIN_LEVEL") & 4) == 4;
        var bMetDiscipline = (oRs("FAC_FUNCTIE_DISCIPLINE")=="1");

        var has3D_INS = false;
        var has3D_LOC = false;
        var has3D_BLD = false;
        var has3D_PRS = false;
        var has3D_USR = false;

        // Check for our special 3D column names
        sql = "SELECT INITCAP(column_name) column_name"
            + "  FROM user_tab_columns"
            + " WHERE table_name = " + safe.quoted_sql_upper(ptableName)
            + "   AND column_name LIKE 'FCLT_3D_%'"
            + " ORDER BY COLUMN_ID";

        var oRsCol = Oracle.Execute(sql);
        var column_name;

        while (!oRsCol.eof)
        {
            column_name = (oRsCol.Fields("column_name").Value).toUpperCase();

            if (column_name.substring(0,7) == "FCLT_3D")
            {
                has3D_INS = has3D_INS || column_name == "FCLT_3D_DISCIPLINE_KEY"
                has3D_LOC = has3D_LOC || column_name == "FCLT_3D_LOCATIE_KEY"
                has3D_BLD = has3D_BLD || column_name == "FCLT_3D_GEBOUW_KEY"
                has3D_PRS = has3D_PRS || column_name == "FCLT_3D_AFDELING_KEY"
                has3D_USR = has3D_USR || column_name == "FCLT_3D_USER_KEY"
            }
            oRsCol.MoveNext();
        }


    __Log("autfunction="+autfunction+", MIN_LEVEL="+oRs("FAC_FUNCTIE_MIN_LEVEL")+", FUNCTIE_DISCIPLINE="+oRs('FAC_FUNCTIE_DISCIPLINE'))
    __Log("bMetALGAuth="+bMetALGAuth+", bMetPRSAuth="+bMetPRSAuth+", bMetDiscipline="+bMetDiscipline)
    __Log("Column names: has3D_LOC="+has3D_LOC+", has3D_PRS="+has3D_PRS+", has3D_INS="+has3D_INS + ", has3D_USR="+has3D_USR)

        var authparams = user.checkAutorisation(autfunction);

        if (has3D_INS && bMetDiscipline)
        {
            var disciplines = "";
            sql = "SELECT ins_discipline_key FROM fac_v_my_disciplines "
                +   "  WHERE fac_functie_code = "+safe.quoted_sql(autfunction)
                +   "    AND prs_perslid_key="+user_key;
            oRs = Oracle.Execute(sql);
            while (!oRs.Eof) {
              if (disciplines == "") disciplines = oRs("INS_DISCIPLINE_KEY").value;
              else disciplines += ", " + oRs("INS_DISCIPLINE_KEY").value;
              oRs.MoveNext();
            }
            if (disciplines == "") disciplines = "-1"
            where3D = " FCLT_3D_DISCIPLINE_KEY IN (" + disciplines + ")";
        }
        if (has3D_LOC && bMetALGAuth && authparams.ALGreadlevel > 0)
        {
            if (where3D != "") where3D += " AND "
            where3D += " FCLT_3D_LOCATIE_KEY IN"
                     +   "(SELECT alg_locatie_key FROM fac_v_my_locations "
                     +   "  WHERE niveau ="+authparams.ALGreadlevel
                     +   "    AND prs_perslid_key="+user_key+")"

        }
        if (has3D_BLD && bMetALGAuth && authparams.ALGreadlevel > 0)
        {
            if (where3D != "") where3D += " AND "
            where3D += " FCLT_3D_GEBOUW_KEY IN"
                     +   "(SELECT alg_gebouw_key FROM fac_v_my_buildings "
                     +   "  WHERE niveau ="+authparams.ALGreadlevel
                     +   "    AND prs_perslid_key="+user_key+")"

        }
        if (has3D_PRS && bMetPRSAuth && authparams.PRSreadlevel > 0)
        {
            if (where3D != "") where3D += " AND "
            where3D += " FCLT_3D_AFDELING_KEY IN"
                     + "    (SELECT prs_afdeling_key FROM prs_v_afdeling_familie a"
                     + "      WHERE a.prs_afdeling_elder_key IN"
                     + "        (SELECT aa.prs_afdeling_elder_key"
                     + "           FROM prs_v_afdeling_familie aa"
                     + "          WHERE aa.prs_afdeling_key = " + user.prs_afdeling_key()
                     + "            AND aa.niveau = " + authparams.PRSreadlevel + "))"
        }
        if (has3D_USR )
        {
            if (where3D != "") where3D += " AND "
            where3D += " FCLT_3D_USER_KEY = " + user_key
        }
       return where3D;
    },

    // Aborts als pcolname geen filtercol is van ptableName!
    requireFilterCol: function _requireFilterCol(ptableName, pcolname)
    {
        // deze check even vrij laten voor infobord 'misbruik'
        // het is ook amper een lek te noemen omdat je er alleen de dataset
        // verder kunt beperken dat het systeem al doet.
        // if (pcolname.toUpperCase().substr(0, 7) != 'FCLT_F_')
        //    shared.internal_error("Invalid filter column name");

        // mbmb
        var i = ptableName.indexOf('.');
        if (i != -1){
            ptableName = ptableName.substring(i+1);
         }


        var sql = "SELECT 1"
                + "  FROM user_tab_columns"
                + " WHERE table_name = " + safe.quoted_sql_upper(ptableName)
                + "   AND column_name = "  + safe.quoted_sql_upper(pcolname);

        var oRs = Oracle.Execute(sql);
        if (oRs.Eof)
            shared.internal_error("Invalid filter column name");

        oRs.Close()
    },

    // Bepaal de naam van de equivalente getabelliseerde view, en controleer ook of die bestaat
    // Zo niet, dan krijg je gewoon de viewnaam terug
    tabelizedViewname: function (pviewname)
    {
        var lviewname = "";
        if (typeof pviewname == 'string')
            lviewname = 'T_'+pviewname.substring(0,28);

        // controleer of die echt bestaat
        var sql = "SELECT 1"
                + "  FROM user_tables"
                + " WHERE table_name = " + safe.quoted_sql_upper(lviewname);
        var oRs = Oracle.Execute(sql);

        if (oRs.Eof) {
            lviewname = pviewname;  // bestaat niet (job niet gescheduled of ORA-1031 ?)
            __DoLog('<p style="color:red">tabelized view bestaat niet, check de tabelizer-job</p>');
        }
        oRs.Close()

        return lviewname;
    },
    // We kennen (helaas) drie varianten om de info van de kolommen te bepalen
    // A) Opzoeken viewnaam in Oracle user_tab_columns. Dit is heel efficient maar wel beperkt in de typering
    // B) Openen Recordset en uit de ADO properties halen. Potentieel traag (is deze versie echt nog nodig?)
    // C) (nieuw) uit FAC_USRRAP_COLS handmatig gespecificeerd
    fac_usrrap_info: function (usrrap_key)
    {
        var sql  = "SELECT "+lcl.xsqla('fac_usrrap_info','fac_usrrap_key')
                 + "     , "+lcl.xsqla('fac_usrrap_omschrijving', 'fac_usrrap_key')
                 + "     , fac_usrrap_vraagbegindatum"
                 + "     , fac_usrrap_vraageinddatum"
                 + "     , fac_usrrap_view_name"
                 + "     , fac_functie_key"
                 + "     , fac_usrrap_functie"
                 + "  FROM fac_usrrap"
                 + " WHERE fac_usrrap_key = " + usrrap_key;
        var oRs = Oracle.Execute(sql);
        var result = { info : oRs.Fields("fac_usrrap_info").value,
                       omschrijving : oRs.Fields("fac_usrrap_omschrijving").value,
                       vraagbegindatum: oRs.Fields("fac_usrrap_vraagbegindatum").value=="1",
                       vraageinddatum: oRs.Fields("fac_usrrap_vraageinddatum").value=="1",
                       view_name: oRs.Fields("fac_usrrap_view_name").value,
                       fac_functie_key: oRs.Fields("fac_functie_key").value,
                       functie: oRs.Fields("fac_usrrap_functie").value,
                       columns: []
                     }
        oRs.Close();

        var sql = "SELECT *"
                + "  FROM fac_usrrap_cols"
                + " WHERE fac_usrrap_key = " + usrrap_key
                + " ORDER BY fac_usrrap_cols_volgnr";
        var oRs = Oracle.Execute(sql);
        if (!oRs.Eof)
        {
            while (!oRs.eof)
            {
                var colpar = {
                               id: oRs("fac_usrrap_cols_key").Value,
                               caption: oRs("fac_usrrap_cols_caption").Value,
                               column_name: oRs("fac_usrrap_cols_column_name").Value,
                               datatype: oRs("fac_usrrap_cols_datatype").Value,
                               group: oRs("fac_usrrap_cols_group").Value==1,
                               filter: oRs("fac_usrrap_cols_filter").Value, // 'A'=Automatic
                               sequence: oRs("fac_usrrap_cols_volgnr").Value,
                               align: null,
                               visible: 'V'
                             };
                result.columns.push(colpar);
                oRs.MoveNext()
            }
            oRs.Close();
        }
        else // Oldstyle uit user_tab_columns afleiden
        {
            oRs.Close();
            // Stored procedures zijn XXXX.RAP_YYYYY
            result.view_name_short = result.view_name.toUpperCase();
            var i = result.view_name_short.indexOf('.');
            if (i != -1)
                result.view_name_short = result.view_name_short.substring(i+1);
            var sql = "SELECT INITCAP(column_name) column_name"
                    + "     , data_type"
                    + "     , data_length"
                    + "     , data_precision"
                    + "     , data_scale"
                    + "  FROM user_tab_columns"
                    + " WHERE table_name = UPPER(" + safe.quoted_sql(result.view_name_short) + ")"
                    + " ORDER BY column_id";
            var oRs = Oracle.Execute(sql);
            while (!oRs.eof)
            {
                var colpar = { caption: oRs.Fields("column_name").Value,
                               column_name: oRs.Fields("column_name").Value.toLowerCase(),
                               datatype: null,
                               group: 'G',
                               align: null,
                               visible: 'V',
                               filter: null
                             };
                var special_cols = colpar.column_name.toUpperCase().match(/^(HIDE_F_|FCLT_X_|FCLT_3D_|FCLT_KEY|FCLT_F_|HTML_|FCLT_D_|FCLT_C_)/);
                if (special_cols)
                    colpar.caption = colpar.caption.substring(special_cols[0].length);

                var ucolname = colpar.column_name.toUpperCase();
                if (ucolname.match(/^(HIDE_F_|FCLT_X_|FCLT_3D_|FCLT_KEY)/))
                    colpar.visible = 'H'; // Hidden

                if (result.view_name_short.match(/_V_UDR/))
                    colpar.visible = 'H'; // Hidden, die hebben te veel kolommen

                if (ucolname.match(/^(FCLT_F_|FCLT_D_)/))
                    colpar.filter = 'A';

                var ora_type = oRs("data_type").Value;
                var ora_length = oRs("data_length").Value;
                var ora_precision = oRs("data_precision").Value;
                var ora_scale = oRs("data_scale").Value;

                if (ucolname.match("^FCLT_F_|FCLT_X_")) // Filter, altijd varchar
                {
                   colpar.filter = 'A';
                }
                else if (ucolname.match("^FCLT_C_")) // Currency
                {
                   colpar.datatype = 'currency';
                }
                else if (ucolname.match("^HTML_"))
                {
                   colpar.datatype = 'html';
                }
                else if (ora_type == 'NUMBER')
                {
                   colpar.datatype = 'number';
                   if (ora_scale > 0)
                   {
                       colpar.datatype = 'float';
                       colpar.align = "right"
                   }
                }
                else if (ora_type == "DATE") //
                {
                   colpar.datatype = 'date';
                }
                else if (ucolname.match("^FCLT_D_"))
                {
                    result.vraagbegindatum = true;
                    result.vraageinddatum = true;
                    // colpar.datatype = 'date'; neen, het is char
                }

                result.columns.push(colpar);
                oRs.MoveNext();
            }
            oRs.Close();
        }
        return result;
    }
}
%>
