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

     File:               fin_search.asp
     Description:        Filterscherm voor overzicht facturen
     Parameters:         finnum               Factuurnummer
                         fin_bron_key         Factuur bron
                         fin_type             Factuurtype
                         opdr_key             Opdracht key
                         status               Status
                         debtor               Eigen debiteurnummer
     Globals:
     Context:
     Note:               TODO We zouden de status listbox nog als checkboxen kunnen maken..

*/ %>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/bedrijfselector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/plaatsselector.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/xd.inc" -->
<!-- #include file="fin.inc" -->
<%
FCLTHeader.Requires({ plugins:["jQuery", "kenmerk"] });


/***** Get webform parameters *****/
// Je komt bij FIN niet binnen met een bepaalde rol (urole).

var date_from = getQParamDate("date_from", null);
var date_to = getQParamDate("date_to", null);
var today = new Date ();
//var date_from = (date_from == ""? today : new Date(parseInt(date_from, 10)));
//var date_to = (date_to == ""? today : new Date(parseInt(date_to, 10)));
var dateFromInitEmpty = true;
var dateToInitEmpty = true;
if (date_from)
{
  dateFromInitEmpty = false;
}
if (date_to)
{
  dateToInitEmpty = false;
}

var finnum = getQParam("finnum", ""); // Factuurnummer
var fin_bron_key = getQParamInt("fin_bron_key", -1); // Factuurbron Handmatig/Excel/Mail
var fin_type = getQParam("fin_type", -1); // Factuurtype "O", "B" of "C"
var opdrnr = getQParam("opdrnr", -1); // Opdrachtnummer
var finstatus = getQParamInt("finstatus", -1); // Factuurstatus
var debtor = getQParam("debtor", -1); // Eigen debiteurnummer
var handler_key = getQParamInt("handler_key", -1); // Uitvoerende
var goedkeurder_key = getQParamInt("goedkeurder_key", -1); // Goedkeurderd
var budh_key = getQParamInt("budh_key", -1); // Default budgethouder (dummy als ik alleen mijn kps mag zien)
var kpgrp_key_arr = getQParamIntArray("kpgrp_key", [-1]); // Kostenplaatsgroep.
var autosearch = getQParamInt("autosearch", 0) == 1; // Direct lijst tonen
var reg_key = getQParamInt("regio_key", -1); // Regio
var dis_key = getQParamInt("district_key", -1); // District
var loc_key = getQParamInt("locatie_key", -1); // Locatie
var bld_key = getQParamInt("gebouw_key", -1); // Gebouw
var verantw_key = getQParamInt("verantw", -1); // Gebouw verantwoordelijke
var alg_startlevel = getQParamInt("alg_startlevel", 1); // Startlevel van plaatsselector (Regio/Locatie)

var fin_actual = getQParamInt("fin_actual", 1) == 1; // Standaard aangevinkt indien niet meegegeven
var fin_deleted = getQParamInt("fin_deleted", 0) == 1; // Standaard niet aangevinkt indien niet meegegeven
// minimaal één van beiden moet aangekruist zijn
if (!fin_actual && !fin_deleted)
  fin_actual = true;

if (finstatus == -1 && finnum == "" && opdrnr == -1)
{
  finstatus = 2; // Ingevoerd;
}
/***** End get webform parameters *****/

// Alleen PRSreadlevel en PRSwritelevel van belang want fac_functie_min_level = 7 (lezen en schrijven organisatie)
var authparamsEXTFIN = user.checkAutorisation("WEB_EXTORD", true);
var authparamsFINFOF = user.checkAutorisation("WEB_FINFOF", true);
var authparamsFINBOF = user.checkAutorisation("WEB_FINBOF", true);
var authparamsMLDFIN = user.checkAutorisation("WEB_MLDFIN", true);

user.auth_required_or_abort((user.iamContact() && authparamsEXTFIN) || authparamsFINFOF || authparamsFINBOF || user.isBudgethouder());

