<% /*
    $Revision$
    $Id$

    File:           model_rooms.inc

    Description:    room model.
    Parameters:
    Context:

    Notes:
*/
%>
<!-- #include file="../ALG/alg.inc" -->
<!-- #include file="./model_cadcontours.inc" -->
<!-- #include file="./model_custom_fields.inc"-->
<!-- #include file="./model_tracking.inc"-->
<!-- #include file="./model_prs_ruimteafdeling.inc"-->
<%
function model_rooms(room_key, params)
{
    params = params || {};
    this.table = "alg_ruimte";
    this.primary = "alg_ruimte_key";
    this.records_name = "rooms";
    this.record_name = "room";
    this.fields =
            {"id"          : { dbs: "alg_ruimte_key",                typ: "key",      filter: "exact" },
             "name"        : { dbs: "alg_ruimte_nr",                 typ: "varchar",  filter: "like",               track: true, label: L("lcl_estate_ruimte_man_nr") },
             "floor"       : { dbs: "alg_verdieping_key",            typ: "key",      foreign: "alg_verdieping",    filter: "exact" },
             "roomtype"    : { dbs: "alg_srtruimte_key",             typ: "key",      foreign: "alg_srtruimte",     track: true, label: L("lcl_estate_ruimte_man_sort") },
             "servicelevel": { dbs: "mld_dienstniveau_key",          typ: "key",      foreign: "mld_dienstniveau",  track: true, label: L("lcl_mld_dienst_niveau") },
             "description" : { dbs: "alg_ruimte_omschrijving",       typ: "varchar",  filter: "like",               track: true, label: L("lcl_estate_ruimte_man_descr") },
             "grossarea"   : { dbs: "alg_ruimte_bruto_vloeropp",     typ: "float",    track: true, label: L("lcl_estate_ruimte_bruto_vloeropp") },
             "area1"       : { dbs: "alg_ruimte_opp_alt1",           typ: "float",    track: true, label: L("lcl_estate_ruimte_opp_alt1") },
             "area2"       : { dbs: "alg_ruimte_opp_alt2",           typ: "float",    track: true, label: L("lcl_estate_ruimte_opp_alt2") },
             "perimeter"   : { dbs: "alg_ruimte_omtrek",             typ: "float",    track: true, label: L("lcl_estate_ruimte_man_omtrek") },
             "volume"      : { dbs: "alg_ruimte_inhoud",             typ: "float",    track: true, label: L("lcl_estate_ruimte_man_inhoud") },
             "remark"      : { dbs: "alg_ruimte_opmerking",          typ: "varchar",  track: true, label: L("lcl_estate_ruimte_man_opmerk") },
             "openfrom"    : { dbs: "alg_ruimte_beginuur",           typ: "float",    track: true, label: L("lcl_estate_gebouw_beginuur") },
             "opento"      : { dbs: "alg_ruimte_einduur",            typ: "float",    track: true, label: L("lcl_estate_gebouw_einduur") },
             "workdays"    : { dbs: "alg_ruimte_werkdagen",          typ: "number" },
             "deleted"     : { dbs: "alg_ruimte_verwijder",          typ: "datetime" }
             /* niet gebruikt:
             { dbs: "_ALG_RUIMTE_VLOER_OMSCHRIJVING", typ: "varchar",  frm: "room_flrom" },
             { dbs: "_ALG_RUIMTE_OPP_GEVELGLAS",      typ: "float",    frm: "room_gegl"  },
             { dbs: "_ALG_RUIMTE_OPP_SEPARATIEGLAS",  typ: "float",    frm: "room_segl"  },
             { dbs: "_ALG_RUIMTE_OPP_GEVELBEKLEDING", typ: "float",    frm: "room_gebe"  },
             { dbs: "_ALG_RUIMTE_ACADKEY",            typ: "varchar",  frm: "room_ackey" },
             { dbs: "_ALG_RUIMTE_GETEKEND",           typ: "date",     frm: "room_tek"   },
             */
            };
    this.controls =
              [ {name: "scope",        type: "varchar" },
                {name: "show_deleted", type: "boolean" }
              ];
    this.defaults =
              { onrgoedlvl: "R"
              };
    this.includes =
              {"cadcontours": { model: model_cadcontours,
                                joinfunction: function ()
                                {
                                    var sqlSync = "SELECT y.alg_ruimte_key cad_ruimte_key"
                                                + "     , y.cadlabel"
                                                + "     , t.cad_tekening_key"
                                                + "  FROM " + S("fg_syncruimteview") + " y"
                                                + "     , cad_tekening t"
                                                + "     , alg_ruimte r "
                                                + " WHERE t.alg_verdieping_key = y.alg_verdieping_key"
                                                + "   AND y.alg_ruimte_key = r.alg_ruimte_key";

                                    return { tables: ["("+sqlSync+") sync"],
                                             where: "alg_ruimte.alg_ruimte_key = sync.cad_ruimte_key(+)"
                                                    + " AND sync.cadlabel = cad_imp_contour.cad_imp_contour_nr(+)"
                                                    + " AND sync.cad_tekening_key = cad_imp_contour.cad_tekening_key(+)"
                                           }
                                }
                },
                "custom_fields" : {
                    "model": new model_custom_fields(this, "ALG", { readman: true, readuse: true }),
                    "joinfield": "flexparentkey"
                },
                "tracking": {
                    "model": new model_tracking(["ruimte"]),
                    "joinfield": "fac_tracking_refkey"
                },
                "departments": {
                    "model": new model_prs_ruimteafdeling(),
                    "joinfield": "room"
                }
              }

    function _check_authorization (params, method)
        {
            params.message = "";
            var autfunction = (params.filter.scope == "fe"? "WEB_ALGUSE" : "WEB_ALGMAN");
            params.authparams = user.checkAutorisation(autfunction, null, null, true); // pessimistisch

            switch (method)
            {
                case "GET":
                    if (params.filter.id)
                    {
                        var room_key = params.filter.id;
                        var this_alg = alg.func_enabled(room_key, /* this.defaults.onrgoedlvl */ 'R');
                        user.auth_required_or_abort(this_alg.readman || this_alg.readuse);
                    }
                    break;
                case "DELETE":
                    var autfunction = "WEB_RUIMAN";
                    var authParams = user.checkAutorisation(autfunction);
                    // en verder met de autorisatie van PUT...
                case "PUT":
                    var room_key = params.filter.id;
                    var this_alg = alg.func_enabled(room_key, /* this.defaults.onrgoedlvl */ 'R');
                    user.auth_required_or_abort(this_alg.writeman || this_alg.writeuse);
                    params.isNew = false;
                    break;
                case "POST":
                    var room_key = -1;
                    var this_alg = alg.func_enabled(room_key, /* this.defaults.onrgoedlvl */ 'R');
                    user.auth_required_or_abort(this_alg.writeman);
                    params.isNew = true;
                    break;
            }
            params.func_enabled = this_alg || {};
        };

    function _analyze_fields (dbfields, params, jsondata) /* analyseer inkomende data, common voor PUT en POST */
        {
            var beginuur = "openfrom" in dbfields? dbfields["openfrom"] : -2;
            if (beginuur.val == -2)
                delete dbfields.openfrom;
            else if (beginuur.val == -1)
            {
                api2.field_alter(dbfields, "openfrom", null, this);
            }
            else //(beginuur.val != -2)
                api2.field_alter(dbfields, "openfrom", beginuur.val, this)

            var einduur = "opento" in dbfields? dbfields["opento"] : -2;
            if (einduur.val == -2)
                delete dbfields.opento;
            else
                api2.field_alter(dbfields, "opento", (einduur.val == -1 ? null : einduur.val), this);
        };

    function _save_flexproperties(room_key, params, jsondata)
        {
            var flextrack = [];
            var flexdata = jsondata.custom_fields;

            currentKenmerkenSQL = " SELECT k.alg_kenmerk_key"
                                + "      , ok.alg_onrgoedkenmerk_waarde"
                                + "   FROM alg_onrgoedkenmerk ok"
                                + "      , alg_kenmerk k"
                                + "  WHERE k.alg_kenmerk_key = ok.alg_kenmerk_key"
                                + "    AND alg_onrgoedkenmerk_verwijder IS NULL"
                                + "    AND alg_onrgoed_niveau = " + safe.quoted_sql(/* this.defaults.onrgoedlvl */ 'r')
                                + "    AND alg_onrgoed_key = " + room_key;

            allKenmerkenSQL     = " SELECT "+lcl.xsql("k.alg_kenmerk_omschrijving","k.alg_kenmerk_key")+" kenmerk_omschrijving"
                                + "      , alg_kenmerk_key srtkenmerk_key"
                                + "      , fac_kenmerkdomein_key"
                                + "   FROM alg_kenmerk k"
                                + "  WHERE k.alg_kenmerk_verwijder IS NULL"
                                + "    AND k.alg_kenmerk_niveau = " + safe.quoted_sql("R") /* this.defaults.onrgoedlvl */
                                + "    AND k.alg_kenmerk_key = "; /* wordt in saveFlexkenmerken uitgebreid */

            flextrack = saveFlexKenmerken( room_key,
                                           { kenmerkTable: "alg_onrgoedkenmerk",
                                             kenmerkParentKey : "alg_onrgoed_key",
                                             kenmerkWaarde: "alg_onrgoedkenmerk_waarde",
                                             kenmerkKey: "alg_kenmerk_key",
                                             currentKenmerkenSQL: currentKenmerkenSQL,
                                             allKenmerkenSQL: allKenmerkenSQL,
                                             kenmerkOmschrijving: "alg_kenmerk_omschrijving",
                                             kenmerkSoortKey: "alg_kenmerk_key",
                                             requestQF: Request.Form,
                                             flexdata: flexdata,
                                             isNew: params.isNew,
                                             flexPath: "ALG/R",
                                             tracking: true,
                                             moduleName: "ALG_ONRGOED_NIVEAU",
                                             moduleVal: "R",
                                             module: "ALG"
                                           }
                                         );

            return flextrack;
        }

    this.REST_GET = function _GET(params, jsondata)
        {
            _check_authorization(params, "GET");
            var query = api2.sqlfields(params, this);

            if (!params.filter.show_deleted)
                query.wheres.push("alg_ruimte_verwijder IS NULL");

            if (params.filter.isNew)
                query.wheres.push("alg_ruimte_key = -1");  // Forceer leeg record.

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

            var sql = "SELECT " + query.selects.join(", ")
                    + "  FROM " + query.tables.join(", ")
                    + (query.wheres.length ? " WHERE " + query.wheres.join(" AND " ) : "")

            if (params.authparams.ALGreadlevel > -1)
            {   // Er is een scope-beperking van kracht
                sql += " AND " + this.table + ".alg_ruimte_key IN"
                     + " (SELECT alg_ruimte_key FROM fac_v_my_rooms"
                     + " WHERE prs_perslid_key = " + user_key
                     + " AND niveau = " + params.authparams.ALGreadlevel + ")";
            }
            sql += " ORDER BY alg_ruimte_key"; // Nodig voor includes
            if (query.orderbys.length)
                sql += ", " + query.orderbys.join(", ");

            var json = api2.sql2json (params, sql, this);

            return json;
        }

    this.REST_PUT = function (params, jsondata, the_key) /* update room */
        {
            _check_authorization(params, "PUT");
            if (!jsondata.id) jsondata.id = the_key;
            var room_key = the_key;

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

            var wheres = [" alg_ruimte_key = " + room_key];
            var roomUpd = buildTrackingUpdate("alg_ruimte", wheres.join(" AND " ), dbfields, { noValidateToken: true });

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

            var flextrack = _save_flexproperties(room_key, params, jsondata);

            if (roomUpd.trackarray.length || flextrack.length)
                shared.trackaction("ALGRUP", room_key, roomUpd.trackarray.concat(flextrack).join("\n"));

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

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

            var dbfields = api2.update_fields(params, this, jsondata); // Build updater
            _analyze_fields(dbfields, params, jsondata);
            dbfields["id"] = {dbs: "alg_ruimte_key", typ: "key", seq: "alg_s_alg_onroerendgoed_keys" };
            var roomIns = buildInsert("alg_ruimte", dbfields, { noValidateToken: true });
            var room_key = roomIns.sequences["alg_ruimte_key"];

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

            var flextrack = _save_flexproperties(room_key, params, jsondata);

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

    this.REST_DELETE = function (params, the_key) /* delete room */
        {
            _check_authorization(params, "DELETE");
            var room_key = params.filter.id;
            var sql = "UPDATE alg_ruimte"
                    + "   SET alg_ruimte_verwijder = SYSDATE"
                    + " WHERE alg_ruimte_key = " + room_key;

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

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

    if (room_key) // Niet bij initialisatie van model.
    {
        if (room_key > 0)
        {
            params.filter = params.filter || {};
            params.filter.id = room_key;
            if (! ("include" in params) )
                params.include = { include: ["custom_fields"]};

            var xxx_array = this.REST_GET(params);
            if (!xxx_array.length)
                shared.record_not_found();
            this.data = xxx_array[0];
        }
        else
        {
            _check_authorization (params, "POST")
        }
    }
}
%>