--
-- $Id$
--
-- Script containing customer specific configuration sql statements for RABO: Rabobank

DEFINE thisfile = 'RABO.SQL'
DEFINE dbuser   = '^RABO'

SET ECHO ON
SET DEFINE ON
COLUMN fcltlogfile NEW_VALUE fcltlogfile NOPRINT;
WHENEVER SQLERROR EXIT;
SELECT adm.scriptspoolfile('&dbuser', '&thisfile') AS fcltlogfile FROM DUAL;
WHENEVER SQLERROR CONTINUE;
SPOOL &fcltlogfile
SET DEFINE OFF

------ payload begin ------

-- export overrules
-- exact
-- Leverancier overrulles


-- exact verkoop
CREATE OR REPLACE VIEW rabo_v_export_exact_verkoop    (RESULT, result_order) AS SELECT RESULT, result_order FROM aaxx_v_export_exact_verkoop;
CREATE OR REPLACE PROCEDURE rabo_select_exact_verkoop (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2
)
AS
BEGIN
  aaxx_select_exact_verkoop(p_applname, p_applrun, to_char(sysdate, 'yyyy'));
END;
/
CREATE OR REPLACE PROCEDURE rabo_export_exact_verkoop (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2,
   p_filedir    IN   VARCHAR2,
   p_filename   IN   VARCHAR2
)
AS
BEGIN
  aaxx_export_exact_verkoop(p_applname, p_applrun, p_filedir, p_filename, to_char(sysdate, 'yyyy'));
END;
/

-- exact verkoop over het vorige jaar
CREATE OR REPLACE VIEW rabo_v_export_exact_verkoop_vj    (RESULT, result_order) AS SELECT RESULT, result_order FROM aaxx_v_export_exact_verkoop;
CREATE OR REPLACE PROCEDURE rabo_select_exact_verkoop_vj (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2
)
AS
BEGIN
  aaxx_select_exact_verkoop(p_applname, p_applrun, to_char(to_number(to_char(sysdate, 'yyyy'))-1));
END;
/
CREATE OR REPLACE PROCEDURE rabo_export_exact_verkoop_vj (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2,
   p_filedir    IN   VARCHAR2,
   p_filename   IN   VARCHAR2
)
AS
BEGIN
  aaxx_export_exact_verkoop(p_applname, p_applrun, p_filedir, p_filename, to_char(to_number(to_char(sysdate, 'yyyy'))-1));
END;
/

-- exact projecturen (XML)
CREATE OR REPLACE VIEW rabo_v_export_exact_uren (result, result_order)
AS SELECT result, result_order FROM aaxx_v_export_exact_uren_xml;
CREATE OR REPLACE PROCEDURE rabo_select_exact_uren (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2
)
AS
BEGIN
  aaxx_select_exact_uren_xml(p_applname, p_applrun, '');
END;
/

-- verwerk exact projecturen (XML)
CREATE OR REPLACE PROCEDURE rabo_export_verwerk_exact_uren (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2,
   p_filedir    IN   VARCHAR2,
   p_filename   IN   VARCHAR2
)
AS
BEGIN
  aaxx_export_verwerk_exact_uren(p_applname, p_applrun, p_filedir, p_filename, '');
END;
/


-- bundel catering
CREATE OR REPLACE VIEW rabo_v_export_bundel_catering    (RESULT, result_order) AS SELECT RESULT, result_order FROM aaxx_v_export_bundel_catering;
CREATE OR REPLACE PROCEDURE rabo_export_bundel_catering (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2,
   p_filedir    IN   VARCHAR2,
   p_filename   IN   VARCHAR2
)
AS
BEGIN
  aaxx_export_bundel_catering(p_applname, p_applrun, p_filedir, p_filename);
END;
/


