--
-- $Id$
--
-- Customer specific once-script BLCC#70821.sql.
DEFINE thisfile = 'BLCC#70821.sql'
DEFINE dbuser   = '^BLCC'

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

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

-- BLCC#70821: Splits de 2501=Soft Services Cleaning contracten per 28-02-2022!
SET SERVEROUTPUT ON size 1000000;

DECLARE
   CURSOR ccnt (p_splitsindexdatum DATE)
   IS
        SELECT '[' || c.cnt_contract_nummer_intern || '.' || COALESCE (c.cnt_contract_versie, '0') || '] '
                  aanduiding,
               c.ins_discipline_key,
               c.cnt_contract_key,
               c.cnt_contract_nummer_intern,
               c.cnt_contract_versie,
               c.cnt_contract_looptijd_tot einddatum
          FROM cnt_v_aanwezigcontract c
         WHERE c.ins_discipline_key IN (2501)        -- Soft Services Cleaning
               AND c.cnt_contract_status = 0                     -- Definitief
               AND c.cnt_contract_looptijd_tot > p_splitsindexdatum
               AND NOT EXISTS -- Beschouw alleen laatste versie van contracten
                     (SELECT 1
                        FROM cnt_v_aanwezigcontract
                       WHERE cnt_contract_nummer_intern = c.cnt_contract_nummer_intern
                             AND cnt_contract_versie > COALESCE (c.cnt_contract_versie, '0'))
      ORDER BY TO_NUMBER (c.cnt_contract_nummer_intern);

   c_splitsindexdatum   DATE := TO_DATE ('01032022', 'ddmmyyyy');
   v_errormsg           VARCHAR2 (1000);
   oracle_err_num       NUMBER;
   oracle_err_mes       VARCHAR2 (200);
   v_count              NUMBER;
BEGIN
   v_count := 0;

   FOR rec IN ccnt (c_splitsindexdatum)
   LOOP
      BEGIN
         v_errormsg := 'Fout splitsen contract.';
         cnt.splitscontract (rec.cnt_contract_key, c_splitsindexdatum, NULL, NULL);
         COMMIT;

         v_count := v_count + 1;
      EXCEPTION
         WHEN OTHERS
         THEN
            oracle_err_num := SQLCODE;
            oracle_err_mes := SUBSTR (SQLERRM, 1, 200);
            v_errormsg := v_errormsg || ' ORACLE (error ' || oracle_err_num || '/' || oracle_err_mes || ')';
            DBMS_OUTPUT.PUT_LINE ('E: ' || rec.aanduiding || v_errormsg);
            COMMIT;
      END;
   END LOOP;

   DBMS_OUTPUT.PUT_LINE ('S: ' || TO_CHAR (v_count) || ' contracten gesplitst');
   COMMIT;
END;
/

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

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

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