<% /*
    $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"-->
<!-- #include file="./model_bez_kenmerk.inc"-->
<%
function model_visitors()
{
    this.table = "bez_bezoekers";
    this.primary = "bez_bezoekers_key";
    this.records_name = "visitors"
    this.record_name = "visitor";
    this.autfunction = "WEB_BEZUSE"; // TODO!!
    this.multi_update = true;

    this.fields = {"id"         : { dbs: "bez_bezoekers_key",
                                    typ: "key",
                                    "seq": "bez_s_bez_bezoekers_key" },
                   "name"       : { dbs: "bez_afspraak_naam",    typ: "varchar",  label: L("lcl_vis_name"),      track: true},
                   "company"    : { dbs: "bez_afspraak_bedrijf", typ: "varchar",  label: L("lcl_vis_company"),   track: true},
                   "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")},
                   "phone"      : { dbs: "bez_bezoekers_telefoon",typ: "varchar", label: L("lcl_bez_telefoon"),   track: true},
                   "email"      : { dbs: "bez_bezoekers_email",   typ: "varchar", label: L("lcl_bez_email")},
                   "licenseplate": { dbs: "bez_bezoekers_kenteken",typ: "varchar", label: L("lcl_bez_kenteken"),  track: true},
                   "appointment": { dbs: "bez_afspraak_key",     typ: "key",      foreign: "bez_afspraak", "insertonly": true },
                   // Parkeerplaatsen is een ietwat bijzonder veld....
                   "parking"    : { dbs: "bez_parking_dummy",
                                    sql: "(SELECT MIN(res_rsv_deel_key)"
                                       + "  FROM res_rsv_deel rrd"
                                       + "  WHERE rrd.bez_bezoekers_key = bez_bezoekers.bez_bezoekers_key)",
                                    typ: "key",
                                    foreign: { tbl: "(SELECT res_rsv_deel_key, res_deel_omschrijving"
                                                  + "  FROM res_deel rd, res_rsv_deel rrd"
                                                  + "  WHERE rd.res_deel_key = rrd.res_deel_key)",
                                               key: "res_rsv_deel_key",
                                               desc: "res_deel_omschrijving"
                                             }
                                  },
                   "arrived"    : { dbs: "bez_bezoekers_done_actual",       typ: "datetime", label: L("lcl_bez_done_actual_date")},
                   "departed"   : { dbs: "bez_bezoekers_out_actual",        typ: "datetime", label: L("lcl_bez_out_actual_date")},
                   "externnr"   : { dbs: "bez_bezoekers_externnr",          typ: "varchar",  label: L("extern_nr"),       readonly: !(user.has("WEB_FACTAB") || user.has("WEB_FACXNR")) },
                   "externsyncdate": { dbs: "bez_bezoekers_externsyncdate", typ: "datetime", label: L("extern_syncdate"), readonly: !(user.has("WEB_FACTAB") || user.has("WEB_FACXNR")) }
                  };

    this.includes= {
                    "custom_fields" : {
                        "model": new model_custom_fields(this, new model_bez_kenmerk({ internal: true }), { readman: true, readuse: true }),
                        "joinfield": "flexparentkey",
                        "enable_update": true
                    }
                   }

    this.list = { columns: ["name", "company", "in", "out"] };

    this.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, this );

            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, this);
            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.bez_afspraak_key, bez_bezoekers.bez_bezoekers_key";
            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 visitors */
    {
        var scope = params.filter.scope || "fe";
        this.autfunction = { fe : "WEB_BEZUSE", fo : "WEB_BEZFOF", bo : "WEB_BEZBOF", mi : "WEB_RESBAC" } [scope];
        // TODO: Tracking?
        if ("parking" in jsondata) // TODO herclaimen bij gewijzigde tijden of locatie!
        {                          // Vooralsnog verantwoordelijkheid bij API-bouwer
          var olddata = api2.GET(this, the_key);
          if (olddata && olddata.parking)
          {
            if (!jsondata.parking) // oude weg
            {
                var sql = "DELETE FROM res_rsv_deel WHERE bez_bezoekers_key = " + the_key;
                Oracle.Execute(sql);
            }
          }
          else
          {
              if (jsondata.parking)
              {
                var gebouwterreinkey = "NULL"; // We ondersteunen nog geen expliciete gebouwkeuze
                var prkgebter = bez.onlyGebouw(olddata.appointment.id);
                var gebouwterreinkey = prkgebter > 0? prkgebter: "null"; // de enige goede

                var sql = "BEGIN bez.claim_parking(" + the_key + ", " + gebouwterreinkey + "); END;"
                Oracle.Execute(sql);
              }
          }
        }
        // prepare for detection of set bez_bezoekers_done
        var olddone = null;
        var bezoeker = "";
        if ("in" in jsondata)
        {
            var oRs = Oracle.Execute("SELECT bez_bezoekers_done, bez_afspraak_naam"
                            + "  FROM bez_bezoekers"
                            + " WHERE bez_bezoekers_key = " + the_key);
            olddone = oRs("bez_bezoekers_done").Value;
            bezoeker = oRs("bez_afspraak_naam").Value;
            oRs.Close();
        }

        var result = generic_REST_PUT(this)(params, jsondata, the_key);
        // send BEZDON when visitor is in
        if ("in" in jsondata && !!jsondata["in"] && !olddone) // "in" is a reserved word as well as a database field!!!
        {
            shared.trackaction("BEZDON", the_key, L("lcl_bez_is_in_1") + bezoeker + L("lcl_bez_is_in_2") ); // checkin
        }

        // Klantspecifieke check functie (hookfunction) voor de invoer
        var pResult = new HookResult();
        if (!custfunc.bez_postsave([result.key], pResult))
        {
            abort_with_warning(pResult.errmsg);
        }

        return result;
    }

    this.REST_POST = function (params, jsondata, parent_key)
    {
        var result = generic_REST_POST(this)(params, jsondata, parent_key); /* new visitors */
        if (jsondata.parking)
        {
           var gebouwterreinkey = "NULL"; // We ondersteunen nog geen expliciete gebouwkeuze
           var prkgebter = bez.onlyGebouw(parent_key); // parent_key is de afspraak_key
           var gebouwterreinkey = prkgebter > 0? prkgebter: "null"; // de enige goede

          var sql = "BEGIN bez.claim_parking(" + result.key + ", " + gebouwterreinkey + "); END;"
          Oracle.Execute(sql);
        }

        // Klantspecifieke check functie (hookfunction) voor de invoer
        var pResult = new HookResult();
        if (!custfunc.bez_postsave([result.key], pResult))
        {
            abort_with_warning(pResult.errmsg);
        }

        return result;
    }

    this.REST_DELETE = function (params, the_key) /* delete visitors */
    {
        var scope = params.filter.scope || "fe";
        this.autfunction = { fe : "WEB_BEZUSE", fo : "WEB_BEZFOF", bo : "WEB_BEZBOF", mi : "WEB_RESBAC" } [scope];
        var autparams = user.checkAutorisation(this.autfunction);
        user.auth_required_or_abort(autparams.PRSwritelevel < 9 && autparams.ALGwritelevel < 9);
    
        var pResult = new HookResult();

        if (!custfunc.bez_predelete(the_key, pResult))
        {
            abort_with_warning(pResult.errmsg);
        }

        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); // Parkeerplaats (res_rsv_deel) cascadeert wel mee

        if (!custfunc.bez_postdelete(the_key, pResult))
        {
            abort_with_warning(pResult.errmsg);
        }
    }


}
%>