<% /*
     $Revision$
     $Id$
    File:               opdr_list.inc
    Description:        Show an overview of orders in list-form,
                        which meets with the given requirements
    Parameters:
        urole           user role (only bo until now)
        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
        opdr_id         search for orders with the given order key
        catalogus_key   search for orders with the given catalogus (discipline) key
        besgroep_key    search for orders with the given besgroep (srtgroup) key
        item_key        search for orders with the given item (srtdeel) key
        supplier_key    search for orders with the given supplier key
        requestor_key   search for orders for selected requestor
        personfor_key   search for orders for person
        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
        besopdrstafg    search for orders with the status besopdrstafg
        besopdrstnew    search for orders with the status besopdrstnew
        besopdrstbeh    search for orders with the status besopdrstbeh
        besopdrstbes    search for orders with the status besopdrstbes
        besopdrstbev    search for orders with the status besopdrstbev
        besopdrstlev    search for orders with the status besopdrstlev
        besopdrstver    search for orders with the status besopdrstver

    Context:            Search action from opdr_search.asp form
    Note:

*/ %>

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

<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["../bes/opdr_list.js"]
                    });

function opdr_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.catalogus_key : key
  // params.besgroep_key  : key
  // params.item_key      : key
  // params.supplier_key  : key
  // params.requestor_key : key
  // params.personfor_key : key
  // params.dep_key       : key
  // params.kp            : wildcard string
  // params.item          : wildcard string
  // params.besopdrstafg  : boolean (true | false)
  // params.besopdrstnew  : boolean (true | false)
  // params.besopdrstbeh  : boolean (true | false)
  // params.besopdrstbes  : boolean (true | false)
  // params.besopdrstbev  : boolean (true | false)
  // params.besopdrstlev  : boolean (true | false)
  // params.besopdrstver  : boolean (true | false)

  var authparams = user.checkAutorisation(pautfunction);

  var urole = params.urole;

  // 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 opdr_id = params.opdr_id;
  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 requestor_key = params.requestor_key;
  var personfor_key = params.personfor_key;
  var dep_key = params.dep_key;
  var kp = params.kp;
  var item = params.item;
  var adr_key = params.adr_key;
  var loc_key = params.loc_key;
  var besopdrstafg = params.besopdrstafg;
  var besopdrstnew = params.besopdrstnew;
  var besopdrstbeh = params.besopdrstbeh;
  var besopdrstbes = params.besopdrstbes;
  var besopdrstbev = params.besopdrstbev;
  var besopdrstlev = params.besopdrstlev;
  var besopdrstver = params.besopdrstver;

  var showopdrstatus = "";
  if (besopdrstafg) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "1";
  if (besopdrstnew) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "2";
  if (besopdrstbeh) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "3";
  if (besopdrstbes) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "4";
  if (besopdrstbev) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "5";
  if (besopdrstlev) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "6";
  if (besopdrstver) showopdrstatus = (showopdrstatus == ""? "" : showopdrstatus + ",") + "7";

%>

  <html>
    <head>
<%    FCLTHeader.Generate({ outputmode: outputmode }); %>
      <script type="text/javascript">
        // Text strings used by bes_list.js
        urole = "<%=urole%>";
        bes_bestelopdr_prefix = "<%=S("bes_bestelopdr_prefix")%>";
      </script>
    </head>

    <body id="listbody">

<%
      // Distinct omdat een bes_bestelopdr over meerdere bes_bestelling_items kan gaan
      sql = "SELECT DISTINCT b.bes_bestelopdr_key"
          + ",      bes_bestelopdr_datum datum"
          + ",      bes_bestelling_retourvan_key"
          + ",      be.prs_bedrijf_naam prs_bedrijf_naam"
          // straks + ",      bes.bestelopdr_tooltip(b.bes_bestelopdr_key) tooltip" // TODO JGL: Dit is een dure tooltip!
          + ",      b.bes_bestelopdr_status"
          + ",      ma.mld_adres_naam afleveradres"
          + ",      bst.bes_bestelling_plaats"
          + ",      bst.bes_bestelling_leverdatum"
          + ", " + S("prs_pers_string") + " requestor"
          + ", (SELECT " + S("prs_pers_string")
            + " FROM prs_perslid p"
            + " WHERE p.prs_perslid_key = bst.prs_perslid_key_voor) ordervoor"