-- script om dagelijks terugkerende scripts aan te roepen.
CREATE OR REPLACE PROCEDURE rabo_select_daily_task (p_applname IN VARCHAR2, p_applrun IN VARCHAR2)
AS

    CURSOR c
    IS
        SELECT ins_deel_omschrijving,
               ins_deel_mjb_score1,
               ins_deel_mjb_score2,
               ins_srtcontroledl_xcp_key,
               (SELECT ins_kenmerkdeel_waarde
                  FROM ins_kenmerkdeel kd, ins_kenmerk k, ins_srtkenmerk sk
                 WHERE     kd.ins_deel_key = d.ins_deel_key
                       AND kd.ins_kenmerk_key = k.ins_kenmerk_key
                       AND k.ins_srtkenmerk_key = sk.ins_srtkenmerk_key
                       AND sk.ins_srtkenmerk_omschrijving = 'Kritische asset')
                   kritisch,
               (SELECT TO_CHAR (ins_deelsrtcontrole_datum_org, 'YYYY')
                  FROM ins_deelsrtcontrole dsc
                 WHERE     dsc.ins_deel_key = d.ins_deel_key
                       AND dsc.ins_srtcontrole_key = x.ins_srtcontrole_key
                       AND dsc.ins_deelsrtcontrole_status = 0)
                   orgdatum,
               COALESCE (fac.nextcyclusdate (
                             COALESCE (
                                 (SELECT MAX (ins_deelsrtcontrole_datum)
                                    FROM ins_deelsrtcontrole dsc
                                   WHERE     ins_deelsrtcontrole_status <> 0
                                         AND dsc.ins_deel_key =
                                             d.ins_deel_key
                                         AND dsc.ins_srtcontrole_key =
                                             x.ins_srtcontrole_key),
                                 DECODE (x.ins_srtcontroledl_xcp_startdat,
                                         NULL, d.ins_deel_aanmaak,
                                         TO_DATE (NULL))),
                             1,                                    -- interval
                             ins_srtcontroledl_xcp_eenheid,
                             ins_srtcontroledl_xcp_periode,
                             ins_srtcontroledl_xcp_bits,
                             1,
                             1),
                         ins_srtcontroledl_xcp_startdat) volgende
          FROM ins_deel               d,
               ins_srtcontroledl_xcp  x,
               ins_srtcontrole        sc,
               ctr_disc_params        dp
         WHERE     d.ins_deel_key = x.ins_deel_key
               AND x.ins_srtcontrole_key = sc.ins_srtcontrole_key
               AND sc.ctr_discipline_key = dp.ctr_ins_discipline_key
               AND dp.ctr_disc_params_ismjob = 1;

    v_prio     NUMBER;
    v_freeze   VARCHAR2 (4);

BEGIN
   -- we gaan dagelijks de conditiescores bijwerken.
   cnd_export_nen2767_cond_score ('NEN2767_COND_SCORE', SYSDATE, NULL, NULL);

   -- vervolgens worden deze geagregeerd naar gebouw en locatieniveau.
   cnd_export_nen2767_aggr_score('NEN2767_AGGR_SCORE', SYSDATE,NULL,NULL);

   -- pas de urgentie bij de taken aan
   SELECT fac.getSetting ('mjb_feeze_year')
     INTO v_freeze
     FROM DUAL;

   FOR rec IN c
   LOOP
      -- kritische installatie en planning dit jaar of vorig jaar niet uitgevoerd.
      IF     rec.kritisch = 1
         AND (TO_CHAR (rec.volgende, 'yyyy') = v_freeze OR rec.orgdatum <= v_freeze)
      THEN
          v_prio := 3;
      -- planning vorig jaar + storingshistorie
      ELSIF rec.orgdatum < v_freeze
      THEN
         v_prio := 3;
      --prioriteit < 4
      ELSIF rec.ins_deel_mjb_score2 < 4 OR rec.ins_deel_mjb_score1 >= 4
      THEN
         v_prio := 3;
      ELSIF rec.ins_deel_mjb_score2 < 7
      THEN
         v_prio := 2;
      ELSE
         v_prio := 1;
      END IF;

      UPDATE ins_srtcontroledl_xcp x
         SET ins_srtcontroledl_xcp_prio = v_prio
       WHERE x.ins_srtcontroledl_xcp_key = rec.ins_srtcontroledl_xcp_key;
   END LOOP;

   aaxx_daily_task (p_applname, p_applrun);
END;
/

CREATE OR REPLACE VIEW rabo_v_export_status_axxerion (
   result,
   result_order
   )
AS
   SELECT fac_rapport_regel, fac_rapport_volgnr
     FROM fac_rapport
    WHERE fac_rapport_node = SUBSTR ('STATUS_AXXERION', 1, 12);


CREATE OR REPLACE PROCEDURE rabo_select_status_axxerion (p_applname   IN VARCHAR2,
                                                         p_applrun    IN VARCHAR2)
