    <% /*
     $Revision$
     $Id$
     File:               bes_list.inc
     Description:        Show an overview of orders in list-form,
                        which meets with the given requirements
     Parameters:
         urole           user role (fe, fo, bo, mi)
         outputmode      behave in an output mode, print to 0 = screen, 1 = printer, 2 = excel, etc.
         showall         show all orders which meets with the given requirements
         rfo_key         search for orders with the given rfo/order key
         datefrom        search for orders at the selected date-month-year
         dateto          search for orders at the selected date-month-year
         catalogus_key   search for orders with the given catalogus key (discipline key)
         besgroep_key    search for orders with the given groep key (srtgroup key)
         item_key        search for orders with the given item key (srtdeel key)
         supplier_key    search for orders with the given supplier key
         groupbes        groupbes the orders by
         groupbes2       groupbes2 the orders by
         requestor_key   search for orders for selected requestor
         personfor_key   search for orders for person
         company_key     search for orders for the selected company
         dep_key         search for orders for the selected department
         kp              search for orders with the given account text in account description
         item            search for orders with the given account text in item description
         besstafg        search for orders with the status besstafg
         besstnew        search for orders with the status besstnew
         besstfia        search for orders with the status besstfia
         besstacc        search for orders with the status besstacc
         besstbes        search for orders with the status besstbes
         besstlev        search for orders with the status besstlev
         besstver        search for orders with the status besstver
         besstann        search for orders with the status besstann
         besordstafg     search for orders with the status besordstafg
         besordstnew     search for orders with the status besordstnew
         besordstbeh     search for orders with the status besordstbeh
         besordstbes     search for orders with the status besordstbes
         besordstbev     search for orders with the status besordstbev
         besordstlev     search for orders with the status besordstlev
         besordstver     search for orders with the status besordstver
         mld_key         bestellingen met deze mld_melding_key
     Context:            Search action from bes_search.asp form
     Note:

 // KNOWN ISSUES:   20-8-2004 15:06/PF          PLEASE READ
 //
 // A We check the WRITE authorization for a Catalogue to display. This should be READ, and
 //   we must add(query) per row whether we have WRITE access for that row,
 //   to enable/disable the buttons
 // B We must check prslevel PER DISCIPLINE. Now we check
 //
 // Dit betekent dus nu:
 // - je moet schrijfrechten (BO/FO) op een catalogus hebben om een bestelling ervan te kunnen
 //   zien; je kunt die dan ook behandelen. Readonly aanbieden van bestelaanvragen wordt nu niet
 //   ondersteund.
 // - als ik voor EEN catalogus rechten heb voor een organisatieonderdeel, zie ik de bestellingen van
 //   al mijn catalogus voor dat organisatieonderdeel.
 //
*/ %>

<!-- #include file="../Shared/discx3d.inc" -->
<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/getkenmerksql.inc" -->
<!-- #include file="../Shared/rater.inc" -->
<!-- #include file="bes.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["../BES/bes_list.js", "jquery-ui.js"]
                    });

