<%@language = "javascript" %>
<% /*
     $Revision$
     $Id$

     File:         cnt_edit_contract_save.asp
     Description:  SUBMIT-form
*/
var JSON_Result = true;
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../shared/save2db.inc" -->
<!-- #include file="../Shared/kenmerk_common.inc"-->
<!-- #include file="cnt.inc" -->

<%
protectRequest.validateToken();
var cnt_key = getQParamInt("cnt_key", -1);
var cnt_disc_key = getQParamInt("srtdisc");
var copy = (getQParamInt("cnt_copy", 0) == 1);
var cnt_copy_key = -1;
if (copy)
{
    cnt_copy_key = cnt_key;
    cnt_key = -1;
}
var cnt_kosten = getFParamFloat("cnt_cntkstn", 0);
var isNew = (cnt_key < 0);

var sql = "SELECT cdp.cnt_srtcontract_type"
        + "     , cdp.cnt_disc_params_opties"
        + "  FROM cnt_disc_params cdp"
        + " WHERE cdp.cnt_ins_discipline_key = " + cnt_disc_key;
var oRs = Oracle.Execute(sql);
var srtcontract_type = oRs("cnt_srtcontract_type").Value;
var magAutomatischVerlengen = (oRs("cnt_disc_params_opties").Value & 1) == 1;
var doapprove = S("cnt_contract_approval") == 1;
oRs.Close();

function getVerlengenTekst(p)
{
  var ps = "??";
  switch (p) {
    case -1: { ps = L("lcl_unknown"); break; }
    case  0: { ps = L("lcl_No"); break; }
    case  1: { ps = L("lcl_Yes"); break; }
    case  5: { ps = L("lcl_cnt_prolongation_auto"); break; }
  }
  return ps;
}

if (!isNew)
{
  var cnt_info = cnt.cnt_contract_info(cnt_key); // Haal gegevens van het contract op.
  var this_cnt = cnt.func_enabled_contract(cnt_key, cnt_info); // Wat heb ik zoal aan rechten op dit contract?
  user.auth_required_or_abort(this_cnt.canChange);
}
else
{ // Nieuw contract
  if (doapprove)
    // Het approval mechanisme is actief.
    // Als het approval mechanisme actief is mag ik met WEB_CNTUSE rechten ook een contract aanmaken.
    var autfunction = ["WEB_CNTUSE", "WEB_CNTMAN"];
  else
    // Het approval mechanisme is NIET actief.
    var autfunction = "WEB_CNTMAN";

  var authparams = user.checkAutorisation(autfunction);

  // Als het approval mechanisme actief is dan altijd eerst naar status Nieuw(2),
  // uitgezonderd de Mantel/Master contracten, die gaan altijd langs het goedkeuringsproces.
  var cnt_info = { contract_status: (doapprove && srtcontract_type != 6? 2 : 0) }
}

// Bestaat het contractnummer al?
var cnt_internal_nr = getFParam("cnt_cntnrint", ""); /* bij null wordt automatisch de key gebruikt */
// Bij wijzigen in een leeg contractnummer wordt de key genomen en dan moet je daarop controleren.
if (!isNew && sharedTrim(cnt_internal_nr) == "")
  cnt_internal_nr = "" + cnt_key;
var sql = "SELECT 1 FROM cnt_contract"
        + " WHERE UPPER(cnt_contract_nummer_intern) = " + safe.quoted_sql_upper(sharedTrim(cnt_internal_nr))
        + "   AND cnt_contract_verwijder IS NULL "
        + (!isNew
          ? " AND cnt_contract_key <> " + cnt_key
            + " AND COALESCE(cnt_contract_versie, '0') = COALESCE(" + safe.quoted_sql(cnt_info.versie) + ", '0')"
          : "");
var oRs = Oracle.Execute(sql);
if (!oRs.eof)
{
  abort_with_warning(L("lcl_cnt_nummer_not_unique"));
}
oRs.Close();