AS
   CURSOR c (
      p_from                 DATE,
      p_to                   DATE)
   IS
        SELECT mld_melding_externnr,
               fac_tracking_datum,
               DECODE (sn.fac_srtnotificatie_code,
                       'MLDACP', 'ACCEPT',
                       'MLDREJ', 'REJECT',
                       'MLDAFM', 'CLOSE',
                       'MLDAFR', 'FINCLOSE',
                       'MLDUPD', 'UPDATE',
                       'Invalid')
                  status,
               mld_melding_einddatum,
               mld_melding_opmerking,
               DECODE (fac_srtnotificatie_code, 'MLDUPD', 1, 0) volgorde
          FROM fac_tracking t, fac_srtnotificatie sn, mld_melding m
         WHERE fac_tracking_datum BETWEEN p_from AND p_to
           AND t.fac_srtnotificatie_key = sn.fac_srtnotificatie_key
           AND t.fac_tracking_refkey = m.mld_melding_key
           AND m.mld_melding_externnr IS NOT NULL
           AND (sn.fac_srtnotificatie_code = 'MLDACP'
             OR sn.fac_srtnotificatie_code = 'MLDREJ'
             OR sn.fac_srtnotificatie_code = 'MLDAFM'
             OR sn.fac_srtnotificatie_code = 'MLDAFR'
             OR sn.fac_srtnotificatie_code = 'MLDUPD')
      ORDER BY mld_melding_externnr, volgorde, fac_tracking_datum;

   v_from       DATE;
   v_to         DATE;
   v_count      NUMBER;
   v_externnr   VARCHAR2 (10);
   v_bestand    VARCHAR2 (100);
   v_empty      NUMBER;
BEGIN
   v_count := 0;
   v_empty := 1;
   v_externnr := '9999';
   v_bestand := SUBSTR (p_applname, 1, 12);

   -- de laatste synchronisatietijd wordt opgeslagen in fac_rapport met een speciale node naam eindigend op een 1.
   -- mocht deze niet gevuld zijn (initieel) dan gebruiken we het huidige uur.
   BEGIN
      SELECT fac.safe_to_date (fac_rapport_regel, 'yyyy-mm-dd hh24:mi')
        INTO v_from
        FROM fac_rapport
       WHERE SUBSTR (v_bestand, 1, 11) || '1' = fac_rapport_node;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         v_from := TRUNC (SYSDATE, 'HH24');
   END;

   -- het einde van de periode mag niet verder liggen dan de huidige tijd
   v_to := v_from + 1 / (24 * 4);

   IF v_to > SYSDATE
   THEN
      v_to := v_from;
   END IF;

   -- Eerst opruiming
   DELETE FROM imp_log
         WHERE imp_log_applicatie = p_applname;

   DELETE fac_rapport
    WHERE fac_rapport_node = v_bestand;

   -- als de export een tijdje niet gedraaid is dan halen we dit weer in door de periode groter te maken.
   WHILE v_to + 1 / (24 * 4) < SYSDATE AND v_count < 10
   LOOP
      v_to := v_to + 1 / (24 * 4);
      v_count := v_count + 1;
   END LOOP;

   -- header
   aaxx_add_xml_row (v_bestand, '<?xml version="1.0" encoding="windows-1252"?>');
   aaxx_add_xml_row (v_bestand, '<facilitor>');
   aaxx_add_xml_row (v_bestand, '<meldingstatusses>');

   FOR rec IN c (v_from, v_to)
   LOOP
      v_empty := 0;

      IF NOT (rec.mld_melding_externnr = v_externnr AND rec.status = 'UPDATE')
      THEN
         v_externnr := rec.mld_melding_externnr;
         aaxx_add_xml_row (v_bestand, '<meldingstatus key="' || rec.mld_melding_externnr || '">');
         aaxx_add_xml_element (v_bestand,
                               'timestamp',
                               TO_CHAR (rec.fac_tracking_datum, 'dd-mm-yyyy hh24:mi'));
         aaxx_add_xml_element (v_bestand, 'status', rec.status);
         aaxx_add_xml_element (v_bestand, 'afhandeling', SUBSTR(rec.mld_melding_opmerking,1,1900));
         aaxx_add_xml_element (v_bestand,
                               'oplosdatum',
                               TO_CHAR (rec.mld_melding_einddatum, 'dd-mm-yyyy hh24:mi'));
         aaxx_add_xml_row (v_bestand, '</meldingstatus>');
      END IF;
   END LOOP;

   aaxx_add_xml_row (v_bestand, '</meldingstatusses>');
   aaxx_add_xml_row (v_bestand, '</facilitor>');

   -- Als er niet geexporteerd is dan gaan we alle regels verwijderen
   -- zodat er niet een leeg xml bestand komt te staan met alleen de facilitor tags.
   IF v_empty = 1
   THEN
      DELETE fac_rapport
       WHERE fac_rapport_node = v_bestand;
   END IF;

   DELETE fac_rapport
    WHERE fac_rapport_node = SUBSTR (v_bestand, 1, 11) || '1';

   INSERT INTO fac_rapport (fac_rapport_node, fac_rapport_regel)
       VALUES (SUBSTR (v_bestand, 1, 11) || '1', TO_CHAR (v_to, 'yyyy-mm-dd hh24:mi'));