// Ik ken 2 varianten: allemaal of alleen de mijne.
var alleenmijnkostenplaatsen = (!(user.iamContact() && authparamsEXTFIN) && !authparamsFINFOF && !authparamsFINBOF && !authparamsMLDFIN);  // geen EXTFIN + contactpers, FINFOF, FINBOF of MLDFIN -> budgethouder.

// Fast check to see if we have more than one costcentregroup
sql= "SELECT 1 FROM (SELECT COUNT (prs_kostenplaatsgrp_key) aantal FROM prs_kostenplaatsgrp) WHERE aantal > 1";
oRs = Oracle.Execute(sql);
var anykpngrp = !oRs.eof;
oRs.close();
%>

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

    <script language=JavaScript>
      function checkboxStatus()
      {
        if (!document.getElementById("fin_actual").checked && !document.getElementById("fin_deleted").checked )
          document.getElementById("fin_actual").checked = true;
      }

<% if (xd.enabled()) { %>
      function xdclicked()
      {
        var doxd = document.getElementById("xd").checked;
        $(".noxd").toggle(!doxd);
        $(".onlyxd").toggleClass('hidden', !doxd);
      }

<% } %>
      // Altijd kenmerken. Niet afhankelijk van backoffice rol
      function doSubmit()
      {
<% if (xd.enabled()) { %>
        if ($("#xd").is(":checked"))
        {
              $("form[name=u2]").attr("action", "fin_search_list_xd.asp");
        } else {
              $("form[name=u2]").attr("action", "fin_search_list.asp");
        }
<% } %>
        // Submitten met kenmerken
        doSubmitWithKenmerken(); // kenmerken niet afhankelijk van een discipline of factuurtype of zo.
      }

      async function myModal(init)
      {
        // kenmerken niet afhankelijk van een discipline of factuurtype of zo.
        var key = 0;
        var url = "load_kenmerk.asp?advanced=1&hasFilter=1&kenmerk_niveau=F";
        var titel = L("lcl_fin_kenmerken");
        await showKenmerkModal(url, titel, init)
      }

<%    if (autosearch)
      { %>
        window.afterfiltersready = function () { doSubmit() };
<%    } %>

      // Controleer invoer "Factuurbedrag boven". Is het een number?
      function checksumover()
      {
        var sumover = parseFloat($("#sumover").val().replace(',', '.'));
        if (isNaN(sumover))
          sumover = 0;
        if ($("#sumover").val() != '' && !isNaN(sumover))
          $("#sumover").val(num2currEditable(sumover));
      }

      // Controleer invoer "Factuurbedrag onder". Is het een number?
      function checksumbelow()
      {
        var sumbelow = parseFloat($("#sumbelow").val().replace(',', '.'));
        if (isNaN(sumbelow))
          sumbelow = 0;
        if ($("#sumbelow").val() != '' && !isNaN(sumbelow))
          $("#sumbelow").val(num2currEditable(sumbelow));
      }
    </script>
  </head>

  <body id="searchbody">
    <form name="u2" target="workFrame" action="fin_search_list.asp" method="get">
      <% SEARCH_PAGE_START({ header: L("lcl_filterblok") }); %>
        <% SEARCH_BLOCK_START();%>
<%
            if (xd.enabled())
                RWCHECKBOXTR("xd", "fldxd", L("lcl_xd_crossdomain"), false, {html: "onclick='xdclicked()'"});
%>
            <!-- Factuurnummer -->
            <tr class="primsearch">
              <td class="label"><label for="finnum"><%=L("lcl_fin_number")%></label></td>
              <td>
                <input type="text" class="fldshort" name="finnum" <%=(finnum != -1) ? "value='" + safe.htmlattr(finnum) + "'" : ""%>>
              </td>
            </tr>

