<% /*
    $Revision$
    $Id$

    File:           model_bgt_budget.inc

    Description:    Model voor bgt_budget

    Context:

    Notes:
*/
%>
<!-- #include file="../bgt/bgt_tools.inc" -->
<!-- #include file="../api2/model_bgt_budgetmutatie.inc" -->
<%
var v_checkauth = getQParamInt("id", 0) > 0;

function model_bgt_budget()
{
    this.records_name = "budgets";
    this.record_name = "budget";
    this.table = "bgt_budget";
    this.primary = "bgt_budget_key";
    this.autfunction = "WEB_BGTUSE";
    this.record_title = L("bgt_budget");
    this.records_title = L("bgt_budget_m");

    this.fields = {
        "id": {
            "dbs": "bgt_budget_key",
            "label": L("lcl_key"),
            "typ": "key",
            "hidden_fld": true,
            "required": true,
            "seq": "bgt_s_bgt_budget_key"
        },
        "budgetdiscipline": {
            "dbs": "ins_discipline_key",
            "label": L("bgt_discipline_omschrijving"),
            "typ": "key",
            "required": true,
            "insertonly": true,
            "foreign": bgt_budgetdiscipline_foreign(v_checkauth),
            "showtransit": true
        },
        "budgetproject": {
            "dbs": "bgt_project_key",
            "label": L("bgt_project_omschrijving"),
            "typ": "key",
            "required": true,
            "insertonly": true,
            "foreign": bgt_budgetproject_foreign(),
            "delayload": true,
            "showtransit": true
        },
        "budgetcostcategory": {
            "dbs": "bgt_kostenrubriek_key",
            "label": L("bgt_kostenrubriek_oms"),
            "typ": "key",
            "required": true,
            "insertonly": true,
            "foreign": bgt_budgetcostcategory_foreign(),
            "delayload": true,
            "showtransit": true
        },
        "costtypegroup": {
            "dbs": "prs_kostensoortgrp_key",
            "label": L("prs_kostensoortgrp_key"),
            "typ": "key",
            "required": false,
            "insertonly": true,
            "foreign": bgt_costtypegroup_foreign(),
            "delayload": true,
            "showtransit": true,
            "LOVinit": ""
        },
        "costtype": {
            "dbs": "prs_kostensoort_key",
            "label": L("prs_kostensoort_key"),
            "typ": "key",
            "required": false,
            "insertonly": true,
            "foreign": bgt_costtype_foreign(),
            "delayload": true,
            "showtransit": true
        },
        "amountoriginal": {
            "dbs": "bgt_budget_bedrag_origineel",
            "sql": "(BGT.getBudgetOpDatum(bgt_budget.bgt_budget_key, 0, NULL))",
            "label": L("bgt_budget_origineel"),
            "typ": "float",
            "iscurrency": true,
            "total": true
        },
        "vatoriginal": {
            "dbs": "bgt_budget_btwbedrag_origineel",
            "sql": "(BGT.getBudgetOpDatum(bgt_budget.bgt_budget_key, 1, NULL))",
            "label": L("bgt_budget_origineel")+" "+L("lcl_fin_btwtabelwaarde_oms"),
            "typ": "float",
            "iscurrency": true,
            "total": true
        },
        "amountmutation": {
            "dbs": "bgt_budget_bedrag_mutatie",
            "sql": "(BGT.getBudgetSoortMutatie(CASE WHEN bgt_budget.prs_kostensoort_key IS NULL THEN bgt_budget.bgt_kostenrubriek_key ELSE -1 END"
                                          + " , -1"
                                          + " ,CASE WHEN bgt_budget.prs_kostensoort_key IS NULL THEN -1 ELSE bgt_budget.prs_kostensoort_key END"
                                          + " , 0, 'EM', NULL))",
            "label": L("bgt_budget_mutaties"),
            "typ": "float",
            "iscurrency": true,
            "total": true
        },
        "amountreservation": {
            "dbs": "bgt_budget_bedrag_reserve",
            "sql": "(BGT.getBudgetSoortMutatie(CASE WHEN bgt_budget.prs_kostensoort_key IS NULL THEN bgt_budget.bgt_kostenrubriek_key ELSE -1 END"
                                          + " , -1"
                                          + " ,CASE WHEN bgt_budget.prs_kostensoort_key IS NULL THEN -1 ELSE bgt_budget.prs_kostensoort_key END"
                                          + ", 0, 'ARW', NULL))",
            "label": L("bgt_budget_vnreserve"),
            "typ": "float",
            "iscurrency": true,
            "total": true
        },
        "amount": {
            "dbs": "bgt_budget_bedrag",
            "label": L("bgt_budget_bedrag"),
            "typ": "float",
            "iscurrency": true,
            "total": true,
            "defaultvalue": 0
            },
        "vat": {
            "dbs": "bgt_budget_btwbedrag",
            "label": L("bgt_budget_btwbedrag"),
            "typ": "float",
            "iscurrency": true,
            "total": true,
            "defaultvalue": 0
            },
        "amountincl": {
            "dbs": "bgt_budget_bedrag_incl",
            "sql": "bgt_budget_bedrag + bgt_budget_btwbedrag",
            "label": L("lcl_fin_total_sum"),
            "typ": "float",
            "readonly": true,
            "sqlshow": true,
            "iscurrency": true,
            "total": true,
            "defaultvalue": "0",
            "clone": false
        },
        "contingency": {
          "dbs": "bgt_budget_isreserve",
          "label": L("bgt_budget_isreserve"),
          "typ": "check0",
          "defaultvalue": 0
        },
        "account": {
            "dbs": "prs_kostenplaats_key",
            "label": L("bgt_budget_account"),
            "typ": "key",
            "foreign": bgt_account_foreign()
        },
        "begin": {
            "dbs": "bgt_budget_begin",
            "label": L("bgt_budget_begin"),
            "typ": "date",
            "required": false
            },
        "end": {
            "dbs": "bgt_budget_eind",
            "label": L("bgt_budget_eind"),
            "typ": "date",
            "required": false
            },
        "costgroup": {
            "dbs": "prs_kostenplaatsgrp_key",
            "label": L("bgt_budget_accountgrp"),
            "typ": "key",
            "foreign": {
                "tbl": "prs_kostenplaatsgrp",
                "key": "prs_kostenplaatsgrp_key",
                "desc": "prs_kostenplaatsgrp_oms"
            },
            "hidden_fld": true
        }
    };

    this.edit = {
//        "modal": true
    };

    this.list = {
        "columns": [
            "budgetcostcategory",
            "costtypegroup",
            "costtype",
            "amount",
            "vat"
        ]
    };


    this.hook_pre_edit = function (obj, fld)
    {
        var btw_data = {};
        if (obj.id > -1)
        {
            var sql = "SELECT s.prs_kostensoort_btw"
                    + "     , f.fin_btwtabelwaarde_perc"
                    + "  FROM bgt_budget b"
                    + "     , prs_kostensoort s"
                    + "     , fin_btwtabelwaarde f"
                    + " WHERE s.fin_btwtabelwaarde_key = f.fin_btwtabelwaarde_key"
                    + "   AND b.prs_kostensoort_key = s.prs_kostensoort_key"
                    + "   AND b.bgt_budget_key = " + obj.id;
            var oRs = Oracle.Execute(sql);
            if (!oRs.eof)
            {
                btw_data.btw_inc = oRs("prs_kostensoort_btw").Value;
                btw_data.btw_val = oRs("fin_btwtabelwaarde_perc").Value;
            }
            oRs.Close();
        }
        else
        {
            // Een nieuw budget heeft nog geen origineel- en mutatie-bedrag.
            delete fld.amountoriginal;
            delete fld.amountmutation;
        }
        %>
        <script>
            var cur_mode = "budget_edit"; // Laat alleen de kostensoorten zien waaraan nog geen budget gekoppeld is.
            var btw_data = <%=JSON.stringify(btw_data)%>;
            var budgetdiscipline_key = <%=(obj.budgetdiscipline ? obj.budgetdiscipline.id : -1)%>;
            var budgetproject_key    = <%=(obj.budgetproject    ? obj.budgetproject.id    : -1)%>;
        </script>
        <%
    }

    this.hook_pre_post = function(params, obj)
    {
        // Wordt alleen gebruikt bij toevoegen.
    }


    this.hook_pre_put = function(params, obj, key)
    {   // Zoek bij wijzigen van kostenplaats de kostenplaatsgrp_key op
        // Om te voorkomen dat de defaultwaarde voor isreserve wordt ingevuld
        // (de checkbox is readonly gemaakt voor bestaande record), hier de juiste waarde erin zetten.
        var sql = "SELECT bgt_budget_isreserve"
                + "  FROM bgt_budget"
                + " WHERE bgt_budget_key = " + key;
        var oRs = Oracle.Execute(sql);
        obj.contingency = oRs("bgt_budget_isreserve").Value;
        oRs.Close();
    }

    this.hook_pre_delete = function(params, key)
    {
        var ismulti = getQParamInt("multi",0) == 1;
        var key_arr = [];
        if (ismulti)
            key_arr = getFParamIntArray("id");
        else
            key_arr.push(key);

        var sql_c = "SELECT COUNT(*) aantal"
                  + "  FROM mld_opdr"
                  + " WHERE prs_kostensoort_key IN"
                  + " (SELECT prs_kostensoort_key"
                  + "    FROM bgt_budget"
                  + "   WHERE bgt_budget_key IN (" + key_arr.join(",") + ")"
                  + " )";
        var oRs_c = Oracle.Execute(sql_c);
        var nr_mld_opdr = oRs_c("aantal").Value;
        oRs_c.Close();
        if (nr_mld_opdr > 0)
        {
            abort_with_warning(L("bgt_budget_delete_val1").format(L("lcl_fin_contracten"))); // De geselecteerde budgetten hebben contracten. Verwijder deze eerst.
        }

        var sql_m = "SELECT COUNT(*) aantal"
                  + "  FROM bgt_budgetmutatie"
                  + " WHERE bgt_budget_key_naar IN (" + key_arr.join(",") + ")"
                  + "    OR bgt_budget_key_van  IN (" + key_arr.join(",") + ")";
        var oRs_m = Oracle.Execute(sql_m);
        var nr_mutatie = oRs_m("aantal").Value;
        oRs_m.Close();
        if (nr_mutatie > 0)
        {
            abort_with_warning(L("bgt_budget_delete_val1").format(L("bgt_budget_mutaties"))); // De geselecteerde budgetten hebben mutaties. Verwijder deze eerst.
        }
        // Er zijn geen contracten of budgetmutaties bij de geselecteerde budget(ten) bekend.
        // Verwijderen is geen probleem meer.
    }

    var gparams = {
        "GET": {
            "tables": ["bgt_project"],
            "wheres": [ "bgt_budget.bgt_project_key = bgt_project.bgt_project_key"
                      , "bgt_project.bgt_project_verwijder IS NULL"
                      ]
        }};
    var v_budgetdiscipline = getQParamInt("budgetdiscipline", -1);
    if (v_budgetdiscipline == -1)
    {
        gparams.GET.wheres.push("bgt_budget.ins_discipline_key IN"
                              + " (SELECT w.ins_discipline_key"
                              + "    FROM fac_v_webgebruiker w"
                              + "       , ins_tab_discipline d"
                              + "   WHERE w.ins_discipline_key = d.ins_discipline_key"
                              + "     AND w.prs_perslid_key = " + user_key
                              + "     AND (w.fac_gebruiker_prs_level_read<9 OR w.fac_gebruiker_alg_level_read<9)"
                              + "     AND d.ins_discipline_module = 'BGT'"
                              + "     AND d.ins_discipline_verwijder IS NULL"
                              + " )"
                               );
    }
    this.REST_GET = generic_REST_GET(this, gparams);

    this.REST_PUT = generic_REST_PUT(this);
    var autparams = user.checkAutorisation(this.autfunction);
    var canWrite = (autparams.PRSwritelevel < 9 && autparams.ALGwritelevel < 9);
    if (canWrite)
    {
        this.REST_POST   = generic_REST_POST(this);
        this.REST_DELETE = generic_REST_DELETE(this);
    }
}
%>