END;
/



CREATE OR REPLACE PROCEDURE rabo_import_bijlagen (p_import_key IN NUMBER)
AS
   CURSOR c_cursor
   IS
        SELECT *
          FROM fac_imp_file
         WHERE fac_import_key = p_import_key
      ORDER BY fac_imp_file_index;

   v_newline             VARCHAR2 (1000);                                             -- Import line
   v_field               VARCHAR2 (100);                                             -- Import field
   v_fielddelimitor      VARCHAR2 (1);                                            -- Field seperator
   v_errormsg            VARCHAR (200);
   v_errorhint           VARCHAR (200);
   v_index               NUMBER;
   oracle_err_num        NUMBER;
   oracle_err_mes        VARCHAR2 (200);

   -- De importvelden
   v_referentie          VARCHAR2 (200);
   v_documentname        VARCHAR2 (200);
   v_extensie            VARCHAR2 (200);
   v_filename            VARCHAR2 (200);

   v_melding_key         mld_melding.mld_melding_key%TYPE;
   v_stdmelding_key      mld_stdmelding.mld_stdmelding_key%TYPE;
   v_discpline_key       ins_tab_discipline.ins_discipline_key%TYPE;
   v_srtdiscipline_key   ins_srtdiscipline.ins_srtdiscipline_key%TYPE;
   v_kenmerk_key         ins_kenmerk.ins_kenmerk_key%TYPE;
   header_found          BOOLEAN;