var fields =  [ { dbs: "cnt_contract_nummer_intern",  typ: "varchar", frm: "cnt_cntnrint",      track: L("lcl_cnt_intern_nr") },
                { dbs: "ins_discipline_key",          typ: "key",     val: cnt_disc_key },
                { dbs: "cnt_contract_omschrijving",   typ: "varchar", frm: "cnt_cntomst",       track: L("lcl_cnt_descr") },
                { dbs: "cnt_contract_nummer",         typ: "varchar", frm: "cnt_cntnr",         track: L("lcl_cnt_contractnr") },
                { dbs: "cnt_contract_mantel_key",     typ: "key",     frm: "cnt_macntkey",      track: L("lcl_cnt_mantel"),          foreign: "cnt_contract" },
                { dbs: "cnt_contract_document",       typ: "varchar", frm: "cnt_cntdoc",        track: L("lcl_cnt_document") },
                { dbs: "prs_afdeling_key_eig",        typ: "key",     frm: "cnt_owner",         track: L("lcl_cnt_owner"),           foreign: "prs_afdeling" },
                { dbs: "prs_perslid_key_eig",         typ: "key",     frm: "cnt_owner_prs",     track: L("lcl_cnt_contact_eig"),     foreign: "prs_perslid" },
                { dbs: "prs_perslid_key_beh",         typ: "key",     frm: "cnt_manager",       track: L("lcl_cnt_manager"),         foreign: "prs_perslid" },
                { dbs: "cnt_contract_opmerking",      typ: "varchar", frm: "cnt_cntopm",        track: L("lcl_remark") },
                { dbs: "cnt_contract_looptijd_van",   typ: "date",    frm: "flddatevan",        track: L("lcl_cnt_date_start") },
                { dbs: "cnt_contract_looptijd_tot",   typ: "date",    frm: "flddatetot",        track: L("lcl_cnt_date_end") },
                { dbs: "cnt_contract_inactiveren",    typ: "check0",  frm: "cnt_auto_close",    track: L("lcl_cnt_auto_close") },
                { dbs: "cnt_contract_opzegtermijn",   typ: "key",     frm: "cnt_cancel_period", track: L("lcl_cnt_cancel_period"),   foreign: "cnt_termijn" },
                { dbs: "cnt_contract_rappeltermijn",  typ: "key",     frm: "cnt_rappel_period", track: L("lcl_cnt_rappel_period"),   foreign: "cnt_termijn" },
                { dbs: "cnt_prs_bedrijf_key",         typ: "key",     frm: "cnt_bdrkey",        track: L("lcl_cnt_mutatie_huurder"), foreign: "prs_bedrijf" },
                { dbs: "cnt_prs_perslid_key",         typ: "key",     frm: "cnt_prskey",        track: L("lcl_cnt_name"),            foreign: "prs_perslid" },
                { dbs: "cnt_prs_afdeling_key",        typ: "key",     frm: "cnt_afdkey",        track: L("lcl_cnt_afdeling"),        foreign: "prs_afdeling"  },
                { dbs: "prs_dienst_key",              typ: "key",     frm: "dienst",            track: L("lcl_prs_companies_dienst"),foreign: "prs_dienst" },
                { dbs: "prs_contactpersoon_key",      typ: "key",     frm: "cnt_contprs",       track: L("lcl_cnt_contact_prs"),     foreign: "prs_contactpersoon" },
                { dbs: "cnt_contract_termijnkosten",  typ: "float",   frm: "cnt_termkstn",      track: L("lcl_cnt_period_sum") },
                { dbs: "cnt_contract_termijntermijn", typ: "key",     frm: "cnt_term_period",   track: L("lcl_cnt_period_period"),   foreign: "cnt_termijn" },
                { dbs: "cnt_contract_kosten",         typ: "float",   frm: "cnt_cntkstn",       track: L("lcl_cnt_contract_sum") },
                { dbs: "cnt_contract_uurloon",        typ: "float",   frm: "cnt_uurloon",       track: L("lcl_hour_rate") },
                { dbs: "cnt_contract_korting",        typ: "float",   frm: "cnt_korting",       track: L("lcl_cnt_discount") },
                { dbs: "prs_kostenplaats_key",        typ: "key",     frm: "prs_kstplkey",      track: L("lcl_cnt_kostenplaats"),    foreign: "prs_kostenplaats" },
                { dbs: "prs_kostensoort_key",         typ: "key",     frm: "prs_kstsrtkey",     track: L("lcl_cnt_kostensoort"),     foreign: "prs_kostensoort" }
              ];

