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

    File:               bes_opdr.asp
    Description:        Edit voor bestellingen-opdrachten
    Parameters:
                        urole
                        opdr_key
    Context:
    Note:
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/adresselector.inc" -->
<!-- #include file="../shared/save2db.inc" -->
<!-- #include file="bes.inc" -->
<!-- #include file="bes_flexkenmerk.inc" -->

<%
FCLTHeader.Requires({ plugins: ["jQuery"] })

var urole = getQParamSafe("urole");
var minfo = (urole == "mi");
var opdr_key = getQParamInt("opdr_key");

var bes_bestelopdr = bes.bestelopdracht_info(opdr_key); // Globale variabele met alle bes_bestelopdr informatie
var bes_bestelling = bes.bestelling_info(bes_bestelopdr.bes_key_str[0]);

var this_bestelopdr = bes.func_enabled_bestelopdracht(opdr_key);
var this_bestelling = bes.func_enabled_bestelling(bes_bestelling)

%>

<html>
  <head>
<%  FCLTHeader.Generate(); %>
  </head>
<%

  var authparams = user.checkAutorisation("WEB_BESBOF");
  user.auth_required_or_abort(this_bestelopdr.canChange);

  var submitting = getQParamInt("submit", 0) == 1;
  if (submitting)
  {
    protectRequest.validateToken();

    var fields =  [ { dbs: "bes_bestelopdr_opmerking", typ: "varchar", frm: "opmerk",   track: L("lcl_remark"), len: 320 },
                    { dbs: "mld_adres_key_lev",        typ: "key",     frm: "levering", track: L("lcl_bes_adres_lev"), foreign: "MLD_V_AFLEVERADRES" } ,
                    { dbs: "mld_adres_key_fac",        typ: "key",     frm: "factuur",  track: L("lcl_bes_adres_fac"), foreign: "MLD_V_FACTUURADRES" } ,
                    { dbs: "bes_bestelopdr_flag",      typ: "number",  frm: "besopdrflag" }
                  ];
    if (getFParam("chkproceed", "off") == "on")
        fields.push({ dbs: "bes_bestelopdr_status", typ: "key", val: 3});
    var besOpdrUpd = buildTrackingUpdate("bes_bestelopdr", " bes_bestelopdr_key = " + opdr_key, fields);

    itemregels = getFParamInt("itemregels");
    var besopdr_id = "";
    for (i = 1; i <= itemregels; i++)
    {
      cnt  = getFParamInt('cnt' + i);
      ikey = getFParamInt('ikey' + i);
      iopm = getFParam('opm' + i, "");
      //  : Moet (desnoods) prijs niet overgenomen uit bes_bestelling_item_prijs?
      sql = "UPDATE bes_bestelopdr_item"
          + "   SET bes_bestelopdr_item_aantal = " + cnt
          + "     , bes_bestelopdr_item_prijs = "
          + "           (SELECT bes.getsrtdeelprijs(bes_srtdeel_key, NULL)"
          + "              FROM bes_bestelling_item WHERE "
          + "               bes_bestelopdr_item_key = " + ikey + ")"
          + "     , bes_bestelopdr_item_opmerking = " + safe.quoted_sql(iopm)
          + " WHERE bes_bestelopdr_item_key = " + ikey;

      Oracle.Execute(sql);

      if (bes_bestelopdr.artikel_arr[i-1].aantal > cnt)
      {
        sql = "SELECT boi.bes_bestelopdr_item_omschrijv"
            + "     , bo.bes_bestelopdr_id"
            + "  FROM bes_bestelopdr_item boi"
            + "     , bes_bestelopdr bo"
            + " WHERE boi.bes_bestelopdr_key = bo.bes_bestelopdr_key"
            + "   AND bes_bestelopdr_item_key = " + ikey;
        oRs = Oracle.Execute(sql);
        var item_oms = oRs("bes_bestelopdr_item_omschrijv").Value;
        besopdr_id = oRs("bes_bestelopdr_id").Value;
        besOpdrUpd.trackarray.push(L("lcl_bes_amount") + ": " + buildTrackText("float", bes_bestelopdr.artikel_arr[i-1].aantal, cnt) + " (" + item_oms + ")");
      }
    }

    Oracle.Execute(besOpdrUpd.sql);

    // Als de status 4 (In bestelling (bevestigd)) is zou het zo kunnen zijn dat nu (na deze wijziging) alles geleverd is.
    if (bes_bestelopdr.status == 4)
    { // Laat de gevolgen bepalen..
      bes.updatebestelopdrstatus(opdr_key);
      bes.updatebestellingstatus(bes_bestelling.bes_key);
    }

    // Update nog tracken
    shared.trackaction("BES2UP",
                       opdr_key,
                       L("lcl_bes_is_bes2uptrack").format(S("bes_bestelopdr_prefix") + besopdr_id) + "\n" + besOpdrUpd.trackarray.join("\n"));



%>  <script type="text/javascript">
      FcltMgr.closeDetail(window, { warning: null } );
    </script>
<%  Response.End;
  }