<%            <!-- Datum van -->
              FCLTcalendar( "findate_from",
                            { label: L("lcl_period_from"),
                              initEmpty: dateFromInitEmpty,
                              trclass: "primseach",
                              datum: date_from,
                              volgnr: 1
                            });
              <!-- Datum tot -->
              FCLTcalendar( "findate_to",
                            { label: L("lcl_period_to"),
                              initEmpty: dateToInitEmpty,
                              trclass:"primsearch",
                              datum: date_to,
                              volgnr: 2
                            });

%>            <!-- Uitvoerende -->
              <tr class="primsearch onlyxd hidden">
                <td class="label"><label for="uitvoerendetekst"><%=L("lcl_handler")%></label></td>
                <td>
                  <input type="text" class="fld wildcard" name="uitvoerendetekst" value="">
                </td>
              </tr>
<%            FCLTbedrijfselector("handler","handler",
                                  { companyKey: handler_key,
                                    label: L("lcl_handler"),
                                    filtercode: ((user.iamContact() && authparamsEXTFIN) && !authparamsFINFOF && !authparamsFINBOF? "CP" : "X"),
                                    trclass:"primsearch noxd",
                                    emptyOption: "",
                                    whenEmpty: L("lcl_search_generic")
                                  });
              if (S("fin_enable_goedkeuren") != 0)
              {
%>              <!-- Goedkeurder -->
                <tr class="primsearch onlyxd hidden">
                  <td class="label"><label for="goedkeurdertekst"><%=L("lcl_fin_goedkeurder")%></label></td>
                  <td>
                    <input type="text" class="fld wildcard" name="goedkeurdertekst" value="">
                  </td>
                </tr>
<%              // Alleen de goedkeurders.
                FCLTpersoonselector("goedkeurder",
                                    "sgGoedkeurder",
                                    { perslidKey: goedkeurder_key,
                                      label: L("lcl_fin_goedkeurder"),
                                      filtercode: "FING", // Goedkeurder.
                                      trclass: "primsearch noxd",
                                      // autlevel hoeft niet meegegeven te worden omdat FIN geen PRS rechten heeft. FCLTpersoonselector neemt dan -1 voor autlevel.
                                      emptyOption: "",
                                      whenEmpty: L("lcl_search_generic")
                                    });
              }
%>

            <!-- Eigen debiteurennummer -->
            <tr class="primsearch">
              <td class="label"><nobr><label for="debtor"><%=L("lcl_fin_debtor_nr")%></label></nobr></td>
              <td>
                <input type="text" class="fldshort" name="debtor" <%=(debtor != -1) ? "value='" + safe.htmlattr(debtor) + "'" : ""%>>
              </td>
            </tr>

            <!-- Actuele en verwijderde facturen -->
<%
            sql =        "SELECT 0, " + safe.quoted_sql(fin.getfinbrontext(0)) + " FROM DUAL"
                + " UNION SELECT 1, " + safe.quoted_sql(fin.getfinbrontext(1)) + " FROM DUAL"
                + " UNION SELECT 2, " + safe.quoted_sql(fin.getfinbrontext(2)) + " FROM DUAL";
            FCLTselector("finbron",
                         sql,
                         { initKey: fin_bron_key,
                           label: L("lcl_fin_invoice_source"),
                           trclass: "primsearch",
                           emptyOption: ""
                         });

              <!-- status -->
              sql = "SELECT         1, " + safe.quoted_sql(fin.getfinstatustext(1)) + " FROM DUAL"
                  + " UNION SELECT  2, " + safe.quoted_sql(fin.getfinstatustext(2)) + " FROM DUAL"
                  + " UNION SELECT  3, " + safe.quoted_sql(fin.getfinstatustext(3)) + " FROM DUAL"
                  + " UNION SELECT  5, " + safe.quoted_sql(fin.getfinstatustext(5)) + " FROM DUAL"
                  + " UNION SELECT  6, " + safe.quoted_sql(fin.getfinstatustext(6)) + " FROM DUAL"
                  + " UNION SELECT  7, " + safe.quoted_sql(fin.getfinstatustext(7)) + " FROM DUAL"
                  + " ORDER BY 1";
              FCLTselector("finstatus",
                           sql,
                           { initKey: finstatus,
                             label: L("lcl_fin_fin_status"),
                             trclass: "primsearch",
                             emptyOption: ""
                           });