var warning = "";
var keepForm = false;
var success = true;
if (!isNew)
{
  var verlengen = getFParamInt("cntverlengen", -2); // 0=vragen nee, 1=vragen ja, -1=NULL(geen), 5=automatisch (verlengen)
  if (verlengen > -2)
  {
    var newverlengen = verlengen;
    if (verlengen == -1) verlengen = "";
    fields.push({ dbs: "cnt_contract_verlenging", typ: "number", val: verlengen, track: true /* afzonderlijke tracking, wel oldjsval */ });

    var prolong_period = (magAutomatischVerlengen && (verlengen == 5) ? getFParamInt("cnt_prolongation_period", 1) : null);
    fields.push({ dbs: "cnt_contract_verleng_termijn", typ: "key", val: prolong_period, track: L("lcl_cnt_prolongation_period"), foreign: "cnt_termijn"});
  }

  cntUpd = buildTrackingUpdate("cnt_contract", "cnt_contract_key = " + cnt_key, fields);

  var err = Oracle.Execute(cntUpd.sql, true);
  if (err.friendlyMsg)
  {
    warning = err.friendlyMsg;
    keepForm = true;
    success = false;
  }
  // tracking komt samen met de flexkenmerken

  if (verlengen > -2)
  { // tracking verlenging is ingewikkelder (De waarden NULL en 0 worden beide als lege waarde gezien), die doen we handmatig
    var oldverlengen = cntUpd.oldjsvals["cnt_contract_verlenging"] == null? -1 : cntUpd.oldjsvals["cnt_contract_verlenging"];
    if (oldverlengen != newverlengen)
    {
      oldverlengen = getVerlengenTekst(oldverlengen);
      newverlengen = getVerlengenTekst(newverlengen);
      var tracktxt = oldverlengen + L("lcl_trackto") + newverlengen;
      cntUpd.trackarray.push(L("lcl_cnt_verlengen") + ": " + tracktxt);
    }
  }
}
else
{ // Nieuw contract.
  // Bepaal volgende contractnummer.
  var oRs_n = Oracle.Execute("SELECT cnt_s_cnt_contract_key.nextval FROM DUAL");
  var next_cnt_key = oRs_n(0).value;
  oRs_n.Close();

  if (!cnt_internal_nr)
  { // Automatische nummering (Er is geen contractnummer ingevuld).
    // Check of het volgende contractnummer al in gebruik is als contractnummer. Anders nemen we de volgende sequence.
    var found = false;
    while (!found)
    { // Nog geen geschikt contractnummer gevonden. Check het volgende contractnummer (next_cnt_key).
      sql = "SELECT 1 FROM cnt_contract"
          + " WHERE UPPER(cnt_contract_nummer_intern) = '" + next_cnt_key + "'"
          + "   AND cnt_contract_verwijder IS NULL"
          + "   AND cnt_contract_key <> " + next_cnt_key
          + "   AND COALESCE(cnt_contract_versie, '0') = '0'";
      oRs = Oracle.Execute(sql);
      if (!oRs.eof)
      { // Volgende contractnummer is niet geschikt als contractnummer. We schuiven eentje door en pakken de volgende sequence.
        oRs_n = Oracle.Execute("SELECT cnt_s_cnt_contract_key.nextval FROM DUAL");
        next_cnt_key = oRs_n(0).value;
        oRs_n.Close();
      }
      else
        // Volgende contractnummer (next_cnt_key) bestaat nog niet.
        found = true;
      oRs.Close();
    }
  }
  fields.push({ dbs: "cnt_contract_key",            typ: "key",     val: next_cnt_key });

  var auto_verlengen = getFParamInt("cntverlengen", 0) == 5;
  if (magAutomatischVerlengen && auto_verlengen)
  {
    fields.push({ dbs: "cnt_contract_verlenging",      typ: "number", frm: "cntverlengen",            track: L("lcl_cnt_verlengen")});
    fields.push({ dbs: "cnt_contract_verleng_termijn", typ: "key",    frm: "cnt_prolongation_period", track: L("lcl_cnt_prolongation_period"), foreign: "cnt_termijn"});
  }

  var regIns = buildInsert("cnt_contract", fields);
  var cnt_key = next_cnt_key;
  sql = regIns.sql;
  var err = Oracle.Execute(sql, true);
  if (err.friendlyMsg)
  {
    warning = err.friendlyMsg;
    keepForm = true;
    success = false;
  }
  else
    // Zetten van de contact status. Indien het contract approval mechanisme actief is dan moet de contract status Nieuw(2) worden en anders Actief(0).
    // Uitgezonderd de Mantel/Master contracten, die gaan altijd langs het goedkeuringsproces naar de status Actief(0).
    cnt.setcontractstatus(cnt_key, cnt_info.contract_status); // Zorgt ook voor tracking en daarmee notificatie.
}

