/*  Author: Venkata Potluri
    Date:   Oct 22, 2015
   This SQL will import the special accrual item for each out of balance transaction into EIM_LOY_ACRLIT table */

DECLARE
   LOG_ROW_ID   NUMBER := 0;
   ROW_COUNT    NUMBER := 0;

   CURSOR C1
   IS
      SELECT PT.PROMO_POINTS,
             PT.PROCESS_DT,
             PT.ROW_ID,
             PT.MEM_NUM,
             T.TXN_NUM,
             ROWNUM
        FROM SIEBEL_PURGE.TEMP_TXN_10212015 PT
             INNER JOIN SIEBEL.S_LOY_TXN T ON PT.ROW_ID = T.ROW_ID
       WHERE     PT.PROCESS_DT BETWEEN TO_DATE ('10/18/2015', 'mm/dd/yyyy')
                                   AND SYSDATE
             AND PT.PROCESS_DT IS NOT NULL
             AND PT.NUM_POINTS <> PT.TOTAL_POINTS
             AND PT.PROMO_POINTS > 0;
BEGIN
   SELECT CASE WHEN MAX (ROW_ID) IS NOT NULL THEN MAX (ROW_ID) + 1 ELSE 1 END
     INTO LOG_ROW_ID
     FROM SIEBEL_PURGE.PURGE_LOG_10012012 Z;

   INSERT INTO SIEBEL_PURGE.PURGE_LOG_10012012 (ROW_ID,
                                                PROCESS_NAME,
                                                START_TIME)
      SELECT LOG_ROW_ID, 'Populate EIM_LOY_ACRLIT', SYSDATE FROM DUAL;

   COMMIT;

   FOR SF IN C1
   LOOP
      INSERT INTO SIEBEL.EIM_LOY_ACRLIT (ROW_ID,
                                         CREATED_BY,
                                         LAST_UPD_BY,
                                         IF_ROW_BATCH_NUM,
                                         IF_ROW_STAT,
                                         ITEM_NUM,
                                         ACTION_ROW_ID,
                                         ACCRUALED_VALUE,
                                         EXPIRATION_DT,
                                         PRTNR_PT_DEBT_QTY,
                                         USED_VALUE,
                                         MEMBER_MEM_NUM,
                                         TXN_NUM,
                                         PROCESS_DT,
                                         RET_EFF_DT)
           VALUES (SF.ROWNUM,
                   '0-1',
                   '0-1',
                   9000,
                   'FOR_IMPORT',
                   'PURGESPECIALFIX' || TO_CHAR (SF.ROWNUM),
                   '1-182T',
                   SF.PROMO_POINTS,
                   TO_DATE ('10/01/2112', 'mm/dd/yyyy'),
                   0,
                   0,
                   SF.MEM_NUM,
                   SF.TXN_NUM,
                   SF.PROCESS_DT,
                   SF.PROCESS_DT);

      ROW_COUNT := ROW_COUNT + SQL%ROWCOUNT;
      COMMIT;
   END LOOP;

   UPDATE SIEBEL_PURGE.PURGE_LOG_10012012
      SET END_TIME = SYSDATE, PROCESSED_ROWS = ROW_COUNT
    WHERE ROW_ID = LOG_ROW_ID;

   COMMIT;
END;
/

QUIT