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

     File:         cnt_edit_contract_save.asp
     Description:  SUBMIT-form
*/ %>

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


<% FCLTHeader.Requires({ plugins:["jQuery"] }) %>
<%
var cnt_key = getQParamInt("cnt_key", -1);
var srtdisc = getQParamInt("srtdisc");
var cnt_kosten = getFParamFloat("cnt_cntkstn", 0);
var isNew = (cnt_key < 0);

var sql = "SELECT cdp.cnt_srtcontract_type"
        + "  FROM cnt_disc_params cdp"
        + " WHERE cdp.cnt_ins_discipline_key = " + srtdisc;
var oRs = Oracle.Execute(sql);
var srtcontract_type = oRs("cnt_srtcontract_type").Value;
var doapprove = S("cnt_contract_approval") == 1;

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", null); /* bij null wordt automatisch de key gebruikt */
var sql = "SELECT 1 FROM cnt_contract"
        + " WHERE UPPER(cnt_contract_nummer_intern) = " + safe.quoted_sql_upper(cnt_internal_nr)
        + "   AND cnt_contract_verwijder IS NULL "
        + (!isNew
          ? " AND cnt_contract_key <> " + cnt_key
            + " AND cnt_contract_versie = " + safe.quoted_sql(cnt_info.versie)
          : "");
var oRs = Oracle.Execute(sql);
if (!oRs.eof)
{
  abort_with_warning(L("lcl_cnt_nummer_not_unique"));
}

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: srtdisc },
                { 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_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;
if (!isNew)
{
  var verlengen = getFParamInt("cntverlengen", -2); // 0=vragen nee, 1=vragen ja, -1=NULL(geen)
  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 */ });
  }

  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;
  }
  // 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 = cnt.getvervangentext(oldverlengen);
      newverlengen = cnt.getvervangentext(newverlengen);
      var tracktxt = oldverlengen + L("lcl_trackto") + newverlengen;
      cntUpd.trackarray.push(L("lcl_cnt_verlengen") + ": " + tracktxt);
    }
  }
}
else
{ // Nieuw contract.
  fields.push({  dbs: "cnt_contract_key",         typ: "key",      seq: "cnt_s_cnt_contract_key" });
  var regIns = buildInsert("cnt_contract", fields);
  var cnt_key = regIns.sequences["cnt_contract_key"];
  sql = regIns.sql;
  var err = Oracle.Execute(sql, true);
  if (err.friendlyMsg)
  {
    warning = err.friendlyMsg;
    keepForm = true;
  }
  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"
                      + "   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 " + lcl.xsql('t.cnt_srtkenmerk_omschrijving', 't.cnt_srtkenmerk_key') + " kenmerk_omschrijving"
                      + "      , t.cnt_srtkenmerk_key srtkenmerk_key"
                      + "      , fac_kenmerkdomein_key"
                      + "   FROM cnt_kenmerk k"
                      + "      , cnt_srtkenmerk t"
                      + "  WHERE k.cnt_srtkenmerk_key = t.cnt_srtkenmerk_key"
                      + "    AND 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",
                                               currentKenmerkenSQL: currentKenmerkenSQL,
                                               allKenmerkenSQL: allKenmerkenSQL,
                                               kenmerkOmschrijving: "cnt_srtkenmerk_omschrijving",
                                               kenmerkSoortKey: "cnt_srtkenmerk_key",
                                               requestQF: Request.Form,
                                               isNew: isNew, flexPath: "CNT/C",
                                               tracking: true,
                                               module: "CNT"
                                            }
                                  )

  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);
%>
<html>
  <head>
    <%  FCLTHeader.Generate() %>
    <script>
        $(document).ready(function () {
            FcltMgr.closeDetail(window, { cnt_key: <%=cnt_key%>,
                                          warning: "<%=safe.jsstring(warning)%>",
                                          keepForm: <%=keepForm?"true":"false"%>
                                         }); } );
    </script>
  </head>
  <body>
  </body>
</html>