if (!warning)
{
  currentKenmerkenSQL = "SELECT k.cnt_kenmerk_key"
                      + "     , ko.cnt_kenmerkcontract_waarde"
                      + "     , k.cnt_kenmerk_toonbaar"
                      + "     , k.fac_functie_key"
                      + "  FROM cnt_kenmerkcontract ko"
                      + "     , cnt_kenmerk k"
                      + " WHERE k.cnt_kenmerk_key = ko.cnt_kenmerk_key"
                      + "   AND cnt_kenmerkcontract_verwijder IS NULL"
                      + "   AND cnt_contract_key(+) = " + cnt_key;

  allKenmerkenSQL     = "SELECT COALESCE (" + lcl.xsql("k.cnt_kenmerk_omschrijving", "k.cnt_kenmerk_key")
                      + "              ,  " + lcl.xsql("t.cnt_srtkenmerk_omschrijving", "t.cnt_srtkenmerk_key") + ") kenmerk_omschrijving"
                      + "     , t.cnt_srtkenmerk_kenmerktype kenmerk_kenmerktype"
                      + "     , t.cnt_srtkenmerk_systeem     kenmerk_systeem"
                      + "     , k.cnt_kenmerk_toonbaar       kenmerk_readonly"
                      + "     , k.cnt_kenmerk_uniek          kenmerk_uniek"
                      + "     , fac_kenmerkdomein_key"
                      + "  FROM cnt_kenmerk k"
                      + "     , cnt_srtkenmerk t"
                      + " WHERE k.cnt_srtkenmerk_key = t.cnt_srtkenmerk_key"
                      + "   AND k.cnt_kenmerk_key = "; /* wordt in saveFlexkenmerken uitgebreid */

  var flextrack = saveFlexKenmerken(cnt_key, { kenmerkTable: "cnt_kenmerkcontract",
                                               kenmerkParentKey : "cnt_contract_key",
                                               kenmerkWaarde: "cnt_kenmerkcontract_waarde",
                                               kenmerkKey: "cnt_kenmerk_key",
                                               kenmerkToonbaar: "cnt_kenmerk_toonbaar",
                                               currentKenmerkenSQL: currentKenmerkenSQL,
                                               allKenmerkenSQL: allKenmerkenSQL,
                                               kenmerkOmschrijving: "kenmerk_omschrijving",
                                               kenmerkSoortKey: "cnt_srtkenmerk_key",
                                               requestQF: Request.Form,
                                               isNew: isNew,
                                               flexPath: "CNT/C",
                                               tracking: true,
                                               module: "CNT"
                                            }
                                  )

  if (copy) // copy scope as well
  {

    var flexsql = "SELECT k_old.cnt_kenmerk_key k_old"
                + ", k_old.cnt_kenmerk_key k_new"
                + " FROM cnt_srtkenmerk t"
                + ", cnt_discipline s"
                + ", cnt_kenmerk k_old"
                + ", cnt_contract c_old"
                + " WHERE c_old.cnt_contract_key = " + cnt_copy_key
                + " AND s.ins_discipline_key = c_old.ins_discipline_key"
                + " AND (k_old.cnt_srtcontract_key = s.ins_discipline_key OR k_old.cnt_srtcontract_key IS NULL)"
                + " AND t.cnt_srtkenmerk_kenmerktype IN ('F', 'E', 'M') "
                + " AND k_old.cnt_kenmerk_verwijder IS NULL "
                + " AND k_old.cnt_srtkenmerk_key = t.cnt_srtkenmerk_key "
                + " AND t.cnt_srtkenmerk_verwijder IS NULL";

    CopyFlexFolders("CNT", "C", cnt_copy_key, "C", cnt_key, flexsql);

    var prePlaatsScopeSql = "SELECT cnt_alg_plaats_code, cnt_alg_plaats_key"
                          + "  FROM cnt_contract_plaats"
                          + " WHERE cnt_contract_key = " + cnt_copy_key
                          + "   AND cnt_contract_plaats_verwijder IS NULL";
    var preOracle = Oracle.Execute(prePlaatsScopeSql);

    if (!preOracle.EoF)
    {
        var cnt_alg_code = preOracle("cnt_alg_plaats_code").Value;
        var cnt_alg_key = preOracle("cnt_alg_plaats_key").Value;
        prePlaatsScopeSql = "";
        switch(cnt_alg_code) {
            case 'R':
                prePlaatsScopeSql = "SELECT alg_ruimte_key FROM alg_v_aanwezigruimte WHERE alg_ruimte_key = " + cnt_alg_key;
                break;
            case 'V':
                prePlaatsScopeSql = "SELECT alg_verdieping_key FROM alg_v_aanwezigverdieping WHERE alg_verdieping_key = " + cnt_alg_key;
                break;
            case 'G':
                prePlaatsScopeSql = "SELECT alg_gebouw_key FROM alg_v_aanweziggebouw WHERE alg_gebouw_key = " + cnt_alg_key;
                break;
            case 'T':
                prePlaatsScopeSql = "SELECT alg_terreinsector_key FROM alg_v_aanwezigterreinsector WHERE alg_terreinsector_key = " + cnt_alg_key;
                break;
            case 'L':
                prePlaatsScopeSql = "SELECT alg_locatie_key FROM alg_v_aanweziglocatie WHERE alg_locatie_key = " + cnt_alg_key;
                break;
            default:
                break;
        }
        if (prePlaatsScopeSql != "")
        {
            preOracle2 = Oracle.Execute(prePlaatsScopeSql);
            if (!preOracle2.EoF)
            {
                var copyPlaatsScopeSql = "INSERT INTO cnt_contract_plaats (cnt_contract_key,"
                                       + "                                 cnt_alg_plaats_code,"
                                       + "                                 cnt_alg_plaats_key,"
                                       + "                                 cnt_contract_plaats_gewicht)"
                                       + "   SELECT " + cnt_key + ","
                                       + "          cnt_alg_plaats_code,"
                                       + "          cnt_alg_plaats_key,"
                                       + "          cnt_contract_plaats_gewicht"
                                       + "     FROM cnt_contract_plaats"
                                       + "    WHERE cnt_contract_key = " + cnt_copy_key
                                       + "      AND cnt_contract_plaats_verwijder IS NULL";
                Oracle.Execute(copyPlaatsScopeSql);
            }
            preOracle2.Close();
        }
    }
    preOracle.Close();

    var copyObjectScopeSql = "INSERT INTO cnt_contract_object (cnt_contract_key,"
                           + "                                 cnt_ins_srtdeel_key,"
                           + "                                 cnt_ins_deel_key)"
                           + "   SELECT " + cnt_key + ","
                           + "          cnt_ins_srtdeel_key,"
                           + "          cnt_ins_deel_key"
                           + "     FROM cnt_contract_object"
                           + "    WHERE cnt_contract_key = " + cnt_copy_key
                           + "      AND cnt_contract_object_verwijder IS NULL";
    Oracle.Execute(copyObjectScopeSql);
  }

  if (!isNew && (cntUpd.trackarray.length || flextrack.length))
    shared.trackaction("CNTUPD", cnt_key, L("lcl_cnt_is_cntupd") + "\n" + cntUpd.trackarray.concat(flextrack).join("\n"));

  // Als de contractkosten aangepast zijn wordt nooit opnieuw gefiatteerd. Dan moet er een nieuw contract worden afgesplitst.
  // Tijdens het opslaan veranderd nooit de status in Ter goedkeuring. Dus geen cnt.sendNeedApprovalNotifications(..,..).
}

cnt.unlock(cnt_key);

var result = { cnt_key: cnt_key,
               success: success,
               keepForm: keepForm,
               warning: warning
             };
Response.Write(JSON.stringify(result));
%><% ASPPAGE_END(); %>
