<% /*
    $Revision$
    $Id$

    File:           model_companies.inc

    Description:    Bedrijven model.
    Parameters:
    Context:

    Notes:
*/
%>
<!-- #include file="../prs/prs.inc" -->
<!-- #include file="./model_custom_fields.inc"-->
<!-- #include file="./model_prs_kenmerk.inc"-->
<!-- #include file="./model_prs_bedrijfadres.inc"-->
<%

function model_companies()
{
    this.table = "prs_bedrijf";
    this.primary = "prs_bedrijf_key";
    this.records_name = "companies";
    this.record_name = "company";
    this.soft_delete = "prs_bedrijf_verwijder";
    this.autfunction = false;

    this.fields = {
        "id"           : { dbs: "prs_bedrijf_key"             , typ: "key" },
        "name"         : { dbs: "prs_bedrijf_naam"            , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_name") },
        "postaddress"  : { dbs: "prs_bedrijf_post_adres"      , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_post_adres") },
        "postzipcode"  : { dbs: "prs_bedrijf_post_postcode"   , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_post_postcode") },
        "postcity"     : { dbs: "prs_bedrijf_post_plaats"     , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_post_plaats") },
        "postcountry"  : { dbs: "prs_bedrijf_post_land"       , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_post_land") },
        "visitaddress" : { dbs: "prs_bedrijf_bezoek_adres"    , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_bezoek_adres") },
        "visitzipcode" : { dbs: "prs_bedrijf_bezoek_postcode" , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_bezoek_postcode") },
        "visitcity"    : { dbs: "prs_bedrijf_bezoek_plaats"   , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_bezoek_plaats") },
        "visitcountry" : { dbs: "prs_bedrijf_bezoek_land"     , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_bezoek_land") },
        "phone"        : { dbs: "prs_bedrijf_telefoon"        , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_telefoon") },
        "phone2"       : { dbs: "prs_bedrijf_telefoon2"       , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_telefoon2") },
        "email"        : { dbs: "prs_bedrijf_email"           , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_email") },
        "contactname"  : { dbs: "prs_bedrijf_contact_persoon" , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_contact_person") },
        "contactphone" : { dbs: "prs_bedrijf_contact_telefoon", typ: "varchar", filter: "like",  track: L("lcl_prs_companies_contact_telefoon") },
        "remark"       : { dbs: "prs_bedrijf_opmerking"       , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_opmerking") },
        "remark2"      : { dbs: "prs_bedrijf_opmerking2"      , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_opmerking2") },
        "hourrate"     : { dbs: "prs_bedrijf_uurloon"         , typ: "float",   "iscurrency": true, filter: "like" },
        "code"         : { dbs: "prs_leverancier_nr"          , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_leverancier_nr") },
        "agreement"    : { dbs: "prs_overeenkomst_nr"         , typ: "varchar", filter: "like",  track: L("lcl_prs_companies_overeenkomst_nr") },
        "agreementdate": { dbs: "prs_overeenkomst_datum"      , typ: "date",    filter: "range", track: L("lcl_prs_companies_overeenkomst_datum") },
        "isinternal"   : { dbs: "prs_bedrijf_intern"          , typ: "number" },
        "issupplier"   : { dbs: "prs_bedrijf_leverancier"     , typ: "number" },
        "isexecutor"   : { dbs: "prs_bedrijf_uitvoerende"     , typ: "number" }, /*naam?*/
        "iscontractor" : { dbs: "prs_bedrijf_contract"        , typ: "number" },
        "isrenter"     : { dbs: "prs_bedrijf_huurder"         , typ: "number" },
        "location"     : { dbs: "prs_bedrijfdienstlocatie.alg_locatie_key", typ: "key", foreign: "alg_locatie", filter: prs.getLocationSql },
        "service"      : { dbs: "prs_bedrijfdienstlocatie.prs_dienst_key",  typ: "key", foreign: "prs_dienst",  filter: "like" }
    };


    this.includes = {
        "custom_fields" : {
            "model": new model_custom_fields(this, new model_prs_kenmerk("B", { internal: true }), { readman: true, readuse: true, pNiveau: "B" }),
            "joinfield": "flexparentkey"
        },
        "companyconnect": {
            "model": new model_prs_bedrijfadres(),
            "joinfield": "company",
            "enable_update": true
        }
    };

    function _pre_analyze_fields (params, jsondata) /* analyseer inkomende jsondata, common voor PUT en POST */
    {
    };

    function _analyze_fields (dbfields, params, jsondata) /* analyseer inkomende data, common voor PUT en POST */
    {
    };

    function _validate_fields (dbfields, params, jsondata) /* valideer fields, alle constraints die niet door de database worden afgevangen */
    {
        if (S("prs_bedrijf_leveranciernr_unique") == 1)
        {   // Controleer of het leveranciersnummer al wordt gebruikt bij een bedrijf
            var bedrijf_key = (!params.isNew && params && params.filter && params.filter.id ? params.filter.id : null);
            var sql = "SELECT b.prs_bedrijf_key"
                    + "  FROM prs_v_aanwezigbedrijf b"
                    + " WHERE UPPER(b.prs_leverancier_nr) = " + safe.quoted_sql_upper(jsondata.code)
                    + (bedrijf_key ? " AND b.prs_bedrijf_key NOT IN (" + bedrijf_key + ")" : "");
            var oRs = Oracle.Execute(sql);
            if (!oRs.eof)
            {   // Er is al een bedrijf met dezelfde leveranciersnummer aanwezig
                abort_with_warning(L("lcl_prs_levnr_unique"));
            }
            oRs.close();
        }
    };

    this.REST_GET = function _GET(params)
        {
            var autfunction = "WEB_RELMAN";
            var bedrijf_key = (!params.isNew && params && params.filter && params.filter.id ? params.filter.id : -1);
            if (bedrijf_key > 0) {
                var sql = "SELECT NVL(prs_bedrijf_intern, 0) intern"
                        + "  FROM prs_bedrijf"
                        + " WHERE prs_bedrijf_key = " + bedrijf_key;
                var oRs = Oracle.Execute(sql);
                if (!oRs.EOF && oRs("intern").Value != 0) { // Extern systeem
                    autfunction = "WEB_PRSMAN";
                }
                oRs.Close();
            }
            params.authparams = user.checkAutorisation(autfunction, null, null, true); // pessimistisch

            // TODO: Add authorization
            var query = api2.sqlfields(params, this);
            query.wheres.push("prs_bedrijf_verwijder IS NULL");

            /* we need the dienstlocatie for the service and location */
            query.tables.push("prs_bedrijfdienstlocatie");
            query.wheres.push("prs_bedrijfdienstlocatie.prs_bedrijf_key(+) = prs_bedrijf.prs_bedrijf_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 prs_bedrijf_naam";

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

            return json;
        };

    this.REST_PUT = function _PUT(params, jsondata, the_key) /* update company */
        {
            var bedrijf_key = the_key;
            var autfunction = ["WEB_PRSMAN", "WEB_RELMAN", "WEB_RELUSE"];
            var authparams = user.checkAutorisation(autfunction, true);
            user.auth_required_or_abort(authparams && (authparams.ALGwritelevel < 9 || authparams.PRSwritelevel < 9));

            _pre_analyze_fields(params, jsondata);
            var dbfields = api2.update_fields(params, this, jsondata); // Build updater
            _analyze_fields(dbfields, params, jsondata);
            _validate_fields(dbfields, params, jsondata);

            var wheres = [" prs_bedrijf_key = " + bedrijf_key];
            var prsUpd = buildTrackingUpdate("prs_bedrijf", wheres.join(" AND " ), dbfields, { noValidateToken: true });
            var err = Oracle.Execute(prsUpd.sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

            var prstrack = api2.process_includes(params, this, jsondata, the_key);

            // update nog tracken
            var all_track = (prsUpd && prsUpd.trackarray ? prsUpd.trackarray : []);
            all_track = all_track.concat(prstrack);
            if (all_track.length)
                shared.trackaction("PRSUPB", bedrijf_key, all_track.join("\n") );

            return { key: bedrijf_key };
        };

    this.REST_POST = function _POST(params, jsondata) /* new company */
        {
            var autfunction = ["WEB_PRSMAN", "WEB_RELMAN", "WEB_RELUSE"];
            var authparams = user.checkAutorisation(autfunction, true);
            user.auth_required_or_abort(authparams && (authparams.ALGwritelevel < 9 || authparams.PRSwritelevel < 9));

            params.isNew = true; // negeer eventuele bestaande keys

            _pre_analyze_fields(params, jsondata);
            var dbfields = api2.update_fields(params, this, jsondata); // Build updater
            _analyze_fields(dbfields, params, jsondata);
            _validate_fields(dbfields, params, jsondata);

            dbfields["id"] = { dbs: "prs_bedrijf_key", typ: "key", seq: "prs_s_prs_alluitvoerende_keys" };
            var prsIns = buildInsert("prs_bedrijf", dbfields, { noValidateToken: true} );
            var bedrijf_key = prsIns.sequences["prs_bedrijf_key"];

            var sql = prsIns.sql;
            var err = Oracle.Execute(sql, true);
            if (err.friendlyMsg)
                abort_with_warning(err.friendlyMsg);

            var prstrack = api2.process_includes(params, this, jsondata, bedrijf_key);
            // Geen trackaction voor nieuwe bedrijven.

            return { key: bedrijf_key };
        };

    this.REST_DELETE = function (params, the_key) /* delete company */
        {   // Gekopieerd uit prs_delete.asp
            var bedrijf_key = the_key;

            var p_authparams = user.checkAutorisation("WEB_PRSMAN", true);
            var deletePRSMAN = p_authparams && p_authparams.PRSwritelevel < 9;
            var r_authparams = user.checkAutorisation( (S("bgt_enabled")==1 ? "WEB_BGTUSE" : "WEB_RELMAN"), true);
            var deleteRELMAN = r_authparams && r_authparams.PRSwritelevel < 9;
            var canDelete = (deletePRSMAN || deleteRELMAN);

            if (canDelete)
            {
                var sql = "SELECT nvl(prs_bedrijf_intern, 0) intern"
                        + "  FROM prs_bedrijf"
                        + " WHERE prs_bedrijf_key = " + bedrijf_key;
                var oRs = Oracle.Execute(sql);
                if (oRs.eof || ((oRs("intern").value == 1) && !deletePRSMAN)
                            || ((oRs("intern").value == 0) && !deleteRELMAN)
                   )
                {
                    canDelete = false;
                }
                oRs.Close();
                user.auth_required_or_abort(canDelete);
                // Verwijderdatum van het bedrijf zetten en niet fysiek verwijderen
                return generic_REST_DELETE(this)(params, the_key);
            }
        };
}
%>