%>
              <tr class="primsearch">
                <td class="label"><label><%=L("lcl_show")%></label></td>
                <td>
                  <input type="checkbox" class="fldfinactual" name="fin_actual" id="fin_actual" onClick="checkboxStatus()" value="1" <%=fin_actual? "checked" : ""%>>
                  <label for="fin_actual"><%=L("lcl_fin_show_actual")%></label>
                  <input type="checkbox" class="fldfindeleted" name="fin_deleted" id="fin_deleted" onClick="checkboxStatus()" value="1" <%=fin_deleted? "checked" : ""%>>
                  <label for="fin_deleted"><%=L("lcl_fin_show_deleted")%></label>
                </td>
              </tr>
<%
            if (S("fin_factuur_flags") > 1) // Flags checkboxen -->
            {
                for (flagkey=0; flagkey < S("fin_factuur_flags"); flagkey++)
                {
                    var label = "<label for='flag" + flagkey + "'>"
                              + "  <span class='finflag" + flagkey + " fins'>"
                              +      I("fa-fclt-flag" + (flagkey == 0 ? "0" : ""))
                              + "  </span> " + safe.html(L("lcl_fin_flag" + flagkey))
                              + "</label>";
                    RWCHECKBOXTR("flag" + flagkey, "fldcheck", (flagkey == 0 ? L("lcl_fin_flags") : ""), 1, { twocols: true, posthtml: label });
                }
            }
            SEARCH_BLOCK_END();
            SEARCH_BLOCK_START();
            // Factuurtype
              sql = "SELECT 'O'"
                  + ", " + safe.quoted_sql(L("lcl_fin_opdrachten")) + " FROM DUAL"
                  + " UNION"
                  + " SELECT 'C'"
                  + ", " + safe.quoted_sql(L("lcl_fin_contracten"))
                  + " FROM DUAL"
                  + " UNION"
                  + " SELECT 'B'"
                  + ", " + safe.quoted_sql(L("lcl_fin_bestellingen"))
                  + " FROM DUAL"
                  + " ORDER BY 2"
              FCLTselector("fintype",
                           sql,
                           { initKey: fin_type,
                             label: L("lcl_fin_factuur_type"),
                             trclass: "primsearch",
                             emptyOption: ""
                           })

              if (authparamsFINFOF || authparamsFINBOF)
              {
                var ALGreadlevel = 9;
                if (authparamsFINFOF) {
                  ALGreadlevel = Math.min(ALGreadlevel, authparamsFINFOF.ALGreadlevel);
                }
                if (authparamsFINBOF) {
                  ALGreadlevel = Math.min(ALGreadlevel, authparamsFINBOF.ALGreadlevel);
                }

                // Locatie/gebouw
                FCLTplaatsselector(ALGreadlevel,
                                   { regiokey: reg_key,
                                     districtkey: dis_key,
                                     locatiekey: loc_key,
                                     gebouwkey: bld_key,
                                     startlevel: alg_startlevel,
                                     eindlevel: 3, // gebouw
                                     terrein: true,
                                     trclass: "noxd",
                                     whenEmpty: L("lcl_search_generic"),  // want filter
                                     filtercode: "EXP"
                                   });
              }
%>
              <!-- Gebouw verantwoordelijke -->