%>
  <script type="text/javascript">

    function bes_opdrsubmit()
    {   //TODO CheckLengte
        if (hasBadFields())
        {
          FcltMgr.alert(L("lcl_shared_validator_invalid"));
          return false;
        }
        document.forms.u2.submit();
        return true;
    }

    function bes_opdrcancel()
    {
        FcltMgr.closeDetail(window, { cancel: true } );
    }

    $(function()
    {
        $('textarea').resize(function() { FcltMgr.resized(window) });
        $('textarea').autogrow();
    });

  </script>
  <body class="editmode">
  <% SUBFRAME_START(); %>
<%
    var buttons =  [ {title: L("lcl_submit"), icon: "fa-fclt-save", action: "bes_opdrsubmit()" },
                     {title: L("lcl_cancel"), icon: "fa-fclt-cancel", action: "bes_opdrcancel()" }];

    IFRAMER_HEADER(L("lcl_bes_opdrframe_algemeen"), buttons)

%>
    <script type="text/javascript">
      function recalcPrice(key)
      {
        var m_count = parseInt(document.u2['cnt' + key].value);
        var valid = true;
        var error = "";
        if (isNaN(m_count)) {
            document.u2['cnt'+key].value = document.u2['am' + key].value;
            return;
        }

        // Het aantal moet groter of gelijk blijven aan het aantal geleverd.
        // Trouwens alleen als de status 4 is of daarna kunnen er artikelen geleverd zijn.
        var m_count_ontv = parseInt(document.u2['cnt'+key].getAttribute("aantalontv"));

        if (m_count < m_count_ontv)
        {
          valid = false;
          error = L("lcl_bes_aantontv_mess").format(m_count_ontv);
          document.u2['cnt'+key].value = m_count_ontv;
          m_count = m_count_ontv;
        }

        // Aantal kan niet verhoogd worden.
        var m_count_max = parseInt(document.u2['max' + key].value);
        if (m_count > m_count_max)
        {
          valid = false;
          error = L("lcl_bes_verhogen_mess");
          document.u2['cnt'+key].value = m_count_max;
          m_count = m_count_max;
        }
        validateField(document.u2['cnt' + key], valid, error);

        var price = parseFloat(document.u2['pr'+key].value);
        var c_count = m_count * price;
        $('#price' + key).text(num2curr(c_count));

        var amount = document.u2['am' + key].value;
        document.u2['am' + key].value = m_count;

        var o_count = amount * price;
        document.u2.total.value = parseFloat(document.u2.total.value) - o_count + c_count;
        document.u2.total_txt.value = num2curr(parseFloat(document.u2.total.value));
      }
    </script>

    <form action="bes_edit_opdr.asp?submit=1&urole=<%=urole%>&opdr_key=<%=opdr_key%>" method=post name=u2 >
