<% /*
    $Revision$
    $Id$

    File:           model_reservationconsumables.inc

    Description:    reserveren delen model.
    Parameters:
    Context:

    Notes:
*/

%>
<!-- #include file="../Shared/discxalg3d.inc"-->
<%
function status_bo(json)
{
    var status_bo_key = json;
    var status_bo = res.getbostatustext(status_bo_key) || "";

    return status_bo;
}

function model_reservationconsumables()
{
    this.table = "res_rsv_artikel";
    this.primary = "res_rsv_artikel_key";
    this.records_name = "reservationconsumables";
    this.record_name = "reservationconsumable";

    this.fields = {
        "id"         : { dbs: "res_rsv_artikel_key",          typ: "key", seq:"res_s_res_rsv_artikel_key"},
        "reservation": { dbs: "res_rsv_ruimte_key",           typ: "key", foreign: "res_rsv_ruimte" },
        "consumable" : { dbs: "res_artikel_key",              typ: "key", foreign: "res_artikel" },
        "freename"   : { dbs: "res_rsv_artikel_omschrijving", typ: "varchar" },
        "amount"     : { dbs: "res_rsv_artikel_aantal",       typ: "number" },
        "status"     : { dbs: "res_status_bo_key",            typ: "key", foreign: status_bo },
        "from"       : { dbs: "res_rsv_artikel_levering",     typ: "datetime" },
        //"to"       : { dbs: "res_rsv_artikel_tot",          typ: "date"     },
        "price"      : { dbs: "res_rsv_artikel_prijs",        typ: "float",   "iscurrency": true },
        "processed"  : { dbs: "res_rsv_artikel_verwerkt",     typ: "datetime" },
        "closed"     : { dbs: "res_rsv_artikel_afgemeld",     typ: "datetime" },
        "changed"    : { dbs: "res_rsv_artikel_mutatie",      typ: "datetime" },
        "dirtlevel"  : { dbs: "res_rsv_artikel_dirtlevel",    typ: "number"   },
        "delivered"  : { dbs: "res_rsv_artikel_geleverd",     typ: "datetime" },
        "pickup"     : { dbs: "res_rsv_artikel_afhalen",      typ: "datetime" },
        "externnr"   : { dbs: "res_rsv_artikel_externnr",     typ: "varchar",       readonly: !(user.has("WEB_FACTAB") || user.has("WEB_FACXNR")) },
        "externsyncdate": { dbs: "res_rsv_artikel_externsyncdate", typ: "datetime", readonly: !(user.has("WEB_FACTAB") || user.has("WEB_FACXNR")) }
    };

    this.list = {
        columns: [
            "id",
            "from",
            "amount",
            "consumable",
            "price"
        ]
    };


    this._validate_fields = function (dbfields, params, jsondata)
    {
        var scope = params.filter.scope || "fe";
        this.autfunction = { fe : "WEB_RESUSE", fo : "WEB_RESFOF", bo : "WEB_RESBOF", mi : "WEB_RESBAC" } [scope];
        params.authparams = user.checkAutorisation(this.autfunction, null, null, true); // pessimistisch
    }

    this._check_dirty = function (rsv_ruimte_key, scope, this_res)
    {
        var check_fail_sql = "";
        var set_dirty_sql = "";
        if (!(S("res_fo_catering_scopeless") && (scope == "fo" || scope == "bo")))
        {   // Controle of artikelen dirty zijn.
            set_dirty_sql = " res.set_artikelen_dirty (" + rsv_ruimte_key + ");";
            if (S("res_fe_allow_dirty") != 1 && this_res.canChangeFEOnly)
            {
                check_fail_sql = " if res.dirty_level_all(" + rsv_ruimte_key + ") <> 0 then"
                               + "    raise_application_error (-20001, " + safe.quoted_sql(L("lcl_res_fe_no_dirty")) + ");"
                               + " end if;"
            }
        }
        var sql = "BEGIN "
                +   set_dirty_sql
                +   check_fail_sql
                + "END;";
        var err = Oracle.Execute(sql, true);
        if (err.friendlyMsg)
            abort_with_warning(err.friendlyMsg);
    }

    this.REST_GET = function _GET(params)
    {
        this._validate_fields({}, params, {});

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

        if (params.filter.id > 0)
        {
            var this_res = {canReadAny: false};
            var sql = "SELECT res_rsv_ruimte_key"
                    + "  FROM res_rsv_artikel"
                    + " WHERE res_rsv_artikel_key = " + params.filter.id;
            var oRs = Oracle.Execute(sql);
            if (!oRs.eof)
            {
                var rsv_ruimte_key = oRs("res_rsv_ruimte_key").Value;
                var this_res = res.func_enabled(rsv_ruimte_key);
            }
            oRs.Close();
            user.auth_required_or_abort(this_res.canReadAny);

            query.wheres.push("res_rsv_artikel_key = " + params.filter.id);
        }

        if (params.filter.api2 && params.filter.api2 != this.records_name)
        {
            query.wheres.push("res_rsv_artikel_verwijder IS NULL");

            query.tables.push("res_rsv_ruimte");
            query.wheres.push("res_rsv_ruimte.res_rsv_ruimte_key = res_rsv_artikel.res_rsv_ruimte_key");
            query.wheres.push(user_key + " IN (res_rsv_ruimte_host_key, res_rsv_ruimte_contact_key)"); // Altijd fe vooralnog
            query.wheres.push("res_rsv_ruimte_van BETWEEN SYSDATE - " + S("facilitiespast_res") + " AND SYSDATE + " + S("facilitiesfuture_res"));

            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 " ) : "")
                + " ORDER BY res_rsv_artikel_key";

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

        return json;
    };

    this.REST_POST = function (params, jsondata, parent_key)    /* new reservable consumable */
    {
        var rsv_ruimte_key = parent_key;
        var res_artikel_key = jsondata.consumable.id;
        var this_res = res.func_enabled(rsv_ruimte_key); // Wat heb ik zoal aan rechten op deze specifieke reservering
        this._validate_fields({}, params, jsondata);
        var sql = "SELECT ra.res_artikel_vrije_omschrijving"
                + "     , res_disc_params_bonotify"
                + "  FROM res_artikel ra"
                + "     , res_disc_params rdp"
                + " WHERE ra.res_discipline_key = rdp.res_ins_discipline_key"
                + "   AND ra.res_artikel_key = " + res_artikel_key;
        var oRs = Oracle.Execute(sql);
        var hasFreename = (oRs("res_artikel_vrije_omschrijving").Value == 1);
        var bonotify = oRs("res_disc_params_bonotify").Value == 1;
        oRs.Close();

        if (hasFreename)
        {
            var newFreename = sharedTrim(jsondata.freename || "");
            if (newFreename == "")
                abort_with_warning(L("lcl_res_rsv_art_name"));
        }
        else
        {   // Geen vrije omschrijving, deze dus veld leeg maken.
            delete jsondata.freename;
        }

        if (jsondata.amount == 0)
            abort_with_warning(L("lcl_res_rsv_art_count"));

        params.sqlOnly = true;
        var gen_result = generic_REST_POST(this)(params, jsondata);
        var rsv_artikel_key = gen_result.newKey;
        delete params.sqlOnly;

        // Controle of artikelen dirty zijn.
        var check_fail_sql = "";
        var set_dirty_sql = "";
        var set_noti_sql = "";
        if (!(S("res_fo_catering_scopeless") && (scope == "fo" || scope == "bo")))
        {   
            set_dirty_sql = " res.set_artikelen_dirty (" + rsv_ruimte_key + ");";
            if (S("res_fe_allow_dirty") != 1 && this_res.canChangeFEOnly)
            {
                check_fail_sql = " if res.dirty_level_all(" + rsv_ruimte_key + ") <> 0 then"
                               + "    raise_application_error (-20001, " + safe.quoted_sql(L("lcl_res_fe_no_dirty")) + ");"
                               + " end if;"
            }
        }
        if (bonotify)
            set_noti_sql = " res.notifybackoffice(" + rsv_ruimte_key + ", 'RESNEW', 'C', " + res_artikel_key + ");";
        var sql = "BEGIN "
                +   gen_result.genIns.sql + ";"
                +   set_dirty_sql
                +   check_fail_sql
                +   set_noti_sql
                + "END;";
        var err = Oracle.Execute(sql, true);
        if (err.friendlyMsg)
            abort_with_warning(err.friendlyMsg);

        // NB: parameter "track" in this.fields niet aanwezig, dus ook geen tracking!
        var trackarray = [res.trackartikel(res_artikel_key, "insert")];
        if (trackarray.length > 0 && !params.delayTracking)
            shared.trackaction("RESNEW", rsv_artikel_key, trackarray.join("\n"));

        params.isNew = false; // Voorkom dat een volgende reservationconsumable ook een insert wordt.
        return { key: rsv_artikel_key };
    }

    this.REST_PUT = function (params, jsondata, the_key) /* update reservable consumables */
    {
        var rsv_artikel_key = the_key;
        var scope = params.filter.scope || "fe";
        this._validate_fields({}, params, jsondata);

        var sql = "SELECT r.res_rsv_ruimte_key"
                + "  FROM res_rsv_ruimte r"
                + "     , res_rsv_artikel a"
                + " WHERE r.res_rsv_ruimte_key = a.res_rsv_ruimte_key"
                + "   AND a.res_rsv_artikel_key = " + rsv_artikel_key;
        var oRs = Oracle.Execute(sql);
        var rsv_ruimte_key = oRs("res_rsv_ruimte_key").value;
        oRs.Close();
        var this_res = res.func_enabled(rsv_ruimte_key); // Wat heb ik zoal aan rechten op deze specifieke reservering

        var sql = "SELECT ra.res_artikel_vrije_omschrijving"
                + "     , rra.res_rsv_artikel_omschrijving"
                + "  FROM res_artikel ra"
                + "     , res_rsv_artikel rra"
                + " WHERE ra.res_artikel_key = rra.res_artikel_key"
                + "   AND rra.res_rsv_artikel_key = " + rsv_artikel_key;
        var oRs = Oracle.Execute(sql);
        var hasFreename = (oRs("res_artikel_vrije_omschrijving").Value == 1);
        var curFreename = oRs("res_rsv_artikel_omschrijving").Value;
        oRs.Close();

        if (hasFreename)
        {
            if (jsondata.freename)
            {
                var newFreename = sharedTrim(jsondata.freename || "");
                if (newFreename == "")
                    abort_with_warning(L("lcl_res_rsv_art_name"));
            }
        }
        else
        {   // Geen vrije omschrijving, dus verwijderen als er toch wat staat.
            if (curFreename)
                jsondata.freename = "";
            else
                delete jsondata.freename;
        }

        if (jsondata.amount == 0)
            abort_with_warning(L("lcl_res_rsv_art_count"));

        params.sqlOnly = true;
        var gen_result = generic_REST_PUT(this)(params, jsondata, the_key);
        delete params.sqlOnly;
         // Controle of artikelen dirty zijn.
        var check_fail_sql = "";
        var set_dirty_sql = "";
        if (!(S("res_fo_catering_scopeless") && (scope == "fo" || scope == "bo")))
        {  
            set_dirty_sql = " res.set_artikelen_dirty (" + rsv_ruimte_key + ");";
            if (S("res_fe_allow_dirty") != 1 && this_res.canChangeFEOnly)
            {
                check_fail_sql = " if res.dirty_level_all(" + rsv_ruimte_key + ") <> 0 then"
                               + "    raise_application_error (-20001, " + safe.quoted_sql(L("lcl_res_fe_no_dirty")) + ");"
                               + " end if;"
            }
        }
        var sql = "BEGIN "
                +   gen_result.genUpd.sql + ";"
                +   set_dirty_sql
                +   check_fail_sql
                + "END;";
        var err = Oracle.Execute(sql, true);
        if (err.friendlyMsg)
            abort_with_warning(err.friendlyMsg);

        // NB: parameter "track" in this.fields niet aanwezig, dus ook geen tracking!
        var trackarray = gen_result.genUpd.trackarray;
        if (trackarray.length > 0 && !params.delayTracking)
            shared.trackaction("RESUPD", the_key, L("lcl_updated") + "\n" + trackarray.join("\n"));

        return { key: rsv_artikel_key };
    }

    this.REST_DELETE = function (params, the_key) /* delete reservable consumable */
    {
        this._validate_fields({}, params, {});
        return generic_REST_DELETE(this)(params, the_key);
    }
}
%>
