<% /*
    $Revision$
    $Id$

    File:           model_persons.inc

    Description:    Perslid model.
    Parameters:
    Context:

    - Notes:        - Standaard voegen we de gegevens van de hoofdwerkplek toe
                    - Ooit doen we er nog een include bij van alle werkplekken.

*/

%>
<!-- #include file="../Shared/discxalg3d.inc"-->
<!-- #include file="../api2/model_custom_fields.inc"-->
<!-- #include file="../api2/model_fac_tracking.inc"-->
<!-- #include file="../api2/model_fac_gebruikersgroep.inc" -->
<!-- #include file="./model_prs_kenmerk.inc"-->
<%

function genderLOV()
{
    var s = ";"   + L("lcl_prs_person_geslachtO")
          + ";0;" + L("lcl_prs_person_geslachtV")
          + ";1;" + L("lcl_prs_person_geslachtM")
          + ";9;" + L("lcl_prs_person_geslachtX");
    return s;
}

function model_prs_perslid(params)
{
    params = params || {};
    this.records_name = "persons";
    this.record_name = "person";
    this.table = "prs_perslid";
    this.trackcode = "PRSUPD";
    this.audit = { // Parameters voor fac_audit.
        "childtable": "fac_gebruikersgroep",
        "childaudit": {"sql":   "SELECT fac_audit_tabelkey"
                              + "  FROM fac_audit"
                              + " WHERE fac_audit_tabelnaam = 'fac_gebruikersgroep'"
                              + "   AND fac_audit_veldnaam = 'prs_perslid_key'"
                              + "   AND fac_audit_waarde_oud IN ('{1}')"
        }
    };
    this.soft_delete = "prs_perslid_verwijder";
    this.primary = "prs_perslid_key";
    this.record_title = L("prs_perslid");
    this.records_title = L("prs_perslid_m");
    this.autfunction = params.internal?false:"WEB_PRSSYS"; // we controleren zelf

    if ((typeof mode != "undefined") && (params.extra_auth.length > 0))
    {
        this.autfunction = [this.autfunction].concat(params.extra_auth);
    }

    this.fields = {
        "id": {
            "dbs": "prs_perslid_key",
            "label": L("lcl_key"),
            "typ": "key",
            "seq": "prs_s_prs_alluitvoerende_keys"
        },
        "name": {
            "dbs": "pf.prs_perslid_naam_friendly",
            "dbsa": "(SELECT pf.prs_perslid_naam_friendly FROM prs_v_perslid_fullnames_all pf WHERE pf.prs_perslid_key = x.prs_perslid_key)",
            "label": L("lcl_prs_person_name"),
            "typ": "varchar"
        },
        "lastname": {
            "dbs": "prs_perslid_naam",
            "label": L("lcl_prs_person_achternaam"),
            "typ": "varchar",
            "filter": "like"
        },
        "firstname": {
            "dbs": "prs_perslid_voornaam",
            "label": L("lcl_prs_person_voornaam"),
            "typ": "varchar",
            "filter": "like"
        },
        "title": {
            "dbs": "prs_perslid_titel",
            "label": L("lcl_prs_person_title"),
            "typ": "varchar"
        },
        "employeenumber": {
            "dbs": "prs_perslid_nr",
            "label": L("lcl_prs_person_nr"),
            "typ": "varchar",
            "filter": "exact",
            "caseinsensitive": true
        },
        "initials": {
            "dbs": "prs_perslid_voorletters",
            "label": L("lcl_prs_person_initials"),
            "typ": "varchar"
        },
        "middlename": {
            "dbs": "prs_perslid_tussenvoegsel",
            "label": L("lcl_prs_person_tussen"),
            "typ": "varchar"
        },
        "gender": {
            "dbs": "prs_perslid_geslacht",
            "label": L("lcl_prs_person_geslacht"),
            "typ": "number",
            "LOV": genderLOV()
        },
        "language": {
            "dbs": "prs_perslid_lang",
            "label": L("lcl_lcl_taal"),
            "typ": "varchar"
        },
        "phone": {
            "dbs": "prs_perslid_telefoonnr",
            "label": L("lcl_prs_person_phone"),
            "typ": "varchar"
        },
        "mobile": {
            "dbs": "prs_perslid_mobiel",
            "label": L("lcl_prs_person_mobile"),
            "typ": "varchar"
        },
        "email": {
            "dbs": "prs_perslid_email",
            "label": L("lcl_prs_person_email"),
            "typ": "varchar",
            "caseinsensitive": true
        },
        "login": {
            "dbs": "prs_perslid_oslogin",
            "label": L("lcl_prs_person_login"),
            "typ": "varchar",
            "len": 256,
            "filter": "exact",
            "caseinsensitive": true,
            "hasupper": "prs_perslid_oslogin"
        },
        "lastlogin": {
            "dbs": "prs_perslid_login",
            "label": L("lcl_prs_person_lastlogin"),
            "typ": "date",
            "readonly": true
        },
        "externallogin": { // SCIM only. Identiek aan prs_perslid_oslogin maar dan niet uppercased of afgekapt
            "dbs": "prs_perslid_externoslogin",
            "label": L("prs_perslid_externoslogin"),
            "typ": "varchar",
            "len": 256,
            "filter": "exact",
            "caseinsensitive": true
        },
        "employment": {
            "dbs": "prs_perslid_dienstverband",
            "label": L("lcl_prs_person_dienstverband"),
            "typ": "float"
        },
        "startdate": {
            "dbs": "prs_perslid_ingangsdatum",
            "label": L("lcl_prs_person_ingangsdatum"),
            "typ": "date"
        },
        "enddate": {
            "dbs": "prs_perslid_einddatum",
            "label": L("lcl_prs_person_einddatum"),
            "typ": "date"
        },
        "created": {
            "dbs": "prs_perslid_aanmaak",
            "label": L("prs_perslid_aanmaak"),
            "typ": "datetime",
            "readonly": true
        },
        "deactivated": {
            "dbs": "prs_perslid_inactief",
            "label": L("prs_perslid_inactief"),
            "typ": "datetime"
        },
        "function": {
            "dbs": "prs_srtperslid_key",
            "label": L("lcl_prs_person_function"),
            "typ": "key",
            "foreign": {
                "tbl": "prs_srtperslid",
                "key": "prs_srtperslid_key",
                "desc": "prs_srtperslid_omschrijving",
                "desc_is_unique": "prs_srtperslid_verwijder IS NULL"
            }
        },
        "profile": {
            "dbs": "fac_profiel_key",
            "label": L("fac_profiel"),
            "typ": "key",
            "foreign": {
                "tbl": "fac_profiel",
                "key": "fac_profiel_key",
                "desc": "fac_profiel_omschrijving",
                "desc_is_unique": true // wordt overigens niet afgedwongen
            }
        },
        "department": {
            "dbs": "prs_afdeling_key",
            "label": L("lcl_prs_organisatie"),
            "typ": "key",
            "foreign": "prs_afdeling"
        },
        "costcentre": {
            "dbs": "prs_kostenplaats_key",
            "label": L("prs_kostenplaats"),
            "typ": "key",
            "foreign": "prs_kostenplaats"
        },
        "externalid": {
            "dbs": "prs_perslid_externid",
            "label": L("prs_perslid_externid"),
            "typ": "varchar",
            "filter": "exact"
        },
        "externsyncdate": {
            "dbs": "prs_perslid_externsyncdate",
            "label": L("prs_perslid_externsyncdate"),
            "typ": "datetime",
            "readonly": params.internal || !(user.has("WEB_FACTAB") || user.has("WEB_FACXNR"))
        },
        "visibility": {
            "dbs": "prs_perslid_visibility",
            "label": L("lcl_prs_person_visibility"),
            "typ": "number"
        },
        "company": {
            "dbs": "pa.prs_bedrijf_key",
            "label": L("lcl_prs_company"),
            "typ": "key",
            "foreign": "prs_bedrijf"
        },
        "location": {
            "dbs": "wg.alg_locatie_key",
            "label": L("lcl_location"),
            "typ": "key",
            "foreign": {
                "tbl": "alg_locatie",
                "key": "alg_locatie_key",
                "desc": "alg_locatie_omschrijving"
            },
            "nosearch": true
        },
        "building": {
            "dbs": "wg.alg_gebouw_key",
            "label": L("lcl_building"),
            "typ": "key",
            "foreign": {
                "tbl": "alg_gebouw",
                "key": "alg_gebouw_key",
                "desc": "alg_gebouw_code"
            },
            "nosearch": true
        },
        "floor": {
            "dbs": "wg.alg_verdieping_key",
            "label": L("lcl_floor"),
            "typ": "key",
            "foreign": {
                "tbl": "alg_verdieping",
                "key": "alg_verdieping_key",
                "desc": "alg_verdieping_code"
            },
            "nosearch": true
        },
        "room": {
            "dbs": "wg.alg_ruimte_key",
            "label": L("lcl_room"),
            "typ": "key",
            "foreign": {
                "tbl": "alg_ruimte",
                "key": "alg_ruimte_key",
                "desc": "alg_ruimte_nr"
            },
            "nosearch": true
        }
    };

    this.includes = {
        "authorization": {
            "model": new model_fac_gebruikersgroep(params),
            "label": L("fac_groep_m"),
            "joinfield": "person",
            "enable_update": true,
            "multiadd": "authorizationgroup"
        },
        "custom_fields" : {
            "model": new model_custom_fields(this, new model_prs_kenmerk("P", { internal: true }), { readman: true, readuse: true, pNiveau: "P" }),
            "joinfield": "flexparentkey",
            "enable_update": true,
            "no_autowrap": true
        },
        "tracking": {
            "model": new model_tracking(["perslid"]),
            "joinfield": "trackingrefkey"
        }
    };

    this.REST_GET = function _GET(params)
        {
            var query = api2.sqlfields(params, this);
            query.tables.push("prs_v_perslid_fullnames_all  pf");
            query.wheres.push("pf.prs_perslid_key(+) = prs_perslid.prs_perslid_key");
            query.tables.push("prs_v_werkplek_gegevens  wg");
            query.tables.push("prs_v_afdeling  pa");
            query.wheres.push("pa.prs_afdeling_key = prs_perslid.prs_afdeling_key");
            query.tables.push("prs_v_hoofdperslidwerkplek2 pw");
            query.wheres.push("pw.prs_perslid_key(+) = prs_perslid.prs_perslid_key");
            query.wheres.push("pw.prs_werkplek_key = wg.prs_werkplek_key(+)");

            var hasPRSSYS = user.has("WEB_PRSSYS");
            query.wheres.push("prs_perslid.prs_perslid_verwijder IS NULL");
            var authparamsUSE = user.checkAutorisation("WEB_PRSUSE", true);
            if (hasPRSSYS)
            {
                /* zijn we verder klaar */
            }
            else if (!authparamsUSE) // PAS OP: Dit verwacht AAFM-API niet!!!
            {
                query.wheres.push("prs_perslid.prs_perslid_key = " + user_key);
            }
            else
            {
				// Zonder PRSSYS heb je hier niets mee te maken
                query.wheres.push("(prs_perslid_oslogin IS NULL OR SUBSTR(prs_perslid_oslogin, 0, 1) <> '_')");

                // TODO: Ook nog ALG autorisatie?
                if (authparamsUSE.PRSreadlevel == 0) // prs_bedrijf
                {
                    query.wheres.push("pa.prs_bedrijf_key = " + user.afdeling().prs_bedrijf_key());
                }
                else if (authparamsUSE.PRSreadlevel > 0)
                {
                    query.wheres.push(
                           "prs_perslid.prs_afdeling_key IN "
                        +  "    (SELECT prs_afdeling_key"
                        +  "       FROM prs_v_afdeling_familie a"
                        +  "      WHERE a.prs_afdeling_elder_key IN"
                        +  "        (SELECT aa.prs_afdeling_elder_key"
                        +  "           FROM prs_v_afdeling_familie aa"
                        +  "          WHERE aa.prs_afdeling_key = " + user.prs_afdeling_key()
                        +  "            AND aa.niveau = " + authparamsUSE.PRSreadlevel + "))");
                }
            }

            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 prs_perslid.prs_perslid_naam, prs_perslid.prs_perslid_voornaam, prs_perslid_key";
            if (query.orderbys.length)
                sql += ", " + query.orderbys.join(", ");

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

            return json;
        };

    // We willen vooral dat je via Admin/Autorisatie personen niet met API kunt bewerken
    if (!params.readonly) // wel bijvoorbeeld idp die personen kan aanmaken of SCIM api
    {
        if (!params.internal)
        {
            var autparams = user.checkAutorisation("WEB_PRSMAN", true);
            var prsman_write = (autparams && autparams.PRSwritelevel < 9 && autparams.ALGwritelevel < 9);
        }
        if (params.internal || prsman_write)
            this.autfunction = false; // dat is nu wel gecontroleerd

        this.REST_POST = function (params, jsondata, parent_key)
        {
            if (jsondata.externalid)
            {   // Als hij al verwijderd bestond reanimeren we
                // Onze eigen REST_GET geeft nooit verwijderde records, daarom via SQL
                var sql = "SELECT prs_perslid_key, "
                        + "       prs_perslid_verwijder"
                        + "  FROM prs_perslid"
                        + " WHERE prs_perslid_externid = " + safe.quoted_sql(jsondata.externalid)
                        + "   AND prs_perslid_verwijder IS NOT NULL";
                var oRs = Oracle.Execute(sql);
                if (!oRs.Eof)
                {
                    var the_key = oRs("prs_perslid_key").Value;
                    var verwijder = new Date(oRs("prs_perslid_verwijder").Value);
                    oRs.Close();
                    var sql = "UPDATE prs_perslid"
                            + "   SET prs_perslid_verwijder = NULL"
                            + " WHERE prs_perslid_key = " + the_key;
                    Oracle.Execute(sql);
                    shared.trackaction("PRSLOG", the_key, "User was deleted on {0}, now reanimated.".format(toDateTimeString(verwijder, true)));

                    var post_result = generic_REST_PUT(this)(params, jsondata, the_key); // bijwerken
                    // Klantspecifieke check functie (hookfunction) voor de invoer
                    var pResult = new HookResult();
                    if (!custfunc.prs_postsave(the_key, pResult))
                    {
                        abort_with_warning(pResult.errmsg);
                    }
                    return post_result;
                }
                oRs.Close();
                // doorvallen naar gewone POST
            }
            // Else gewoon een nieuwe
            var post_result = generic_REST_POST(this)(params, jsondata, parent_key);
            // Klantspecifieke check functie (hookfunction) voor de invoer
            var pResult = new HookResult();
            if (!custfunc.prs_postsave(post_result.key, pResult))
            {
                abort_with_warning(pResult.errmsg);
            }
            return post_result;
        }

        if (params.internal || prsman_write)
        {
            this.REST_PUT = function (params, jsondata, the_key)
            {
                if (!("deactivated" in jsondata))
                    jsondata["deactivated"] = null; // niet expliciet deactivated dan altijd reanimeren

                var put_result = generic_REST_PUT(this)(params, jsondata, the_key);

                var pResult = new HookResult();
                if (!custfunc.prs_postsave(the_key, pResult))
                {
                    abort_with_warning(pResult.errmsg);
                }
                return put_result;
            }
            this.REST_DELETE = generic_REST_DELETE(this);
            this.REST_PATCH = this.REST_PUT;
        }
        else
        {
            var autparams = user.checkAutorisation("WEB_PROFIL", true);
            if (autparams && autparams.PRSwritelevel < 9 && autparams.ALGwritelevel < 9)
            {
                this.REST_PUT = function (params, jsondata, the_key)
                {
                    if (params.filter.id != user_key || params.filter.mode != "attachment") // Bijlagen *bij jezelf* mag je uploaden
                        abort_with_warning(L("lcl_no_auth"), 403);
                    this.autfunction = false; // dat is nu wel gecontroleerd
                    var put_result = generic_REST_PUT(this)(params, jsondata, the_key);

                    var pResult = new HookResult();
                    if (!custfunc.prs_postsave(the_key, pResult))
                    {
                        abort_with_warning(pResult.errmsg);
                    }
                    return put_result;
                }
            }
        }
    }
}
%>