<% /*
    $Revision$
    $Id$

    File:           model_contracts.inc

    Description:    contract model.
    Parameters:
    Context:

    Notes:          Zonder filters worden de lopende actieve contracten opgeleverd (binnen scope)
                    TODO: 3D autorisatie, ook fe/eigen conracten vs CNTUSE/CNTMAN
*/
%>
<!-- #include file="../Shared/discx3d.inc" -->
<!-- #include file="../cnt/cnt.inc" -->
<!-- #include file="./model_tracking.inc"-->
<!-- #include file="./model_cnt_factuurschema.inc"-->
<%

model_contracts =
{
    module:       "CNT",
    table:        "cnt_contract",
    primary:      "cnt_contract_key",
    records_name: "contracts",
    record_name:  "contract",
    fields: {"id"           : { dbs: "cnt_contract_key",           typ: "key",                                                                            filter: "exact" },
             "name"         : { dbs: "cnt_contract_nummer_intern", typ: "varchar",                                                                        filter: "exact" },
             "description"  : { dbs: "cnt_contract_omschrijving",  typ: "varchar",                                                                        filter: "like" },
             "startdate"    : { dbs: "cnt_contract_looptijd_van",  typ: "date",                                    track: true, label: L("lcl_cnt_date_start"),        filter: "range" },
             "reminderdate" : { dbs: "cnt_contract_rappeldatum",   typ: "date",                                    track: true, label: L("lcl_cnt_rappel_date"),       filter: "range",
                                sql: "cnt.cnt_getRappeldatum(cnt_contract.cnt_contract_key)" },
             "canceldate"   : { dbs: "cnt_contract_opzegdatum",    typ: "date",                                    track: true, label: L("lcl_cnt_cancel_date"),       filter: "range",
                                sql: "cnt.cnt_getOpzegdatum(cnt_contract.cnt_contract_key)" },
             "enddate"      : { dbs: "cnt_contract_looptijd_tot",  typ: "date",                                    track: true, label: L("lcl_cnt_enddate"),           filter: "range" },
             "contractor"   : { dbs: "cnt_prs_bedrijf_key",        typ: "key",      foreign: "prs_bedrijf",        track: true, label: L("lcl_cnt_contractant"),       filter: "exact" },
             "person"       : { dbs: "cnt_prs_perslid_key",        typ: "key",      foreign: "prs_perslid",        track: true, label: L("lcl_cnt_name"),              filter: "exact" },
             "status"       : { dbs: "cnt_contract_status",        typ: "key",      foreign: cnt.getcntstatustext, track: true, label: L("lcl_status"),                filter: "exact" },
             "department"   : { dbs: "prs_afdeling_key_eig",       typ: "key",      foreign: "prs_afdeling",       track: true, label: L("lcl_cnt_owner"),             filter: "exact" },
             "service"      : { dbs: "prs_dienst_key",             typ: "key",      foreign: "prs_dienst",         track: true, label: L("lcl_prs_companies_dienst"),  filter: "exact" },
             "contracttype" : { dbs: "ins_discipline_key",         typ: "key",      foreign: "cnt_discipline",     track: true, label: L("lcl_cnt_srttype"),           filter: "exact" },
             // LET OP: De locatie (of gebouw, terrein of ruimte) kan naast de tabel cnt_contract_plaats ook via de tabellen cnt_contract_object of cnt_contract_onrgoed gekoppeld zijn.
             "location"     : { dbs: "cnt_contract_plaats.cnt_alg_plaats_key",
                                                                   typ: "key",      foreign: "alg_locatie",        track: true, label: L("lcl_location"),              filter: cnt.getLocationSql }
            },
    includes: {
                "tracking": {
                                  model: new model_tracking(['contract']),
                                  joinfield: "fac_tracking_refkey"
                            },
                "schedule": {
                                  model: new model_cnt_factuurschema(),
                                  joinfield: "cnt_contract_key"
                            }
              },

    REST_GET: function _GET(params)
        {
            var scope = params.filter.scope || "fe";
            var autfunction = { fe : "WEB_CNTUSE", fo : "WEB_CNTUSE", bo : "WEB_CNTMAN"} [scope];  /* gokje; fe hoefde vroeger geen rechten voor eigen contracten...*/
            params.authparams = user.checkAutorisation(autfunction, null, null, true); /* pessimistic */

            // Hier kom je niet meer terecht als bovenstaande autorisatiecheck niet tot succes leidt.

            var query = api2.sqlfields(params, model_contracts );
            query.wheres.push("cnt_contract_verwijder IS NULL");

            if (scope == "fe")
            {
                query.wheres.push("(prs_perslid_key_eig=" + user_key + " OR prs_perslid_key_beh=" + user_key + ")");
            }

            if (!params.filter.id)
            {
                if (!params.filter.status)
                {
                    /* Limitation: if no status filter, then default to the active statusses (0) */
                    query.wheres.push("cnt_contract_status = 0");
                }
                if (!(params.filter.startdate || params.filter.reminderdate || params.filter.canceldate || params.filter.enddate))
                {
                    /* Limitation: if no date filters, then default to the active contracts */
                    query.wheres.push("TRUNC(SYSDATE) BETWEEN cnt_contract_looptijd_van AND cnt_contract_looptijd_tot");
                }
            }

            query.tables.push("cnt_contract_plaats");
            query.wheres.push("cnt_contract.cnt_contract_key = cnt_contract_plaats.cnt_contract_key(+)");
            query.wheres.push("cnt_contract_plaats.cnt_contract_plaats_verwijder IS NULL");
            if (params.filter.location)
            {
              query.wheres.push("cnt_contract_plaats.cnt_alg_plaats_code IN ('L', 'G', 'T')");
              //query.wheres.push("cnt_contract_plaats.cnt_alg_plaats_key IN (" + params.filter.location + ")");
              //query.wheres.push("c.cnt_contract_key IN"
              //                + " (SELECT cnt_contract_key FROM cnt_v_aanwezigcontract_plaats"
              //                + "   WHERE (cnt_alg_plaats_code = 'L' AND cnt_alg_plaats_key IN (" + params.filter.location + "))");
            }

            // Ik zeg in deze versie: autorisatiescope op contractsoort (discipline) en nog maar ns niet op ALG of PRS. Akkoord?
            query.wheres.push("ins_discipline_key IN"
                            + " (SELECT ins_discipline_key FROM fac_v_webgebruiker"
                            + "   WHERE fac_functie_key = (SELECT fac_functie_key FROM fac_functie WHERE fac_functie_code=" + safe.quoted_sql(autfunction) + ")"
                            + "     AND prs_perslid_key=" + user_key + " AND (fac_gebruiker_prs_level_read<9 OR fac_gebruiker_alg_level_read<9))");

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

            var sql = "SELECT " + query.selects.join(", ")
                    + "  FROM " + query.tables.join(", ")
                    + " WHERE " + query.wheres.join(" AND " )
                    + " ORDER BY cnt_contract_key";
            if (query.orderbys.length)
                sql += ", " + query.orderbys.join(", ");

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

            return json;
        },
    _analyze_fields: function (dbfields, params, jsondata) /* analyseer inkomende data, common voor PUT en POST */
    {
    },
    _validate_fields: function (dbfields, params, jsondata) /* valideer dbfields, alle constraints die niet door de database worden afgevangen */
    {
    },

    xxREST_PUT: function (params, jsondata, the_key) /* update contract */
        {
        },
    xxREST_POST: function (params, jsondata) /* new contract */
        {
        },

    xxREST_DELETE: function (params, the_key) /* delete contract */
        {
        }
}
%>