<%
       BLOCK_START("besOpdr", L("lcl_bes_opdrframe_algemeen"), {icon: "fa-shipping-fast"});

        ROFIELDTR("fld", L("lcl_bes_Supplier"), bes_bestelopdr.prs_bedrijf_naam);

        if (bes_bestelling.perslid_key_voor > 0 && bes_bestelling.perslid_key_voor != bes_bestelopdr.perslid_key)
        {
            FCLTpersoonselector(
               "personFor",
               "sgPersonFor",
                 { perslidKey: bes_bestelling.perslid_key_voor,
                   label: L("lcl_bes_order_for"),
                   readonly: true,
                   moreinfo: true
                 });
        }

        if (bes_bestelopdr.status == 1)
        { %>
          <tr><td></td><td>
               <input type="checkbox" name="chkproceed" id="chkproceed" value="on" CHECKED><label for="chkproceed"><%=L("lcl_bes_submit_proceed")%></label>
          </td>
          </tr>
<%      }

        FCLTadresselector("levering", "sgAdres",
                        {
                           label: L("lcl_bes_adres_lev"),
                           adresKey:  bes_bestelopdr.mld_adres_key_lev,
                           emptyOption: (bes_bestelopdr.mld_adres_key_lev < 0? null : ""),
                           filtercode: "A",
                           autlevel: authparams.ALGreadlevel
                        }) ;

        FCLTadresselector("factuur", "sgAdres1",
                        {
                           label: L("lcl_bes_adres_fac"),
                           adresKey:  bes_bestelopdr.mld_adres_key_fac,
                           emptyOption: (bes_bestelopdr.mld_adres_key_fac < 0? null : ""),
                           filtercode: "F",
                           autlevel: authparams.ALGreadlevel
                        }) ;
        RWTEXTAREATR("opmerk", "fldtxt", L("lcl_remark"), bes_bestelopdr.opmerking, {html: "rows='3'", suppressEmpty: true}); // Afhandeling, reden niet akkoord
        ROTEXTAREATR("fldtxt", L("lcl_bes_comment"), bes_bestelopdr.delivery_opmerk, {suppressEmpty: true});
        // Hieronder 2 velden van de bestelaanvraag
        if (S("bes_afleverruimte_verplicht") < 2) {
            ROFIELDTR ("fld", L("lcl_bes_del_room"), bes_bestelling.afleverruimte);
        }
        ROTEXTAREATR("fldtxt", L("lcl_bes_bestelling_lev_opm"), bes_bestelling.lev_opm, {suppressEmpty: true} );

        BLOCK_END();

        BLOCK_START("besOpdrAdm", L("lcl_bes_opdralgemeengegevens"), {icon: "fa-question-square"});
        ROFIELDTR("fld", L("lcl_bes_RFOs"), S("bes_bestelling_prefix") + bes_bestelopdr.bes_key_str.join(", "));
        if (bes_bestelopdr.bes_key_str.length == 1)
        {
          // Originele aanvraag weergeven indien aanwezig
          if (bes_bestelling.parent_key)
            ROFIELDTR ("fld", L("lcl_bes_origineel"), S("bes_bestelling_prefix") + bes_bestelling.parent_key);
        }
        ROFIELDTR("fld", L("lcl_bes_Bes_status"), bes_bestelopdr.statustxt);
        ROFIELDTR("fld", L("lcl_bes_Bes_Owner"), bes_bestelopdr.prs_perslid_naam);
        if (this_bestelopdr.canWriteFlags && (S("bes_bestelopdr_flags") > 0))
        {
            var sql = [];
            for (var i = 0; i < S("bes_bestelopdr_flags"); i++)
            {
                sql.push("SELECT " + i + ", "+safe.quoted_sql(L("lcl_bestelopdr_flag" + i)) + " FROM DUAL");
            }
            FCLTselector("besopdrflag",
                         sql.join(" UNION ALL "),
                         { initKey: bes_bestelopdr.flag,
                           label: L("lcl_bestelopdr_flags"),
                           flag: bes_bestelopdr.flag
                         });
        }

        BLOCK_END();

        generateFlexKenmerkCode ({ urole: urole,
                                   bes_key: bes_bestelling.bes_key, // Bestelling key
                                   disc_key: bes_bestelling.dis_key,
                                   kenmerktype: "B",
                                   bestelopdracht: true,
                                   reado: true
                                 });

        BLOCK_START("besOpdrItems", L("lcl_bes_geselecteerd"), { wide: true, nopadding: true, icon: "fa-list" });

        /* is magazijnlocatie gevuld bij een artikel dan tonen we die ook */
        var aantmagloc = 0;
        for (var i = 0; i < bes_bestelopdr.artikel_arr.length; i++)
        {
             if (bes_bestelopdr.artikel_arr[i].bes_mag_loc)
               aantmagloc++;
        }