//          + ",      bst.prs_perslid_key"
//          + ",      bst.prs_perslid_key_voor"
          + ",      b.bes_bestelopdr_id"
          + ",      bid.ins_discipline_key"
          + ",      bes_bestelling_parentkey"
          + ",      bes_bestelopdr_opmerking"
          + ",      bes_bestelopdr_delivery_opmerk"
          + ",      (SELECT SUM(boi1.bes_bestelopdr_item_aantal)"
          + "          FROM bes_bestelopdr_item boi1"
          + "         WHERE boi1.bes_bestelopdr_key = boi.bes_bestelopdr_key) bes_bestelopdr_item_aantal"
          + ",      (SELECT SUM(boi1.bes_bestelopdr_item_aantalontv)"
          + "          FROM bes_bestelopdr_item boi1"
          + "         WHERE boi1.bes_bestelopdr_key = boi.bes_bestelopdr_key) bes_bestelopdr_item_aantalontv"
          + "  FROM bes_bestelopdr b"
          + ",      prs_bedrijf be"
          + ",      mld_adres ma"
          + ",      bes_bestelopdr_item boi"
          + ",      bes_bestelling_item bi"
          + ",      bes_bestelling bst"
          + ",      bes_srtdeel isd"
          + ",      bes_srtgroep isg"
          + ",      ins_tab_discipline bid"
          + ",      prs_perslid p"
          + ",      prs_v_afdeling_boom boom"
          + ",      alg_locatie l"
          + ",      alg_district di"
          + " WHERE be.prs_bedrijf_key = b.prs_bedrijf_key "
          + "   AND ma.mld_adres_key=b.mld_adres_key_lev"
          + "   AND bi.bes_bestelopdr_item_key = boi.bes_bestelopdr_item_key"
          + "   AND bst.bes_bestelling_key = bi.bes_bestelling_key "
          + "   AND boi.bes_bestelopdr_key = b.bes_bestelopdr_key "
          + "   AND bi.bes_srtdeel_key = isd.bes_srtdeel_key"
          + "   AND isd.bes_srtgroep_key = isg.bes_srtgroep_key"
          + "   AND isg.ins_discipline_key = bid.ins_discipline_key"
          + "   AND p.prs_perslid_key = b.prs_perslid_key" // De aanmaker van de bestelopdracht.
          + "   AND p.prs_afdeling_key = boom.prs_afdeling_key"
          + "   AND ma.alg_locatie_key = l.alg_locatie_key(+)"
          + "   AND l.alg_district_key = di.alg_district_key(+)"
          // Alleen change bestellingopdrachten (embargo) tonen.
          + "   AND bst.bes_bestelling_key NOT IN (SELECT b1.bes_bestelling_parentkey"
          + "                                        FROM bes_bestelling b1"
          + "                                       WHERE b1.bes_bestelling_parentkey IS NOT NULL)";

      if (opdr_id)
      {
        sql += " AND UPPER(b.bes_bestelopdr_id) LIKE " + safe.quoted_sql_wild(opdr_id + "%");
      }
      else // Niet op opdrachtnummer gezocht, maar op andere criteria
      {
        if (requestor_key) // opdracht behorende bij aanvrager van bestelling
          sql += " AND p.prs_perslid_key = " + requestor_key;

        if (personfor_key)
          sql += " AND bst.prs_perslid_key_voor = " + personfor_key;

        if (dep_key)
        { // opdrachten van aanvragers uit deze afdelingen
          sql += " AND p.prs_afdeling_key = " + dep_key;
        }

        if (kp)
        {
          sql += " AND bst.prs_kostenplaats_key IN"
               + " (SELECT prs_kostenplaats_key"
               + " FROM prs_kostenplaats"
               + " WHERE prs_kostenplaats_upper LIKE " + safe.quoted_sql_wild(kp + "%") +")";
        }

        if (item)
          sql += " AND UPPER(isd.bes_srtdeel_omschrijving) LIKE " + safe.quoted_sql_wild("%" + item + "%");

        // AND b.bes_bestelopdr_key IN (...item_key...) hoef niet gebruikt te worden omdat geen bedragen worden getoond.
        if (item_key)
          sql += " AND isd.bes_srtdeel_key = " + item_key;
        else if (besgroep_key)
          sql += " AND isg.bes_srtgroep_key = " + besgroep_key;
        else if (catalogus_key)
          sql += " AND bid.ins_discipline_key = " + catalogus_key;

        if (adr_key)
        { // opdrachten van een bepaald afleveradres
          sql += " AND ma.mld_adres_key = " + adr_key;
        }
        if (loc_key)
        { // opdrachten voro een bepaalde locatie
          sql += " AND ma.alg_locatie_key = " + loc_key;
        }

        if (showopdrstatus != "")
          //sql += " AND bst.bes_bestelling_status IN (" + showopdrstatus + ")"
          sql += " AND b.bes_bestelopdr_status IN (" + showopdrstatus + ")"

        if (supplier_key)
          sql += " AND be.prs_bedrijf_key = " + supplier_key;
      }

      // apply 3D authorization to the locations and to the to the organisations (both ALG and PRS)
      // merk op: CONN heeft bijvoorbeeld verschillend voor PRS niveau en UWVA verschillen voor ALG_niveau
      // We ondersteunen alleen district en locatie niveau!
      sql = discx3d(sql,
                    "bid.ins_discipline_key",
                    "di.alg_regio_key",
                    "l.alg_district_key",
                    "l.alg_locatie_key",
                    "", // UNSUPPORTED_GEBOUW
                    "", // UNSUPPORTED_VERDIEPING
                    "", // UNSUPPORTED_RUIMTE
                    "boom.prs_bedrijf_key",
                    "boom.prs_afdeling_key",
                    pautfunction,
                    (!opdr_id && catalogus_key? catalogus_key : ""),
                    2);

      // bes.bestelopdr_tooltip pas helemaal aan de buitenkant voor performance
      sql = "SELECT xx.*, bes.bestelopdr_tooltip (xx.bes_bestelopdr_key) tooltip"
          + "  FROM (" + sql + ") xx"
          + " ORDER BY bes_bestelopdr_status, prs_bedrijf_naam, bes_bestelopdr_key DESC";

      /**********************************
       * Callback functies ResultsetTable
       *********************************/

      function fnrowData(oRs)
      {
        var opdrId = oRs("bes_bestelopdr_id").Value;
        // bReado = (m_stat==1 || m_stat==2)?'1':'0';

        var data = { opdrId: opdrId};
        return JSON.stringify(data);
      }

      function fnrowActionEnabler(oRs)
      {
        var bestelopdr_key = oRs("bes_bestelopdr_key").value;
        // TODO: bestelopdrKey of discipline en prs_perslid_key meegeven aan func_enabled_bestelopdr
        //var bes_bestelopdr = bes.bestelopdracht_info(bestelopdr_key);
        var this_bestelopdr = bes.func_enabled_bestelopdracht(bestelopdr_key);

        var eEdit = true;
        var eDeliver = this_bestelopdr.canDeliver;
        var eSend = this_bestelopdr.canSend;
        var eReject = this_bestelopdr.canReject;
        var eAccept = this_bestelopdr.canAccept;
        var data = {eEdit: eEdit, eDeliver:eDeliver, eSend:eSend, eReject:eReject, eAccept: eAccept};

        return data;
      }

      function fncolBesOpdrId(oRs)
      {
        return S("bes_bestelopdr_prefix") + oRs.fields("bes_bestelopdr_id").value + (oRs.fields("bes_bestelling_parentkey").value > 0? "*" : "");
      }

      function fncolStatusText(oRs)
      {
        var opdrStatus = oRs("bes_bestelopdr_status").Value;
        var retourvanKey = oRs("bes_bestelling_retourvan_key").Value;
        if (opdrStatus == 6 && retourvanKey > 0)
          return L("lcl_bes_collected");
        var itemAantal = oRs("bes_bestelopdr_item_aantal").Value;
        var itemAantalOntv = oRs("bes_bestelopdr_item_aantalontv").Value;
        if (opdrStatus == 4 && itemAantalOntv > 0 && itemAantalOntv < itemAantal)
          return L("lcl_bes_deels_geleverd");
        else
          return bes.getbesopdrstatustext(opdrStatus);
      }

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

      var rst = new ResultsetTable({keyColumn: "bes_bestelopdr_key",
                                    ID: "opdrtable",
                                    rowData: fnrowData,
                                    rowActionEnabler: fnrowActionEnabler,
                                    sql: sql,
                                    filterParams: params,
                                    outputmode: outputmode,
                                    title: L("lcl_bes_bestelling_orders"),
                                    showAll: showall
                                    });

      // Kolommen
      rst.addColumn(new Column({caption: L("lcl_ord_order_num"), content: fncolBesOpdrId}));
      rst.addColumn(new Column({caption: L("lcl_bes_add_date"), content: "datum", datatype: "date"}));
      rst.addColumn(new Column({caption: L("lcl_bes_Supplier"), content: "prs_bedrijf_naam", tooltip: "tooltip"}));
      rst.addColumn(new Column({caption: L("lcl_rfo_requestor"), content: "requestor"}));
      rst.addColumn(new Column({caption: L("lcl_bes_order_for"), content: fncolOrderVoor, combine: true}));
      rst.addColumn(new Column({caption: L("lcl_bes_del_place"), content: "afleveradres"}));
      rst.addColumn(new Column({caption: L("lcl_bes_del_room"), content: "bes_bestelling_plaats", combine: true }));
      rst.addColumn(new Column({caption: L("lcl_bes_deli_date"), content: "bes_bestelling_leverdatum", datatype: "date"}));
      rst.addColumn(new Column({caption: L("lcl_bes_Bes_status"), content: fncolStatusText}));
      if (outputmode != 0)
      {
        rst.addColumn(new Column({caption: L("lcl_remark"), content: "bes_bestelopdr_opmerking"}));
        rst.addColumn(new Column({caption: L("lcl_bes_comment"), content: "bes_bestelopdr_delivery_opmerk"}));
      }

      // Acties
      rst.addAction({action: "opdrEdit",    caption: L("lcl_edit"),          isDefault: true});
      rst.addAction({action: "opdrSent",    caption: L("lcl_ord_is_ordsnt"), enabler: "eSend",    multi: true, multiOnce: true});
      rst.addAction({action: "opdrReject",  caption: L("lcl_reject"),        enabler: "eReject",  multi: true, multiOnce: true});
      rst.addAction({action: "opdrAccept",  caption: L("lcl_accept"),        enabler: "eAccept", multi: true, multiOnce: true});
      rst.addAction({action: "opdrDeliver", caption: L("lcl_bes_delivery"),  enabler: "eDeliver"});

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