<% /*
    $Revision$
    $Id$

    File:           model_visitors.inc

    Description:    Bezoekers model.
    Parameters:
    Context:

    Notes:
*/

%>
<!-- #include file="../Shared/discxalg3d.inc"-->
<!-- #include file="../bez/bez.inc" -->
<!-- #include file="./model_custom_fields.inc"-->
<%
model_visitors =
{
    table: "bez_bezoekers",
    primary: "bez_bezoekers_key",
    records_name: "visitors",
    record_name: "visitor",

    fields: {"id"         : { dbs: "bez_bezoekers_key",    typ: "key",      filter: "exact" },
             "name"       : { dbs: "bez_afspraak_naam",    typ: "varchar",  label: L("lcl_vis_name")},
             "company"    : { dbs: "bez_afspraak_bedrijf", typ: "varchar",  label: L("lcl_vis_company")},
             "badge"      : { dbs: "bez_bezoekers_pasnr",  typ: "varchar",  label: L("lcl_vis_badgenr")},
             "in"         : { dbs: "bez_bezoekers_done",   typ: "datetime", label: L("lcl_bez_done_date")},
             "out"        : { dbs: "bez_bezoekers_out",    typ: "datetime", label: L("lcl_bez_out_date")},
             "appointment": { dbs: "bez_afspraak_key",     typ: "key",      xforeign: "bez_afspraak"}
            },

    includes: {
                "custom_fields" : {
                    "model": new model_custom_fields(this, "BEZ", { readman: true, readuse: true }),
                    "joinfield": "flexparentkey"
                }
    },

    list: { columns: ["name", "company", "in", "out"] },

    REST_GET: function _GET(params)
        {
            var scope = params.filter.scope || "fe";
            var autfunction = { fe : "WEB_BEZUSE", fo : "WEB_BEZFOF", bo : "WEB_BEZBOF", mi : "WEB_RESBAC" } [scope];
            params.authparams = user.checkAutorisation(autfunction, null, null, true); // pessimistisch

            var query = api2.sqlfields(params, model_visitors );

            if (params.filter.id)
            {
                var sql = "SELECT bez_afspraak_key "
                        + "  FROM bez_bezoekers"
                        + " WHERE bez_bezoekers_key = " + params.filter.id;
                var oRs = Oracle.Execute(sql);
                if (oRs.Eof)
                {
                    oRs.Close()
                    return [];
                }
                params.filter.appointment = oRs("bez_afspraak_key").Value;
                oRs.Close()
            }
            if (params.filter.appointment)
            {
                var afspr_key = parseInt(params.filter.appointment, 10);
                if (isNaN(afspr_key))
                    return [];
                var this_bez = bez.func_enabled_afspraak(afspr_key);
                user.auth_required_or_abort(this_bez.canReadAny);
            }
            else if (scope == "fe")
            {
                query.wheres.push("(bez_afspraak_contact_key = " + user_key
                                + "     OR bez_afspraak_host_key = " + user_key + ")");
                query.wheres.push("bez_afspraak_datum BETWEEN SYSDATE - " + S("facilitiespast_bez") + " AND SYSDATE + " + S("facilitiesfuture_bez"));
            }
            else // TODO: Add authorization
            {
                if (!params.filter.start_from && !params.filter.end_from && !params.filter.start_to && !params.filter.end_to)
                    query.wheres.push("bez_afspraak_datum >= TRUNC(SYSDATE)"); // afspraken van vandaag en komende dagen!
            }

            query.tables.push("bez_afspraak");
            query.wheres.push("bez_afspraak.bez_afspraak_key = bez_bezoekers.bez_afspraak_key");

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

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

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

            return json;
        },
    REST_PUT: function (params, jsondata, the_key) /* update visitors */
        {
            var dbfields = api2.update_fields(params, model_visitors, jsondata); // Build updater

            // bezUpd heeft na afloop eventueel oldjsvals
            var bezUpd = buildTrackingUpdate("bez_bezoekers", " bez_bezoekers_key = " + the_key, dbfields, { noValidateToken: true });
            Oracle.Execute(bezUpd.sql);

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

            //var result = saveBezoekers(afspr_key, -1, { urole: urole, loctimechanged: changed });
            //if (result.beztrack && result.beztrack.length > 0)
            //bezUpd.trackarray.push(result.beztrack.join("\n"));

            return { key: the_key };
        },
    REST_POST: function (params, jsondata, parent_key) /* new visitors */
        {
            var dbfields = api2.update_fields(params, model_visitors, jsondata); // Build updater
            dbfields["id"] = { dbs: "bez_bezoekers_key",        typ: "key",     seq: "bez_s_bez_bezoekers_key" };
            dbfields["afspraak"] = { dbs: "bez_afspraak_key",         typ: "key",     val: parent_key };

            var bezIns = buildInsert("bez_bezoekers", dbfields, { noValidateToken: true });
            var bez_key = bezIns.sequences["bez_bezoekers_key"];
            Oracle.Execute(bezIns.sql);
            //var bezUpd = {trackarray: [L("lcl_bez_is_bezadd") + ": " + beznaam + "/" + bed]};
            // TODO: Wat teruggeven?
            return { key: bez_key };
        },
    REST_DELETE: function (params, the_key) /* delete visitors */
    {
        var wheres = [" bez_bezoekers_key = " + the_key];
        // TODO: Autorisatie
        //wheres.push("(bez_afspraak_contact_key = " + user_key // Altijd fe vooralnog
        //                   + "     OR bez_afspraak_host_key = " + user_key + ")");
        var sql = "DELETE FROM bez_bezoekers"
                + " WHERE " + wheres.join(" AND " );

        Oracle.Execute(sql);
    }
}
%>