function bes_list (pautfunction, params)
{
  // Valid and supported parameters are:
  // params.urole         : the usuals two-letter lowercase string
  // params.outputmode    : print to 0 = screen, 1 = printer, 2 = excel, etc.
  // params.showall       : boolean (true | false)
  // params.rfo_key       : key
  // params.datefrom      : date
  // params.dateto        : date
  // params.catalogus_key : key
  // params.besgroep_key  : key
  // params.item_key      : key
  // params.supplier_key  : key
  // params.groupbes      : key
  // params.groupbes2     : key
  // params.requestor_key : key
  // params.personfor_key : key
  // params.company_key   : key
  // params.dep_key       : key
  // params.kp            : wildcard string
  // params.item          : wildcard string
  // params.besstafg      : boolean (true | false)
  // params.besstnew      : boolean (true | false)
  // params.besstfia      : boolean (true | false)
  // params.besstacc      : boolean (true | false)
  // params.besstbes      : boolean (true | false)
  // params.besstlev      : boolean (true | false)
  // params.besstver      : boolean (true | false)
  // params.besstann      : boolean (true | false)
  // params.besordstafg   : boolean (true | false)
  // params.besordstnew   : boolean (true | false)
  // params.besordstbeh   : boolean (true | false)
  // params.besordstbes   : boolean (true | false)
  // params.besordstbev   : boolean (true | false)
  // params.besordstlev   : boolean (true | false)
  // params.besordstver   : boolean (true | false)

  var authparams = user.checkAutorisation(pautfunction);

  var urole = params.urole;
  var fronto = (urole == "fo");
  var backo = (urole == "bo");
  var minfo = (urole == "mi"); // NOT APPLICABLE?
  var frontend = (urole == "fe" || (!fronto & !backo & !minfo));

  // Voor resulttable de globalen zetten; zou ng anders moeten.
  var outputmode = params.outputmode; // print to 0 = screen, 1 = printer, 2 = excel, etc.
  var print = (outputmode == 1 || outputmode == 5);
  var excel = (outputmode == 2 || outputmode == 6);
  var showall = params.showall;

  var rfo_key = params.rfo_key;
  //var rfo_status_str = params.rfo_status_str;
  var datefrom = params.datefrom;
  var dateto = params.dateto;
  var catalogus_key = params.catalogus_key;
  var besgroep_key = params.besgroep_key;
  var item_key = params.item_key;
  var supplier_key = params.supplier_key;
  var groupbes = params.groupbes;
  var groupbes2 = params.groupbes2;
  if (groupbes == 12) // geen groepering?
    groupbes2 = null; // Dan zeker geen niveau 2
  var requestor_key = params.requestor_key;
  var personfor_key = params.personfor_key;
  var company_key = params.company_key;
  var dep_key = params.dep_key;
  var kp = params.kp;
  var item = params.item;
  var besstafg = params.besstafg;
  var besstnew = params.besstnew;
  var besstfia = params.besstfia;
  var besstacc = params.besstacc;
  var besstbes = params.besstbes;
  var besstlev = params.besstlev;
  var besstver = params.besstver;
  var besstann = params.besstann;
  var besordstafg = params.besordstafg;
  var besordstnew = params.besordstnew;
  var besordstbeh = params.besordstbeh;
  var besordstbes = params.besordstbes;
  var besordstbev = params.besordstbev;
  var besordstlev = params.besordstlev;
  var besordstver = params.besordstver;

  var showbesstatus = "";
  if (besstafg) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "1";
  if (besstnew) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "2";
  if (besstfia) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "3";
  if (besstacc) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "4";
  if (besstbes) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "5";
  if (besstlev) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "6";
  if (besstver) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "7";
  if (besstann) showbesstatus = (showbesstatus == ""? "" : showbesstatus + ",") + "8";

  var showordstatus = "";
  if (besordstafg) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "1";
  if (besordstnew) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "2";
  if (besordstbeh) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "3";
  if (besordstbes) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "4";
  if (besordstbev) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "5";
  if (besordstlev) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "6";
  if (besordstver) showordstatus = (showordstatus == ""? "" : showordstatus + ",") + "7";

%>

  <html>
    <head>
<%    FCLTHeader.Generate({ outputmode: outputmode }); %>
      <script type="text/javascript">
        // Text strings used by bes_list.js
        urole = "<%=urole%>";
        bes_bestelling_prefix = "<%=S("bes_bestelling_prefix")%>";
        bes_bestelopdr_prefix = "<%=S("bes_bestelopdr_prefix")%>";
      </script>
    </head>
    <body id="listbody">
<%
      /******************************************
       * General Callback functies ResultsetTable
       *****************************************/

      function fncolBesNr(oRs)
      { // Eigenlijk wil je een markering bij de parent, niet bij het child TODO
        return S("bes_bestelling_prefix") + (oRs.fields("bes_bestelling_parentkey").value > 0 ? oRs.fields("bes_bestelling_parentkey").value + "*" : oRs.fields("bes_bestelling_key").value);
      }

      function fncolOordeel(oRs)
      {
        var result = null;
        var displ_val = oRs("oordeel").Value;
        var displ_txt = oRs("oordeel_opm").Value;
        if (displ_val)
        {
          if (excel || print)
            result = "<span id='oordeel' title='" + safe.htmlattr(displ_txt)+"'>" + displ_val + "</span>";
          else
            result = rating.stars(displ_val, {rating: {id: "oordeel", note: displ_txt}});
        }
        return result;
      }

      function fncolOordeelAvg(oRs)
      {
        var result = null;
        var displ_val = oRs("oordeel").Value;
        if (displ_val && displ_val != 0)
        {
          if (excel || print)
            result = "<span id='oordeel'>" + safe.displayfloat(displ_val, 1) + "</span>";
          else
            result = rater(displ_val, {readonly: true});
        }
        return result;
      }

      /**********************************************
       * End general Callback functies ResultsetTable
       *********************************************/

      // Algemene functie voor FrontOffice, BackOffice en Management Info
      // Maakt filter sql voor Catalogus, Group en Item filters
      function makeDisGroepItemsSql(pcatalogus_key, pgroep_key, pitem_key, pitem)
      {
        var sqlDGI = "";
        if (pcatalogus_key || pgroep_key || pitem_key)
        {
          sqlDGI = (minfo && (groupbes == 1 || groupbes == 6) // Management Info Opdrachten
                   ? " AND bo.bes_bestelopdr_key IN"
                     + " (SELECT bes_bestelopdr_key"
                     + " FROM bes_bestelopdr_item boi"
                     + ", bes_bestelling_item bi"
                     + " WHERE bi.bes_bestelopdr_item_key = boi.bes_bestelopdr_item_key"
                   : " AND b.bes_bestelling_key IN"
                     + " (SELECT bes_bestelling_key" // FrontOffice, BackoOffice en Management Info Aanvragen
                     + " FROM bes_bestelling_item"
                     + " WHERE 1 = 1");

          if (pitem_key) // Item filter
          {
            sqlDGI += " AND bes_srtdeel_key = " + pitem_key
                    + ((pitem && (fronto || backo))
                      ? " AND bes_srtdeel_key IN"
                        + " (SELECT bes_srtdeel_key"
                        + " FROM bes_srtdeel"
                        + " WHERE UPPER(bes_srtdeel_omschrijving) LIKE " + safe.quoted_sql_wild("%" + pitem + "%")
                        + ")"
                      : "")
                    + ")";
          }
          else
          {
            if (pgroep_key) // Groep filter
            {
              sqlDGI += " AND bes_srtdeel_key IN"
                        + " (SELECT bes_srtdeel_key"
                        + " FROM bes_srtdeel"
                        + " WHERE bes_srtgroep_key = " + pgroep_key
                        + ((pitem && (fronto || backo))
                           ? " AND UPPER(bes_srtdeel_omschrijving) LIKE " + safe.quoted_sql_wild("%" + pitem + "%")
                           : "")
                        + "))";
            }
            else
            {
              if (pcatalogus_key) // Catalogus filter
              {
                sqlDGI += " AND bes_srtdeel_key IN"
                          + " (SELECT bes_srtdeel_key"
                          + " FROM bes_srtdeel"
                          + " WHERE bes_srtgroep_key IN"
                            + " (SELECT bes_srtgroep_key"
                            + " FROM BES_v_aanwezigsrtgroep"
                            + " WHERE ins_discipline_key = " + pcatalogus_key
                            + ")"
                            + ((pitem && (fronto || backo))
                               ? " AND UPPER(bes_srtdeel_omschrijving) LIKE " + safe.quoted_sql_wild("%" + pitem + "%")
                               : "")
                            + "))";
              }
            }
          }
        }
        return sqlDGI;
      }

      function makeDisGroepItemsFilter(pcatalogus_key, pgroep_key, pitem_key, pitem)
      {
        var filterDGI = "";
        if (pitem_key) // Item filter
        {
          filterDGI = " AND srt.bes_srtdeel_key = " + pitem_key;
        }
        else
        {
          if (pgroep_key) // Groep filter
          {
            filterDGI = " AND grp.bes_srtgroep_key = " + pgroep_key;
          }
          else
          {
            if (pcatalogus_key) // Catalogus filter
            {
              filterDGI = " AND dis.ins_discipline_key = " + pcatalogus_key;
            }
          }
        }
        return filterDGI;
      }


      // Management Info
      if (minfo) // Management Info
      {
        var sql_date = null;
        if (datefrom && dateto)
        {
          var ora_date1 = datefrom.beginToSQL();
          var ora_date2 = dateto.endToSQL();
          sql_date = " BETWEEN " + ora_date1 + " AND " + ora_date2;
        }
        else if (datefrom)
        {
          var ora_date1 = datefrom.beginToSQL();
          sql_date = " >= " + ora_date1;
        }
        else if (dateto)
        {
          var ora_date2 = dateto.endToSQL();
          sql_date = " < " + ora_date2;
        }

        // Embargo bestellingen uitsluiten (als er eentje met parent is, willen we die zonder niet zien).
        var sql_filter = " AND NOT EXISTS (SELECT b1.bes_bestelling_key"
                       + "                   FROM bes_bestelling b1"
                       + "                  WHERE bes_bestelling_parentkey = b.bes_bestelling_key)";

        if (params.mld_key)
            sql_filter += " AND b.mld_melding_key = " + params.mld_key;

        if ((groupbes == 12) || (groupbes == 0) || (groupbes == 2) || (groupbes == 3) ||
            (groupbes == 4) || (groupbes == 5) || (groupbes == 7) ||
            (groupbes == 8) || (groupbes == 10) || (groupbes == 11))
        {
          if (rfo_key)
          { // JGL: TRAAG!!!!
            sql_filter += " AND COALESCE(b.bes_bestelling_parentkey, b.bes_bestelling_key) = " + rfo_key;
          }
          else
          {
            if (showbesstatus)
              sql_filter += " AND b.bes_bestelling_status IN (" + showbesstatus + ")";
            if (showordstatus || supplier_key)
            {
              sql_filter += " AND b.bes_bestelling_key IN"
                            + " (SELECT bes_bestelling_key"
                            + " FROM bes_bestelling_item bi"
                            + " WHERE"
              if (showordstatus)
              {
                sql_filter += " bes_bestelopdr_item_key IN"
                              + " (SELECT bes_bestelopdr_item_key"
                              + " FROM bes_bestelopdr bo"
                              + ", bes_bestelopdr_item boi"
                              + " WHERE bo.bes_bestelopdr_key = boi.bes_bestelopdr_key"
                              + " AND bes_bestelopdr_status IN (" + showordstatus + ")";
                if (supplier_key)
                  sql_filter += " AND bo.prs_bedrijf_key = " + supplier_key;
                sql_filter += "))";
              }
              else // supplier_key aanwezig
              {
                sql_filter += " bes_bestelopdr_item_key IN"
                              + " (SELECT bes_bestelopdr_item_key"
                              + " FROM bes_bestelopdr bo"
                              + ", bes_bestelopdr_item boi"
                              + " WHERE bo.bes_bestelopdr_key = boi.bes_bestelopdr_key"
                              + " AND  bo.prs_bedrijf_key = " + supplier_key + "))";
              }
            }

            if (requestor_key)
                   sql_filter += " AND b.prs_perslid_key = " + requestor_key;

            if (personfor_key)
                   sql_filter += " AND b.prs_perslid_key_voor = " + personfor_key;

            if (dep_key)
            {
              // Net als bij opdr_list.inc zoeken over alle afdelingen.
              sql_filter += " AND p.prs_afdeling_key IN"
                            + " (SELECT a.prs_afdeling_key"
                            + " FROM prs_v_afdeling_familie a"
                            + " WHERE a.prs_afdeling_elder_key = " + dep_key + ")";
            }

            if (company_key)
              sql_filter += " AND boom.prs_bedrijf_key = " + company_key;

            if (kp)
              sql_filter += " AND (SELECT UPPER(k.prs_kostenplaats_nr)"
                            + " FROM prs_kostenplaats k"
                            + " WHERE k.prs_kostenplaats_key = b.prs_kostenplaats_key)"
                            + " LIKE " + safe.quoted_sql_wild(kp);

            sql_filter += makeDisGroepItemsSql(catalogus_key, besgroep_key, item_key);

            if (sql_date)
              sql_filter += " AND b.bes_bestelling_datum" + sql_date;
          }
        }

        /**********************************************
         * Callback functies ResultsetTable for only MI
         *********************************************/

        function fnrowDataRFO(oRs)
        {
          var eSubmit = false;
          var besType = oRs("bes_bestelling_module").value;

          var data = {eSubmit:eSubmit, besType:besType};
          return JSON.stringify(data);
        }

        function fnrowDataOrder(oRs)
        {
          var eSubmit = false;
          var besOpdrKey = oRs("bes_bestelopdr_key").value;
          var besOpdrType = oRs("bes_bestelopdr_module").value;
          var besOpdrId = oRs("bes_bestelopdr_id").value;

          var data = {eSubmit:eSubmit, besOpdrKey:besOpdrKey, besOpdrType:besOpdrType, besOpdrId: besOpdrId};
          return JSON.stringify(data);
        }

        function fncolBesOpdrNr(oRs)
        {
          return S("bes_bestelopdr_prefix") + oRs.fields("bes_bestelopdr_id").value;
        }

        function fncolStatusOmschr(oRs)
        {
          return ((oRs("bes_bestelling_status").value == 6
                   && (oRs("bes_bestelling_retourvan_key").value
                   && oRs("bes_bestelling_retourvan_key").value > 0))
                 ? L("lcl_bes_collected")
                 : bes.getbesbestellingstatustext(oRs("bes_bestelling_status").value))
        }

        function fncolOrderVoorMI(oRs)
        {
          var bestellingvoor = oRs("ordervoor").value
          if (!excel && oRs("requestor").value == bestellingvoor)
          	bestellingvoor = "";
          return safe.html(bestellingvoor);
        }

        var tot_aantal_bes = 0;
        var tot_aantal_art = 0
        var tot_totaalbedrag = 0;
        var tot_inktotaalbedrag = 0;
        var sum_satisfaction = 0;
        var cnt_satisfaction = 0;
        var aantal_oordeel = 0;

        function fntotalCalc(oRs)
        {
          tot_totaalbedrag += oRs("totaalbedrag").Value;
          tot_inktotaalbedrag += oRs("inktotaalbedrag").Value;

          if (groupbes == 0)
          { // Totaal oordeel is alle cijfers opgeteld gedeeld door het aantal beoordelingen.
            if (oRs("oordeel").Value)
            {
              sum_satisfaction += oRs("oordeel").Value;
              aantal_oordeel++;
            }
          }
          else
          {
            tot_aantal_bes += oRs("aantalbes").Value;
            if (groupbes == 12 || groupbes == 5)
              tot_aantal_art += oRs("aantalart").Value;

            if (groupbes != 12)
            { // Totaal oordeel is alle cijfers opgeteld gedeeld door het aantal beoordelingen.
              sum_satisfaction += oRs("sum_satisfaction").Value;
              cnt_satisfaction += oRs("cnt_satisfaction").Value;
            }
          }
        }

        function fntotalShow(column, nrlines)
        {
            function doOordeel(cnt_satisfaction, sum_satisfaction)
            {
              var result = cnt_satisfaction > 0? sum_satisfaction/cnt_satisfaction : 0;
              if (excel || print)
                result = (result!=0? safe.displayfloat(sum_satisfaction/cnt_satisfaction, 1) : "");
              else
                result = rater(result, {readonly: true});
              return result;
            }

          var result = "";
          switch (column.caption)
          {
            case L("lcl_bes_amount_key")   : result = tot_aantal_bes; break;
            case L("lcl_bes_artamount")    : result = tot_aantal_art; break;
            case L("lcl_bes_oordeel")      : if (groupbes == 0)
                                               result = aantal_oordeel > 0? doOordeel(aantal_oordeel, sum_satisfaction) : "";
                                             else
                                               result = cnt_satisfaction > 0? doOordeel(cnt_satisfaction, sum_satisfaction) : "";
                                             break;
            case L("lcl_rfo_total_sum_eur"): result = safe.curr(tot_totaalbedrag); break;
            case L("lcl_rfo_total_inksum") : result = safe.curr(tot_inktotaalbedrag); break;
          }
          return result;
        }

        /**************************************************
         * End callback functies ResultsetTable for only MI
         *************************************************/

        // Aanvraag
        if (groupbes == 0)
        {
          // RFO
          sql = "SELECT b.bes_bestelling_key"
              + ", bes_bestelling_parentkey"
              + ", bes_bestelling_datum"
              + ", bes_bestelling_retourvan_key"
              + ", " + S("prs_pers_string") + " requestor"
              + ", " + S("prs_dep_string") + " organisation"
              + ", (SELECT " + S("prs_pers_string")
                + " FROM prs_perslid p"
                + " WHERE p.prs_perslid_key = b.prs_perslid_key_voor) ordervoor";

          sql_group_by = " GROUP BY b.bes_bestelling_key"
                       + ", bes_bestelling_parentkey"
                       + ", bes_bestelling_datum"
                       + ", b.bes_bestelling_status"
                       + ", b.bes_bestelling_retourvan_key"
                       + ", " + S("prs_pers_string")
                       + ", " + S("prs_dep_string")
                       + ", b.bes_bestelling_status"
                       + ", b.bes_bestelling_module"
                       + ", b.bes_bestelling_satisfaction"
                       + ", b.prs_perslid_key_voor";

          sql += ", b.bes_bestelling_status"
               + ", b.bes_bestelling_module"
               + ", b.bes_bestelling_satisfaction oordeel"
               + ", MAX(b.bes_bestelling_satisfaction_op) oordeel_opm"
               + " , SUM( bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
               + " , SUM( bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
               + " FROM bes_bestelling_item bi"
               + ", bes_srtdeel srt"
               + ", bes_bestelling b"
               + ", prs_perslid p"
               + ", prs_v_afdeling d"
               + ", mld_adres m"
               + ", prs_v_afdeling_boom boom"
               + ", bes_srtgroep grp"
               + ", ins_tab_discipline dis"
               + ", alg_locatie l"
               + ", alg_district di"
               + " WHERE srt.bes_srtgroep_key = grp.bes_srtgroep_key"
               + " AND grp.ins_discipline_key = dis.ins_discipline_key"
               + " AND bi.bes_srtdeel_key = srt.bes_srtdeel_key"
               + " AND bi.bes_bestelling_key = b.bes_bestelling_key"
               + " AND p.prs_perslid_key = b.prs_perslid_key"
               + " AND p.prs_afdeling_key = d.prs_afdeling_key"
               + " AND d.prs_afdeling_key = boom.prs_afdeling_key"
               + " AND b.mld_adres_key_lev = m.mld_adres_key"
               + " AND m.alg_locatie_key = l.alg_locatie_key(+)"
               + " AND l.alg_district_key = di.alg_district_key(+)";

          sql += sql_filter;

          sql = discx3d (sql,
                         "dis.ins_discipline_key",
                         "di.alg_regio_key",
                         "di.alg_district_key",
                         "l.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

          sql += " ORDER BY bes_bestelling_status"
               + ", bes_bestelling_key";
// PF: lijkt me nogal zinloos (en Oracle moppert)
//               + ", " + S("prs_dep_string")
//               + ", " + S("prs_pers_string") + " DESC";

          var rst = new ResultsetTable({keyColumn: "bes_bestelling_key",
                                        ID: "bestable",
                                        rowData: fnrowDataRFO,
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall,
                                        totalCalc: fntotalCalc,
                                        totalShow: fntotalShow
                                       });

          // Kolommen
          rst.addColumn(new Column({caption: L("lcl_bes_key"), content: fncolBesNr}));
          rst.addColumn(new Column({caption: L("lcl_bes_add_date"), content: "bes_bestelling_datum"}));
          rst.addColumn(new Column({caption: L("lcl_rfo_requestor"), content: "requestor"}));
          rst.addColumn(new Column({caption: L("lcl_bes_order_for"), content: fncolOrderVoorMI, combine: true, hasActions: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_organisation"), content: "organisation"}));
          rst.addColumn(new Column({caption: L("lcl_bes_RFO_status"), content: fncolStatusOmschr}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true})); //@@ TODO: AANPASSEN
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_oordeel"), content: fncolOordeel, datatype: "float", decimals: 1, total: true}));
          if (excel || print)
            rst.addColumn(new Column({caption: L("lcl_fac_like_remark"), content: "oordeel_opm"}));

          // Acties
          rst.addAction({image: "../Pictures/spot1.jpg", action: "besEdit;", caption: L("lcl_edit"), isDefault: true});

          var count = rst.processResultset();
        }

        var select2 = '';
        var from2 = '';
        var where2 = '';
        var th2 = '';

        // start grouping other than aanvraag ****************************************************
        if (groupbes2 == 8)
        { // Aanvraag - Kostenplaats
          if (groupbes == 8)
          { // Aanvraag - Kostenplaats
            groupbes2 = null;
          }
          else
          { // Servicepunt of Locatie
            select2 = ", " + S("prs_kpn_string")
            from2 = ", prs_kostenplaats k";
            where2 = " AND b.prs_kostenplaats_key = k.prs_kostenplaats_key(+)";
            th2 = L("lcl_bes_ordernr");
          }
        }

        if (groupbes2 == 10 || groupbes2 == 11)
        { // district - locatie
          if (groupbes == 10 || groupbes == 11)
          { // district - locatie
            groupbes2 = null;
          }
          else
          {
            select2 = ", " + (groupbes2 == 10? "di.alg_district_omschrijving" : "l.alg_locatie_omschrijving")
            th2 = (groupbes2 == 10? L("lcl_district") : L("lcl_mi_location"));
          }
        }

        select_oordeel = ", SUM(b.bes_bestelling_satisfaction) sum_satisfaction"
                       + ", COUNT(b.bes_bestelling_satisfaction) cnt_satisfaction"
                       + ", AVG(b.bes_bestelling_satisfaction) oordeel";


        if ((groupbes == 2) || (groupbes == 7))
        { // Aanvraag - Cluster/Aanvraag - Afdeling (Organisatie niveau 1 en 2)
          sql = "SELECT d.prs_afdeling_key"
              + "     , b.bes_bestelling_key"
              + "     , " + S("prs_dep_string") + " afdeling"
              + "     , SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
              + "     , SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
              + select_oordeel;

          sql_group_by = " GROUP BY d.prs_afdeling_key"
                       + "        , " + S("prs_dep_string")
                       + "        , b.bes_bestelling_key";

          if (groupbes2)
          {
            sql += select2 + " sel2col";
            sql_group_by += select2;
          }

          sql += " FROM bes_bestelling_item bi"
               + ", bes_srtdeel srt"
               + ", bes_bestelling b"
               + ", prs_perslid p"
               + ", prs_afdeling afd"
               + ", prs_v_afdeling_boom boom"
               + ", prs_v_afdeling d"
               + from2
               + ", bes_srtgroep grp"
               + ", ins_tab_discipline dis"
               + ", mld_adres adr"
               + ", alg_locatie l"
               + ", alg_district di"
               + " WHERE srt.bes_srtgroep_key = grp.bes_srtgroep_key"
               + " AND grp.ins_discipline_key = dis.ins_discipline_key"
               + " AND bi.bes_srtdeel_key = srt.bes_srtdeel_key"
               + " AND bi.bes_bestelling_key = b.bes_bestelling_key"
               + " AND p.prs_perslid_key = b.prs_perslid_key"
               + " AND p.prs_afdeling_key = afd.prs_afdeling_key"
               + " AND afd.prs_afdeling_key = boom.prs_afdeling_key"
               + " AND d.prs_afdeling_key(+) = boom.prs_afdeling_key" + (groupbes == 2? "1" : "2")
               + " AND b.mld_adres_key_lev = adr.mld_adres_key"
               + " AND adr.alg_locatie_key = l.alg_locatie_key(+)"
               + " AND l.alg_district_key = di.alg_district_key(+)"
               + where2;

          sql += sql_filter;
          sql += makeDisGroepItemsFilter(catalogus_key, besgroep_key, item_key);

          sql = discx3d (sql,
                         "dis.ins_discipline_key",
                         "di.alg_regio_key",
                         "di.alg_district_key",
                         "l.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

          sql = "SELECT x.prs_afdeling_key"
              + "     , COUNT(x.bes_bestelling_key) aantalbes"
              + "     , COALESCE(x.afdeling, ' ') afdeling"
              + "     , SUM(x.totaalbedrag) totaalbedrag"
              + "     , SUM(x.inktotaalbedrag) inktotaalbedrag"
              + "     , SUM(x.sum_satisfaction) sum_satisfaction"
              + "     , SUM(x.cnt_satisfaction) cnt_satisfaction"
              + (groupbes2
                ? "     , x.sel2col sel2col"
                : "")
              + "     , AVG(x.oordeel) oordeel"
              + " FROM (" + sql + ") x"
              + " GROUP BY x.prs_afdeling_key"
              + "        , x.afdeling"
              + (groupbes2
                ? "        , x.sel2col"
                : "")
              + " ORDER BY afdeling";

          var rst = new ResultsetTable({keyColumn: "prs_afdeling_key",
                                        ID: "bestable",
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall,
                                        totalCalc: fntotalCalc,
                                        totalShow: fntotalShow
                                       });

          // Kolommen
          rst.addColumn(new Column({align: "left", caption: (groupbes == 2? L("lcl_dep_name_level1") : L("lcl_dep_name_level2")), content: "afdeling"}));
          if (groupbes2)
            rst.addColumn(new Column({caption: th2, content: "sel2col" }));
          rst.addColumn(new Column({caption: L("lcl_bes_amount_key"), content: "aantalbes", datatype: "number", total: true}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true}));
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_oordeel"), content: fncolOordeelAvg, datatype: "float", decimals: 1, total: true}));

          var count = rst.processResultset();
        }

        if (groupbes == 8)
        { // Aanvraag - Kostenplaats
          sql = "SELECT k.prs_kostenplaats_key"
              + ", b.bes_bestelling_key"
              + " , " + S("prs_kpn_string") + " kostenplaats"
              + " , SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
              + " , SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
              + select_oordeel;

          sql_group_by = " GROUP BY k.prs_kostenplaats_key"
                       + "        , " + S("prs_kpn_string")
                       + "        , b.bes_bestelling_key";

          if (groupbes2)
          {
            sql += select2 + " sel2col";
            sql_group_by += select2;
          }

          sql += " FROM bes_bestelling_item bi"
               + ", bes_srtdeel srt"
               + ", bes_bestelling b"
               + ", prs_kostenplaats k"
               + ", prs_perslid p"
               + ", prs_v_afdeling_boom boom"
               + ", bes_srtgroep grp"
               + ", ins_tab_discipline dis"
               + ", mld_adres adr"
               + ", alg_locatie l"
               + ", alg_district di"
               + from2
               + " WHERE srt.bes_srtgroep_key = grp.bes_srtgroep_key"
               + " AND grp.ins_discipline_key = dis.ins_discipline_key"
               + " AND bi.bes_srtdeel_key = srt.bes_srtdeel_key"
               + " AND bi.bes_bestelling_key = b.bes_bestelling_key"
               + " AND b.prs_perslid_key = p.prs_perslid_key"
               + " AND p.prs_afdeling_key = boom.prs_afdeling_key"
               + " AND k.prs_kostenplaats_key(+) = b.prs_kostenplaats_key"
               + " AND b.mld_adres_key_lev = adr.mld_adres_key"
               + " AND adr.alg_locatie_key = l.alg_locatie_key(+)"
               + " AND l.alg_district_key = di.alg_district_key(+)"
               + where2;

          sql += sql_filter;
          sql += makeDisGroepItemsFilter(catalogus_key, besgroep_key, item_key);

          sql = discx3d (sql,
                         "dis.ins_discipline_key",
                         "di.alg_regio_key",
                         "di.alg_district_key",
                         "l.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

          sql = "SELECT x.prs_kostenplaats_key"
              + "     , COUNT(x.bes_bestelling_key) aantalbes"
              + "     , x.kostenplaats kostenplaats"
              + "     , SUM(x.totaalbedrag) totaalbedrag"
              + "     , SUM(x.inktotaalbedrag) inktotaalbedrag"
              + "     , SUM(x.sum_satisfaction) sum_satisfaction"
              + "     , SUM(x.cnt_satisfaction) cnt_satisfaction"
              + "     , AVG(x.oordeel) oordeel"
              + (groupbes2
                ? "   , x.sel2col sel2col"
                : "")
              + " FROM (" + sql + ") x"
              + " GROUP BY x.prs_kostenplaats_key"
              + "        , x.kostenplaats"
              + (groupbes2
                ? "      , x.sel2col"
                : "")
              + " ORDER BY 3";

          var rst = new ResultsetTable({keyColumn: "prs_kostenplaats_key",
                                        sql: sql,
                                        ID: "bestable",
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall,
                                        totalCalc: fntotalCalc,
                                        totalShow: fntotalShow
                                       });

          // Kolommen
          rst.addColumn(new Column({caption: L("lcl_bes_ordernr"), content: "kostenplaats"}));
          if (groupbes2)
            rst.addColumn(new Column({caption: th2, content: "sel2col" }));
          rst.addColumn(new Column({caption: L("lcl_bes_amount_key"), content: "aantalbes", datatype: "number", total: true}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true}));
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_oordeel"), content: fncolOordeelAvg, datatype: "float", decimals: 1, total: true}));

          var count = rst.processResultset();
        }

        if ((groupbes == 10) || (groupbes == 11))
        { // District/Locatie -->
          var th1 = (groupbes == 10 ? L("lcl_district") : L("lcl_mi_location"));

          sql = "SELECT" + (groupbes == 10? " di.alg_district_key" : " l.alg_locatie_key") + " dlkey"
              + "     , b.bes_bestelling_key"
              + (groupbes == 10
                ? "   , di.alg_district_omschrijving"
                : "   , l.alg_locatie_omschrijving") + " dlomschrijving"
              + "     , SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
              + "     , SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
              + select_oordeel;

          sql_group_by = " GROUP BY"
                       + (groupbes == 10
                         ? " di.alg_district_key"
                           + "    , di.alg_district_omschrijving"
                         : " l.alg_locatie_key"
                           + "    , l.alg_locatie_omschrijving")
                       + "        , b.bes_bestelling_key";

          if (groupbes2)
          {
            sql += select2 + " sel2col";
            sql_group_by += select2;
          }

          sql += " FROM bes_bestelling_item bi"
               + ", bes_srtdeel srt"
               + ", bes_bestelling b"
               + ", prs_perslid p"
               + ", prs_v_afdeling_boom boom"
               + ", bes_srtgroep grp"
               + ", ins_tab_discipline dis"
               + ", mld_adres adr"
               + ", alg_locatie l"
               + ", alg_district di"
               + from2
               + " WHERE srt.bes_srtgroep_key = grp.bes_srtgroep_key"
               + " AND grp.ins_discipline_key = dis.ins_discipline_key"
               + " AND bi.bes_srtdeel_key = srt.bes_srtdeel_key"
               + " AND bi.bes_bestelling_key = b.bes_bestelling_key"
               + " AND b.prs_perslid_key = p.prs_perslid_key"
               + " AND p.prs_afdeling_key = boom.prs_afdeling_key"
               + " AND b.mld_adres_key_lev = adr.mld_adres_key"
               + " AND adr.alg_locatie_key = l.alg_locatie_key(+)"
               + " AND l.alg_district_key = di.alg_district_key(+)"
               + where2;

          sql += sql_filter;
          sql += makeDisGroepItemsFilter(catalogus_key, besgroep_key, item_key);

          sql = discx3d (sql,
                         "dis.ins_discipline_key",
                         "di.alg_regio_key",
                         "di.alg_district_key",
                         "l.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

          sql = "SELECT x.dlkey dlkey"
              + "     , COUNT(x.bes_bestelling_key) aantalbes"
              + "     , x.dlomschrijving dlomschrijving"
              + "     , SUM(x.totaalbedrag) totaalbedrag"
              + "     , SUM(x.inktotaalbedrag) inktotaalbedrag"
              + "     , SUM(x.sum_satisfaction) sum_satisfaction"
              + "     , SUM(x.cnt_satisfaction) cnt_satisfaction"
              + "     , AVG(x.oordeel) oordeel"
              + (groupbes2
                ? "     , x.sel2col sel2col"
                : "")
              + " FROM (" + sql + ") x"
              + " GROUP BY x.dlkey"
              + "        , x.dlomschrijving"
              + (groupbes2
                ? "        , x.sel2col"
                : "")
              + " ORDER BY dlomschrijving";

          var rst = new ResultsetTable({keyColumn: "dlkey",
                                        ID: "bestable",
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall,
                                        totalCalc: fntotalCalc,
                                        totalShow: fntotalShow
                                       });

          // Kolommen
          rst.addColumn(new Column({caption: th1, content: "dlomschrijving"}));
          if (groupbes2)
            rst.addColumn(new Column({caption: th2, content: "sel2col" }));
          rst.addColumn(new Column({caption: L("lcl_bes_amount_key"), content: "aantalbes", datatype: "number", total: true}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true}));
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_oordeel"), content: fncolOordeelAvg, datatype: "float", decimals: 1, total: true}));

          var count = rst.processResultset();
        }

        if ((groupbes == 12) || (groupbes == 3) || (groupbes == 4) || (groupbes == 5))
        { // Geen/Aanvraag - Catalogus/Aanvraag - Groep/Aanvraag - Item
          if (groupbes == 12) // Geen
          {
            sql = "SELECT b.bes_bestelling_key"
                + ", bes_bestelling_parentkey"
                + ", srt.bes_srtdeel_key"
                + ", " + lcl.xsqla('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                + ", " + lcl.xsqla('grp.bes_srtgroep_omschrijving','grp.bes_srtgroep_key')
                + ", " + lcl.xsqla('srt.bes_srtdeel_nr','srt.bes_srtdeel_key')
                + ", " + lcl.xsqla('srt.bes_srtdeel_omschrijving','srt.bes_srtdeel_key')
                + ", 1 aantalbes"
                + ", bi.bes_bestelling_item_aantal aantalart"
                + ", bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0) totaalbedrag"
                + ", bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0) inktotaalbedrag";

            sql_group_by = "";
          }

          if (groupbes == 3) // op catalogus
          {
            sql = "SELECT dis.ins_discipline_key ins_discipline_key"
                + ", " + lcl.xsqla('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                + ", b.bes_bestelling_key"
                + ", SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
                + ", SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
                + select_oordeel;

            sql_group_by = " GROUP BY dis.ins_discipline_key"
                         + ", " + lcl.xsql('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                         + ", b.bes_bestelling_key";
          }

          if (groupbes == 4) // op groep
          {
            sql = "SELECT grp.bes_srtgroep_key"
                + ", "+ lcl.xsqla('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                + ", "+ lcl.xsqla('grp.bes_srtgroep_omschrijving','grp.bes_srtgroep_key')
                + ", b.bes_bestelling_key"
                + ", SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
                + ", SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
                + select_oordeel;

            sql_group_by = " GROUP BY grp.bes_srtgroep_key"
                         + ", "+ lcl.xsql('grp.bes_srtgroep_omschrijving','grp.bes_srtgroep_key')
                         + ", "+ lcl.xsql('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                         + ", b.bes_bestelling_key";
          }

          if (groupbes == 5) // op artikel
          {
            sql = "SELECT srt.bes_srtdeel_key"
                + ", "+ lcl.xsqla('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                + ", "+ lcl.xsqla('grp.bes_srtgroep_omschrijving','grp.bes_srtgroep_key')
                + ", "+ lcl.xsqla('srt.bes_srtdeel_nr','srt.bes_srtdeel_key')
                + ", "+ lcl.xsqla('srt.bes_srtdeel_omschrijving','srt.bes_srtdeel_key')
                + ", b.bes_bestelling_key"
                + ", SUM(bi.bes_bestelling_item_aantal) aantalart"
                + ", SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_prijs, 0)) totaalbedrag"
                + ", SUM(bi.bes_bestelling_item_aantal * COALESCE(bi.bes_bestelling_item_inkprijs, 0)) inktotaalbedrag"
                + select_oordeel;

            sql_group_by = " GROUP BY srt.bes_srtdeel_key"
                         + ", "+ lcl.xsql('srt.bes_srtdeel_nr','srt.bes_srtdeel_key')
                         + ", "+ lcl.xsql('srt.bes_srtdeel_omschrijving','srt.bes_srtdeel_key')
                         + ", "+ lcl.xsql('grp.bes_srtgroep_omschrijving','grp.bes_srtgroep_key')
                         + ", "+ lcl.xsql('dis.ins_discipline_omschrijving','dis.ins_discipline_key')
                         + ", b.bes_bestelling_key";
          }

          if (groupbes2)
          {
            sql += select2 + " sel2col";
            sql_group_by += select2;
          }

          sql += " FROM bes_bestelling_item bi"
               + ", bes_srtdeel srt"
               + ", bes_bestelling b"
               + ", prs_perslid p"
               + ", prs_v_afdeling d"
               + ", prs_v_afdeling_boom boom"
               + ", bes_srtgroep grp"
               + ", ins_tab_discipline dis"
               + ", mld_adres adr"
               + ", alg_locatie l"
               + ", alg_district di"
               + from2
               + " WHERE bi.bes_srtdeel_key = srt.bes_srtdeel_key"
               + " AND srt.bes_srtgroep_key = grp.bes_srtgroep_key"
               + " AND grp.ins_discipline_key = dis.ins_discipline_key"
               + " AND bi.bes_bestelling_key = b.bes_bestelling_key"
               + " AND p.prs_perslid_key = b.prs_perslid_key"
               + " AND p.prs_afdeling_key = d.prs_afdeling_key"
               + " AND d.prs_afdeling_key = boom.prs_afdeling_key"
               + " AND b.mld_adres_key_lev = adr.mld_adres_key"
               + " AND adr.alg_locatie_key = l.alg_locatie_key(+)"
               + " AND l.alg_district_key = dI.alg_district_key(+)"
               + where2;

          sql += sql_filter;
          sql += makeDisGroepItemsFilter(catalogus_key, besgroep_key, item_key);

          sql = discx3d (sql,
                         "dis.ins_discipline_key",
                         "di.alg_regio_key",
                         "di.alg_district_key",
                         "l.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

          if (groupbes == 12)
            sql += " ORDER BY 1, 3, 4, 5";
          else
          {
            if (groupbes == 3)
              sql_start = "SELECT x.ins_discipline_key"
                        + "     , x.ins_discipline_omschrijving";
            if (groupbes == 4)
              sql_start = "SELECT x.bes_srtgroep_key"
                        + "     , x.ins_discipline_omschrijving"
                        + "     , bes_srtgroep_omschrijving";
            if (groupbes == 5)
              sql_start = "SELECT x.bes_srtdeel_key"
                        + "     , x.ins_discipline_omschrijving"
                        + "     , x.bes_srtgroep_omschrijving"
                        + "     , x.bes_srtdeel_nr"
                        + "     , x.bes_srtdeel_omschrijving"
                        + "     , SUM(x.aantalart) aantalart";

            sql = sql_start
                + "     , COUNT(x.bes_bestelling_key) aantalbes"
                + "     , SUM(x.totaalbedrag) totaalbedrag"
                + "     , SUM(x.inktotaalbedrag) inktotaalbedrag"
                + "     , SUM(x.sum_satisfaction) sum_satisfaction"
                + "     , SUM(x.cnt_satisfaction) cnt_satisfaction"
                + "     , AVG(x.oordeel) oordeel"
                + (groupbes2
                  ? "     , x.sel2col sel2col"
                  : "")
                + "  FROM (" + sql + ") x";

            if (groupbes == 3)
              sql += " GROUP BY x.ins_discipline_key"
                   + "        , x.ins_discipline_omschrijving";
            if (groupbes == 4)
              sql += " GROUP BY x.bes_srtgroep_key"
                   + "        , x.ins_discipline_omschrijving"
                   + "        , x.bes_srtgroep_omschrijving";
            if (groupbes == 5)
              sql += " GROUP BY x.bes_srtdeel_key"
                   + "        , x.ins_discipline_omschrijving"
                   + "        , x.bes_srtgroep_omschrijving"
                   + "        , x.bes_srtdeel_nr"
                   + "        , x.bes_srtdeel_omschrijving";

            sql += (groupbes2
                   ? "        , x.sel2col"
                   : "")
                 + " ORDER BY 2, 3, 4";
          }

          var keyCol = "";
          if (groupbes == 3)
            keyCol = "ins_discipline_key";
          else if  (groupbes == 4)
            keyCol = "bes_srtgroep_key";
          else if (groupbes == 5)
            keyCol = "bes_srtdeel_key";
          else if (groupbes == 12)
            keyCol = "bes_srtdeel_key";

          var rst = new ResultsetTable({keyColumn: keyCol,
                                        ID: "bestable",
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall,
                                        totalCalc: fntotalCalc,
                                        totalShow: fntotalShow
                                       });

          // Kolommen
          if (groupbes == 12)
              rst.addColumn(new Column({caption: L("lcl_bes_key"), content: fncolBesNr}));
          rst.addColumn(new Column({caption: L("lcl_bes_Catalogus"), content: "ins_discipline_omschrijving"}));
          if (groupbes == 12 || groupbes == 5)
          {
              rst.addColumn(new Column({caption: L("lcl_bes_srtgroup"), content: "bes_srtgroep_omschrijving"}));
              rst.addColumn(new Column({caption: L("lcl_bes_srtdeel_nr"), content: "bes_srtdeel_nr"}));
              rst.addColumn(new Column({caption: L("lcl_bes_srtdeel"), content: "bes_srtdeel_omschrijving"}));
          }
          if (groupbes == 4)
          {
              rst.addColumn(new Column({caption: L("lcl_bes_srtgroup"), content: "bes_srtgroep_omschrijving"}));
          }
          // groupbes == 3 heeft alleen catalogus

          if (groupbes2)
            rst.addColumn(new Column({caption: th2, content: "sel2col" }));
          if (groupbes != 12)
            rst.addColumn(new Column({caption: L("lcl_bes_amount_key"), content: "aantalbes", datatype: "number", total: true}));
          if (groupbes == 12 || groupbes == 5)
            rst.addColumn(new Column({caption: L("lcl_bes_artamount"), content: "aantalart", datatype: "number", total: true}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true}));
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));
          if (groupbes != 12)
            rst.addColumn(new Column({caption: L("lcl_bes_oordeel"), content: fncolOordeelAvg, datatype: "float", decimals: 1, total: true}));

          var count = rst.processResultset();
        }


        if ((groupbes == 1) || (groupbes == 6))
        { // Opdracht/Opdracht - Leverancier
          sql_filter += " AND p.prs_afdeling_key = d.prs_afdeling_key(+)";

          if (rfo_key)
          {
            sql_filter += " AND UPPER(bo.bes_bestelopdr_id) LIKE " + safe.quoted_sql_wild(rfo_key + "%");
          }
          else
          {
            if (showordstatus)
               sql_filter += " AND bo.bes_bestelopdr_status IN (" + showordstatus + ")";

            if (showbesstatus) {
              sql_filter += " AND bi.bes_bestelopdr_item_key IN"
                            + " (SELECT bes_bestelopdr_item_key"
                            + " FROM bes_bestelling_item"
                            + " WHERE bes_bestelling_key IN"
                              + " (SELECT bes_bestelling_key "
                              + " FROM bes_bestelling"
                              + " WHERE bes_bestelling_status IN (" + showbesstatus + ")))";
            }

            if (requestor_key)
              sql_filter += " AND bo.prs_perslid_key = " + requestor_key;

            if (personfor_key)
              sql_filter += " AND bo.prs_perslid_key_voor = " + personfor_key;

            if (kp)
            {
              sql_filter += " AND bi.bes_bestelopdr_item_key IN "
                            + " (SELECT bes_bestelopdr_item_key"
                            + " FROM bes_bestelling bl"
                            + ", bes_bestelling_item bi"
                            + " WHERE bi.bes_bestelling_key = bl.bes_bestelling_key"
                            + " AND"
                            + " (SELECT UPPER(k.prs_kostenplaats_nr)"
                            + " FROM prs_kostenplaats k"
                            + " WHERE k.prs_kostenplaats_key = bl.prs_kostenplaats_key) LIKE " + safe.quoted_sql_wild(kp) + ")";
            }

            sql_filter += makeDisGroepItemsSql(catalogus_key, besgroep_key, item_key);

            if (supplier_key)
              sql_filter += " AND bo.prs_bedrijf_key = " + supplier_key;
            if (sql_date)
              sql_filter += " AND bo.bes_bestelopdr_datum" + sql_date;
            if (dep_key)
              sql_filter += " AND p.prs_afdeling_key IN"
                            + " (SELECT a.prs_afdeling_key"
                            + " FROM prs_v_afdeling_familie a"
                            + " WHERE a.prs_afdeling_elder_key = " + dep_key + ")";
          }
        }

        if (groupbes == 1)
        { // Opdracht
          sql = "SELECT bbi.bes_bestelling_key"
              + ", NULL bes_bestelling_parentkey"  // doen we hier mee?
              + ", bo.bes_bestelopdr_key"
              + ", bo.bes_bestelopdr_id"
              + ", bo.bes_bestelopdr_datum"
              + ", (SELECT bst.bes_bestelling_retourvan_key"
              + "     FROM bes_bestelling bst"
              + ",         bes_bestelling_item bbi"
              + "    WHERE bst.bes_bestelling_key = bbi.bes_bestelling_key"
              + "      AND bbi.bes_bestelopdr_item_key = bi.bes_bestelopdr_item_key) bes_bestelling_retourvan_key"
              + ", prs_bedrijf_naam supplier"
              + ", " + S("prs_pers_string") + " besteller"
              + ", " + S("prs_dep_string") + " organisation"
              + ", bo.bes_bestelopdr_status"
              + ", bo.bes_bestelopdr_module"
              + ", dis.ins_discipline_key"
              + "," + lcl.xsql("dis.ins_discipline_omschrijving", "dis.ins_discipline_key") +" catalogus"
              + ", d.prs_afdeling_key"
              + ", (bi.bes_bestelopdr_item_aantal * bes_bestelopdr_item_prijs) totaalbedrag"  // klopt dit wel?
              + ", (bi.bes_bestelopdr_item_aantal * bes_bestelopdr_item_inkprijs) inktotaalbedrag"
              + ", l.alg_locatie_key"
              + ", di.alg_district_key"
              + ", di.alg_regio_key"
              + ", bo.bes_bestelopdr_delivery_opmerk"
              + " FROM bes_bestelopdr_item bi"
              + ", bes_bestelopdr bo"
              + ", prs_bedrijf be"
              + ", prs_perslid p"
              + ", prs_v_afdeling d"
              // next lines: tbv 3D autorisatie mbt discipline(catalogus) en afdeling (organisatie)
              + ", prs_v_afdeling_boom boom"
              + ", bes_bestelling_item bbi"
              + ", bes_bestelling b"
              + ", bes_srtdeel srt"
              + ", bes_srtgroep grp"
              + ", ins_tab_discipline dis"
              // MB--indien op aanvrager: ADD next line if 3D-auto organisatie op aanvrager (en niet op opdrachtgever/fiatteur).
              // sql += ",bes_bestelling bstl"
              // next lines: tbv 3D autorisatie mbt district en locatie
              + ", mld_adres adr"
              + ", alg_locatie l"
              + ", alg_district di"
              + " WHERE b.bes_bestelling_key = bbi.bes_bestelling_key"
              + " AND be.prs_bedrijf_key = bo.prs_bedrijf_key"
              + " AND bi.bes_bestelopdr_key = bo.bes_bestelopdr_key"
              + " AND p.prs_perslid_key = bo.prs_perslid_key" // MB--indien op aanvrager:: deze regel uitcommentarieren
              // MB--indien op aanvrager: add next 2 lines
              // + " and p.prs_perslid_key = bstl.prs_perslid_key "
              // + " and bstl.bes_bestelling_key = bbi.bes_bestelling_key"
              // next 2 lines: 3D-autoriatie op organisatie
              + " AND p.prs_afdeling_key = d.prs_afdeling_key"
              + " AND d.prs_afdeling_key = boom.prs_afdeling_key"
              // next 4 lines: 3D-autoriatie op discipline
              + " AND bbi.bes_bestelopdr_item_key = bi.bes_bestelopdr_item_key"
              + " AND bbi.bes_srtdeel_key = srt.bes_srtdeel_key"
              + " AND srt.bes_srtgroep_key = grp.bes_srtgroep_key"
              + " AND grp.ins_discipline_key = dis.ins_discipline_key"
              // next 3 lines: 3D-autoriatie op district en locatie
              + " AND bo.mld_adres_key_lev = adr.mld_adres_key"
              + " AND adr.alg_locatie_key = l.alg_locatie_key(+)"
              + " AND l.alg_district_key = dI.alg_district_key(+)"
              + sql_filter;

          sql += makeDisGroepItemsFilter(catalogus_key, besgroep_key, item_key);

          sql = "SELECT x.bes_bestelling_key"
              + "     , x.bes_bestelopdr_key"
              + "     , x.bes_bestelopdr_id"
              + "     , x.bes_bestelopdr_datum"
              + "     , x.bes_bestelling_retourvan_key"
              + "     , x.bes_bestelopdr_status"
              + "     , x.bes_bestelopdr_module"
              + "     , x.supplier"
              + "     , x.catalogus"
              + "     , x.besteller"
              + "     , x.organisation"
              + "     , SUM(x.totaalbedrag) totaalbedrag"
              + "     , SUM(x.inktotaalbedrag) inktotaalbedrag"
              + "     , x.alg_locatie_key"
              + "     , x.alg_district_key"
              + "     , x.alg_regio_key"
              + "     , x.bes_bestelopdr_delivery_opmerk"
              + "  FROM (" + sql + ") x"
              + "     , prs_v_afdeling_boom boom"
              + " WHERE x.prs_afdeling_key = boom.prs_afdeling_key";

          sql_group_by = " GROUP BY x.bes_bestelling_key"
                       + ", x.bes_bestelopdr_key"
                       + ", x.bes_bestelopdr_id"
                       + ", x.bes_bestelopdr_datum"
                       + ", x.bes_bestelling_retourvan_key"
                       + ", x.supplier"
                       + ", x.catalogus"
                       + ", x.besteller"
                       + ", x.organisation"
                       + ", x.bes_bestelopdr_status"
                       + ", x.bes_bestelopdr_module"
                       + ", x.alg_locatie_key"
                       + ", x.alg_district_key"
                       + ", x.alg_regio_key"
                       + ", x.bes_bestelopdr_delivery_opmerk";

          sql = discx3d (sql,
                         "x.ins_discipline_key",
                         "x.alg_regio_key",
                         "x.alg_district_key",
                         "x.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

//          sql += " ORDER BY x.bes_bestelopdr_status"
//               + ", x.bes_bestelopdr_id"
//               + ", x.supplier"
//               + ", x.besteller"
//               + ", x.organisation DESC";

          function fncolStatusText(oRs)
          {
            var opdrStatus = oRs("bes_bestelopdr_status").Value;
             if(opdrStatus == 6 && oRs("bes_bestelling_retourvan_key").Value > 0)
                return L("lcl_bes_collected");
             else
                return bes.getbesopdrstatustext(opdrStatus);
          }

          var rst = new ResultsetTable({keyColumn: "bes_bestelling_key",
                                        ID: "bestable",
                                        rowData: fnrowDataOrder,
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall
                                       });

          // Kolommen
          rst.addColumn(new Column({caption: L("lcl_ord_order_num"), content: fncolBesOpdrNr}));
          rst.addColumn(new Column({caption: L("lcl_bes_add_date"), content: "bes_bestelopdr_datum"}));
          rst.addColumn(new Column({caption: L("lcl_bes_Supplier"), content: "supplier", hasActions: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_discipline"), content: "catalogus"}));
          rst.addColumn(new Column({caption: L("lcl_bes_Persoon"), content: "besteller"}));
          rst.addColumn(new Column({caption: L("lcl_bes_Afdeling"), content: "organisation"}));
          rst.addColumn(new Column({caption: L("lcl_bes_Bes_status"), content: fncolStatusText}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true}));
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));
          rst.addColumn(new Column({caption: L("lcl_bes_comment"), content: "bes_bestelopdr_delivery_opmerk", purpose: PRINTING_ONLY}));

          // Acties
          rst.addAction({image: "../Pictures/spot1.jpg", action: "besOpdrShow", caption: L("lcl_edit"), isDefault: true});

          var count = rst.processResultset();
        }

        if (groupbes == 6)
        { // Opdracht - Leverancier
          sql = "SELECT be.prs_bedrijf_key prs_bedrijf_key"
              + "     , be.prs_bedrijf_naam supplier"
              + "     , bo.bes_bestelopdr_key"
              + "     , SUM(bi.bes_bestelopdr_item_aantal * bi.bes_bestelopdr_item_prijs) totaalbedrag"  // klopt dit wel?
              + "     , SUM(bi.bes_bestelopdr_item_aantal * bi.bes_bestelopdr_item_inkprijs) inktotaalbedrag";

          sql_group_by = " GROUP BY be.prs_bedrijf_key, be.prs_bedrijf_naam, bo.bes_bestelopdr_key";

          sql += " FROM bes_bestelopdr_item bi"
               + ", bes_bestelopdr bo"
               + ", prs_bedrijf be"
               + ", prs_perslid p"
               + ", prs_v_afdeling d"
               // next line: tbv 3D autorisatie mbt discipline(catalogus) en afdeling (organisatie)
               + ", prs_v_afdeling_boom boom"
               + ", bes_bestelling_item bbi"
               + ", bes_bestelling b"
               + ", bes_srtdeel srt"
               + ", bes_srtgroep grp"
               + ", ins_tab_discipline dis"
               + ", mld_adres adr"
               + ", alg_locatie l"
               + ", alg_district di";

          sql += " WHERE b.bes_bestelling_key = bbi.bes_bestelling_key"
               + " AND be.prs_bedrijf_key = bo.prs_bedrijf_key"
               + " AND bi.bes_bestelopdr_key = bo.bes_bestelopdr_key"
               + " AND p.prs_perslid_key = bo.prs_perslid_key"
               // next 2 lines: 3D-autoriatie op organisatie
               + " AND p.prs_afdeling_key = d.prs_afdeling_key"
               + " AND d.prs_afdeling_key = boom.prs_afdeling_key"
               // next 4 lines: 3D-autoriatie op discipline
               + " AND bbi.bes_bestelopdr_item_key = bi.bes_bestelopdr_item_key"
               + " AND bbi.bes_srtdeel_key = srt.bes_srtdeel_key"
               + " AND srt.bes_srtgroep_key = grp.bes_srtgroep_key"
               + " AND grp.ins_discipline_key = dis.ins_discipline_key"
               + " AND bo.mld_adres_key_lev = adr.mld_adres_key"
               + " AND adr.alg_locatie_key = l.alg_locatie_key(+)"
               + " AND l.alg_district_key = dI.alg_district_key(+)";

          sql += sql_filter;
          sql += makeDisGroepItemsFilter(catalogus_key, besgroep_key, item_key);

          sql = discx3d (sql,
                         "dis.ins_discipline_key",
                         "di.alg_regio_key",
                         "di.alg_district_key",
                         "l.alg_locatie_key",
                         "gebouw_auth_not_supported",
                         "verdieping_auth_not_supported",
                         "ruimte_auth_not_supported",
                         "boom.prs_bedrijf_key",
                         "boom.prs_afdeling_key",
                         pautfunction,
                         (catalogus_key? catalogus_key : ""),
                         2,
                         sql_group_by);

          sql = "SELECT x.prs_bedrijf_key"
              + "     , x.supplier supplier"
              + "     , COUNT (x.bes_bestelopdr_key) aantal"
              + "     , SUM (x.totaalbedrag) totaalbedrag"
              + "     , SUM (x.inktotaalbedrag) inktotaalbedrag"
              + "  FROM (" + sql + ") x"
              + " GROUP BY x.prs_bedrijf_key"
              + "        , x.supplier"
              + " ORDER BY supplier";

          var rst = new ResultsetTable({keyColumn: "prs_bedrijf_key",
                                        sql: sql,
                                        ID: "bestable",
                                        sql: sql,
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_bes_bestellingen"),
                                        showAll: showall
                                       });

          // Kolommen
          rst.addColumn(new Column({caption: L("lcl_bes_Supplier"), content: "supplier"}));
          rst.addColumn(new Column({caption: L("lcl_bes_order_amount"), content: "aantal", datatype: "number", total: true}));
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "totaalbedrag", datatype: "currency", total: true}));
          if (S("bes_show_inkprijs") == 1)
            rst.addColumn(new Column({caption: L("lcl_rfo_total_inksum"), content: "inktotaalbedrag", datatype: "currency", total: true}));

          var count = rst.processResultset();
        }
      }
      else if (frontend) // Front End
      {
        var prsKeys = user.collegakeylist();

        sql = "SELECT b.bes_bestelling_key"
            + ", b.bes_bestelling_parentkey"
            + ", b.bes_bestelling_datum datum"
						+ ", bes_bestelling_leverdatum leverdatum"            
            + ", bes_bestelling_retourvan_key"
            + ", b.bes_bestelling_module"
            + ", ma.mld_adres_naam"
            + ", b.bes_bestelling_plaats"
            + ", " + S("prs_kpn_string") + " kpn_string"
            + ", SUM(COALESCE(bi.bes_bestelling_item_prijs, 0) * bi.bes_bestelling_item_aantal) bedrag"
            + ", b.bes_bestelling_status"
            + "," + S("prs_pers_string") + " naam"
            + ", (SELECT " + S("prs_pers_string")
              + " FROM prs_perslid p"
              + " WHERE p.prs_perslid_key = b.prs_perslid_key_voor) ordervoor"
            + " FROM bes_bestelling b, mld_adres ma, prs_kostenplaats k"
            + ", bes_bestelling_item bi, prs_perslid p"
            + ", bes_srtdeel isd"
            + " WHERE (b.prs_perslid_key IN (" + prsKeys + ")"
              + " OR b.prs_perslid_key_voor IN (" + prsKeys + "))"
            + " AND ma.mld_adres_key = b.mld_adres_key_lev "
            + " AND b.prs_kostenplaats_key=k.prs_kostenplaats_key(+)"
            + " AND b.fac_activiteit_key IS NULL"
            + " AND bi.bes_srtdeel_key = isd.bes_srtdeel_key"
            + " AND bi.bes_bestelling_key = b.bes_bestelling_key"
            + " AND b.prs_perslid_key = p.prs_perslid_key"
            + " AND b.bes_bestelling_key NOT IN (SELECT b1.bes_bestelling_parentkey"
            + "                                    FROM bes_bestelling b1"
            + "                                   WHERE b1.bes_bestelling_parentkey IS NOT NULL)";

        if (showbesstatus)
            sql += " AND b.bes_bestelling_status IN (" + showbesstatus + ")"

        if (params.mld_key)
            sql += " AND b.mld_melding_key = " + params.mld_key;

        if (authparams.ALGreadlevel >= 0)
          sql +=" AND ma.alg_locatie_key IN"
                + " (SELECT alg_locatie_key"
                + " FROM fac_v_my_locations "
                + " WHERE (prs_perslid_key IN (" + prsKeys + ")"
                  + " OR prs_perslid_key_voor IN (" + prsKeys + "))"
                + " AND niveau = " + authparams.ALGreadlevel + ")"
       sql += " AND b.bes_bestelling_module = 'BES'"
            + " GROUP BY "
            + " b.bes_bestelling_key"
            + ", b.bes_bestelling_parentkey"
            + ", b.bes_bestelling_datum"
						+ ", bes_bestelling_leverdatum"            
            + ", bes_bestelling_status"
            + ", b.bes_bestelling_retourvan_key"
            + ", b.bes_bestelling_module"
            + ", ma.mld_adres_naam"
            + ", b.bes_bestelling_plaats"
            + ", " + S("prs_kpn_string")
            + ", b.bes_bestelling_datum"
            + ", b.bes_bestelling_status "
            + "," + S("prs_pers_string")
            + ", b.prs_perslid_key_voor"
            + " ORDER BY b.bes_bestelling_datum DESC";

        /**********************************************
         * Callback functies ResultsetTable for fe only
         *********************************************/

        function fnrowDataFE(oRs)
        {
          var besType = oRs("bes_bestelling_module").value;
          var data = {besType:besType};

          return JSON.stringify(data);
        }

        function fnrowActionEnablerFE(oRs)
        {
          var m_stat = oRs("bes_bestelling_status").value;
          var besType = oRs("bes_bestelling_module").value;

          var eEdit = true; // Altijd aanwezig
          var data = { eEdit: eEdit  };

          return data;
        }

        function fncolOrderVoorFE(oRs)
        {
          var bestellingvoor = oRs("ordervoor").value
          if (!excel && oRs("naam").value == bestellingvoor)
          	bestellingvoor = "";
          return safe.html(bestellingvoor);
        }

        /**************************************************
         * End callback functies ResultsetTable for fe only
         *************************************************/

        var rst = new ResultsetTable({keyColumn: "bes_bestelling_key",
                                      ID: "bestable",
                                      rowData: fnrowDataFE,
                                      rowActionEnabler: fnrowActionEnablerFE,
                                      sql: sql,
                                      filterParams: params,
                                      outputmode: outputmode,
                                      title: L("lcl_bes_bestellingen"),
                                      showAll: showall
                                     });

        // Kolommen
        rst.addColumn(new Column({caption: L("lcl_bes_key"), content: fncolBesNr}));
        rst.addColumn(new Column({caption: L("lcl_bes_add_date"), content: "datum", datatype: "datetime"}));
        rst.addColumn(new Column({caption: L("lcl_bes_RFO_status"), content: fncolStatusOmschr}));
        rst.addColumn(new Column({caption: L("lcl_delivery_address"), content: "mld_adres_naam", hasActions: true}));
        rst.addColumn(new Column({caption: L("lcl_bes_del_room"), content: "bes_bestelling_plaats" }));
        rst.addColumn(new Column({caption: L("lcl_bes_deli_date"), content: "leverdatum", datatype: "date"}));
        rst.addColumn(new Column({caption: L("lcl_account"), content: "kpn_string"}));
        rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "bedrag", datatype: "currency"}));
        if (user.hasCollegas()) // Mogelijk anderen naast jezelf
        {
          rst.addColumn(new Column({caption: L("lcl_rfo_requestor"), content: "naam"}));
          rst.addColumn(new Column({caption: L("lcl_bes_order_for"), content: fncolOrderVoorFE, combine: true}));
        }
        // Acties
        rst.addAction({image: "../Pictures/spot1.jpg", action: "besEdit", caption: L("lcl_edit"), isDefault: true});

        var count = rst.processResultset();
      }
      else if (fronto || backo) // Front Office en Back Office
      {
        // Kan ik zelf fiatteren?: true:  totaalbedrag <= can_selfapprove
        //                         false  totaalbedrag > can_selfapprove
        // TODO: Het totaalbedrag zou eigenlijk berekend moeten worden via staffelprijzen en staffelkortingen.
        //       Dit zou een databasefunctie moeten worden.
        //       Tot nu toe gebruikt geen enkele klant staffelprijzen en staffelkortingen.
        //       Dus voor nu kan totaalbedrag berekend worden via de som van aantal maal prijs
        var totaalbedrag = "(SELECT SUM(i1.bes_bestelling_item_aantal * COALESCE(i1.bes_bestelling_item_prijs, 0))"
                         + "   FROM bes_bestelling_item i1"
                         + "  WHERE i1.bes_bestelling_key = b.bes_bestelling_key)";

        // Deze mag/hoeft niet meer te fiatteren
        var exclude_fiatter = " COALESCE(b.bes_bestelling_fiat_user, "
                            + " CASE"
                            + " WHEN " + totaalbedrag + " <= " + S("can_selfapprove")
                            + " THEN -1"
                            + " ELSE b.prs_perslid_key"
                            + " END)";

        sql = "SELECT b.bes_bestelling_key"
            + ", bes_bestelling_parentkey"
            + ", bes_bestelling_datum datum"
            + ", bes_bestelling_leverdatum leverdatum"
            + ", bes_bestelling_retourvan_key"
            + ", (SELECT " + S("prs_pers_string")
              + " FROM prs_perslid p"
              + " WHERE p.prs_perslid_key = b.prs_perslid_key_voor) ordervoor"
            + ", " + S("prs_pers_string") + " prs_string"
            + ", m.mld_adres_naam"
            + ", b.bes_bestelling_plaats"
            + ", bes_bestelling_opmerking"
            + ", b.bes_bestelling_status"
            + ", b.bes_bestelling_module"
            + ", MAX("+ lcl.xsql('bd.ins_discipline_omschrijving','bd.ins_discipline_key') +") categorie"
            + ", UPPER(MAX("+ lcl.xsql('bd.ins_discipline_omschrijving','bd.ins_discipline_key') +")) uppercategorie"
            + ", SUM(i.bes_bestelling_item_aantal * COALESCE(i.bes_bestelling_item_prijs, 0)) bedrag"
            + ", (SELECT k.prs_perslid_key"
              + " FROM prs_kostenplaats k"
              + " WHERE k.prs_kostenplaats_key = b.prs_kostenplaats_key) budgethouder"
            + ", SUM(i.bes_bestelling_item_aantal) aantal"
            + ", MAX(bes_bestelopdr_item_key) isordered"
            + ", (SELECT " + S("prs_pers_string")
              + " FROM prs_perslid p"
              + " WHERE p.prs_perslid_key = prs.getkpverantwoordelijke (b.prs_kostenplaats_key, " + S("prs_approvemethod") + ", " + exclude_fiatter + ")) fiatteur"
            + ", (SELECT " + S("prs_pers_string")
              + " FROM prs_perslid p"
              + " WHERE p.prs_perslid_key = b.bes_bestelling_fiat_user) fiat_user"
            + ", bd.ins_discipline_key"
            + ", l.alg_locatie_key"
            + " FROM bes_bestelling b"
            + ", bes_bestelling_item i"
            + ", bes_srtdeel isd"
            + ", bes_srtgroep isg"
            + ", bes_v_aanwezigdiscipline bd" // UWV heeft verwijderde disciplines met bestellingen
            + ", prs_perslid p"
            + ", mld_adres m"
            + ", prs_v_afdeling_boom boom"
            + ", prs_kostenplaats k"
            + ", alg_locatie l"
            + ", alg_district di"
            + " WHERE b.mld_adres_key_lev = m.mld_adres_key"
            + " AND b.bes_bestelling_key = i.bes_bestelling_key"
            + " AND b.fac_activiteit_key IS NULL"
            + " AND i.bes_srtdeel_key = isd.bes_srtdeel_key"
            + " AND isd.bes_srtgroep_key = isg.bes_srtgroep_key"
            + " AND isg.ins_discipline_key = bd.ins_discipline_key"
            + " AND p.prs_perslid_key = b.prs_perslid_key"
            // Only orders for persons in my organisation as determined by 3D authorization are visible
            // See NOTE B
            + (((fronto || backo) && (authparams.PRSreadlevel > 0))
              ? " AND p.prs_afdeling_key IN "
                + "    (SELECT prs_afdeling_key FROM prs_v_afdeling_familie a"
                + "      WHERE a.prs_afdeling_elder_key IN"
                + "        (SELECT aa.prs_afdeling_elder_key"
                + "           FROM prs_v_afdeling_familie aa"
                + "          WHERE aa.prs_afdeling_key = " + user.prs_afdeling_key()
                + "            AND aa.niveau = " + authparams.PRSreadlevel + "))"
              : "")
            + " AND p.prs_afdeling_key = boom.prs_afdeling_key"
            + " AND b.prs_kostenplaats_key = k.prs_kostenplaats_key(+)"
            + " AND m.alg_locatie_key = l.alg_locatie_key(+)"
            + " AND l.alg_district_key = di.alg_district_key(+)"
            // Alleen change bestellingen (embargo) tonen.
            + " AND b.bes_bestelling_key NOT IN (SELECT b1.bes_bestelling_parentkey"
            + "                                    FROM bes_bestelling b1"
            + "                                   WHERE b1.bes_bestelling_parentkey IS NOT NULL)";

        if (params.mld_key)
          sql += " AND b.mld_melding_key = " + params.mld_key;

        if (rfo_key)
        {
          sql += " AND COALESCE(b.bes_bestelling_parentkey, b.bes_bestelling_key) = " + rfo_key;
        }
        else
        {
          sql += makeDisGroepItemsSql(catalogus_key, besgroep_key, item_key, item);

          if (requestor_key)
          {
            sql += " AND b.prs_perslid_key = " + requestor_key;
          }
          if (personfor_key)
            sql += " AND b.prs_perslid_key_voor = " + personfor_key;
          if (kp)
            sql += " AND k.prs_kostenplaats_upper LIKE " + safe.quoted_sql_wild(kp + "%");
          if (dep_key)
            sql += " AND p.prs_afdeling_key = " + dep_key;
          if (authparams.ALGreadlevel >= 0)
          {
            sql += " AND m.alg_locatie_key IN (SELECT alg_locatie_key FROM fac_v_my_locations"
                 + " WHERE prs_perslid_key = " + user_key + " AND niveau = " + authparams.ALGreadlevel + ")"
          }

          if (showbesstatus != '') sql += " AND bes_bestelling_status IN (" + showbesstatus + ")";

          // ========================================
          // Next add filter condition for flex-props
          // ========================================

          sql += getKenmerkSql("BES", "b.bes_bestelling_key");
        }

        var sql_group_by = " GROUP BY b.bes_bestelling_key"
                         + ", bes_bestelling_parentkey"
                         + ", bes_bestelling_datum"
                         + ", bes_bestelling_leverdatum"
                         + ", bd.ins_discipline_key"
                         + (excel? ", UPPER("+ lcl.xsql('bd.ins_discipline_omschrijving','bd.ins_discipline_key') +")" : "")
                         + ", b.bes_bestelling_retourvan_key"
                         + ", " + S("prs_pers_string")
                         + ", m.mld_adres_naam"
                         + ", b.bes_bestelling_plaats"
                         + ", bes_bestelling_opmerking"
                         + ", b.bes_bestelling_status"
                         + ", b.bes_bestelling_module"
                         + ", b.prs_kostenplaats_key"
                         + ", b.prs_perslid_key"
                         + ", k.prs_perslid_key"
                         + ", k.prs_kostenplaatsgrp_key"
                         + ", b.bes_bestelling_fiat_user"
                         + ", l.alg_locatie_key"
                         + ", prs_perslid_key_voor";

        sql = discx3d (sql,
                       "bd.ins_discipline_key",
                       "di.alg_regio_key",
                       "di.alg_district_key",
                       "l.alg_locatie_key",
                       "gebouw_auth_not_supported",
                       "verdieping_auth_not_supported",
                       "ruimte_auth_not_supported",
                       "boom.prs_bedrijf_key",
                       "boom.prs_afdeling_key",
                       pautfunction,
                       (!rfo_key && catalogus_key? catalogus_key : ""),
                       2,
                       sql_group_by);

        sql += " ORDER BY" + (excel? " uppercategorie," : "")
             + " bes_bestelling_status, bes_bestelling_key DESC";

        /*****************************************************
         * Callback functies ResultsetTable for fo and bo only
         ****************************************************/

        function fnrowClassFOBO(oRs)
        {
          var rowclass = '';
          var m_stat = oRs("bes_bestelling_status").value;
          if (backo && m_stat == 2)
            rowclass = 'vervallen';

          if (oRs("aantal").value < 0)
            rowclass = 'retour';  // ipv selectable

          return rowclass;
        }

        // Extra data voor de client om daar dynamisch buttons te kunnen activeren.
        function fnrowData(oRs)
        {
          var besKey = oRs("bes_bestelling_key").value;
          var besType = oRs("bes_bestelling_module").value;
          var data = {besKey: besKey, besType: besType};

          return JSON.stringify(data);
        }

        function fnrowActionEnablerFOBO(oRs)
        {
          var eEdit   = true; // Altijd aanwezig
          var m_stat = oRs("bes_bestelling_status").value;
          if (m_stat == 3) // func_enabled_bestelling is traag, alleen als echt noodzakelijk
          {
            // We weten al dat we mogen lezen. Geef dat mee aan func_enabled_bestelling, die wordt daar efficienter van
            var bes_bestelling = bes.bestelling_info(oRs("bes_bestelling_key").Value);
            var this_bes = bes.func_enabled_bestelling(bes_bestelling, { knownread: true });
            var eAccept = this_bes.canAccept || this_bes.canAccept2 || this_bes.canAccept3 || this_bes.canAccept4 || this_bes.canAccept5;
            var eReject = this_bes.canReject;
          }
          var eSubmit = (m_stat == 4 && !oRs("isordered").value); // eigenlijk this_bes.canSubmit maar we hebben niet
                                                                  // altijd bes.func_enabled_bestelling gedaan

          var data = {eAccept: eAccept, eReject: eReject, eEdit: eEdit, eSubmit: eSubmit};

          return data;
        }

        function fncolApprover(oRs)
        { // in 5.0 is het onafhankelijk van bedragen, zie ../fac/fac_fiatttering_list voor meer uitleg
          // als hij nog niet volledig is gefiatteerd tonen we de eerstevolgende fiatteur
          // als hij wel volledig is gefiatteerd tonen we de laatste fiatteur
          var m_stat = oRs("bes_bestelling_status").value;
          if (m_stat == 2) // we zijn nog niet klaar met fiatteren
          {
            approver = oRs.fields("fiatteur").value;
          }
          else
          {
            approver = oRs.fields("fiat_user").value; // die heeft eventueel gefiatteerd
          }
          return safe.html(approver);
        }

        function fncolStatus(oRs)
        {
            var m_stat = oRs("bes_bestelling_status").value;
            if (m_stat == 4 && !oRs("isordered").value)
                return fncolStatusOmschr(oRs) + "\nNog geen opdracht";
            else
                return fncolStatusOmschr(oRs);
        }

        function fncolOrderVoorFOBO(oRs)
        {
          var bestellingvoor = oRs("ordervoor").value
          if (!excel && oRs("prs_string").value == bestellingvoor)
          	bestellingvoor = "";
          return safe.html(bestellingvoor);
        }

        /*********************************************************
         * End callback functies ResultsetTable for fo and bo only
         ********************************************************/
        var buttons = [];
        if (fronto && authparams.PRSwritelevel < 9 && authparams.ALGwritelevel < 9)
        {
            var addurl = "appl/bes/bes_bestelling.asp?x=x";
            addurl += buildTransitParam(["urole", "mld_key"], params)  // TODO: welke allemaal?
            buttons.push({ icon: "plus.png", title: L("lcl_add"), action: "FcltMgr.openDetail('"+addurl+"', '"+L("lcl_add")+"')" });
        }
        var rst = new ResultsetTable({keyColumn: "bes_bestelling_key",
                                      ID: "bestable",
                                      rowClass: fnrowClassFOBO,
                                      rowData: fnrowData,
                                      rowActionEnabler: fnrowActionEnablerFOBO,
                                      sql: sql,
                                      flexModule: "BES",
                                      noPrint: params.tiny,
                                      flexId: "bes_bestelling_key",
                                      flexGroupId: "ins_discipline_key",
                                      filterParams: params,
                                      outputmode: outputmode,
                                      title: L("lcl_bes_bestellingen"),
                                      showAll: showall,
                                      buttons: buttons
                                     });

        // Kolommen
        rst.addColumn(new Column({caption: L("lcl_bes_key"), content: fncolBesNr}));
        rst.addColumn(new Column({caption: L("lcl_bes_add_date"), content: "datum", datatype: "date"}));
        if (outputmode != 0)
          rst.addColumn(new Column({caption: L("lcl_bes_deli_date"), content: "leverdatum", datatype: "date"}));
        rst.addColumn(new Column({caption: L("lcl_bes_discipline"), content: "categorie", hasActions: true}));
        rst.addColumn(new Column({caption: L("lcl_bes_RFO_status"), content: fncolStatus}));
        rst.addColumn(new Column({caption: L("lcl_rfo_requestor"), content: "prs_string"}));
        rst.addColumn(new Column({caption: L("lcl_bes_order_for"), content: fncolOrderVoorFOBO, combine: true}));
        rst.addColumn(new Column({caption: L("lcl_delivery_address"), content: "mld_adres_naam"}));
        rst.addColumn(new Column({caption: L("lcl_bes_del_room"), content: "bes_bestelling_plaats", combine:true}));
        if (backo)
          rst.addColumn(new Column({caption: L("lcl_rfo_total_sum_eur"), content: "bedrag", datatype: "currency", total: true}));
        rst.addColumn(new Column({caption: L("lcl_bes_approver"), content: fncolApprover}));

        // Acties
        rst.addAction({action: "besEdit", caption: L("lcl_edit"), isDefault: true});
        rst.addAction({action: "besAccept", caption: L("lcl_bes_accept"), enabler: "eAccept", multi: !params.tiny, multiOnce: true});
        rst.addAction({action: "besReject", caption: L("lcl_reject"), enabler: "eReject", multi: !params.tiny, multiOnce: true});
        // Geen multi als S("mld_order_autoprint") = 1; (orders will be printed each time they are saved)
        // anders worden na bestellen multi opdrachtbonnen geprint wat ook foutmeldingen geeft
        rst.addAction({action: "besSubmit", caption: L("lcl_bes_submit"), enabler: "eSubmit", multi: (S("mld_order_autoprint") != 1 && !params.tiny), multiOnce: true});

        var count = rst.processResultset();
      } %>
    </body>
  </html>
<%
}
%>