%>
        <tr>
            <th><%=L("lcl_bes_srtdeel_nr")%></th>
            <th><%=L("lcl_bes_discipline")%></th>
            <th><%=L("lcl_bes_srtdeel")%></th>
            <th style="text-align:right"><%=L("lcl_bes_amount")%></th>
            <th style="text-align:right"><%=L("lcl_bes_Price") + " " + (bes_bestelopdr.inclBTW? L("lcl_shared_inclBTW") : L("lcl_shared_exclBTW"))%></th>
            <% if (aantmagloc > 0) { %>
              <th><%=L("lcl_bes_notitie")%></th>
            <%}%>
            <th><%=L("lcl_bes_item_comment")%></th>
        </tr>
<%

        for (var i = 0; i < bes_bestelopdr.artikel_arr.length; i++)
        { %>
          <tr>
              <td><%=safe.html(bes_bestelopdr.artikel_arr[i].artikelnr)%></td>
              <td><%=safe.html(bes_bestelopdr.artikel_arr[i].catalogus_omschr)%></td>
              <td><%=safe.html(bes_bestelopdr.artikel_arr[i].omschr)%></td>
              <td align="right">
                  <input type="text" maxlength="5" style="text-align:right" onBlur="recalcPrice(<%=i+1%>);"
                   id="cnt<%=i+1%>" class="fld fld_dlvrnr" name="cnt<%=i+1%>" value="<%=bes_bestelopdr.artikel_arr[i].aantal%>"
                   aantalontv="<%=bes_bestelopdr.artikel_arr[i].aantalontv%>">
                  <input type='hidden' id='am<%=i+1%>' name='am<%=i+1%>' value='<%=bes_bestelopdr.artikel_arr[i].aantal%>'>
                  <input type='hidden' id='max<%=i+1%>' name='max<%=i+1%>' value='<%=bes_bestelopdr.artikel_arr[i].aantal%>'>
                  <input type='hidden' id='pr<%=i+1%>' name='pr<%=i+1%>' value='<%=safe.jsfloat(bes_bestelopdr.artikel_arr[i].item_prijs)%>'>
                  <input type='hidden' id='ikey<%=i+1%>' name='ikey<%=i+1%>' value='<%=bes_bestelopdr.artikel_arr[i].item_key%>'>
              </td>
              <td id="price<%=i+1%>" align="right"><%=safe.curr(bes_bestelopdr.artikel_arr[i].prijs)%></td>
              <% if (aantmagloc > 0) { %>
                <td><%=safe.html(bes_bestelopdr.artikel_arr[i].bes_mag_loc)%></td>
              <%}%>
              <td><input type="text" id="opm<%=i+1%>" name="opm<%=i+1%>" maxlength="100" class="fld" value="<%=safe.html(bes_bestelopdr.artikel_arr[i].opmerk)%>"></td>
          </tr>
<%      }
        var total = bes_bestelopdr.totaal - bes_bestelopdr.korting + bes_bestelopdr.levkosten;
%>

<%      if (bes_bestelopdr.korting > 0)
        { %>
          <tr>
              <td colspan="4"><label><%=L("lcl_bes_order_discount")%></label></td>
              <td align="right">
                <span><%=safe.curr(bes_bestelopdr.korting * -1)%></span>
              </td>
          </tr>
<%      } %>

<%      if (bes_bestelopdr.levkosten > 0)
        { %>
          <tr>
              <td align="left" colspan="4"><label><%=L("lcl_bes_tpcosts")%></label></td>
              <td align="right">
                <span><%=safe.curr(bes_bestelopdr.levkosten)%></span>
              </td>
          </tr>
<%      } %>

        <tr class="besitemstotal">
            <td align="left" colspan="4"><label for="total_txt"><%=L("lcl_Total")%></label></td>
            <td align="right">
                <input type="text" style="text-align:right" readonly class="fld disabled"  id='total_txt' name='total_txt'
                       value='<%=safe.curr(total)%>'>
            </td>
        </tr>
        <input type='hidden' id='itemregels' name='itemregels' value='<%=bes_bestelopdr.artikel_arr.length%>'>
        <input type='hidden' id='total' name='total' value='<%=safe.jsfloat(total)%>'>
<%
        BLOCK_END();
%>

<% IFACE.FORM_END(); %>
      </form>
    <% SUBFRAME_END(); %>
  </body>
</html>
<% ASPPAGE_END(); %>