<%            // Dit veld is alleen zichtbaar indien er minimaal één gebouwverantwoordelijke geconfigureerd is (suppressNoValues).
              FCLTpersoonselector("verantw",
                              "sgVerantw",
                              { perslidKey: verantw_key,
                                label: L("lcl_bld_ter_verantw"),
                                filtercode: "GTV", // Gebouw Verantwoordelijke
                                trclass: "primsearch noxd",
                                suppressNoValues: true,
                                whenEmpty: L("lcl_search_generic")  // want filter
                              });
%>

              <!-- Opdrachtnummer -->
              <tr class="primsearch noxd">
                <td class="label"><label for="opdrnr"><%=L("lcl_fin_opdrachtnr")%></label></td>
                <td>
                  <input type="text" class="fldshort" name="opdrnr" <%=(opdrnr != -1) ? "value='" + safe.htmlattr(opdrnr) + "'" : ""%>>
                </td>
              </tr>
              <tr class="primsearch onlyxd hidden">
                <td class="label"><label for="budgethoudertekst"><%=L("lcl_prs_budgethouder")%></label></td>
                <td>
                  <input type="text" class="fld wildcard" name="budgethoudertekst" value="">
                </td>
              </tr>
<%
              // Persoon
              FCLTpersoonselector("budh_key", // budgethouders
                                  "sgPerson",
                                  { perslidKey: alleenmijnkostenplaatsen? user_key : budh_key,
                                    label: L("lcl_prs_budgethouder"),
                                    filtercode: "BUD",
                                    readonly: alleenmijnkostenplaatsen,
                                    trclass: "primsearch noxd",
                                    whenEmpty: L("lcl_search_generic")  // want filter
                                  });
              if (anykpngrp)
              {
              // Kostenplaatsgroep.
                  sql = "SELECT prs_kostenplaatsgrp_key"
                      + "     , DECODE (prs_kostenplaatsgrp_nr, NULL, '', prs_kostenplaatsgrp_nr || ' - ') || prs_kostenplaatsgrp_oms oms"
                      + "  FROM prs_kostenplaatsgrp";
                  FCLTselector("kpgrp_key",
                               sql,
                               { initKey: kpgrp_key_arr.join(","),
                                 label: L("lcl_prs_kostenpl_group"),
                                 trclass: "primsearch noxd",
                                 emptyOption: "",
                                 multi: true,
                                 initEmpty: true
                               });
               }

              // Factuurbedrag boven
              RWFIELDTR("sumover",
                        "fldshort",
                        L("lcl_fin_bedrag_boven") + " " + S("currency_pref"),
                        "",
                        { datatype: "currency",
                          trclass: "primsearch",
                          maxlength: 9,
                          html: 'onBlur="checksumover()"'
                        });

              // Factuurbedrag onder
              RWFIELDTR("sumbelow",
                        "fldshort",
                        L("lcl_fin_bedrag_onder") + " " + S("currency_pref"),
                        "",
                        { datatype: "currency",
                          trclass: "primsearch",
                          maxlength: 9,
                          html: 'onBlur="checksumbelow()"'
                        });
%>
            </table>
          </td><!-- end column 2 -->
        </tr>
<%      SEARCH_BLOCK_END();

        var buttons = [];
        buttons.push ( {title: L("lcl_overview_list"),  action: "doSubmit()", importance: 1, icon: "fa-clipboard-list" } ); // Overzicht
        buttons.push ( {title: L("lcl_shared_advanced"),  action: "myModal()", xclass: "noxd", importance: 3, icon: "fa-filter" } );
        SIMPLE_BLOCK_START();
          CreateButtons(buttons, { entersubmit: true, showIcons: true} );
        SIMPLE_BLOCK_END();

        SEARCH_PAGE_END(); %>
      </form>
    <div id="result">
      <iframe width="100%" src="../Shared/empty.asp" name="workFrame" id="workFrame" frameborder="0"
              onload='FcltMgr.iframeLoaded(this)'
              scrolling="no" framespacing='0'>
      </iframe>
    </div>

  </body>
</html>
<% ASPPAGE_END(); %>