BEGIN
   -- Init
   header_found := FALSE;
   v_fielddelimitor := ';';
   v_index := 0;

   SELECT COALESCE(MAX(fac_rapport_volgnr),0)+1
     INTO v_index
     FROM fac_rapport
    WHERE fac_rapport_node = 'BIJLAGEN';

   FOR rec1 IN c_cursor
   LOOP
      BEGIN
         v_newline := rec1.fac_imp_file_line;

         IF SUBSTR (v_newline, 1, 3) = '?'
         THEN
            -- EF BB BF aangetroffen
            fac.imp_writelog (p_import_key,
                              'W',
                              'Byte Order Mark aangetroffen',
                              'Bestand heeft onbehandeld UTF-8 formaat.');
            v_newline := SUBSTR (v_newline, 4);
         END IF;

         v_errorhint := 'Velden inlezen';

         fac.imp_getfield (v_newline, v_fielddelimitor, v_documentname);
         fac.imp_getfield (v_newline, v_fielddelimitor, v_extensie);
         fac.imp_getfield (v_newline, v_fielddelimitor, v_referentie);
         fac.imp_getfield (v_newline, v_fielddelimitor, v_filename);

         v_referentie := REPLACE (v_referentie, 'REQ-');

         -- Skip until a valid header is found
         IF UPPER (rec1.fac_imp_file_line) LIKE 'DOCUMENTNAME;EXTENSIE;REFERENTIE;FILENAME%'
         THEN
            -- Sla de kopregel over.
            header_found := TRUE;
         ELSIF (header_found)
         THEN
            -- zoek de juiste melding erbij
            v_errorhint := 'Geen geldige melding kunnen vinden ref:' || v_referentie;

            SELECT m.mld_melding_key,
                   std.mld_stdmelding_key,
                   d.ins_discipline_key,
                   sd.ins_srtdiscipline_key
              INTO v_melding_key,
                   v_stdmelding_key,
                   v_discpline_key,
                   v_srtdiscipline_key
              FROM mld_melding m,
                   mld_stdmelding std,
                   ins_tab_discipline d,
                   ins_srtdiscipline sd
             WHERE m.mld_melding_externnr = v_referentie
               AND m.mld_stdmelding_key = std.mld_stdmelding_key
               AND std.mld_ins_discipline_key = d.ins_discipline_key
               AND d.ins_srtdiscipline_key = sd.ins_srtdiscipline_key;

            -- En het juist kenmerk erbij zoeken.
            v_errorhint := 'Geen geldig kenmerk kunnen vinden ref:' || v_referentie;

            SELECT mld_kenmerk_key
              INTO v_kenmerk_key
              FROM mld_kenmerk
             WHERE mld_srtkenmerk_key = 1                                                -- Bijlagen
               AND ( (mld_kenmerk_niveau = 'T' AND mld_stdmelding_key = v_srtdiscipline_key)
                 OR (mld_kenmerk_niveau = 'D' AND mld_stdmelding_key = v_discpline_key)
                 OR (mld_kenmerk_niveau = 'S' AND mld_stdmelding_key = v_stdmelding_key));

            INSERT INTO fac_rapport (fac_rapport_node, fac_rapport_volgnr, fac_rapport_regel)
                VALUES ('BIJLAGEN',
                        v_index,
                           'mkdir "d:\Apps\Facilitor\AAFM_DATA\RABO\MLD\M'
                        || TO_CHAR (TRUNC (v_melding_key / 1000), 'FM0000')
                        || '___\M'
                        || v_melding_key
                        || '\'
                        || v_kenmerk_key
                        || '\"');

            v_index := v_index + 1;

            INSERT INTO fac_rapport (fac_rapport_node, fac_rapport_volgnr, fac_rapport_regel)
                VALUES ('BIJLAGEN',
                        v_index,
                           'copy /Y "d:\Apps\Facilitor\ftp_sites\RABO\bijlagen\'
                        || v_filename
                        || '" "d:\Apps\Facilitor\AAFM_DATA\RABO\MLD\M'
                        || TO_CHAR (TRUNC (v_melding_key / 1000), 'FM0000')
                        || '___\M'
                        || v_melding_key
                        || '\'
                        || v_kenmerk_key
                        || '\'
                        ||  v_documentname
                        || DECODE (v_extensie, NULL, '', '.' || v_extensie) || '"');

            v_index := v_index + 1;

            INSERT INTO fac_rapport (fac_rapport_node, fac_rapport_volgnr, fac_rapport_regel)
                VALUES ('BIJLAGEN',
                        v_index,
                           'del "d:\Apps\Facilitor\ftp_sites\RABO\bijlagen\'
                        || v_filename
                        || '"');

            v_index := v_index + 1;

         ELSE                                                    -- geen geldige header aangetroffen
            IF rec1.fac_imp_file_index = 1
            THEN
               fac.imp_writelog (p_import_key,
                                 'I',
                                 'Aangetroffen header',
                                 rec1.fac_imp_file_line);
            END IF;
         END IF;

         COMMIT;
      EXCEPTION
         WHEN OTHERS
         THEN
            oracle_err_num := SQLCODE;
            oracle_err_mes := SUBSTR (SQLERRM, 1, 100);
            v_errormsg := 'OTHERS (error ' || oracle_err_num || '/' || oracle_err_mes || ')';
            fac.imp_writelog (p_import_key,
                              'E',
                              SUBSTR (v_errormsg, 1, 1000),
                              v_errorhint);
      END;
   END LOOP;

   IF NOT header_found
   THEN
      fac.imp_writelog (p_import_key,
                        'E',
                        'Geen geldige header aangetroffen',
                        'Bestand is geen geldig bijlagen bestand.');
   END IF;
END;
/

CREATE OR REPLACE PROCEDURE rabo_update_bijlagen (p_import_key NUMBER)
AS
BEGIN
   NULL;
END;
/

CREATE OR REPLACE VIEW rabo_v_export_bijlagen (RESULT, result_order) AS
SELECT fac_rapport_regel, fac_rapport_volgnr
  FROM fac_rapport
 WHERE fac_rapport_node = 'BIJLAGEN';

CREATE OR REPLACE PROCEDURE rabo_export_bijlagen (
   p_applname   IN   VARCHAR2,
   p_applrun    IN   VARCHAR2,
   p_filedir    IN   VARCHAR2,
   p_filename   IN   VARCHAR2
)
AS
BEGIN
  DELETE fac_rapport WHERE fac_rapport_node = 'BIJLAGEN';
END;
/

------ payload end   ------

SET DEFINE OFF
BEGIN adm.systrackscriptId ('$Id$', 0); END;
/

COMMIT;
SET ECHO OFF
SPOOL OFF
SET DEFINE ON
PROMPT Logfile of this upgrade is: &fcltlogfile