--------------------------------------------------------
--  File created - Monday-July-08-2013
--  Removed TEST packages as these cause great confusion   
--------------------------------------------------------

--------------------------------------------------------
--  DDL for Function CAN_EDIT_PKG_IN_PROJECT
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "CAN_EDIT_PKG_IN_PROJECT" ( nPvId IN NUMBER, nRtagId IN NUMBER ) RETURN NUMBER IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    VExt PACKAGE_VERSIONS.V_EXT%TYPE;
	ProjId NUMBER;
	RowCount NUMBER;
	cReleaseMode CHAR(1);

BEGIN
	
	--RETURN 1;
	
	
	/*--------------- Business Rules Here -------------------*/
	IF (nRtagId IS NULL)  OR  (nRtagId < 1)THEN
		RETURN 0;
	END IF;
	/*-------------------------------------------------------*/
	
	 
	 
	 
	
	
	/*-- First Check. See if package is used through release reference --*/
	SELECT COUNT(rc.PV_ID) INTO RowCount
	  FROM (
	  		SELECT rl.REF_RTAG_ID
			  FROM RELEASE_LINKS rl
			 WHERE rl.RTAG_ID = nRtagId
	  		) rl,
			RELEASE_CONTENT rc
	  WHERE rc.RTAG_ID = rl.REF_RTAG_ID
	    AND rc.PV_ID = nPvId;			
	
	
	-- Decide if package can be edited  
	IF RowCount > 0 THEN
		-- Package is referenced from other release, hence cannot be edited
		RETURN 0;	
		
	ELSE
	
		-- Check is only done for releases in restrictive mode
		SELECT rt.OFFICIAL INTO cReleaseMode
		  FROM RELEASE_TAGS rt
		 WHERE rt.RTAG_ID = nRtagId;
		
		IF cReleaseMode = 'N'OR cReleaseMode = 'R' THEN
			-- Do not do any firther checking,
			-- Package is editable here
			RETURN 1;
		END IF;	
		
	END IF;
	
	
	
	
	/*-- Further checking --*/
	-- Get proj_id
	SELECT rt.PROJ_ID  INTO  ProjId
	  FROM RELEASE_TAGS rt
	 WHERE rt.RTAG_ID = nRtagId;
	   
	
	 
	BEGIN

		-- Get v_ext
		SELECT pv.V_EXT  INTO  Vext
		  FROM PACKAGE_VERSIONS pv
		 WHERE pv.PV_ID = nPvId;  

		EXCEPTION
	    	WHEN NO_DATA_FOUND THEN
	       		Vext := NULL;

	END;	 
	 
	
	--Temp Hack for Step Project
	IF ProjId != 281 THEN
		-- Find if package can be edited in this project
			SELECT COUNT(pe.EXT_NAME) INTO RowCount
	 		FROM PROJECT_EXTENTIONS pe
			WHERE pe.PROJ_ID != ProjId  
	  		AND pe.EXT_NAME = VExt;
	END IF;		
	  
	  
	-- Decide if package can be edited  
	IF RowCount > 0 THEN
		-- Package extension is found in other projects, hece NOT EDITABLE
		RETURN 0;
	ELSE
		RETURN 1;	
	END IF;

	
END CAN_EDIT_PKG_IN_PROJECT;
/
--------------------------------------------------------
--  DDL for Function DT_ADDUSEROBJECT
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "DT_ADDUSEROBJECT" RETURN NUMBER IS NEWOBJECTID NUMBER; BEGIN /* GET THE NEXT VALUE FROM THE SEQUENCE FOR THE OBJECT ID */ SELECT MICROSOFTSEQDTPROPERTIES.NEXTVAL INTO NEWOBJECTID FROM DUAL; /* ADD THE PARENT NODE FOR THE NEW OBJECT */ INSERT INTO MICROSOFTDTPROPERTIES ( ID, OBJECTID, PROPERTY ) VALUES ( NEWOBJECTID, NEWOBJECTID, 'DtgSchemaOBJECT' ); RETURN( NEWOBJECTID ); END DT_ADDUSEROBJECT;
/
--------------------------------------------------------
--  DDL for Function GET_AUTOMATED_LABEL
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "GET_AUTOMATED_LABEL" ( nPvId IN NUMBER ) RETURN VARCHAR2 IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

	sPkgName VARCHAR2(4000);
	sVext VARCHAR2(4000);

BEGIN

	-- Get package details
	SELECT pkg.PKG_NAME, pv.V_EXT INTO sPkgName, sVext
	  FROM PACKAGE_VERSIONS pv,
	  	   PACKAGES pkg
	 WHERE pv.PKG_ID = pkg.PKG_ID
	   AND pv.PV_ID = nPvId;


	-- Generate Label for automated build
	RETURN UPPER( sPkgName ||'.'|| nPvId || sVext ||'.WIP' );

END GET_AUTOMATED_LABEL;
/
--------------------------------------------------------
--  DDL for Function GET_BUILD_NUMBER
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "GET_BUILD_NUMBER" (s_version IN VARCHAR2) RETURN VARCHAR2
IS
/* ---------------------------------------------------------------------------
    Version: 1.0.0
   --------------------------------------------------------------------------- */
BEGIN
    IF is_number(s_version) AND LENGTH(s_version) > 3
    THEN
        RETURN MOD(TO_NUMBER(s_version), 1000);
    ELSE
        RETURN 0;
    END IF;
END get_build_number;
/
--------------------------------------------------------
--  DDL for Function GET_PATCH_VERSION
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "GET_PATCH_VERSION" (s_version IN VARCHAR2) RETURN VARCHAR2
IS
/* ---------------------------------------------------------------------------
    Version: 1.0.0
   --------------------------------------------------------------------------- */
BEGIN
    IF is_number(s_version) AND LENGTH(s_version) > 3
    THEN
        RETURN FLOOR(TO_NUMBER(s_version) / 1000);
    ELSE
        RETURN s_version;
    END IF;
END get_patch_version;
/
--------------------------------------------------------
--  DDL for Function GET_PV_FIRST_MODIFIED
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "GET_PV_FIRST_MODIFIED" (v_pv_id NUMBER) RETURN DATE IS
  ret DATE;
BEGIN
  SELECT q.modified_stamp
    INTO ret
    FROM (
            SELECT level AS lvl, pvc.pv_id, pvc.modified_stamp, pvc.change_type
              FROM package_versions pvc
              START WITH pvc.pv_id = v_pv_id
            CONNECT BY NOCYCLE pvc.pv_id = PRIOR pvc.last_pv_id
          ) Q
  WHERE q.change_type IS NOT NULL
    AND rownum = 1
  ORDER BY q.lvl;

  RETURN ret;
END;
/
--------------------------------------------------------
--  DDL for Function GET_V_EXT
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "GET_V_EXT" (SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE) RETURN VARCHAR2 IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;
    lastDot NUMBER;

BEGIN
    lastDot := INSTR (SSpkg_version, '.', -1);

    IF ( lastDot > 0 ) AND ( lastDot != LENGTH(SSpkg_version) )
    THEN
        -- YES dot separator found --
        SSV_EXT := SUBSTR (SSpkg_version, lastDot, LENGTH(SSpkg_version)-lastDot+1);

        IF IS_VERSION_EXTENSION ( SSV_EXT )
        THEN
            RETURN SSV_EXT;
        ELSE
            RETURN NULL;
        END IF;

    ELSE
        -- NO dot separator found --
        RETURN NULL;
    END IF;

END GET_V_EXT;
/
--------------------------------------------------------
--  DDL for Function IN_LIST_NUMBER
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "IN_LIST_NUMBER" ( sInList IN VARCHAR2 ) RETURN RELMGR_NUMBER_TAB_t IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    sync_rtags		   RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
	pos				   NUMBER;
	in_list			   VARCHAR2(4000) := sInList || ',';

BEGIN

	IF NOT sInList IS NULL
	THEN
		LOOP
	        EXIT WHEN in_list IS NULL;
	        pos := INSTR ( in_list, ',' );
	        sync_rtags.extend;
	        sync_rtags(sync_rtags.count) := LTRIM ( RTRIM ( SUBSTR ( in_list, 1, pos-1 ) ) );
	        in_list := SUBSTR ( in_list, pos+1 );
		END LOOP;
	END IF;

	RETURN sync_rtags;
END IN_LIST_NUMBER;
/
--------------------------------------------------------
--  DDL for Function IN_LIST_NUMBER2
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "IN_LIST_NUMBER2" ( sInList IN VARCHAR2 ) RETURN RELMGR_NUMBER_TAB_t IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    sync_rtags		   RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
	pos				   NUMBER;
	in_list			   VARCHAR2(32767) := sInList || ',';

BEGIN

	IF NOT sInList IS NULL
	THEN
		LOOP
	        EXIT WHEN in_list IS NULL;
	        pos := INSTR ( in_list, ',' );
	        sync_rtags.extend;
	        sync_rtags(sync_rtags.count) := LTRIM ( RTRIM ( SUBSTR ( in_list, 1, pos-1 ) ) );
	        in_list := SUBSTR ( in_list, pos+1 );
		END LOOP;
	END IF;

	RETURN sync_rtags;
END IN_LIST_NUMBER2;
/
--------------------------------------------------------
--  DDL for Function IN_LIST_VARCHAR2
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "IN_LIST_VARCHAR2" ( sInList IN VARCHAR2, cSeparator IN VARCHAR2 ) RETURN RELMGR_VARCHAR2_TAB_t IS

/* ---------------------------------------------------------------------------
    Version: 3.1
   --------------------------------------------------------------------------- */

    cItemCollection	   RELMGR_VARCHAR2_TAB_t := RELMGR_VARCHAR2_TAB_t();
	pos				   NUMBER;
	in_list			   VARCHAR2(4000) := sInList || cSeparator;
	val				   VARCHAR2(4000);

BEGIN

	IF NOT sInList IS NULL
	THEN
		LOOP
	        EXIT WHEN in_list IS NULL;
	        pos := INSTR ( in_list, cSeparator );
			val := LTRIM ( RTRIM ( SUBSTR ( in_list, 1, pos-1 ) ) );
			
			IF (NOT val IS NULL) THEN
		        cItemCollection.extend;
		        cItemCollection(cItemCollection.count) := val;
			END IF;
			
	        in_list := SUBSTR ( in_list, pos+1 );
		END LOOP;
	END IF;

	RETURN cItemCollection;
END IN_LIST_VARCHAR2;
/
--------------------------------------------------------
--  DDL for Function IS_NUMBER
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "IS_NUMBER" (p_val IN VARCHAR2) RETURN BOOLEAN
IS
   temp_num NUMBER;
/* ---------------------------------------------------------------------------
    Version: 1.0.0
   --------------------------------------------------------------------------- */
BEGIN
   temp_num := TO_NUMBER(p_val);
   RETURN true;
EXCEPTION WHEN VALUE_ERROR THEN
   RETURN false;
END IS_NUMBER;
/
--------------------------------------------------------
--  DDL for Function IS_VERSION_EXTENSION
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "IS_VERSION_EXTENSION" (SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE) RETURN BOOLEAN
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

BEGIN
    IF LENGTH ( TRIM (TRANSLATE (SSV_EXT, '.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',' ') ) ) > 0
    THEN
        RETURN FALSE;
    ELSE
        RETURN TRUE;
    END IF;

END IS_VERSION_EXTENSION;
/
--------------------------------------------------------
--  DDL for Function ORA_SYSDATE
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "ORA_SYSDATE" 
RETURN DATE
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */
BEGIN

    RETURN TO_DATE( TO_CHAR( SYSDATE,'DD-MON-YYYY' ),'DD-MON-YYYY' );
END ORA_SYSDATE;
/
--------------------------------------------------------
--  DDL for Function ORA_SYSDATETIME
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "ORA_SYSDATETIME" 
RETURN DATE
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */
BEGIN

    RETURN TO_DATE( TO_CHAR( SYSDATE,'DD-MON-YYYY HH24:MI:SS' ),'DD-MON-YYYY HH24:MI:SS' );
END ORA_SYSDATETIME;
/
--------------------------------------------------------
--  DDL for Function PERL_DBD_TESTFUNC
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "PERL_DBD_TESTFUNC" (a in integer, b in integer) return integer is c integer; begin if b is null then c := 0; else c := b; end if; return a * c + 1; end;
/
--------------------------------------------------------
--  DDL for Function RELEASE_MODE
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MODE" ( nRtagId IN NUMBER ) RETURN CHAR IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

   returnValue CHAR(1);

BEGIN

    /*--------------- Business Rules Here -------------------*/
	/*-------------------------------------------------------*/
	
	-- Get release mode
	SELECT rt.OFFICIAL INTO returnValue
	  FROM RELEASE_TAGS rt
	 WHERE rt.RTAG_ID = nRtagId;
	
	RETURN returnValue;
	
END RELEASE_MODE;
/
--------------------------------------------------------
--  DDL for Package PK_APP_UTILS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_APP_UTILS" IS
/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  26/Apr/2005
||  Spec Version:   1.0
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/

	PROCEDURE GET_CURRENT_PARAMETERS ( ProjId IN VARCHAR2, RtagId IN VARCHAR2, records OUT typeCur);

	/*================================================================================================*/

END PK_APP_UTILS;
/
--------------------------------------------------------
--  DDL for Package PK_ARCHIVE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_ARCHIVE" 
IS
/*
------------------------------
||  Author:  Rupesh Solanki
||  Date:    26 October 2006
||  Version:   1.0
------------------------------
*/

   /*================================================================================================*/
   PROCEDURE populate_packages_table;
   
   PROCEDURE populate_archive_data_table (
      nrtagid   IN   release_tags.rtag_id%TYPE
   );

   PROCEDURE migrate_pv_to_archive_SCHEMA (nrtagid IN release_tags.rtag_id%TYPE);

   PROCEDURE migrate_rtag_to_archive_schema (
      nrtagid   IN   release_tags.rtag_id%TYPE
   );

   PROCEDURE clean_up_archive_data_table (
      nrtagid   IN   release_tags.rtag_id%TYPE
   );

   PROCEDURE write_action_log (
      nuserid   IN   NUMBER,
      nrtagid   IN   release_tags.rtag_id%TYPE
   );
/*================================================================================================*/
END pk_archive;
/
--------------------------------------------------------
--  DDL for Package PK_BUILDAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_BUILDAPI" 
IS
   /*================================================================================================*/
   PROCEDURE add_product_component (
      npvid           IN   NUMBER,
      sosname         IN   VARCHAR2,
      sorigfilepath   IN   VARCHAR2,
      sfilename       IN   VARCHAR2,
      sdestfilepath   IN   VARCHAR2,
      nbytesize       IN   NUMBER,
      scrccksum       IN   VARCHAR2
   );

   PROCEDURE remove_all_product_components (
      npvid     IN   NUMBER,
      sosname   IN   VARCHAR2
   );

   /*================================================================================================*/
   FUNCTION get_osid (sosname IN VARCHAR2)
      RETURN NUMBER;

   /*================================================================================================*/
   PROCEDURE update_build_service (
      sdatabaseserver   IN   VARCHAR2,
      swebserver        IN   VARCHAR2,
      smailserver       IN   VARCHAR2,
      smailsender       IN   VARCHAR2,
      sdiskspace        IN   VARCHAR2,
      ssbommanagement   IN   VARCHAR2
   );

   /*================================================================================================*/
   PROCEDURE update_build_service_info (
      sdatabaseserver   IN   VARCHAR2,
      sarchiveserver    IN   VARCHAR2,
      smailserver       IN   VARCHAR2,
      smailsender       IN   VARCHAR2,
      sdiskspace        IN   VARCHAR2,
      ssbommanagement   IN   VARCHAR2
   );

   /*================================================================================================*/
   PROCEDURE add_gbe_machtype (sgbevalue IN VARCHAR2);

   /*================================================================================================*/
   PROCEDURE remove_gbe_machtype (ngbe_id IN NUMBER);

   /*================================================================================================*/
   PROCEDURE update_gbe_machtype (ngbe_id IN NUMBER, sgbevalue IN VARCHAR2);

   /*================================================================================================*/
   PROCEDURE add_daemon (
      sdaemonhostname   IN   VARCHAR2,
      nrtagid           IN   NUMBER,
      ngbeid            IN   NUMBER,
      sgbebuildfilter   IN   VARCHAR2
   );

   /*================================================================================================*/
   PROCEDURE delete_daemon (srconidlist IN VARCHAR2);

   /*================================================================================================*/
   PROCEDURE update_daemon (
      sdaemonhostname   IN   VARCHAR2,
      nrconid           IN   NUMBER,
      ngbeid            IN   NUMBER,
      sgbebuildfilter   IN   VARCHAR2
   );

   /*================================================================================================*/
   PROCEDURE insert_schedule_info (
      dschedulepause     IN   DATE,
      dscheduleresume    IN   DATE,
      crepeat            IN   VARCHAR2,
      cindefinitepause   IN   VARCHAR2
   );

   /*================================================================================================*/
   PROCEDURE delete_schedule (nscheduleid IN NUMBER);

   /*================================================================================================*/
   PROCEDURE set_infinite_pause;

   /*================================================================================================*/
   PROCEDURE set_resume;

   /*================================================================================================*/
   PROCEDURE delete_out_of_date_schedule;

   /*================================================================================================*/
   PROCEDURE set_daemon_resume (nrconid IN NUMBER);

   /*================================================================================================*/
   PROCEDURE set_daemon_pause (nrconid IN NUMBER);

   /*================================================================================================*/
   PROCEDURE set_daemon_disable (nrconid NUMBER);

   /*================================================================================================*/
   PROCEDURE set_daemon_states (nrtagid NUMBER, nstate NUMBER);

   /*================================================================================================*/
   PROCEDURE mark_daemon_inst_in_progress( nInstId IN NUMBER );
   /*================================================================================================*/
   PROCEDURE mark_daemon_inst_completed( nInstId IN NUMBER );
   /*================================================================================================*/
   FUNCTION get_daemon_inst(
      nRtag_id IN NUMBER,
      nInst_id IN OUT NUMBER,
      nOp_code IN OUT NUMBER,
      nPv_id OUT NUMBER,
      nUser_id OUT NUMBER,
      nInProgress OUT NUMBER
   ) RETURN NUMBER;
   /*================================================================================================*/
   PROCEDURE cleanup_stranded_daemon_insts;
   /*================================================================================================*/
   PROCEDURE insert_daemon_inst(
      nOp_code IN NUMBER,
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER,
      nSchedDate IN DATE,
      nRepeatSecs IN NUMBER,
      nAddedDate IN DATE,
      nUser_id IN NUMBER
   );
   /*================================================================================================*/
   PROCEDURE del_daemon_inst( nInstId IN NUMBER );
   /*================================================================================================*/
   PROCEDURE del_daemon_inst_by_rtag_pvid(
      nOp_code IN NUMBER,
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER
   );
   /*================================================================================================*/
   PROCEDURE update_daemon_inst(
      nInstId IN NUMBER,
      nOp_code IN NUMBER,
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER,
      nSchedDate IN DATE,
      nRepeatSecs IN NUMBER,
      nAddedDate IN DATE,
      nUser_id IN NUMBER
   );
   /*================================================================================================*/
   FUNCTION daemon_ops_for_rtag_pvid(
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER
   ) RETURN VARCHAR2;
   /*================================================================================================*/
   FUNCTION daemon_ops_for_rtag(
      nRtag_id IN NUMBER
   ) RETURN VARCHAR2;
   /*================================================================================================*/
   PROCEDURE add_daemon_config (
      nrtagid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   );
   /*================================================================================================*/
   PROCEDURE update_daemon_config (
      nrconid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   );

   /*================================================================================================*/
   PROCEDURE add_build_machine (
      sdisplay_name          IN   VARCHAR2,
      smachine_hostname      IN   VARCHAR2,
      ngbeid                 IN   NUMBER,
      sdescription           IN   VARCHAR2
   );
   /*================================================================================================*/
   PROCEDURE delete_build_machine (sbmcon_id_list IN VARCHAR2);
   /*================================================================================================*/
   PROCEDURE update_build_machine (
      nbmcon_id              IN   NUMBER,
      sdisplay_name          IN   VARCHAR2,
      smachine_hostname      IN   VARCHAR2,
      ngbeid                 IN   NUMBER,
      sdescription           IN   VARCHAR2
   );
END pk_buildapi;
/
--------------------------------------------------------
--  DDL for Package PK_ENVIRONMENT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_ENVIRONMENT" IS
/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  28/May/2008
||  Spec Version:   1.2
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

	/*================================================================================================*/

	FUNCTION SELECT_ENVIRONMENT_AREA ( cDlock IN PACKAGE_VERSIONS.DLOCKED%TYPE ) RETURN NUMBER;
	FUNCTION GET_PACKAGE_AREA ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	FUNCTION GET_VIEW_LOCATION ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE ADD_PACKAGE ( PvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE ADD_PACKAGE_BULK ( PvIdList IN VARCHAR2, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REPLACE_PACKAGE ( newPvId IN NUMBER, oldPvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	FUNCTION REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, ForceRemove IN CHAR ) RETURN NUMBER;

	PROCEDURE GET_ENVIRONMENT_ITEMS ( ViewType IN NUMBER, UserId IN NUMBER, RtagId IN NUMBER,  sViewIdShowList IN VARCHAR2, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );
	PROCEDURE GET_RELEASED_ITEMS ( ViewType IN NUMBER, UserId IN NUMBER, RtagId IN NUMBER,  sViewIdShowList IN VARCHAR2, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );
	PROCEDURE GET_PENDING_ITEMS ( ViewType IN NUMBER, UserId IN NUMBER, RtagId IN NUMBER,  sViewIdShowList IN VARCHAR2, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );
	PROCEDURE GET_WORK_IN_PROGRESS_ITEMS ( ViewType IN NUMBER, UserId IN NUMBER, RtagId IN NUMBER,  sViewIdShowList IN VARCHAR2, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );

	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );

	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;


	PROCEDURE MAKE_RELEASE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE MAKE_UNRELEASE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );

	PROCEDURE MAKE_PENDING ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE MAKE_APPROVED ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE MAKE_REJECT ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE APPROVE_MERGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );

	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );

	PROCEDURE FIND_PACKAGE ( sKeyword IN VARCHAR2, nRtagId IN NUMBER, nSearchArea IN NUMBER, RecordSet OUT typeCur );
	PROCEDURE FIND_FILE ( sKeyword IN VARCHAR2, nRtagId IN NUMBER, nSearchArea IN NUMBER, nPageSize IN NUMBER, RecordSet OUT typeCur );

	PROCEDURE AUTO_MAKE_RELEASE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, VExt IN
							 PACKAGE_VERSIONS.V_EXT%TYPE, SSV_EXT IN PACKAGE_VERSIONS.V_EXT%TYPE,
							 CloneFromPvId IN NUMBER );

	PROCEDURE GET_PRODRELEASE_ITEMS ( RtagId IN NUMBER, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );

	PROCEDURE GET_INTEGRATION_ITEMS ( RtagId IN NUMBER, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );

	PROCEDURE GET_TEST_ITEMS ( RtagId IN NUMBER, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );

	PROCEDURE GET_DEPLOY_ITEMS ( RtagId IN NUMBER, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );

	PROCEDURE GET_REJECT_ITEMS ( RtagId IN NUMBER, nTrueRecordCount OUT NUMBER, RecordSet OUT typeCur );
	/*================================================================================================*/

END PK_ENVIRONMENT;
/
--------------------------------------------------------
--  DDL for Package PK_LICENCING
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_LICENCING" IS
/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  19/Aug/2008
||  Spec Version:   1.0
------------------------------
*/

   TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
   PROCEDURE ADD_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER );
   PROCEDURE REMOVE_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER );
   PROCEDURE CLONE_LICENCING( fromPvId IN NUMBER, toPvId IN NUMBER, UserId IN NUMBER );
   FUNCTION  IS_LICENCED( PvId IN NUMBER, licenceId IN NUMBER) RETURN NUMBER;
   PROCEDURE REMOVE_ALL_LICENCING( PvId IN NUMBER, UserId IN NUMBER );
   /*================================================================================================*/

END PK_LICENCING;
/
--------------------------------------------------------
--  DDL for Package PK_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_PACKAGE" 
IS
/*
------------------------------
||  Last Modified:  Jeremy Tweddle
||  Modified Date:  24/08/2007
||
------------------------------
*/
   TYPE typecur IS REF CURSOR;

/*================================================================================================*/
   PROCEDURE new_version (
      nlastpvid                   IN       NUMBER,
      snewpkgversion              IN       VARCHAR2 DEFAULT NULL,
      cbuildtype                  IN       CHAR,
      nsettopvid                  IN       NUMBER DEFAULT NULL,
      nrtagid                     IN       NUMBER,
      nuserid                     IN       NUMBER,
      enumissues_state_imported   IN       NUMBER,
      returnpvid                  OUT      NUMBER
   );

   PROCEDURE change_state (
      pvid       IN   NUMBER,
      newstate   IN   package_versions.dlocked%TYPE,
      userid     IN   NUMBER
   );

   PROCEDURE new_patch (
      snewpatchversion   IN       package_versions.pkg_version%TYPE,
      nparentpvid        IN       NUMBER,
      spatchidlist       IN       VARCHAR2,
      nuserid            IN       NUMBER,
      returnpatchid      OUT      NUMBER
   );

   PROCEDURE obsolete_patch (
      patchid            IN   NUMBER,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   );

   PROCEDURE obsolete_patches (
      spatchidlist       IN   VARCHAR2,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   );

   PROCEDURE destroy_package (
      pvid               IN       NUMBER,
      overridewarnings   IN       CHAR DEFAULT 'N',
      problemstring      OUT      VARCHAR2
   );

   PROCEDURE add_process (
      nprocid         IN   processes.proc_id%TYPE,
      shealthtag      IN   processes.proc_name%TYPE,
      sprocdesc       IN   processes.proc_description%TYPE,
      scmdinterface   IN   processes.run_as%TYPE,
      spkgowner       IN   processes.pkg_owner%TYPE,
      sisinterface    IN   processes.is_interface%TYPE,
      npvid           IN   package_processes.pv_id%TYPE,
      nuserid         IN   NUMBER
   );

   PROCEDURE add_package_process (
      nprocidlist   IN   VARCHAR2,
      npvid         IN   package_processes.pv_id%TYPE,
      nuserid       IN   NUMBER
   );
   
   

   PROCEDURE remove_process (
      nprocid   IN   package_processes.proc_id%TYPE,
      npvid     IN   package_processes.pv_id%TYPE,
      nuserid   IN   NUMBER
   );
   
   PROCEDURE move_package (
   	  npvid  			  IN package_versions.pv_id%TYPE,
	  nrtagid 			  IN release_tags.rtag_id%TYPE,
	  nnewrtagid 		  IN release_tags.rtag_id%TYPE,
	  nuserid			  IN NUMBER		 
   ); 
   
   PROCEDURE modify_product_state (
   	  npvid IN package_versions.pv_id%TYPE,
	  nrtagid IN release_tags.rtag_id%TYPE,
	  nstateid IN product_states.state_id%TYPE,
	  nuserid IN NUMBER
   );
   
   PROCEDURE add_code_review_url (
        npvid           IN    NUMBER,
        nprojid         IN    NUMBER,
        surl            IN    VARCHAR2,
        sreason         IN    VARCHAR2,
        ddateofreview   IN    DATE
   );
    
   PROCEDURE update_code_review_url (
        ncrid           IN    NUMBER,
        nprojid         IN    NUMBER,
        surl            IN    VARCHAR2,
        sreason         IN    VARCHAR2
   );
        
   PROCEDURE remove_code_review_url (
        ncrid           IN    NUMBER
   );
/*================================================================================================*/
END pk_package;
/
--------------------------------------------------------
--  DDL for Package PK_PLANNED
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_PLANNED" IS
/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  28/May/2008
||  Spec Version:   1.1
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
	PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );
	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );
	PROCEDURE MERGE_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, mergeOperation IN CHAR);
	/*================================================================================================*/

END PK_PLANNED;
/
--------------------------------------------------------
--  DDL for Package PK_PROJECT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_PROJECT" IS

    TYPE typecur IS REF CURSOR;

    /*------------------------------------------------------------------------*/
    PROCEDURE update_base_url (
        nprojid   IN  projects.proj_id%TYPE,
        sbaseurl  IN  VARCHAR2
    );
    /*------------------------------------------------------------------------*/
    PROCEDURE update_project_config (
    nprojid   IN  projects.proj_id%TYPE,
    sbaseurl  IN  VARCHAR2,
    sjirakey  IN  VARCHAR2
    );
    /*------------------------------------------------------------------------*/

    END pk_project;
/
--------------------------------------------------------
--  DDL for Package PK_RELEASE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_RELEASE" IS
/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  12/Sep/2005
||  Body Version:   3.0
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
	PROCEDURE New_Release ( sReleaseName IN VARCHAR2, sReleaseComments IN VARCHAR2, nProjId IN NUMBER, nSourceRtagId IN NUMBER, sIsBranched IN CHAR, nUserId IN NUMBER );
	PROCEDURE Update_Release ( nRtagId IN NUMBER, sReleaseName IN VARCHAR2, sReleaseComments IN VARCHAR2, nParentRtagId IN NUMBER, nMASSRtagId IN NUMBER, nConfigSpecBranch IN VARCHAR2, sOwnerEmail IN VARCHAR2, nUserId IN NUMBER, cState IN VARCHAR );
	PROCEDURE MOVE_RELEASE ( sRtagIdList IN VARCHAR2, nProjId IN NUMBER, nUserId IN NUMBER  );
	PROCEDURE Destroy_Release ( nRtagId IN NUMBER, nUserId IN NUMBER );
	PROCEDURE Import_Release_Contents ( nSourceRtagId IN NUMBER, nTargetRtagId IN NUMBER, nUserId IN NUMBER );
	PROCEDURE Clean_Release_Contents ( nRtagId IN NUMBER, nUserId IN NUMBER );
	FUNCTION GET_PARENT_RTAG ( nRtagId IN NUMBER, nSourceRtagId IN NUMBER, cIsBranch IN CHAR ) RETURN NUMBER;
	PROCEDURE UPDATE_DISPLAY_ORDER ( nProjId IN NUMBER );
	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );								 
	PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	--PROCEDURE ADD_DEPRECATE_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, nPkgId IN NUMBER );
	PROCEDURE REPLACE_PACKAGE ( newPvId IN NUMBER, oldPvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_MATCHING_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE RUN_POST_ACTIONS ( PvId IN NUMBER, RtagId IN NUMBER );
	PROCEDURE RUN_POST_ACTIONS_BULK ( PvId IN NUMBER );
	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );
	PROCEDURE ADD_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER, ProblemString OUT VARCHAR2 );
	PROCEDURE REMOVE_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER );
	PROCEDURE CAN_USER_WRITE_TO_RELEASE ( RtagId IN NUMBER, PvId IN NUMBER, Permission IN CHAR );
	
	/*================================================================================================*/
	
END PK_RELEASE;
/
--------------------------------------------------------
--  DDL for Package PK_RMAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_RMAPI" 
IS
   TYPE typecur IS REF CURSOR;

   FUNCTION package_dependencies (pkgname VARCHAR2, pkgversion VARCHAR2)
      RETURN typecur;

   FUNCTION wip_iteration_package (
      projname        VARCHAR2,
      iterationname   VARCHAR2,
      pkgname         VARCHAR2
   )
      RETURN typecur;

   FUNCTION auto_make_vcsrelease (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      vcstag                   IN   VARCHAR2,
      dependenciesimportlist   IN   VARCHAR2,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )
      RETURN NUMBER;


   PROCEDURE import_dependencies (
      pvid                     IN   NUMBER,
      dependenciesimportlist   IN   VARCHAR2,
      userid                   IN   NUMBER
   );

   FUNCTION return_last_package_version (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2;

   FUNCTION return_wip (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2;

   PROCEDURE update_dash_board (rtagid IN NUMBER);

   FUNCTION exclude_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2
   )
      RETURN NUMBER;

   FUNCTION exclude_indirect_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2,
      rootpvid      IN   NUMBER,
      rootcause     IN   VARCHAR2,
      rootfile      IN   VARCHAR2
   )
      RETURN NUMBER;

   PROCEDURE insert_abt_actionlog (rconid IN NUMBER, action IN VARCHAR2);

   FUNCTION insert_package_metrics (
      rtagid IN NUMBER,
      pkgname IN VARCHAR2,
      vext IN VARCHAR2,
      metricstring IN VARCHAR2
   )
      RETURN NUMBER;

   PROCEDURE update_release_metrics (rtagid IN NUMBER);

   FUNCTION return_vcs_tag(pvid IN NUMBER) RETURN VARCHAR2;

   PROCEDURE update_vcs_details(ipv_id IN NUMBER, vcstag IN VARCHAR2, user_id IN NUMBER);
   
   FUNCTION isSVN( pkgid IN NUMBER ) RETURN NUMBER;
   
   FUNCTION isSVNbyName( pkgname IN VARCHAR2 ) RETURN NUMBER;

END pk_rmapi;
/
--------------------------------------------------------
--  DDL for Package PK_WORK_IN_PROGRESS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "PK_WORK_IN_PROGRESS" IS
/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  2/May/2005
||  Spec Version:   1.0
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
	PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE_BULK ( PvIdList IN VARCHAR2, RtagId IN NUMBER, UserId IN NUMBER );

	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );	
	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );
	/*================================================================================================*/

END PK_WORK_IN_PROGRESS;
/
--------------------------------------------------------
--  DDL for Package RM_ISSUES
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RM_ISSUES" AS

	TYPE T_Cur IS REF CURSOR;

	FUNCTION VerIsGrtrThanOrEqlToStart( XXstart IN NUMBER, XX IN NUMBER, YYstart IN NUMBER, YY IN NUMBER, ZZstart IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER;
	FUNCTION VersionIsBetween( version IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR ) RETURN NUMBER;
	FUNCTION VerIsLessThanOrEqlToEnd( XXend IN NUMBER, XX IN NUMBER, YYend IN NUMBER, YY IN NUMBER, ZZend IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER;
	FUNCTION GetPkgId( pkgName IN VARCHAR2 ) RETURN NUMBER;

	PROCEDURE AllIssues( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 );
	PROCEDURE LoadIssuesTable( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 );
	PROCEDURE InsertIssuesForDepends( pvID IN NUMBER, top_pkgID IN NUMBER, top_pkgName IN VARCHAR2, top_pvID IN NUMBER, top_pkgVer IN VARCHAR2 );

END Rm_Issues;
/
--------------------------------------------------------
--  DDL for Package Body PK_APP_UTILS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_APP_UTILS" IS

/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  26/Apr/2005
||  Body Version:   1.0
------------------------------
*/


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_CURRENT_PARAMETERS ( ProjId IN VARCHAR2, RtagId IN VARCHAR2, records OUT typeCur)   IS


BEGIN


	IF (NOT RtagId IS NULL) THEN
		-- Case with RTAG_ID present
		OPEN records FOR
		SELECT rt.PROJ_ID,
			   rt.RTAG_ID AS RTAG_ID
		  FROM RELEASE_TAGS rt
		 WHERE rt.RTAG_ID = TO_NUMBER(RtagId);

	ELSIF (NOT ProjId IS NULL) THEN
		-- Case with PROJ_ID present
		OPEN records FOR
		SELECT TO_NUMBER(ProjId) AS PROJ_ID,
			   -1 AS RTAG_ID
		  FROM DUAL;

	ELSE
		-- Case with none present
		OPEN records FOR
		SELECT -1 AS PROJ_ID,
			   -1 AS RTAG_ID
		  FROM DUAL;

	END IF;




   	--RETURN records;

END;
/*-------------------------------------------------------------------------------------------------------*/
END PK_APP_UTILS;
/
--------------------------------------------------------
--  DDL for Package Body PK_ARCHIVE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_ARCHIVE" 
IS
/*
------------------------------
||  Author:  Rupesh Solanki
||  Date:    26 October 2006
||  Version:   1.0
------------------------------
*/
/*---------------------------*/
PROCEDURE populate_packages_table IS

BEGIN
		  INSERT INTO archive_manager.PACKAGES
		  (
		  select * from packages where pkg_id not in 
		  		  (select pkg_id from archive_manager.packages)
		  );

          INSERT INTO archive_manager.PROCESSES
          (
          select * from processes where proc_id not in 
            (select proc_id from archive_manager.processes)
          );
            


END;
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE populate_archive_data_table (
      nrtagid   IN   release_tags.rtag_id%TYPE
   )
   IS
/*
Reason: To populate the archive_data table with information regarding the
         number of package versions that exist in other releases.
*/
      numcount      NUMBER;
      numusedby     NUMBER;
      numruntime    NUMBER;
      
      /* Get all the package versions in the release */
      CURSOR archive_cur
      IS
         SELECT pv_id
           FROM release_content
          WHERE rtag_id = nrtagid;

      archive_rec   archive_cur%ROWTYPE;
   BEGIN
/*--------------- Business Rules Here -------------------*/
/*-------------------------------------------------------*/
      OPEN archive_cur;

      FETCH archive_cur
       INTO archive_rec;

      WHILE archive_cur%FOUND
      LOOP
        /* How many packages depend on this package version? */
         SELECT COUNT (*)
           INTO numusedby
           FROM package_dependencies
          WHERE dpv_id = archive_rec.pv_id;
        
        /* How many project releases use this package version?  */
         SELECT COUNT (*)
           INTO numcount
           FROM release_content
          WHERE pv_id = archive_rec.pv_id;

        /* How many packages have this package version as runtime
        dependency? */
         SELECT COUNT (*)
           INTO numruntime
           FROM runtime_dependencies
          WHERE rtd_id = archive_rec.pv_id;

        /* Insert into the archive_data table if they are not runtime dependant
        and package dependant and they exist in that particular release only*/
         IF numusedby = 0 AND numcount = 1 AND numruntime = 0
         THEN
            INSERT INTO archive_data
                        (rtag_id, pv_id
                        )
                 VALUES (nrtagid, archive_rec.pv_id
                        );
         END IF;

         FETCH archive_cur
          INTO archive_rec;
      END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE migrate_pv_to_archive_schema (
      nrtagid   IN   release_tags.rtag_id%TYPE
   )
   IS
   BEGIN

      /* MIGRATION - PACKAGE_VERSIONS */
      INSERT INTO archive_manager.package_versions
         SELECT *
           FROM package_versions
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* MIGRATION - PACKAGE_BUILD_ENV */
      INSERT INTO archive_manager.package_build_env
         SELECT *
           FROM package_build_env
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PACKAGE_BUILD_ENV */
      DELETE FROM package_build_env
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - PACKAGE_BUILD_INFO */
      INSERT INTO archive_manager.package_build_info
         SELECT *
           FROM package_build_info
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PACKAGE_BUILD_info */
      DELETE FROM package_build_info
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);							  

      /* MIGRATION - UNIT_TESTS  */
      INSERT INTO archive_manager.unit_tests
         SELECT *
           FROM unit_tests
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM UNIT_TESTS*/
      DELETE FROM unit_tests
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - PACKAGE_PROCESSES */
      INSERT INTO archive_manager.package_processes
         SELECT *
           FROM package_processes
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PACKAGE_PROCESSES*/
      DELETE FROM package_processes
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - PACKAGE_DEPENDENCIES */
      INSERT INTO archive_manager.package_dependencies
         SELECT *
           FROM package_dependencies
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PACKAGE_DEPENDENCIES*/
      DELETE FROM package_dependencies
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - CODE_REVIEWS */
      INSERT INTO archive_manager.code_reviews
         SELECT *
           FROM code_reviews
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM CODE_REVIEWS*/
      DELETE FROM code_reviews
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - RUNTIME_DEPENDENCIES*/
      INSERT INTO archive_manager.runtime_dependencies
         SELECT *
           FROM runtime_dependencies
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM RUNTIME_DEPENDENCIES*/
      DELETE FROM runtime_dependencies
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - PACKAGE_DOCUMENTS */
      INSERT INTO archive_manager.package_documents
         SELECT *
           FROM package_documents
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PACKAGE_DOCUMENTS*/
      DELETE FROM package_documents
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - PACKAGE_PATCHES */
      INSERT INTO archive_manager.package_patches
         SELECT *
           FROM package_patches
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PACKAGE_PATCHES*/
      DELETE FROM package_patches
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - CQ_ISSUES */
      INSERT INTO archive_manager.cq_issues
         SELECT *
           FROM cq_issues
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM CQ_ISSUES*/
      DELETE FROM cq_issues
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - ADDITIONAL_NOTES */
      INSERT INTO archive_manager.additional_notes
         SELECT *
           FROM additional_notes
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM ADDITIONAL_NOTES*/
      DELETE FROM additional_notes
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - RELEASE_COMPONENTS */
      INSERT INTO archive_manager.release_components
         SELECT *
           FROM release_components
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM RELEASE_COMPONENTS*/
      DELETE FROM release_components
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - IGNORE_WARNINGS */
      INSERT INTO archive_manager.ignore_warnings
         SELECT *
           FROM ignore_warnings
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM IGNORE_WARNINGS*/
      DELETE FROM ignore_warnings
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* PURGE DATA FROM WORK_IN_PROGRESS */
      DELETE FROM work_in_progress
            WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM PLANNED */
      DELETE FROM planned
            WHERE rtag_id = nrtagid;

      /* MIGRATION - JIRA_ISSUES */
      INSERT INTO archive_manager.jira_issues
         SELECT *
           FROM jira_issues
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM JIRA_ISSUES*/
      DELETE FROM jira_issues
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - PRODUCT_COMPONENTS */
      INSERT INTO archive_manager.product_components
         SELECT *
           FROM product_components
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM PRODUCT_COMPONENTS*/
      DELETE FROM product_components
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);

      /* MIGRATION - ACTION_LOG */
      INSERT INTO archive_manager.action_log
         SELECT *
           FROM action_log
          WHERE pv_id IN (SELECT pv_id
                            FROM archive_data);

      /* PURGE DATA FROM ACTION_LOG*/
      DELETE FROM action_log
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);


   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE migrate_rtag_to_archive_schema (
      nrtagid   IN   release_tags.rtag_id%TYPE
   )
   IS
   BEGIN
      /* MIGRATION - DO_NOT_RIPPLE */
      INSERT INTO archive_manager.do_not_ripple
         SELECT *
           FROM do_not_ripple dnp
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM DO_NOT_RIPPLE */
      DELETE FROM do_not_ripple
            WHERE rtag_id = nrtagid;
			
      /* MIGRATION - ADVISORY_RIPPLES*/
      INSERT INTO archive_manager.advisory_ripples
         SELECT *
           FROM advisory_ripple dnp
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM ADVISORY_RIPPLES*/
      DELETE FROM advisory_ripple
            WHERE rtag_id = nrtagid;			

      /* MIGRATION - RELEASE_CONTENT */
      INSERT INTO archive_manager.release_content
         SELECT *
           FROM release_content
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM RELEASE_CONTENT*/
      DELETE FROM release_content
            WHERE rtag_id = nrtagid;

      /* MIGRATION - NOTIFICATION_HISTORY */
      INSERT INTO archive_manager.notification_history
         SELECT *
           FROM notification_history
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM NOTIFICATION_HISTORY*/
      DELETE FROM notification_history
            WHERE rtag_id = nrtagid;

      /* MIGRATION - BUILD_ORDER   */
      INSERT INTO archive_manager.build_order
         SELECT *
           FROM build_order
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM BUILD_ORDER*/
      DELETE FROM build_order
            WHERE rtag_id = nrtagid;

      /* MIGRATION - PROJECT_ACTION_LOG */
      INSERT INTO archive_manager.project_action_log
         SELECT *
           FROM project_action_log
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM PROJECT_ACTION_LOG */
      DELETE FROM project_action_log
            WHERE rtag_id = nrtagid;

      /* MIGRATION - DEPRECATED_PACKAGES */
      INSERT INTO archive_manager.deprecated_packages
         SELECT *
           FROM deprecated_packages
          WHERE rtag_id = nrtagid;

      /* PURGE DATA FROM DEPRECATED_PACKAGES */
      DELETE FROM deprecated_packages
            WHERE rtag_id = nrtagid;
			
      /* MIGRATION - RELEASE_TAGS */
      INSERT INTO archive_manager.release_tags
         SELECT *
           FROM release_tags
          WHERE rtag_id = nrtagid;
			
			
      /* PURGE DATA FROM PACKAGE_VERSIONS*/
      DELETE FROM package_versions
            WHERE pv_id IN (SELECT pv_id
                              FROM archive_data);
							  
							  			
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE clean_up_archive_data_table (
      nrtagid   IN   release_tags.rtag_id%TYPE
   )
   IS
   BEGIN
      /* Cleaning Up The Archive_Data Table */
      DELETE FROM archive_data
            WHERE rtag_id = nrtagid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE write_action_log (
      nuserid   IN   NUMBER,
      nrtagid   IN   release_tags.rtag_id%TYPE
   )
   IS
   BEGIN
      /* Write Into Archive_Action_Log Table */
      INSERT INTO archive_action_log
                  (user_id, date_time_stamp, rtag_id,
                   description
                  )
           VALUES (nuserid, ora_sysdatetime, nrtagid,
                   'Release has been archived to the ARCHIVE_MANAGER schema'
                  );
   END;
/*-------------------------------------------------------------------------------------------------------*/
END pk_archive; 
/
--------------------------------------------------------
--  DDL for Package Body PK_BUILDAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_BUILDAPI" 
IS
   /*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_product_component (
      npvid           IN   NUMBER,
      sosname         IN   VARCHAR2,
      sorigfilepath   IN   VARCHAR2,
      sfilename       IN   VARCHAR2,
      sdestfilepath   IN   VARCHAR2,
      nbytesize       IN   NUMBER,
      scrccksum       IN   VARCHAR2
   )
   IS
      nosid   NUMBER;
   BEGIN
      /*--------------- Business Rules Here -------------------*/
      -- OS Name Requirements --
      IF (sosname IS NULL)
      THEN
         raise_application_error (-20000, 'OsName cannot be NULL.');
      END IF;

      -- File Requirements --
      IF (NOT sfilename IS NULL)
      THEN
         IF (nbytesize IS NULL)
         THEN
            raise_application_error (-20000, 'Byte Size cannot be NULL.');
         ELSIF (scrccksum IS NULL)
         THEN
            raise_application_error (-20000, 'CRC CKSUM cannot be NULL.');
         END IF;
      END IF;

      -- Folder Requirements --
      -- No requirements for now.

      /*-------------------------------------------------------*/

      -- Get OsId
      nosid := get_osid (sosname);

      -- Insert component entry
      INSERT INTO product_components
                  (pv_id, os_id, file_path, file_name, destination_path,
                  byte_size, crc_cksum
                  )
         VALUES (npvid, nosid, sorigfilepath, sfilename, sdestfilepath,
                  nbytesize, scrccksum
                  );
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Cannot have duplicate product components.'
                                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_all_product_components (
      npvid     IN   NUMBER,
      sosname   IN   VARCHAR2
   )
   IS
      nosid   NUMBER;
   BEGIN
/*--------------- Business Rules Here -------------------*/
/*-------------------------------------------------------*/

      -- Get OsId
      nosid := get_osid (sosname);

      -- Delete component entry
      DELETE FROM product_components pc
            WHERE pc.pv_id = npvid AND pc.os_id = nosid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_osid (sosname IN VARCHAR2)
      RETURN NUMBER
   IS
      code   NUMBER;
   BEGIN
      -- Get Platform Code --
      SELECT pf.code
      INTO code
      FROM platforms pf
      WHERE UPPER (pf.NAME) = UPPER (sosname);

      RETURN code;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         raise_application_error
            (-20000,
               'Platform '
            || sosname
            || ' is not valid. It needs to be added to PLATFORMS table in Release Manager.'
            );
         RAISE;
   END;

/*-------------------------------------------------------------------------------------------------------
Obsolete - Superseded by update_build_service_info
*/

   PROCEDURE update_build_service (
      sdatabaseserver   IN   VARCHAR2,
      swebserver        IN   VARCHAR2,
      smailserver       IN   VARCHAR2,
      smailsender       IN   VARCHAR2,
      sdiskspace        IN   VARCHAR2,
      ssbommanagement   IN   VARCHAR2
   )
   IS
   BEGIN
      UPDATE build_service_config
         SET config = sdatabaseserver
      WHERE service = 'DATABASE SERVER';

      UPDATE build_service_config
         SET config = swebserver
      WHERE service = 'WEB SERVER';

      UPDATE build_service_config
         SET config = smailserver
      WHERE service = 'MAIL SERVER';

      UPDATE build_service_config
         SET config = smailsender
      WHERE service = 'BUILD FAILURE MAIL SENDER';

      UPDATE build_service_config
         SET config = sdiskspace
      WHERE service = 'DPKG_ARCHIVE DISK SPACE USED';

      UPDATE build_service_config
         SET config = ssbommanagement
      WHERE service = 'SBOM MANAGEMENT';
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_build_service_info (
      sdatabaseserver   IN   VARCHAR2,
      sarchiveserver    IN   VARCHAR2,
      smailserver       IN   VARCHAR2,
      smailsender       IN   VARCHAR2,
      sdiskspace        IN   VARCHAR2,
      ssbommanagement   IN   VARCHAR2
   )
   IS
   BEGIN
      UPDATE build_service_config
         SET config = sdatabaseserver
      WHERE service = 'DATABASE SERVER';

      UPDATE build_service_config
         SET config = sarchiveserver
      WHERE service = 'ARCHIVE SERVER';

      UPDATE build_service_config
         SET config = smailserver
      WHERE service = 'MAIL SERVER';

      UPDATE build_service_config
         SET config = smailsender
      WHERE service = 'BUILD FAILURE MAIL SENDER';

      UPDATE build_service_config
         SET config = sdiskspace
      WHERE service = 'DPKG_ARCHIVE DISK SPACE USED';

      UPDATE build_service_config
         SET config = ssbommanagement
      WHERE service = 'SBOM MANAGEMENT';
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_gbe_machtype (sgbevalue IN VARCHAR2)
   IS
      gbe_id   NUMBER;
   BEGIN
      -- Get GBE_ID
      SELECT seq_gbe_id.NEXTVAL
      INTO gbe_id
      FROM DUAL;

      INSERT INTO gbe_machtype
                  (gbe_id, gbe_value
                  )
         VALUES (gbe_id, sgbevalue
                  );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_gbe_machtype (ngbe_id IN NUMBER)
   IS
   BEGIN
      DELETE FROM gbe_machtype
            WHERE gbe_id = ngbe_id;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_gbe_machtype (ngbe_id IN NUMBER, sgbevalue IN VARCHAR2)
   IS
   BEGIN
      UPDATE gbe_machtype
         SET gbe_value = sgbevalue
      WHERE gbe_id = ngbe_id;
   END;

/*-------------------------------------------------------------------------------------------------------*/
  --This function is obsolete.  It was replaced by add_daemon_config. Done for DEVI-046806
   PROCEDURE add_daemon (
      sdaemonhostname   IN   VARCHAR2,
      nrtagid           IN   NUMBER,
      ngbeid            IN   NUMBER,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
      nrecordnumber   NUMBER;
      nrconid         NUMBER;
   BEGIN
      -- Get RCON_ID
      SELECT seq_rcon_id.NEXTVAL
      INTO nrconid
      FROM DUAL;

      SELECT COUNT (*)
      INTO nrecordnumber
      FROM release_config
      WHERE rtag_id = nrtagid;

      IF nrecordnumber = 0
      THEN
         INSERT INTO release_config
                     (rcon_id, rtag_id, daemon_hostname, daemon_mode,
                     gbe_id, gbe_buildfilter
                     )
            VALUES (nrconid, nrtagid, sdaemonhostname, 'M',
                     ngbeid, sgbebuildfilter
                     );
      ELSE
         INSERT INTO release_config
                     (rcon_id, rtag_id, daemon_hostname, daemon_mode,
                     gbe_id, gbe_buildfilter
                     )
            VALUES (nrconid, nrtagid, sdaemonhostname, 'S',
                     ngbeid, sgbebuildfilter
                     );
      END IF;

      -- A newly configured daemon should initially be paused (DEVI-047277)
      INSERT INTO run_level
                  (rcon_id, pause)
           VALUES (nrconid, 1);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_daemon (srconidlist IN VARCHAR2)
   IS
   BEGIN
      -- Entries in the daemon_action_log, run_level and abt_action_log tables must be deleted first.
      DELETE FROM daemon_action_log
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));

      DELETE FROM run_level
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));

      DELETE FROM abt_action_log
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));

      -- Once entries in daemon_action_log, run_level and abt_action_log are removed, the daemon is deleted.
      DELETE FROM release_config
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));
   END;

/*-------------------------------------------------------------------------------------------------------*/
  --This function is obsolete.  It was replaced by update_daemon_config for DEVI-046806
   PROCEDURE update_daemon (
      sdaemonhostname   IN   VARCHAR2,
      nrconid           IN   NUMBER,
      ngbeid            IN   NUMBER,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
   BEGIN
      UPDATE release_config
         SET daemon_hostname = sdaemonhostname,
            gbe_id = ngbeid,
            gbe_buildfilter = sgbebuildfilter
      WHERE rcon_id = nrconid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE insert_schedule_info (
      dschedulepause     IN   DATE,
      dscheduleresume    IN   DATE,
      crepeat            IN   VARCHAR2,
      cindefinitepause   IN   VARCHAR2
   )
   IS
      nscheduledid   NUMBER;
   BEGIN
      -- Get Next Available Scheduled Id
      SELECT seq_scheduled_id.NEXTVAL
      INTO nscheduledid
      FROM DUAL;

      INSERT INTO run_level_schedule
         VALUES (nscheduledid, dschedulepause, dscheduleresume, crepeat,
                  cindefinitepause);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_schedule (nscheduleid IN NUMBER)
   IS
   BEGIN
      DELETE FROM run_level_schedule
            WHERE scheduled_id = nscheduleid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_infinite_pause
   IS
      nscheduledid   NUMBER;
   BEGIN
      -- Get Next Available Scheduled Id
      SELECT seq_scheduled_id.NEXTVAL
      INTO nscheduledid
      FROM DUAL;

      INSERT INTO run_level_schedule
         VALUES (nscheduledid, NULL, NULL, NULL, 'P');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_resume
   IS
   BEGIN
      DELETE FROM run_level_schedule
            WHERE indefinite_pause = 'P';
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_out_of_date_schedule
   IS
   BEGIN
      DELETE FROM run_level_schedule
            WHERE scheduled_resume < ora_sysdatetime AND repeat = 0;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_resume (nrconid IN NUMBER)
   IS
   BEGIN
      UPDATE run_level
         SET PAUSE = NULL
      WHERE rcon_id = nrconid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_pause (nrconid IN NUMBER)
   IS
   BEGIN
      UPDATE run_level
         SET PAUSE = 1
      WHERE rcon_id = nrconid;
   END;
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_disable (nrconid NUMBER)
   IS
   BEGIN
      UPDATE run_level
         SET PAUSE = 2
      WHERE rcon_id = nrconid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_states (nrtagid NUMBER, nstate NUMBER)
   IS
   BEGIN
     UPDATE run_level
     SET pause = nstate
     WHERE rcon_id IN
     (SELECT rc.rcon_id FROM release_config rc WHERE rc.rtag_id = nrtagid);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   -- inserts a new daemon instruction
   -- This is for use by the Release Manager Website code.
   --
   PROCEDURE insert_daemon_inst
   ( nOp_code IN NUMBER
   , nRtag_id IN NUMBER
   , nPv_id IN NUMBER
   , nSchedDate IN DATE
   , nRepeatSecs IN NUMBER
   , nAddedDate IN DATE
   , nUser_id IN NUMBER
   ) IS
      nInstId   NUMBER;
   BEGIN
      -- Get Next Available Scheduled Id
      SELECT seq_daemon_instruction_id.NEXTVAL
      INTO nInstId
      FROM DUAL;

      INSERT INTO Daemon_Instructions
         VALUES (nInstId, nOp_code, nRtag_id,
                  nPv_id, nSchedDate, nRepeatSecs,
                  nAddedDate, nUser_id, '0');
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Table already contains a record with the specified OPERATION, RELEASE, and PACKAGE VERSION'
                                 );
      WHEN OTHERS
      THEN
         raise;
   END insert_daemon_inst;

/*-------------------------------------------------------------------------------------------------------*/
   -- Deletes a daemon instruction matching the specified instruction ID
   --
   PROCEDURE del_daemon_inst
   ( nInstId IN NUMBER
   ) IS

   BEGIN
      DELETE FROM Daemon_Instructions
      WHERE DAEMON_INSTRUCTIONS_ID = nInstId;

   END del_daemon_inst;

/*-------------------------------------------------------------------------------------------------------*/
   -- Deletes a daemon instruction matching the specified op-code, ratag, and pv_id
   --
   PROCEDURE del_daemon_inst_by_rtag_pvid(
      nOp_code IN NUMBER,
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER
   ) IS
   BEGIN
      DELETE FROM Daemon_Instructions
      WHERE OP_CODE = nOp_code
      AND RTAG_ID = nRtag_id
      AND PV_ID   = nPv_id;

   END del_daemon_inst_by_rtag_pvid;

/*-------------------------------------------------------------------------------------------------------*/
   -- Updates a daemon instruction
   -- This is for use by the Release Manager Website code.
   --
   PROCEDURE update_daemon_inst
   ( nInstId IN NUMBER
   , nOp_code IN NUMBER
   , nRtag_id IN NUMBER
   , nPv_id IN NUMBER
   , nSchedDate IN DATE
   , nRepeatSecs IN NUMBER
   , nAddedDate IN DATE
   , nUser_id IN NUMBER
   ) IS
      CURSOR daemon_inst_cur IS
         SELECT *
         FROM daemon_instructions di
         WHERE di.DAEMON_INSTRUCTIONS_ID = nInstId;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;

      exc_inst_removed EXCEPTION;
   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      IF daemon_inst_cur%FOUND THEN

         UPDATE Daemon_Instructions
         SET op_code = nOp_code,
            rtag_id = nRtag_id,
            pv_id   = nPv_id,
            scheduled_datetime = nSchedDate,
            repeat_secs = nRepeatSecs,
            added_datetime = nAddedDate,
            user_id = nUser_id,
            in_progress = '0'
         WHERE daemon_instructions_id = nInstId;
      ELSE
         raise exc_inst_removed;
      END IF;

      CLOSE daemon_inst_cur;
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Table already contains a record with the specified OPERATION, RELEASE, and PACKAGE VERSION'
                                 );
      WHEN exc_inst_removed
      THEN
         raise_application_error (-20000,
                                 'Record was probably deleted by the Buildtool during your edit-form session. Please create a new Daemon Instruction.'
                                 );
      WHEN OTHERS
      THEN
         raise;
   END update_daemon_inst;

/*-------------------------------------------------------------------------------------------------------*/
   -- Returns a comma-separated list of operation codes found for a given rtag and pv_id combination
   -- This is for use by the Release Manager Website code.
   --
   FUNCTION daemon_ops_for_rtag_pvid(
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER
   ) RETURN VARCHAR2
   IS
      CURSOR daemon_inst_cur IS
         SELECT di.OP_CODE
         FROM daemon_instructions di
         WHERE di.RTAG_ID = nRtag_id
            AND di.PV_ID = nPv_id;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;

      sRetList VARCHAR2(4000) := '';

   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      WHILE daemon_inst_cur%FOUND
      LOOP
         sRetList := sRetList || daemon_inst_rec.op_code || ',';

         FETCH daemon_inst_cur
         INTO daemon_inst_rec;
      END LOOP;

      CLOSE daemon_inst_cur;

      RETURN sRetList;
   END daemon_ops_for_rtag_pvid;
/*-------------------------------------------------------------------------------------------------------*/
   -- Returns a comma-separated list of operation codes found for a given rtag
   -- This is for use by the Release Manager Website code.
   --
   FUNCTION daemon_ops_for_rtag(
      nRtag_id IN NUMBER
   ) RETURN VARCHAR2
   IS
      CURSOR daemon_inst_cur IS
         SELECT di.OP_CODE
         FROM daemon_instructions di
         WHERE di.RTAG_ID = nRtag_id;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;

      sRetList VARCHAR2(4000) := '';

   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      WHILE daemon_inst_cur%FOUND
      LOOP
         sRetList := sRetList || daemon_inst_rec.op_code || ',';

         FETCH daemon_inst_cur
         INTO daemon_inst_rec;
      END LOOP;

      CLOSE daemon_inst_cur;

      RETURN sRetList;
   END daemon_ops_for_rtag;
/*-------------------------------------------------------------------------------------------------------*/
   -- Gets a record from the daemon instruction table that can be carried out now and returns the fields
   -- in the record a daemon will need
   -- The Buildtool should use this to find a job to do for a particular release. It should then call
   -- mark_daemon_inst_in_progress(inst_id) before carrying out the work, and then call
   -- mark_daemon_inst_completed(inst_id) to signal its completion.
   -- Can be called repeatedly to get a full list of all instructions for a release, by passing back in
   -- the instruction ID obtained from the previous call (the 1st call should use 0)
   -- Can be called repeatedly to get a full list of all instructions of a specific op-code value for a release,
   -- by passing back in an op-code value of 0 or higher (use -1 if no op-code filtering is needed)
   -- Returns 1 if a record was found, else 0.
   --
   FUNCTION get_daemon_inst(
      nRtag_id IN NUMBER,
      nInst_id IN OUT NUMBER,
      nOp_code IN OUT NUMBER,
      nPv_id OUT NUMBER,
      nUser_id OUT NUMBER,
      nInProgress OUT NUMBER
   ) RETURN NUMBER
   IS
      CURSOR daemon_inst_cur IS
         SELECT di.daemon_instructions_id, di.op_code, di.pv_id ,di.user_id, di.in_progress
           FROM daemon_instructions di
          WHERE di.rtag_id = nRtag_id
            AND di.daemon_instructions_id > nInst_id
            AND di.scheduled_datetime <= ora_sysdatetime
            AND ((nOp_code = -1) OR (nOp_code = di.op_code))
            AND rownum <= 1
       ORDER BY di.daemon_instructions_id;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;
   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      -- If we found a record, return it.
      IF daemon_inst_cur%FOUND THEN
         nInst_id := daemon_inst_rec.daemon_instructions_id;
         nOp_code := daemon_inst_rec.op_code;
         nPv_id   := daemon_inst_rec.pv_id;
         nUser_id := daemon_inst_rec.user_id;
         IF daemon_inst_rec.in_progress = '1' THEN
            nInProgress := 1;
         ELSE
            nInProgress := 0;
         END IF;
         CLOSE daemon_inst_cur;
         RETURN 1;
      END IF;

      CLOSE daemon_inst_cur;
      RETURN 0;

   END get_daemon_inst;
/*-------------------------------------------------------------------------------------------------------*/
   -- Marks a daemon instruction as being processed by a daemon
   -- The Buildtool should use this before it embarks on the work the instruction commands
   --
   PROCEDURE mark_daemon_inst_in_progress( nInstId IN NUMBER )
   IS
   BEGIN
      UPDATE Daemon_Instructions
      SET in_progress = '1'
      WHERE daemon_instructions_id = nInstId;

   END mark_daemon_inst_in_progress;

/*-------------------------------------------------------------------------------------------------------*/
   -- Once the Buildtool has finished carrying out the daemon instruction, it should call this stored
   -- procedure in order to either delete the instruction or update it in the case where it is a repeating
   -- instruction.
   --
   PROCEDURE mark_daemon_inst_completed( nInstId IN NUMBER )
   IS
      repSecs NUMBER;
      schedDate  DATE;

      CURSOR daemon_inst_cur IS
         SELECT di.REPEAT_SECS AS repSecs, di.SCHEDULED_DATETIME AS schedDate
         FROM daemon_instructions di
         WHERE di.daemon_instructions_id = nInstId;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;
   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      IF daemon_inst_cur%FOUND THEN

         -- if instruction repeats daily, add 1 day to the scheduled time and update the record
         IF daemon_inst_rec.repSecs = 86400 THEN
            UPDATE Daemon_Instructions
               SET scheduled_datetime = daemon_inst_rec.schedDate + 1,
                  in_progress = '0'
            WHERE daemon_instructions_id = nInstId;
         ELSE
            -- Delete the daemon instruction, we are done with it
            del_daemon_inst(nInstId);
         END IF;
      END IF;

      CLOSE daemon_inst_cur;

   EXCEPTION
      WHEN OTHERS
      THEN
         raise;

   END mark_daemon_inst_completed;
/*-------------------------------------------------------------------------------------------------------*/
   -- This function deletes any old daemon instruction that appears stranded due to a problem that might
   -- have occured during buildtool operation such as might occur if the buildtool or the machine it was
   -- hosted on came down whilst it was processing a daemon instruction.
   PROCEDURE cleanup_stranded_daemon_insts
   IS
   BEGIN
      -- delete records at least two days old
      DELETE FROM daemon_instructions di
      WHERE  (di.scheduled_datetime + 5) <= ora_sysdatetime;

   END cleanup_stranded_daemon_insts;
/*-------------------------------------------------------------------------------------------------------*/
  --This function supersedes function, add_daemon. Done for DEVI-046806
   PROCEDURE add_daemon_config (
      nrtagid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
      nrecordnumber   NUMBER;
      nrconid         NUMBER;
      sdaemonhostname VARCHAR2(50);
      ngbeid         NUMBER;
   BEGIN
      -- Get RCON_ID
      SELECT seq_rcon_id.NEXTVAL
      INTO nrconid
      FROM DUAL;

      SELECT COUNT (*)
      INTO nrecordnumber
      FROM release_config
      WHERE rtag_id = nrtagid;

      SELECT machine_hostname,gbe_id INTO sdaemonhostname,ngbeid
      FROM build_machine_config
      WHERE bmcon_id = nbmcon_id;

      INSERT INTO release_config
             (rcon_id, rtag_id, daemon_hostname, daemon_mode,
                gbe_id, gbe_buildfilter)
      VALUES (nrconid, nrtagid, sdaemonhostname, sdaemon_mode,
                ngbeid, sgbebuildfilter);

      -- A newly configured daemon should initially be paused (DEVI-047277)
      INSERT INTO run_level
                  (rcon_id, pause)
           VALUES (nrconid, 2);

   END;

/*-------------------------------------------------------------------------------------------------------*/
  --This function supersedes function, update_daemon. Done for DEVI-046806
   PROCEDURE update_daemon_config (
      nrconid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
      sdaemonhostname VARCHAR2(50);
      ngbeid         NUMBER;
   BEGIN

      SELECT machine_hostname,gbe_id INTO sdaemonhostname,ngbeid
      FROM build_machine_config
      WHERE bmcon_id = nbmcon_id;

      UPDATE release_config
         SET daemon_hostname = sdaemonhostname,
            gbe_id = ngbeid,
            daemon_mode = sdaemon_mode,
            gbe_buildfilter = sgbebuildfilter
      WHERE rcon_id = nrconid;
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_build_machine (
      sdisplay_name          IN   VARCHAR2,
      smachine_hostname      IN   VARCHAR2,
      ngbeid                 IN   NUMBER,
      sdescription           IN   VARCHAR2
   )
   IS
      nrecordnumber   NUMBER;
      nbmcon_id       NUMBER;
   BEGIN
      -- Get BMCON_ID
      SELECT seq_bmcon_id.NEXTVAL INTO nbmcon_id FROM DUAL;

      INSERT INTO build_machine_config(bmcon_id, display_name, machine_hostname,gbe_id,description)
            VALUES (nbmcon_id,sdisplay_name,smachine_hostname,ngbeid,sdescription);

   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Cannot have duplicate machines.'
                                 );

   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_build_machine (sbmcon_id_list IN VARCHAR2)
   IS
   BEGIN
      DELETE FROM build_machine_config
            WHERE bmcon_id IN (
                     SELECT * FROM THE
                              (SELECT CAST
                                          (in_list_number (sbmcon_id_list) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_build_machine (
      nbmcon_id              IN   NUMBER,
      sdisplay_name          IN   VARCHAR2,
      smachine_hostname      IN   VARCHAR2,
      ngbeid                 IN   NUMBER,
      sdescription           IN   VARCHAR2
   )
   IS
   BEGIN
      UPDATE build_machine_config
         SET display_name = sdisplay_name,
             machine_hostname = smachine_hostname,
             gbe_id = ngbeid,
             description = sdescription
      WHERE bmcon_id = nbmcon_id;
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Cannot have duplicate machines.'
                                 );
   END;
END pk_buildapi;
/
--------------------------------------------------------
--  DDL for Package Body PK_ENVIRONMENT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_ENVIRONMENT" 
IS

   /*-------------------------------------------------------------------------------------------------------*/
   FUNCTION select_environment_area (cdlock IN package_versions.dlocked%TYPE)
     RETURN NUMBER
   IS
   BEGIN
      /*
     || N - unlocked
     || Y - release and locked
     || P - penging approval
     || A - approved package ready for auto-build
     */
     IF cdlock = 'N' OR cdlock = 'R'
     THEN
       -- WORK IN PROGRESS --
       RETURN 0;
     ELSIF cdlock = 'P' OR cdlock = 'A'
     THEN
       -- PENDING --
       RETURN 1;
     ELSIF cdlock = 'Y'
     THEN
       -- RELEASED --
       RETURN 2;
     ELSE
       -- NOT FOUND --
       raise_application_error
                   (-20000,
                      'Cannot decide where to place package. [cDlock='
                    || cdlock
                    || ']'
                   );
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_package_area (pvid IN NUMBER, rtagid IN NUMBER)
     RETURN NUMBER
   IS
     envtab   NUMBER         := -1;

     CURSOR curarea
     IS
       SELECT 2 AS envtab
         FROM release_content rc
        WHERE rc.rtag_id = rtagid AND rc.pv_id = pvid
       UNION
       SELECT 0 AS envtab
         FROM work_in_progress wip
        WHERE wip.rtag_id = rtagid AND wip.pv_id = pvid
       UNION
       SELECT 1 AS envtab
         FROM planned pl
        WHERE pl.rtag_id = rtagid AND pl.pv_id = pvid;

     recarea   curarea%ROWTYPE;
   BEGIN
     OPEN curarea;

     FETCH curarea
      INTO recarea;

     IF curarea%FOUND
     THEN
       envtab := recarea.envtab;
     END IF;

     CLOSE curarea;

     RETURN envtab;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_view_location (pvid IN NUMBER, rtagid IN NUMBER)
     RETURN NUMBER
   IS
     ispatch   package_versions.dlocked%TYPE;
     viewid   NUMBER                    := -1;

     CURSOR curview
     IS
       SELECT rc.base_view_id AS view_id
         FROM release_content rc
        WHERE rc.rtag_id = rtagid AND rc.pv_id = pvid
       UNION
       SELECT wip.view_id AS view_id
         FROM work_in_progress wip
        WHERE wip.rtag_id = rtagid AND wip.pv_id = pvid
       UNION
       SELECT pl.view_id AS view_id
         FROM planned pl
        WHERE pl.rtag_id = rtagid AND pl.pv_id = pvid;

     recview   curview%ROWTYPE;
   BEGIN
     -- Get dlock state
     SELECT pv.is_patch
      INTO ispatch
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     -- Decide which view id should package go under.
     IF (ispatch != 'Y') OR (ispatch IS NULL)
     THEN
       -- Get VIEW ID of Package
       OPEN curview;

       FETCH curview
        INTO recview;

       IF curview%FOUND
       THEN
         viewid := recview.view_id;
       ELSE
         raise_application_error
            (-20000,
               'Cannot find view_id to proceed. [PvId='
            || pvid
            || ']. The current version may not exist in the release anymore.'
            );
       END IF;

       CLOSE curview;
     ELSE
       -- Get VIEW ID of Patch (view id of parent package)
       SELECT rc.base_view_id
         INTO viewid
         FROM release_content rc, package_patches ppv
        WHERE rc.rtag_id = rtagid
         AND rc.pv_id = ppv.pv_id
         AND ppv.patch_id = pvid;
     END IF;

     RETURN viewid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_package (
     pvid    IN   NUMBER,
     viewid   IN   NUMBER,
     rtagid   IN   NUMBER,
     userid   IN   NUMBER
   )
   IS
     dlocked   package_versions.dlocked%TYPE;
     envtab   NUMBER;
   BEGIN
     IF can_edit_pkg_in_project (pvid, rtagid) = 1
     THEN
       -- Get dlock state
       SELECT pv.dlocked
         INTO dlocked
         FROM package_versions pv
        WHERE pv.pv_id = pvid;

       -- Get which area should go under
       envtab := select_environment_area (dlocked);
       -- Log
       log_action (pvid, 'action', userid, 'Start of Package Add...');

       -- Remove Package
       IF envtab = 0
       THEN
         -- WORK IN PROGRESS --
         pk_work_in_progress.add_package (pvid, viewid, rtagid, userid);
       ELSIF envtab = 1
       THEN
         -- PENDING --
         pk_planned.add_package (pvid, viewid, rtagid, userid);
       ELSIF envtab = 2
       THEN
         -- RELEASED --
         -- NOTE: this package will be replaced with matching package
         pk_release.add_package (pvid, viewid, rtagid, userid);
         -- Now do post Release Actions
         pk_release.run_post_actions (pvid, rtagid);
       END IF;

       -- Log
       log_action (pvid, 'action', userid, 'End of Package Add...');
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_package_bulk (
     pvidlist   IN   VARCHAR2,
     viewid    IN   NUMBER,
     rtagid    IN   NUMBER,
     userid    IN   NUMBER
   )
   IS
     nidcollector   relmgr_number_tab_t         := relmgr_number_tab_t
                                                        ();
     dlocked      package_versions.dlocked%TYPE;
     pvid         NUMBER;
     envtab       NUMBER;
   BEGIN
     /*--------------- Business Rules Here -------------------*/
     IF (pvidlist IS NULL)
     THEN
       raise_application_error (-20000,
                          'Please select at least one package.'
                         );
     END IF;

/*-------------------------------------------------------*/
     nidcollector := in_list_number (pvidlist);

     FOR i IN 1 .. nidcollector.COUNT
     LOOP
       pvid := nidcollector (i);
       add_package (pvid, viewid, rtagid, userid);
     END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE replace_package (
     newpvid  IN   NUMBER,
     oldpvid  IN   NUMBER,
     rtagid   IN   NUMBER,
     userid   IN   NUMBER
   )
   IS
     dlocked      package_versions.dlocked%TYPE;
     viewid       NUMBER;
     envtab       NUMBER;
     ROWCOUNT     NUMBER;
     creleasemode CHAR (1);
     npkgid       NUMBER;
   BEGIN
     /*--------------- Business Rules Here -------------------*/
     -- Check if oldPvId exists. It could have been removed
     SELECT COUNT (pv.pv_id)
       INTO ROWCOUNT
       FROM package_versions pv
      WHERE pv.pv_id = oldpvid;

/*-------------------------------------------------------*/

     /* This procedure is usually used by "History" option in Release Manager */

     -- Get dlock state
     SELECT pv.dlocked
       INTO dlocked
       FROM package_versions pv
      WHERE pv.pv_id = newpvid;

     -- Get VIEW_ID ---
     IF ROWCOUNT = 1
     THEN
       viewid := get_view_location (oldpvid, rtagid);
     ELSE
       -- Set ViewID to default
       viewid := 7;
     END IF;

     -- Get which area should go under
     envtab := select_environment_area (dlocked);
     -- Log
     log_action (oldpvid, 'action', userid, 'Start of Package Replace...');

     -- Replace package
     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --

       -- Delete old package
       pk_work_in_progress.remove_package (oldpvid, rtagid, userid);

       -- Add new package
       pk_work_in_progress.add_package (newpvid, viewid, rtagid, userid);
     ELSIF envtab = 1
     THEN
       -- PENDING --

       -- Delete old package
       pk_planned.remove_package (oldpvid, rtagid, userid);

       -- Add new package
       pk_planned.add_package (newpvid, viewid, rtagid, userid);
     ELSIF envtab = 2
     THEN
       -- RELEASED --

       -- Delete old package
       pk_release.remove_package (oldpvid, rtagid, userid);
       -- Add new package
       pk_release.add_package (newpvid, viewid, rtagid, userid);

       -- update the pegging table
       UPDATE PEGGED_VERSIONS SET pv_id = newpvid WHERE rtag_id = rtagid AND pv_id = oldpvid;

       -- update the advisory ripple table
       UPDATE ADVISORY_RIPPLE SET pv_id = newpvid WHERE rtag_id = rtagid AND pv_id = oldpvid;

       -- Now do post Release Actions
       pk_release.run_post_actions (newpvid, rtagid);
     END IF;

     -- Log
     log_action (oldpvid, 'action', userid, 'End of Package Replace...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION remove_package (
     pvid        IN   NUMBER,
     rtagid      IN   NUMBER,
     userid      IN   NUMBER,
     forceremove IN   CHAR
   )
     RETURN NUMBER
   IS
     envtab      NUMBER;
     isused      BOOLEAN;
     recordcount   NUMBER;
   BEGIN
/*--------------- Business Rules Here -------------------*/
/*-------------------------------------------------------*/

     -- Find location of package
     envtab := get_package_area (pvid, rtagid);

     -- Remove Package
     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       -- Delete package
       pk_work_in_progress.remove_package (pvid, rtagid, userid);

       RETURN 0;
     ELSIF envtab = 1
     THEN
       -- PENDING --
       -- Delete package
       pk_planned.remove_package (pvid, rtagid, userid);

       RETURN 0;
     ELSIF envtab = 2
     THEN
       -- RELEASED --

       -- Check if is used by other packages
       isused := TRUE;

       IF forceremove = 'N'
       THEN
         SELECT COUNT (pv.pv_id)
           INTO recordcount
           FROM (SELECT dpv.pkg_id, dpv.v_ext
                 FROM release_content rc,
                     package_dependencies dep,
                     package_versions dpv
                WHERE rc.rtag_id = rtagid
                  AND rc.pv_id = dep.pv_id
                  AND dep.dpv_id = dpv.pv_id) rdep,
               package_versions pv
          WHERE pv.pkg_id = rdep.pkg_id
            AND NVL (pv.v_ext, '|LINK_A_NULL|') =
                                  NVL (rdep.v_ext, '|LINK_A_NULL|')
            AND pv.pv_id = pvid;

         IF recordcount > 0
         THEN
            RETURN 1;               -- Return 1 as package being used
         ELSE
            isused := FALSE;
         END IF;
       END IF;

       IF forceremove = 'Y' OR NOT isused
       THEN
         -- Delete old package
         pk_release.remove_package (pvid, rtagid, userid);

         -- Delete old package's pegging info
         DELETE FROM PEGGED_VERSIONS pegv WHERE pegv.RTAG_ID = rtagid AND pegv.PV_ID = pvid;

         -- Delete old package's advisory ripple info
         DELETE FROM ADVISORY_RIPPLE avr WHERE avr.RTAG_ID = rtagid AND avr.PV_ID = pvid;

         -- Now do post Release Actions
         pk_release.run_post_actions (pvid, rtagid);
         RETURN 0;
       END IF;
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   -- DEVI-45275 added the return of the new "operation" column in the recordset.

   PROCEDURE get_environment_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (pl.pv_id)
      INTO ntruerecordcount
      FROM environment_view pl
      WHERE pl.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      DECODE (rel.pkg_state,
                            NULL, 0,
                            rel.pkg_state
                           ) AS pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel,
                             view_settings vs,
                             views vi
                        WHERE rel.view_id = vi.view_id
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      DECODE (rel.pkg_state,
                            NULL, 0,
                            rel.pkg_state
                           ) AS pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description,
                      rel.operation
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      DECODE (rel.pkg_state,
                            NULL, 0,
                            rel.pkg_state
                           ) AS pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_released_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description
                         FROM release_content rel, views vi
                        WHERE rel.base_view_id = vi.view_id
                          AND rtag_id = rtagid
                          AND rel.base_view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description
                  FROM release_content rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.base_view_id = vi.view_id
                   AND rel.base_view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description
                         FROM release_content rel,
                             view_settings vs,
                             views vi
                        WHERE rel.base_view_id = vi.view_id
                          AND vs.view_id = rel.base_view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.base_view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description
                  FROM release_content rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.base_view_id = vi.view_id
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.base_view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      release_content rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name, rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      release_content rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_work_in_progress_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (wip.pv_id)
      INTO ntruerecordcount
      FROM work_in_progress wip
      WHERE wip.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description
                         FROM work_in_progress rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description
                  FROM work_in_progress rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description
                         FROM work_in_progress rel,
                             view_settings vs,
                             views vi
                        WHERE rel.view_id = vi.view_id
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description
                  FROM work_in_progress rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      work_in_progress rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      work_in_progress rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   -- DEVI-45275 added the return of the new "operation" column in the recordset.

   PROCEDURE get_pending_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (pl.pv_id)
      INTO ntruerecordcount
      FROM planned pl
      WHERE pl.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM planned rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description,
                      rel.operation
                  FROM planned rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM planned rel, view_settings vs, views vi
                        WHERE rel.view_id = vi.view_id
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description,
                      rel.operation
                  FROM planned rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description,
                      rel.operation
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      planned rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description,
                      rel.operation
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      planned rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_view_content (
     rtagid     IN      NUMBER,
     viewid     IN      NUMBER,
     recordset OUT     typecur
   )
   IS
     isbaseview   CHAR (1);
   BEGIN
     -- Check if the view is BASE VIEW
     SELECT vi.base_view
      INTO isbaseview
      FROM views vi
      WHERE vi.view_id = viewid;

     IF (isbaseview = 'Y')
     THEN
       -- Get Base view content
       OPEN recordset FOR
         SELECT   DECODE (rel.pkg_state,
                      NULL, 0,
                      rel.pkg_state
                     ) AS pkg_state,
                rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                pv.pkg_version, pv.dlocked, pv.pv_description,
                pv.build_type,
                rel.operation
            FROM environment_view rel, PACKAGES pkg, package_versions pv
            WHERE pv.pkg_id = pkg.pkg_id
             AND rel.pv_id = pv.pv_id
             AND rel.view_id = viewid
             AND rel.rtag_id = rtagid
         ORDER BY UPPER (pkg.pkg_name);
     ELSE
       -- Get non base view content
       OPEN recordset FOR
         SELECT   DECODE (rel.pkg_state,
                      NULL, 0,
                      rel.pkg_state
                     ) AS pkg_state,
                rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                pv.pkg_version, pv.dlocked, pv.pv_description,
                pv.build_type,
                rel.operation
            FROM environment_view rel,
                PACKAGES pkg,
                package_versions pv,
                view_def vd
            WHERE pv.pkg_id = pkg.pkg_id
             AND rel.pv_id = pv.pv_id
             AND rel.rtag_id = rtagid
             AND vd.view_id = viewid
             AND vd.pkg_id = pv.pkg_id
         ORDER BY UPPER (pkg.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_package_view (pvid IN NUMBER, rtagid IN NUMBER)
     RETURN NUMBER
   IS
     envtab           NUMBER;
     returnvalue      NUMBER;
     return_not_found NUMBER := -1;
   BEGIN
     envtab := get_package_area (pvid, rtagid);

     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       returnvalue := pk_work_in_progress.get_package_view (pvid, rtagid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       returnvalue := pk_planned.get_package_view (pvid, rtagid);
     ELSIF envtab = 2
     THEN
       -- RELEASED --
       returnvalue := pk_release.get_package_view (pvid, rtagid);
     ELSE
       -- This may be a Patch not located anywhere but unlocked
       returnvalue := return_not_found;
     END IF;

     RETURN returnvalue;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_release (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid        NUMBER;
     envtab        NUMBER;
     ispatch       CHAR (1) := NULL;
     buildtype     CHAR (1) := NULL;
   BEGIN
     -- Check if package is patch
     SELECT pv.is_patch, pv.build_type
      INTO ispatch, buildtype
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     -- Get ViewId
     viewid := get_package_view (pvid, rtagid);
     -- Remove from current area
     envtab := pk_environment.get_package_area (pvid, rtagid);

     -- Make sure that package was in work-in-progress or pending before makeing it release
     -- Exclude patches, ripple builds
     IF (envtab < 0)
     THEN
       -- Not found in work-in-progress or pending
       IF (ispatch IS NULL) AND (buildtype = 'M')
       THEN
         raise_application_error (-20000,
                            'This package cannot be released here.'
                           );
       END IF;
     END IF;

     -- Log
     log_action (pvid, 'action', userid, 'Start of Make Package Release...');

     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       pk_work_in_progress.remove_package (pvid, rtagid, userid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       pk_planned.remove_package (pvid, rtagid, userid);
     END IF;

     -- Change package state
     pk_package.change_state (pvid, 'Y', userid);

     -- Make sure it is valid BASE VIEW
     IF viewid < 1
     THEN
       viewid := 7;                     -- This is default base view
     END IF;

     IF (ispatch IS NULL)
     THEN
       -- Add package to new area
       pk_release.add_package (pvid, viewid, rtagid, userid);
     END IF;

     -- Now do post Release Actions
     pk_release.run_post_actions (pvid, rtagid);

     -- The release has changed and there may now be invalid rtag_id/pv_id combinations in
     -- the DO_NOT_RIPPLE and ADVISORY_RIPPLE Tables so perform a clean-up operation upon them.
     clean_do_not_ripple(rtagid);
     clean_advisory_ripple(rtagid);

     -- Log
     log_action (pvid, 'action', userid, 'End of Make Package Release...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE auto_make_release (
     pvid          IN   NUMBER,
     rtagid        IN   NUMBER,
     userid        IN   NUMBER,
     vext          IN   package_versions.v_ext%TYPE,
     ssv_ext       IN   package_versions.v_ext%TYPE,
     clonefrompvid IN   NUMBER
   )
   IS
     viewid        NUMBER;
     envtab        NUMBER;
     ispatch       CHAR (1) := NULL;
     buildtype      CHAR (1) := NULL;
   BEGIN
     -- Check if package is patch
     SELECT pv.is_patch, pv.build_type
      INTO ispatch, buildtype
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     IF vext <> ssv_ext
     THEN
       -- Get ViewId
       viewid := get_package_view (clonefrompvid, rtagid);
       -- Remove from current area
       envtab := pk_environment.get_package_area (clonefrompvid, rtagid);
     ELSE
       -- Get ViewId
       viewid := get_package_view (pvid, rtagid);
       -- Remove from current area
       envtab := pk_environment.get_package_area (pvid, rtagid);
     END IF;

     -- Make sure that package was in work-in-progress or pending before makeing it release
     -- Exclude patches, ripple builds
     IF (envtab < 0)
     THEN
       -- Not found in work-in-progress or pending
       IF (ispatch IS NULL) AND (buildtype = 'M')
       THEN
         raise_application_error (-20000,
                            'This package cannot be released here.'
                           );
       END IF;
     END IF;

     -- Log
     log_action (pvid, 'action', userid, 'Start of Make Package Release...');

     IF vext <> ssv_ext
     THEN
       IF envtab = 0
       THEN
         -- WORK IN PROGRESS --
         pk_work_in_progress.remove_package (clonefrompvid, rtagid,
                                    userid);
       ELSIF envtab = 1
       THEN
         -- PENDING --
         pk_planned.remove_package (clonefrompvid, rtagid, userid);
       ELSIF envtab = 2
       THEN
         -- RELEASED --
         pk_release.remove_package (clonefrompvid, rtagid, userid);
       END IF;
     ELSE
       IF envtab = 0
       THEN
         -- WORK IN PROGRESS --
         pk_work_in_progress.remove_package (pvid, rtagid, userid);
       ELSIF envtab = 1
       THEN
         -- PENDING --
         pk_planned.remove_package (pvid, rtagid, userid);
       END IF;
     END IF;

     -- Change package state
     pk_package.change_state (pvid, 'Y', userid);

     -- Make sure it is valid BASE VIEW
     IF viewid < 1
     THEN
       viewid := 7;                     -- This is default base view
     END IF;

     IF (ispatch IS NULL)
     THEN
       -- Add package to new area
       pk_release.add_package (pvid, viewid, rtagid, userid);
     END IF;

     -- Now do post Release Actions
     pk_release.run_post_actions (pvid, rtagid);
     -- Now update the Dash_Board Table (DEPRECATED)
     pk_rmapi.update_dash_board (rtagid);

     -- The release has changed and there may now be invalid rtag_id/pv_id combinations in
     -- the DO_NOT_RIPPLE and ADVISORY_RIPPLE Tables so perform a clean-up operation upon them.
     clean_do_not_ripple(rtagid);
     clean_advisory_ripple(rtagid);

     -- Log
     log_action (pvid, 'action', userid, 'End of Make Package Release...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_unrelease (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid   NUMBER;
     envtab   NUMBER;
   BEGIN
     -- Get ViewId
     --ViewId := PK_RELEASE.GET_PACKAGE_VIEW ( PvId, RtagId );
     viewid := get_package_view (pvid, rtagid);
     -- Remove from current area
     envtab := pk_environment.get_package_area (pvid, rtagid);
     -- Log
     log_action (pvid,
              'action',
              userid,
              'Start of Make Package UnRelease...'
             );

     IF envtab = 2
     THEN
       -- RELEASE AREA --
       pk_release.remove_package (pvid, rtagid, userid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       pk_planned.remove_package (pvid, rtagid, userid);
     END IF;

     -- Change package state
     pk_package.change_state (pvid, 'N', userid);

     -- Make sure it is valid BASE VIEW
     IF viewid < 1
     THEN
       viewid := 7;                     -- This is default base view
     END IF;

     -- Add package to new area
     pk_work_in_progress.add_package (pvid, viewid, rtagid, userid);
     -- Now do post Release Actions
     pk_release.run_post_actions (pvid, rtagid);
     -- Log
     log_action (pvid, 'action', userid, 'End of Make Package UnRelease...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_pending (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid     NUMBER;
     ispatch    CHAR (1) := NULL;
     buildtype  CHAR (1) := NULL;
   BEGIN
     -- Check if package is patch
     SELECT pv.is_patch, pv.build_type
      INTO ispatch, buildtype
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     -- Get ViewId
     viewid := get_package_view (pvid, rtagid);
     --ViewId := PK_WORK_IN_PROGRESS.GET_PACKAGE_VIEW ( PvId, RtagId );

     -- Log
     log_action (pvid, 'action', userid, 'Start of Make Package Pending...');

     IF (ispatch IS NULL)
     THEN
       -- Remove from current area
       pk_work_in_progress.remove_package (pvid, rtagid, userid);
       -- Change package state
       pk_package.change_state (pvid, 'P', userid);
       -- Add package to new area
       pk_planned.add_package (pvid, viewid, rtagid, userid);
     END IF;

     -- Log
     log_action (pvid, 'action', userid, 'End of Make Package Pending...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_approved (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
   BEGIN
     -- Log
     log_action (pvid,
                 'action',
                 userid,
                 'Start of Package Pending Approval...'
                 );
     -- Change package state
     pk_package.change_state (pvid, 'A', userid);
     -- Log
     log_action (pvid, 'action', userid,
                 'End of Package Pending Approval...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_reject (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid   NUMBER;
     operation CHAR;
   BEGIN
     -- Get ViewId
     viewid := get_package_view (pvid, rtagid);
     -- ViewId := PK_PLANNED.GET_PACKAGE_VIEW ( PvId, RtagId );

     -- DEVI-45275
     -- If the package version is an official version that is to be rejected from a merge operation
     -- then find out in order to prevent it being added back to work-in-progress table . This will
     -- be denoted by the operation field in the planned table being A or S
     operation := ' ';
     SELECT
     (CASE WHEN pl.operation IS NOT NULL THEN pl.operation ELSE ' ' END) INTO operation
     FROM planned pl
     WHERE pl.PV_ID = pvid
     AND pl.RTAG_ID = rtagid;

     -- Log
     log_action (pvid, 'action', userid, 'Start of Reject Package...');
     -- Remove from current area
     pk_planned.remove_package (pvid, rtagid, userid);

     -- DEVI-45275 - Prevent merge candidate from being added back to work-in-progress table .
     IF operation <> 'A' AND operation <> 'S'
     THEN
     -- Change package state
     pk_package.change_state (pvid, 'R', userid);
     -- Add package to new area
     pk_work_in_progress.add_package (pvid, viewid, rtagid, userid);
     ELSE
      log_action (pvid, 'action', userid, 'Rejected Package Merge');
     END IF;
     -- Log
     log_action (pvid, 'action', userid, 'End of Reject Package...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE change_package_view (
     pvid       IN   NUMBER,
     rtagid     IN   NUMBER,
     newviewid  IN   NUMBER
   )
   IS
     envtab   NUMBER;
   BEGIN
     envtab := pk_environment.get_package_area (pvid, rtagid);

     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       pk_work_in_progress.change_package_view (pvid, rtagid, newviewid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       pk_planned.change_package_view (pvid, rtagid, newviewid);
     ELSIF envtab = 2
     THEN
       -- RELEASED --
       pk_release.change_package_view (pvid, rtagid, newviewid);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE find_package (
     skeyword     IN      VARCHAR2,
     nrtagid      IN      NUMBER,
     nsearcharea  IN      NUMBER,
     recordset    OUT     typecur
   )
   IS
   BEGIN
     IF nsearcharea = 0
     THEN
       /* Search Work In Progress */
       OPEN recordset FOR
         SELECT nsearcharea AS env_area, vi.view_name, pv.dlocked,
                pkg.pkg_name, pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                work_in_progress rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
       ORDER BY UPPER (pkg.pkg_name);
     ELSIF nsearcharea = 1
     THEN
       /* Search Pending */
       OPEN recordset FOR
         SELECT nsearcharea AS env_area, vi.view_name, pv.dlocked,
                pkg.pkg_name, pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                planned rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
       ORDER BY UPPER (pkg.pkg_name);
     ELSIF nsearcharea = 2
     THEN
       /* Search Released */
       OPEN recordset FOR
         SELECT nsearcharea AS env_area, vi.view_name, pv.dlocked,
                pkg.pkg_name, pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                release_content rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.base_view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
         ORDER BY UPPER (pkg.pkg_name);
     ELSIF nsearcharea = 3
     THEN
       /* Search ALL */
       OPEN recordset FOR
         SELECT rc.env_area, vi.view_name, pv.dlocked, pkg.pkg_name,
                pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                environment_view rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
         ORDER BY UPPER (pkg.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE find_file (
     skeyword     IN      VARCHAR2,
     nrtagid      IN      NUMBER,
     nsearcharea  IN      NUMBER,
     npagesize    IN      NUMBER,
     recordset    OUT     typecur
   )
   IS
   BEGIN
     IF nsearcharea = 0
     THEN
       /* Search Work In Progress */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM work_in_progress rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM work_in_progress rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     ELSIF nsearcharea = 1
     THEN
       /* Search Pending */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM planned rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM planned rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     ELSIF nsearcharea = 2
     THEN
       /* Search Released */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Patches */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        DECODE (art.file_path,
                                NULL, pp.patch_id,
                                NULL
                                ) AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art,
                        package_patches pp
                  WHERE pv.pv_id = pp.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.rtag_id = nrtagid
                    AND art.pv_id = pp.patch_id
                    AND rc.pv_id = pp.pv_id
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     ELSIF nsearcharea = 3
     THEN
       /* Search ALL */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM environment_view rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM environment_view rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Patches */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        DECODE (art.file_path,
                                NULL, pp.patch_id,
                                NULL
                               ) AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art,
                        package_patches pp
                  WHERE pv.pv_id = pp.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.rtag_id = nrtagid
                    AND art.pv_id = pp.patch_id
                    AND rc.pv_id = pp.pv_id
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_prodrelease_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of integration products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,   --rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND pv.pv_id NOT IN (SELECT DISTINCT prod_id
                                 FROM deployment_manager.os_contents)
          AND rel.product_state IS NULL
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_integration_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of integration products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 1;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state IN (1, 5)
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_test_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of test products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 2;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state = 2
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_deploy_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of deploy products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 3;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state IN (3, 5)
          AND pv.pv_id NOT IN (SELECT DISTINCT prod_id
                                 FROM deployment_manager.os_contents)
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_reject_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of reject products
     SELECT COUNT (rc.pv_id)
       INTO ntruerecordcount
       FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 4;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state = 4
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;
/*-------------------------------------------------------------------------------------------------------*/
   -- DEVI-45275 - this procedure performs the merge of an existing package version in the planned table
   -- to the release_content table.

  PROCEDURE approve_merge (
   PvId    IN NUMBER,
   RtagId  IN NUMBER,
   UserId  IN NUMBER
  )
  IS
   viewid        NUMBER;
   envtab        NUMBER;
   oper         CHAR;
  BEGIN
      -- Get ViewId
     viewid := get_package_view (pvid, rtagid);

     -- Get the view tab
     envtab := pk_environment.get_package_area (pvid, rtagid);

     -- Make sure that package was in pending before merging it to released
     IF (envtab <> 1)
     THEN
       -- Not found in pending
       raise_application_error (-20000,
                          'This package cannot be released here.'
                         );
     END IF;

     -- Log
     log_action (pvid, 'action', userid, 'Start of Package Merge...');

     -- Get the planned operation type A=Add, S=Subtract
     SELECT ev.operation INTO oper
       FROM environment_view ev
      WHERE ev.rtag_id = RtagId
        AND ev.pv_id = PvId
        AND (ev.operation = 'A' OR ev.operation = 'S');

     -- Remove from Pending
     pk_planned.remove_package (PvId, RtagId, UserId);

     -- Either add to the release, or remove from the release as the operation commands
     IF oper = 'A'
     THEN
       pk_release.add_package(PvId, viewId, RtagId, UserId);

     ELSIF oper = 'S'
     THEN
       pk_release.remove_package(PvId, RtagId, UserId);

       -- Delete old package's pegging info
       DELETE FROM PEGGED_VERSIONS pegv WHERE pegv.RTAG_ID = RtagId AND pegv.PV_ID = PvId;

       -- Delete old package's advisory ripple info
       DELETE FROM ADVISORY_RIPPLE avr WHERE avr.RTAG_ID = RtagId AND avr.PV_ID = PvId;
     END IF;

     touch_release(RtagId);

     -- Log
     log_action (pvid, 'action', userid, 'End of Package Merge...');
  END;
/*-------------------------------------------------------------------------------------------------------*/
END pk_environment;
/
--------------------------------------------------------
--  DDL for Package Body PK_LICENCING
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_LICENCING" IS

/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  19/Aug/2008
||  Body Version:   1.0
------------------------------
*/

   PROCEDURE ADD_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER ) IS
   BEGIN
      IF IS_LICENCED(PvId, licenceId) = 0 THEN
         -- Add entry to licencing table
         INSERT INTO licencing (pv_id, licence)
         VALUES (PvId, licenceId);

         -- log action
         -- TODO
      END IF;

   END;

/*-------------------------------------------------------------------------------------------------------*/

   PROCEDURE REMOVE_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER ) IS
   BEGIN
      IF NOT IS_LICENCED(PvId, licenceId) = 0 THEN
         -- Delete entry from licencing table
         DELETE FROM licencing
         WHERE pv_id = PvId
         AND licence = licenceId;

         -- log action
         -- TODO
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/

   PROCEDURE CLONE_LICENCING( fromPvId IN NUMBER, toPvId IN NUMBER, UserId IN NUMBER ) IS

      CURSOR licencing_cur
      IS
         SELECT *
         FROM licencing
         WHERE pv_id = fromPvId;

      licencing_rec licencing_cur%ROWTYPE;

   BEGIN
      -- For each licence association that the Last PV_ID had, create a similar
      -- arrangement for the new PV_ID
      -- NOTE that any additional licencing associations the new PV_ID has that the old one
      -- does not have, are retained. The assumption is that the user has made those and so we do not
      -- have any right to destroy them without asking them.
      OPEN licencing_cur;

      FETCH licencing_cur
      INTO licencing_rec;

      WHILE licencing_cur%FOUND
      LOOP
         ADD_LICENCE ( toPvId, licencing_rec.licence, UserId );

         FETCH licencing_cur
         INTO licencing_rec;
      END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/

   FUNCTION IS_LICENCED( PvId IN NUMBER, licenceId IN NUMBER) RETURN NUMBER IS
      found NUMBER;
   BEGIN

      SELECT COUNT(*) INTO found
      FROM licencing
      WHERE pv_id = PvId
      AND licence = LicenceId;

      RETURN found;
   END;

/*-------------------------------------------------------------------------------------------------------*/

   PROCEDURE REMOVE_ALL_LICENCING( PvId IN NUMBER, UserId IN NUMBER ) IS

      CURSOR licencing_cur
      IS
         SELECT *
         FROM licencing
         WHERE pv_id = PvId;

      licencing_rec licencing_cur%ROWTYPE;
   BEGIN
      -- For each licence association that the PV_ID had, remove it
      OPEN licencing_cur;

      FETCH licencing_cur
      INTO licencing_rec;

      WHILE licencing_cur%FOUND
      LOOP
         REMOVE_LICENCE ( PvId, licencing_rec.licence, UserId );

         FETCH licencing_cur
         INTO licencing_rec;
      END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/
END PK_LICENCING;
/
--------------------------------------------------------
--  DDL for Package Body PK_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_PACKAGE" 
IS
   /*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE new_version (
      nlastpvid                   IN       NUMBER,
      snewpkgversion              IN       VARCHAR2 DEFAULT NULL,
      cbuildtype                  IN       CHAR,
      nsettopvid                  IN       NUMBER DEFAULT NULL,
      nrtagid                     IN       NUMBER,
      nuserid                     IN       NUMBER,
      enumissues_state_imported   IN       NUMBER,
      returnpvid                  OUT      NUMBER
   )
   IS
      origpkg_id                  package_versions.pkg_id%TYPE;
      origdlocked                 package_versions.dlocked%TYPE;
      ssv_mm                      package_versions.v_mm%TYPE;
      ssv_nmm                     package_versions.v_nmm%TYPE;
      ssv_ext                     package_versions.v_ext%TYPE;
      spackageversion             VARCHAR2 (4000);
      nissuestypes                NUMBER;
      nviewid                     NUMBER;
      reccount                    NUMBER;
      isreleased                  package_versions.dlocked%TYPE := 'N';
      slabel                      VARCHAR2 (4000)               := NULL;

      CURSOR package_versions_cur
      IS
         SELECT pv.pv_id, pv.is_patch, pv.dlocked
           FROM package_versions pv
          WHERE pv.pkg_version = snewpkgversion
            AND pv.pkg_id IN (SELECT DISTINCT origpv.pkg_id
                                         FROM package_versions origpv
                                        WHERE origpv.pv_id = nlastpvid);

      package_versions_rec package_versions_cur%ROWTYPE;

      CURSOR clone_package_versions_cur
      IS
         SELECT DISTINCT pkg_id, dlocked
                    FROM package_versions
                   WHERE pv_id = nlastpvid;

      clone_package_versions_rec clone_package_versions_cur%ROWTYPE;
   BEGIN
      spackageversion := snewpkgversion;

      IF nsettopvid IS NULL
      THEN
         -- SetToPv_id is not supplied, hence proceed.

         /* ---------------------------------------------------- */
         /* Find id package_version exists                       */
         /* ---------------------------------------------------- */
         OPEN package_versions_cur;

         FETCH package_versions_cur
          INTO package_versions_rec;

         IF package_versions_cur%NOTFOUND
         THEN
            ---  Create brand new package ---
            SELECT seq_pv_id.NEXTVAL
              INTO returnpvid
              FROM DUAL;

            -- Split Version to get extention + other
            split_version (spackageversion, ssv_mm, ssv_nmm, ssv_ext);

            -- Get previous package to clone from
            OPEN clone_package_versions_cur;

            FETCH clone_package_versions_cur
             INTO clone_package_versions_rec;

            origpkg_id := clone_package_versions_rec.pkg_id;
            origdlocked := clone_package_versions_rec.dlocked;

            CLOSE clone_package_versions_cur;

            -- Automated built config
            IF (cbuildtype = 'A')
            THEN
               spackageversion := '(' || returnpvid || ')' || ssv_ext;
               -- Make sure that version is still unique
            END IF;

            -- Clone Package Version Details --
            INSERT INTO package_versions(pv_id, pkg_id, pkg_version, dlocked, created_stamp,
                                         creator_id, modified_stamp, modifier_id, v_mm, v_nmm,
                                         v_ext, src_path, pv_description, pv_overview,
                                         last_pv_id, owner_id, is_deployable,
                                         is_build_env_required, build_type, bs_id, is_autobuildable, ripple_field)
                 SELECT returnpvid AS pv_id, origpkg_id AS pkg_id,
                        spackageversion AS pkg_version, 'N' AS dlocked,
                        ora_sysdate AS created_stamp, nuserid AS creator_id,
                        ora_sysdatetime AS modified_stamp,
                        nuserid AS modifier_id, ssv_mm AS v_mm,
                        ssv_nmm AS v_nmm, ssv_ext AS v_ext, pv.src_path,
                        pv.pv_description, pv.pv_overview,
                        nlastpvid AS last_pv_id, pv.owner_id, pv.is_deployable,
                        pv.is_build_env_required, cbuildtype, pv.bs_id, pv.is_autobuildable, pv.ripple_field
                   FROM package_versions pv
                  WHERE pv.pv_id = nlastpvid;

            -- Set Issues Type for cloning ---
            IF origdlocked = 'Y'
            THEN
               nissuestypes := enumissues_state_imported;
            ELSE
               nissuestypes := NULL;
            END IF;

            -- Update Label for automated built
            IF (cbuildtype = 'A')
            THEN
               slabel := get_automated_label (returnpvid);

               UPDATE package_versions pv
                  SET pv.pkg_label = slabel
                WHERE pv.pv_id = returnpvid;
            END IF;

            basic_clone (nlastpvid,
                         returnpvid,
                         nrtagid,
                         nuserid,
                         origpkg_id,
                         nissuestypes
                        );
         ELSE
            --- Package already exists, hence reuse ---
            returnpvid := package_versions_rec.pv_id;
            isreleased := package_versions_rec.dlocked;
         END IF;

         CLOSE package_versions_cur;
      ELSE
         returnpvid := nsettopvid;
      END IF;
   END new_version;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE change_state (
      pvid       IN   NUMBER,
      newstate   IN   package_versions.dlocked%TYPE,
      userid     IN   NUMBER
   )
   IS
   BEGIN
      -- Set package in Released mode
      UPDATE package_versions pv
         SET pv.dlocked = newstate,
             pv.modified_stamp = ora_sysdatetime,
             pv.modifier_id = userid
       WHERE pv.pv_id = pvid;

      -- Log action --
      IF newstate = 'Y'
      THEN
         -- RELEASED --
         log_action (pvid,
                     'makeofficial',
                     userid,
                     'Package state change to: Released'
                    );
      ELSIF newstate = 'N'
      THEN
         -- UNLOCKED --
         log_action (pvid,
                     'makeunofficial',
                     userid,
                     'Package state change to: Ulocked'
                    );
      ELSIF newstate = 'P'
      THEN
         -- PENDING APPROVAL --
         log_action (pvid,
                     'add_to_planned',
                     userid,
                     'Package state change to: Pending Approval'
                    );
      ELSIF newstate = 'R'
      THEN
         -- REJECTED --
         log_action (pvid,
                     'reject_package',
                     userid,
                     'Package state change to: Rejected'
                    );
      ELSIF newstate = 'A'
      THEN
         -- APPROVED --
         log_action (pvid,
                     'approve_package',
                     userid,
                     'Package state change to: Approved'
                    );
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE destroy_package (
      pvid               IN       NUMBER,
      overridewarnings   IN       CHAR DEFAULT 'N',
      problemstring      OUT      VARCHAR2
   )
   IS
      LOCKED     CHAR;
      pkgid      NUMBER;
      ROWCOUNT   NUMBER;
   BEGIN
      /*
      || This will destroy all package details from database.
      || It will only be used to remove unwanted work in progress packages,
      || or mestaken versions
      */

      /*--------------- Business Rules Here -------------------*/
      problemstring := NULL;

      IF overridewarnings = 'N'
      THEN
         -- Package must not be official
         SELECT pv.dlocked
           INTO LOCKED
           FROM package_versions pv
          WHERE pv.pv_id = pvid;

         IF LOCKED = 'Y'
         THEN
            problemstring :=
                  problemstring
               || '- Package is locked and released.'
               || UTL_TCP.crlf;
         END IF;

         -- Cannot remove if used in BOMs
         SELECT COUNT (osc.prod_id)
           INTO ROWCOUNT
           FROM deployment_manager.os_contents osc
          WHERE osc.prod_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is part of Bill-Of-Material (BOM) in Deployment Manager.'
               || UTL_TCP.crlf;
         END IF;

         -- Cannot remove if Referenced as build dependency
         SELECT COUNT (dep.pv_id)
           INTO ROWCOUNT
           FROM package_dependencies dep
          WHERE dep.dpv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is referenced by other package as build dependency.'
               || UTL_TCP.crlf;
         END IF;

         -- Cannot remove if Referenced as runtime dependency
         SELECT COUNT (rd.pv_id)
           INTO ROWCOUNT
           FROM runtime_dependencies rd
          WHERE rd.rtd_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is referenced by other package as runtime dependency.'
               || UTL_TCP.crlf;
         END IF;

         -- Cannot remove if Referenced as patch
         SELECT COUNT (pp.pv_id)
           INTO ROWCOUNT
           FROM package_patches pp
          WHERE pp.patch_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is used as patch by other package.'
               || UTL_TCP.crlf;
         END IF;
      END IF;

/*-------------------------------------------------------*/
      IF (problemstring IS NULL)
      THEN
         --- Remove From Work in Progress
         DELETE FROM work_in_progress wip
               WHERE wip.pv_id = pvid;

         --- Remove From Pending
         DELETE FROM planned pl
               WHERE pl.pv_id = pvid;

         --- Remove From Released area
         DELETE FROM release_content rc
               WHERE rc.pv_id = pvid;

         ---Remove From Package Processes
         DELETE FROM package_processes pp
               WHERE pp.pv_id = pvid;

         --- Remove Dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = pvid;

         DELETE FROM package_dependencies dep
               WHERE dep.dpv_id = pvid;

         --- Remove Runtime dependencies
         DELETE FROM runtime_dependencies rtd
               WHERE rtd.pv_id = pvid;

         DELETE FROM runtime_dependencies rtd
               WHERE rtd.rtd_id = pvid;

         --- Remove components
         DELETE FROM product_components pc
               WHERE pc.pv_id = pvid;

         DELETE FROM release_components rc
               WHERE rc.pv_id = pvid;

         --- Remove From Notification History
         DELETE FROM notification_history nh
               WHERE nh.pv_id = pvid;

         --- Remove From Ignore Warnings
         DELETE FROM ignore_warnings iw
               WHERE iw.pv_id = pvid;

         --- Remove From Additional Notes
         DELETE FROM additional_notes an
               WHERE an.pv_id = pvid;

         --- Remove From CQ Issues
         DELETE FROM cq_issues cq
               WHERE cq.pv_id = pvid;

         --- Remove from Package Patches
         DELETE FROM package_patches pp
               WHERE pp.pv_id = pvid;

         DELETE FROM package_patches pp
               WHERE pp.patch_id = pvid;

         --- Remove From Package Documents
         DELETE FROM package_documents pd
               WHERE pd.pv_id = pvid;

         --- Remove from Code Review
         DELETE FROM code_reviews cr
               WHERE cr.pv_id = pvid;

         --- Remove from Code Review URL
         DELETE FROM code_review_url cru
               WHERE cru.pv_id = pvid;

         --- Remove from Unit Tests
         DELETE FROM unit_tests ut
               WHERE ut.pv_id = pvid;

         --- Remove from Package BuildEnv
         DELETE FROM package_build_env pbe
               WHERE pbe.pv_id = pvid;

         --- Remove from Package Build Info
         DELETE FROM package_build_info pbi
               WHERE pbi.pv_id = pvid;

         --- Remove from Build Order
         DELETE FROM build_order bo
               WHERE bo.pv_id = pvid;

         --- Remove from Licencing
         PK_LICENCING.REMOVE_ALL_LICENCING( pvid, 0 );

         --- Remove from Note Manager
         DELETE FROM note_manager nm
               WHERE nm.nid = pvid;

         --- Remove from Action log
         DELETE FROM action_log al
               WHERE al.pv_id = pvid;

         --- Remove from Do Not Ripple
         DELETE FROM DO_NOT_RIPPLE dnr
               WHERE dnr.PV_ID = pvid;

         --- Remove from Advisory Ripple
         DELETE FROM ADVISORY_RIPPLE ar
               WHERE ar.PV_ID = pvid;

         --- Remove from Jira Issues
         DELETE FROM JIRA_ISSUES jira
               WHERE jira.PV_ID = pvid;

         --- Remove from Package Metrics
         DELETE FROM package_metrics pm
              WHERE pm.pv_id = pvid;

         -- Delete from Pegged Versions
         DELETE FROM pegged_versions pegv
              WHERE pegv.pv_id = pvid;

         --- Finally Remove From Package Versions
         --- Get Package name
         SELECT pv.pkg_id
           INTO pkgid
           FROM package_versions pv
          WHERE pv.pv_id = pvid;

         DELETE FROM package_versions pv
               WHERE pv.pv_id = pvid;

         --- Remove package name if not used any more
         SELECT COUNT (pv.pv_id)
           INTO ROWCOUNT
           FROM package_versions pv
          WHERE pv.pkg_id = pkgid;

         IF ROWCOUNT < 1
         THEN
            DELETE FROM PACKAGES pkg
                  WHERE pkg.pkg_id = pkgid;
         END IF;
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE new_patch (
      snewpatchversion   IN       package_versions.pkg_version%TYPE,
      nparentpvid        IN       NUMBER,
      spatchidlist       IN       VARCHAR2,
      nuserid            IN       NUMBER,
      returnpatchid      OUT      NUMBER
   )
   IS
      patchpv_id           NUMBER;
      parpkg_id            NUMBER;
      lastinstallorder     NUMBER;
      ispatchdlocked       package_versions.dlocked%TYPE;
      ssv_mm               package_versions.v_mm%TYPE;
      ssv_nmm              package_versions.v_nmm%TYPE;
      ssv_ext              package_versions.v_ext%TYPE;
      opatchdepcollector   relmgr_number_tab_t  := relmgr_number_tab_t ();

      CURSOR parent_cur
      IS
         SELECT pv.*, pkg.pkg_name
           FROM package_versions pv, PACKAGES pkg
          WHERE pv.pv_id = nparentpvid AND pv.pkg_id = pkg.pkg_id;

      parent_rec parent_cur%ROWTYPE;

      CURSOR patch_cur
      IS
         SELECT pv.*, pg.pkg_name
           FROM package_versions pv, PACKAGES pg
          WHERE pv.pkg_id = parpkg_id
            AND pv.pkg_version = snewpatchversion
            AND pv.pkg_id = pg.pkg_id;

      patch_rec  patch_cur%ROWTYPE;

      CURSOR releases_cur
      IS
         SELECT rc.pv_id
           FROM release_content rc
          WHERE rc.pv_id = patch_rec.pv_id;

      releases_rec releases_cur%ROWTYPE;
   BEGIN
      -- Get Last Install Order
      SELECT COUNT (*)
        INTO lastinstallorder
        FROM package_patches pp
       WHERE pp.pv_id = nparentpvid;

      -- Get parent details
      OPEN parent_cur;

      FETCH parent_cur
       INTO parent_rec;

      parpkg_id := parent_rec.pkg_id;

      -- Find if patch exists in database
      OPEN patch_cur;

      FETCH patch_cur
       INTO patch_rec;

      -- Parent must be official
      IF parent_rec.dlocked = 'Y'
      THEN
         IF patch_cur%NOTFOUND
         THEN
            ispatchdlocked := 'N';

            -- Create new patch version --
            SELECT seq_pv_id.NEXTVAL
              INTO patchpv_id
              FROM DUAL;

            split_version (snewpatchversion, ssv_mm, ssv_nmm, ssv_ext);

            INSERT INTO package_versions
                        (pv_id, pkg_id, pkg_version,
                         dlocked, created_stamp, creator_id,
                         modified_stamp, modifier_id, v_mm, v_nmm, v_ext,
                         src_path,
                         pv_description,
                         owner_id, is_patch, last_pv_id, build_type, is_build_env_required, bs_id,
                         is_autobuildable, ripple_field
                        )
                 VALUES (patchpv_id, parpkg_id, snewpatchversion,
                         ispatchdlocked, ora_sysdate, nuserid,
                         ora_sysdatetime, nuserid, ssv_mm, ssv_nmm, ssv_ext,
                         parent_rec.src_path,
                            'This is a patch to '
                         || parent_rec.pkg_name
                         || ' '
                         || parent_rec.pkg_version,
                         nuserid, 'Y', patchpv_id, 'M', 'N', 3, 'N', parent_rec.ripple_field
                        );

            INSERT INTO package_patches
                        (pv_id, patch_id, install_order)
                (SELECT nparentpvid AS pv_id, pv.pv_id AS patch_id,
                        lastinstallorder + 1 AS install_order
                   FROM package_versions pv
                  WHERE pv.pv_id = patchpv_id AND pv.is_patch = 'Y');

            /* LOG ACTION */
            log_action (patchpv_id,
                        'new_version',
                        nuserid,
                        'Patch version created: ' || snewpatchversion
                       );
            log_action (nparentpvid,
                        'patch_add',
                        nuserid,
                        'New patch created and attached: ' || snewpatchversion
                       );
         ELSE
            patchpv_id := patch_rec.pv_id;
            ispatchdlocked := patch_rec.dlocked;

            -- Find if pv_id exists in release content (i.e. it cannot be a patch)
            OPEN releases_cur;

            FETCH releases_cur
             INTO releases_rec;

            IF releases_cur%NOTFOUND
            THEN
               -- This pv_id is trully a patch, hence add Y to column IS_PATCH
               UPDATE package_versions
                  SET is_patch = 'Y'
                WHERE pv_id = patchpv_id;

               INSERT INTO package_patches
                           (pv_id, patch_id, install_order)
                   (SELECT nparentpvid AS pv_id, pv.pv_id AS patch_id,
                           lastinstallorder + 1 AS install_order
                      FROM package_versions pv
                     WHERE pv.pv_id = patchpv_id AND pv.is_patch = 'Y');
            END IF;

            CLOSE releases_cur;

            /* LOG ACTION */
            log_action (nparentpvid,
                        'patch_add',
                        nuserid,
                           'Patch version was found and attached: '
                        || snewpatchversion
                       );
         END IF;
      END IF;

      /* Create Patch Dependencies */
      opatchdepcollector := in_list_number (spatchidlist);

      -- Make sure patch is unofficial before altering its dependencies
      IF (opatchdepcollector.COUNT > 0) AND (ispatchdlocked = 'N')
      THEN
         -- Delete Existing Dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = patchpv_id;

         -- Insert new dependencies
         INSERT INTO package_dependencies
                     (pv_id, dpv_id, pkg_id, dpkg_id, build_type)
              SELECT patchpv_id AS pv_id, pv.pv_id AS dpv_id,
                     parpkg_id AS pkg_id, pv.pkg_id AS dpkg_id,
                     'L' AS build_type
                FROM package_versions pv
               WHERE pv.pv_id IN (
                      SELECT *
                        FROM TABLE
                                (CAST
                                    (opatchdepcollector AS relmgr_number_tab_t)
                                ));
      END IF;

      -- Return patch_id
      returnpatchid := patchpv_id;

      CLOSE parent_cur;

      CLOSE patch_cur;
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                     'Patch version '
                                  || snewpatchversion
                                  || ' already exist.'
                                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE obsolete_patch (
      patchid            IN   NUMBER,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   )
   IS
   BEGIN
      -- Update patch
      UPDATE package_versions pv
         SET pv.is_obsolete = isobsolete,
             pv.obsolete_comments = obsoletecomments
       WHERE pv.pv_id = patchid;

      /*
      -- Update patch children
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.DPV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.PV_ID = PatchId
                     );


      -- Update patch parent
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.PV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.DPV_ID = PatchId
                     );

      */

      /* LOG ACTION */
      IF isobsolete IS NOT NULL
      THEN
         log_action (patchid,
                     'patch_obsolete',
                     userid,
                     'Obsolete patch. ' || obsoletecomments
                    );
      ELSE
         log_action (patchid,
                     'patch_obsolete',
                     userid,
                     'Undo patch obsolete.'
                    );
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE obsolete_patches (
      spatchidlist       IN   VARCHAR2,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   )
   IS
   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF spatchidlist IS NULL
      THEN
         raise_application_error (-20000,
                                  'Please select one or more Patches.'
                                 );
      END IF;

/*-------------------------------------------------------*/

      -- Update patch
      UPDATE package_versions pv
         SET pv.is_obsolete = isobsolete,
             pv.obsolete_comments = obsoletecomments
       WHERE pv.pv_id IN (
                SELECT *
                  FROM THE
                          (SELECT CAST
                                     (in_list_number (spatchidlist) AS relmgr_number_tab_t
                                     )
                             FROM DUAL
                          ));
      /*
      -- Update patch children
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.DPV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.PV_ID = PatchId
                     );


      -- Update patch parent
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.PV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.DPV_ID = PatchId
                     );

      */

      /* LOG ACTION
      IF IsObsolete IS NOT NULL THEN
         Log_Action ( PatchId, 'patch_obsolete', UserId,
                     'Obsolete patch. '|| ObsoleteComments );
      ELSE
         Log_Action ( PatchId, 'patch_obsolete', UserId,
                     'Undo patch obsolete.' );
      END IF;  */
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_process (
      nprocid         IN   processes.proc_id%TYPE,
      shealthtag      IN   processes.proc_name%TYPE,
      sprocdesc       IN   processes.proc_description%TYPE,
      scmdinterface   IN   processes.run_as%TYPE,
      spkgowner       IN   processes.pkg_owner%TYPE,
      sisinterface    IN   processes.is_interface%TYPE,
      npvid           IN   package_processes.pv_id%TYPE,
      nuserid         IN   NUMBER
   )
   IS
      pkgname   VARCHAR2 (100);

   BEGIN
      INSERT INTO processes
                  (proc_id, proc_name, proc_description, run_as, pkg_owner,
                   is_interface
                  )
           VALUES (nprocid, shealthtag, sprocdesc, scmdinterface, spkgowner,
                   sisinterface
                  );

      pk_package.add_package_process (nprocid, npvid, nuserid);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_package_process (
      nprocidlist   IN   VARCHAR2,
      npvid         IN   package_processes.pv_id%TYPE,
      nuserid       IN   NUMBER
   )
   IS
      processname   VARCHAR2 (4000);

      CURSOR proc_cur
      IS
         SELECT prc.proc_id
           FROM processes prc
          WHERE prc.proc_id IN (
                   SELECT *
                     FROM THE
                             (SELECT CAST
                                        (in_list_number (nprocidlist) AS relmgr_number_tab_t
                                        )
                                FROM DUAL
                             ));

      proc_rec  proc_cur%ROWTYPE;
   BEGIN
      OPEN proc_cur;

      FETCH proc_cur
       INTO proc_rec;

      WHILE proc_cur%FOUND
      LOOP
         INSERT INTO package_processes (proc_id, pv_id)
              VALUES (proc_rec.proc_id, npvid);

         SELECT prc.proc_name
           INTO processname
           FROM processes prc
          WHERE prc.proc_id = proc_rec.proc_id;

         -- Log Action --
         log_action (npvid,
                     'process_add',
                     nuserid,
                     'Added process with health tag ' || processname
                    );

         FETCH proc_cur
          INTO proc_rec;
      END LOOP;

      CLOSE proc_cur;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_process (
      nprocid   IN   package_processes.proc_id%TYPE,
      npvid     IN   package_processes.pv_id%TYPE,
      nuserid   IN   NUMBER
   )
   IS
      processname   VARCHAR2 (4000);
   BEGIN
      SELECT prc.proc_name
        INTO processname
        FROM processes prc
       WHERE prc.proc_id = nprocid;

      DELETE FROM package_processes
            WHERE proc_id = nprocid AND pv_id = npvid;

      -- Log Action --
      log_action (npvid,
                  'process_remove',
                  nuserid,
                  'Removed process with health tag ' || processname
                 );
   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Rupesh Solanki
   ** Purpose: To move package versions from one release to another
   ** Release: 4th September 2006
   */
   PROCEDURE move_package (
      npvid        IN package_versions.pv_id%TYPE,
      nrtagid      IN release_tags.rtag_id%TYPE,
      nnewrtagid   IN release_tags.rtag_id%TYPE,
      nuserid      IN NUMBER
   )
   IS

      oldrtag_name VARCHAR2(4000);newrtag_name VARCHAR2(4000);

   BEGIN
      SELECT rtag_name into oldrtag_name
      FROM RELEASE_TAGS
      WHERE rtag_id = nrtagid;

      SELECT rtag_name into newrtag_name
      FROM RELEASE_TAGS
      WHERE rtag_id = nnewrtagid;

      /* Table Work In Progress*/
      UPDATE WORK_IN_PROGRESS
      SET RTAG_ID = nnewrtagid
      WHERE RTAG_ID = nrtagid
      AND PV_ID = npvid;

      /* Table PLANNED*/
      UPDATE PLANNED
      SET RTAG_ID = nnewrtagid
      WHERE RTAG_ID = nrtagid
      AND PV_ID = npvid;

      /* Table PEGGED_VERSIONS */
      DELETE FROM PEGGED_VERSIONS pegv
      WHERE pegv.RTAG_ID = nrtagid
      AND pegv.PV_ID = npvid;

      /* Table ADVISORY_RIPPLE*/
      DELETE FROM ADVISORY_RIPPLE
      WHERE RTAG_ID = nrtagid
      AND PV_ID = npvid;


      -- Log Action --
      log_action (npvid,
                  'move_package_version',
                  nuserid,
                  'Moved package version from ' || oldrtag_name || ' to ' || newrtag_name
                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Rupesh Solanki
   ** Purpose: To modify the product state from integration to test to deployment
   ** Release: 25th January 2006
   */
   PROCEDURE modify_product_state (
      npvid    IN package_versions.pv_id%TYPE,
      nrtagid  IN release_tags.rtag_id%TYPE,
      nstateid IN product_states.state_id%TYPE,
      nuserid  IN NUMBER
   ) IS

      sStateName VARCHAR2(4000);
      sRtagName VARCHAR2(4000);

   BEGIN

      UPDATE RELEASE_CONTENT
      SET PRODUCT_STATE = nstateid
      WHERE PV_ID = npvid
      AND RTAG_ID = nrtagid;


      SELECT STATE INTO sStateName
      FROM PRODUCT_STATES
      WHERE STATE_ID = nstateid;

      SELECT RTAG_NAME into sRtagName
      FROM RELEASE_TAGS
      WHERE RTAG_ID = nrtagid;


      -- Log Action --
      log_action (npvid,
                  'modify_product_state',
                     nuserid,
                     sStateName || ' in '|| sRtagName
                  );
   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Jeremy Tweddle
   ** Date: 24/Aug/2007
   */
   PROCEDURE add_code_review_url (
      npvid           IN    NUMBER,
      nprojid         IN    NUMBER,
      surl            IN    VARCHAR2,
      sreason         IN    VARCHAR2,
      ddateofreview   IN    DATE
   ) IS

      ncrid NUMBER;

   BEGIN

      SELECT seq_cr_id.NEXTVAL INTO ncrid FROM DUAL;

      INSERT INTO code_review_url ( cr_id, pv_id, proj_id, url, reason, date_of_review,
                                    last_modified )
      VALUES ( ncrid, npvid, nprojid, surl, sreason, ddateofreview, ora_sysdate );

   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Jeremy Tweddle
   ** Date: 22/Aug/2007
   */
   PROCEDURE update_code_review_url (
      ncrid           IN    NUMBER,
      nprojid         IN    NUMBER,
      surl            IN    VARCHAR2,
      sreason         IN    VARCHAR2
   ) IS

   BEGIN

      UPDATE code_review_url
      SET url = surl,
          proj_id = nprojid,
          reason = sreason,
          last_modified = ora_sysdate
      WHERE cr_id = ncrid;

   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Jeremy Tweddle
   ** Date: 22/Aug/2007
   */
   PROCEDURE remove_code_review_url (
      ncrid  IN    NUMBER
   ) IS

   BEGIN
      DELETE FROM code_review_url
      WHERE cr_id = ncrid;
   END;
/*-------------------------------------------------------------------------------------------------------*/
END pk_package;
/
--------------------------------------------------------
--  DDL for Package Body PK_PLANNED
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_PLANNED" IS

/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  05/Aug/2008
||  Body Version:   1.2
------------------------------
*/


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

    oldPvId NUMBER;
    ReleaseLocation VARCHAR2(4000);
    IsPatch CHAR(1) := NULL;
    sLocation VARCHAR2(4000) := NULL;
    nRtagIdLocation NUMBER;



BEGIN
    /*--------------- Business Rules Here -------------------*/
    /*-------------------------------------------------------*/

    BEGIN
        -- Check if Exists in "Work in progress" anywhere in the world, except "Closed mode" releases
        SELECT proj.PROJ_NAME ||' > '|| rt.RTAG_NAME, rt.RTAG_ID  INTO sLocation, nRtagIdLocation
          FROM PLANNED pl,
               RELEASE_TAGS rt,
               PROJECTS proj
         WHERE pl.PV_ID = newPvId
           AND pl.RTAG_ID = rt.RTAG_ID
           AND rt.OFFICIAL != 'Y'
           AND rt.PROJ_ID = proj.PROJ_ID;

        EXCEPTION
            WHEN NO_DATA_FOUND THEN
                sLocation := NULL;
    END;



    IF (sLocation IS NULL) OR (nRtagIdLocation = RtagId) THEN

        -- Add to "Pending" area
        INSERT INTO PLANNED ( RTAG_ID, PV_ID, VIEW_ID, OPERATION )
        VALUES( RtagId, newPvId, ViewId, 'R' );


        /* LOG ACTION */
        SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
          FROM PROJECTS proj,
               RELEASE_TAGS rt
         WHERE rt.PROJ_ID = proj.PROJ_ID
           AND rt.RTAG_ID = RtagId;

        Log_Action ( newPvId, 'add_to_planned', UserId, 'Location: '|| ReleaseLocation );

    ELSE

        RAISE_APPLICATION_ERROR (-20000, 'This version is already in Pending Area at '|| sLocation ||'.' );

    END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

    ReleaseLocation VARCHAR2(4000);

BEGIN

    /*--------------- Business Rules Here -------------------*/
    /*-------------------------------------------------------*/


    -- Get release location for logging pusposes
    SELECT proj.PROJ_NAME  ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
      FROM PROJECTS proj,
           RELEASE_TAGS rt
     WHERE rt.PROJ_ID = proj.PROJ_ID
       AND rt.RTAG_ID = RtagId;


    -- Delete from Work In Progress
    DELETE
      FROM PLANNED pl
     WHERE pl.RTAG_ID = RtagId
       AND pl.PV_ID = PvId;

    Log_Action ( PvId, 'deleted_from_pending', UserId, 'Location: '|| ReleaseLocation );




END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER IS

    ReturnValue NUMBER;

BEGIN
    SELECT pl.VIEW_ID INTO ReturnValue
      FROM PLANNED pl
     WHERE pl.RTAG_ID = RtagId
       AND pl.PV_ID = PvId;

    RETURN ReturnValue;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur ) IS

    IsBaseView CHAR(1);

BEGIN

    -- Check if the view is BASE VIEW
    SELECT vi.BASE_VIEW INTO IsBaseView
      FROM VIEWS vi
     WHERE vi.VIEW_ID = ViewId;


    IF (IsBaseView = 'Y') THEN
        -- Get Base view content
        OPEN RecordSet FOR
        SELECT 0 AS PKG_STATE,
               NULL AS DEPRECATED_STATE,
               pv.pv_id,
               pkg.pkg_name,
               pv.pkg_version,
               pv.dlocked,
               pv.pv_description,
               pv.BUILD_TYPE,
               rel.operation
          FROM PLANNED rel,
               packages pkg,
               package_versions pv
         WHERE pv.pkg_id = pkg.pkg_id
           AND rel.pv_id = pv.pv_id
           AND rel.VIEW_ID = ViewId
           AND rel.RTAG_ID = RtagId
         ORDER BY UPPER(pkg.PKG_NAME);

    ELSE

        -- Get non base view content
        OPEN RecordSet FOR
        SELECT 0 AS PKG_STATE,
               NULL AS DEPRECATED_STATE,
               pv.pv_id,
               pkg.pkg_name,
               pv.pkg_version,
               pv.dlocked,
               pv.pv_description,
               pv.BUILD_TYPE,
               rel.operation
          FROM PLANNED rel,
               packages pkg,
               package_versions pv,
               VIEW_DEF vd
         WHERE pv.pkg_id = pkg.pkg_id
           AND rel.pv_id = pv.pv_id
           AND rel.RTAG_ID = RtagId
           AND vd.VIEW_ID = ViewId
           AND vd.PKG_ID = pv.PKG_ID
         ORDER BY UPPER(pkg.PKG_NAME);

    END IF;


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER ) IS

BEGIN

    UPDATE PLANNED pl SET
    pl.VIEW_ID = NewViewId
    WHERE pl.PV_ID = PvId
      AND pl.RTAG_ID = RtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
-- DEVI-45275 This new function supports the ability to insert into the planned table, and existing
-- version of a package as part of a release-to-release merge operation carried out within release manager.
-- DEVI-49594 This function has subsequently been changed to allow a merge operation to cancel its
-- opposite operation, if the opposite already exists in the planned table. This supports user activity
-- via the Release Manager merge manager display

PROCEDURE MERGE_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, mergeOperation IN CHAR ) IS

    ReleaseLocation VARCHAR2(4000);

        entryExists NUMBER;
        existingOperation CHAR;
BEGIN
    /*--------------- Business Rules Here -------------------*/
    /*-------------------------------------------------------*/

      -- Determine if the specified PV_ID already exists in the planned table....
      SELECT COUNT (pl.pv_id) INTO entryExists
      FROM PLANNED pl
      WHERE pl.pv_id = newPvId
      AND pl.rtag_id = RtagId
      AND pl.view_id = ViewId;

      -- If the specified PV_ID already exists in the planned table....
      IF entryExists = 1 THEN

         -- Get the operation for the existing entry
         SELECT pl.operation INTO existingOperation
         FROM PLANNED pl
         WHERE pl.pv_id = newPvId
         AND pl.rtag_id = RtagId
         AND pl.view_id = ViewId;

         -- Is the specified merge operation the opposite of the existing entry?
         -- If it is not, then there is nothing to do, otherwise...
         -- NOTE: A = Add, S = Subtract
         IF (mergeOperation = 'S' AND existingOperation = 'A')
            OR (mergeOperation = 'A' AND existingOperation = 'S') THEN

           -- It is the opposite, so effectively it cancels the existing entry
           -- Remove the entry from the planned table
           DELETE
            FROM PLANNED pl
           WHERE pl.pv_id = newPvId
             AND pl.rtag_id = RtagId
             AND pl.view_id = ViewId;

           -- Log action
           SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
             FROM PROJECTS proj,
                  RELEASE_TAGS rt
            WHERE rt.PROJ_ID = proj.PROJ_ID
              AND rt.RTAG_ID = RtagId;

           Log_Action ( newPvId, 'deleted_from_pending', UserId, 'Location: '|| ReleaseLocation );
         END IF;
      ELSE
         -- Add to Planned tabled
         INSERT INTO PLANNED ( RTAG_ID, PV_ID, VIEW_ID, OPERATION )
         VALUES( RtagId, newPvId, ViewId, mergeOperation );

         -- Log Action
         SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
          FROM PROJECTS proj,
               RELEASE_TAGS rt
         WHERE rt.PROJ_ID = proj.PROJ_ID
         AND   rt.RTAG_ID = RtagId;

         Log_Action ( newPvId, 'add_to_planned', UserId, 'Location: '|| ReleaseLocation );
      END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
END PK_PLANNED;
/
--------------------------------------------------------
--  DDL for Package Body PK_PROJECT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_PROJECT" IS

    /*------------------------------------------------------------------------*/
    PROCEDURE update_base_url (
    nprojid   IN  projects.proj_id%TYPE,
    sbaseurl  IN  VARCHAR2
    ) IS
    BEGIN

    UPDATE projects
    SET base_url = sbaseurl
    WHERE proj_id = nprojid;

    END update_base_url;

/*------------------------------------------------------------------------*/
    PROCEDURE update_project_config (
    nprojid   IN  projects.proj_id%TYPE,
    sbaseurl  IN  VARCHAR2,
    sjirakey  IN  VARCHAR2
    ) IS
    BEGIN

    UPDATE projects
    SET base_url = sbaseurl,
        jira_key = sjirakey
    WHERE proj_id = nprojid;

    END update_project_config;
    /*------------------------------------------------------------------------*/

    END pk_project;
/
--------------------------------------------------------
--  DDL for Package Body PK_RELEASE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_RELEASE" IS

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE New_Release ( sReleaseName IN VARCHAR2, sReleaseComments IN VARCHAR2, nProjId IN NUMBER, nSourceRtagId IN NUMBER, sIsBranched IN CHAR, nUserId IN NUMBER ) IS

RtagId NUMBER;
ParentRtagId NUMBER;
RecCount NUMBER := 0;
VtreeId NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   -- Check for missing parameters
   IF (sReleaseName IS NULL) OR (nUserId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! sReleaseName= '|| sReleaseName ||', nUserId='|| nUserId );

   END IF;


   -- Check for duplicate Release Names
   SELECT COUNT(rt.RTAG_ID) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE UPPER( rt.RTAG_NAME ) = UPPER( sReleaseName )
      AND rt.PROJ_ID = nProjId;

   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Release Name '|| sReleaseName ||' is Already Used in this Project.');
   END IF;
   /*-------------------------------------------------------*/


   -- Get rtag_id
   SELECT SEQ_RTAG_ID.NEXTVAL INTO RtagId FROM DUAL;

   SELECT SEQ_VTREE_ID.NEXTVAL INTO VtreeId FROM DUAL;



   -- Get Parent RtagId
   ParentRtagId := GET_PARENT_RTAG ( RtagId, nSourceRtagId, sIsBranched );

   -- If the parent RTAG is NOT in this project then we cannot use it.
   -- We must re-assign the parent to be the new release's RTAG_ID instead
   -- else it will not show up in the projects release tree (DEVI-55480)
   SELECT COUNT(rt.RTAG_ID) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = ParentRtagId
      AND rt.PROJ_ID = nProjId;

   IF (RecCount = 0) THEN
     ParentRtagId := RtagId;
   END IF;

   -- Create new release
   INSERT INTO RELEASE_TAGS ( RTAG_ID, RTAG_NAME, DESCRIPTION, CREATED_STAMP, CREATOR_ID,
                        OFFICIAL, REBUILD_ENV, REBUILD_STAMP,
                        PARENT_RTAG_ID, PROJ_ID, VTREE_ID )
   VALUES ( RtagId,
          sReleaseName,
          sReleaseComments,
          ORA_SYSDATE,
          nUserId,
          'N',
          'N',
          0,
          ParentRtagId,
          nProjId,
          VtreeId );

   -- If a source release is provided, clone its config spec branch information into the new release (DEVI-56650)
   IF (NOT nSourceRtagId IS NULL)
   THEN
      UPDATE RELEASE_TAGS rtd
      SET rtd.config_spec_branch = (SELECT rts.CONFIG_SPEC_BRANCH FROM RELEASE_TAGS rts WHERE rts.RTAG_ID = nSourceRtagId)
      WHERE rtd.RTAG_ID = RtagId;
   END IF;

   -- Update display Order
   UPDATE_DISPLAY_ORDER ( nProjId );

   /* Log Project Action */
   Log_Project_Action ( nProjId, 'new_release', nUserId, sReleaseName, RtagId );


   -- Import Release Contents
   IF (NOT nSourceRtagId IS NULL) THEN
      Import_Release_Contents ( nSourceRtagId, RtagId, nUserId );
   END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE UPDATE_DISPLAY_ORDER ( nProjId IN NUMBER ) IS


BEGIN


   /*--------------- Business Rules Here -------------------*/
   /*-------------------------------------------------------*/

   UPDATE RELEASE_TAGS urt SET
   urt.DISPLAY_ORDER = (
                  SELECT qry.REC_NUM
                    FROM (
                        SELECT rel.*, ROWNUM AS REC_NUM
                          FROM (

                                SELECT rt.RTAG_ID,
                                    rt.DISPLAY_ORDER,
                                     DECODE( rt.PARENT_RTAG_ID,
                                             rt.RTAG_ID, 0, rt.PARENT_RTAG_ID ) AS PARENT_RTAG_ID
                                FROM RELEASE_TAGS rt
                               WHERE rt.PROJ_ID = nProjId

                                ) rel
                        START WITH rel.PARENT_RTAG_ID = 0
                        CONNECT BY PRIOR rel.RTAG_ID = rel.PARENT_RTAG_ID
                        ORDER SIBLINGS BY rel.DISPLAY_ORDER
                        ) qry
                     WHERE qry.RTAG_ID = urt.RTAG_ID
                  )
   WHERE urt.PROJ_ID = nProjId;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE MOVE_RELEASE ( sRtagIdList IN VARCHAR2, nProjId IN NUMBER, nUserId IN NUMBER  ) IS

   nIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
   SeqNum NUMBER;

BEGIN


   /*--------------- Business Rules Here -------------------*/
   /*-------------------------------------------------------*/

   nIdCollector := IN_LIST_NUMBER ( sRtagIdList );

   -- Set start sequence number
   SeqNum := 1;

   FOR i IN 1..nIdCollector.COUNT
   LOOP

      -- Update new display order
      UPDATE RELEASE_TAGS rt SET
         rt.DISPLAY_ORDER = SeqNum
       WHERE rt.PROJ_ID = nProjId
         AND rt.RTAG_ID = nIdCollector(i);

      SeqNum := SeqNum + 1;

   END LOOP;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Update_Release ( nRtagId IN NUMBER, sReleaseName IN VARCHAR2, sReleaseComments IN VARCHAR2, nParentRtagId IN NUMBER, nMASSRtagId IN NUMBER, nConfigSpecBranch IN VARCHAR2, sOwnerEmail IN VARCHAR2, nUserId IN NUMBER, cState IN VARCHAR ) IS

RecCount NUMBER := 0;
ProjId NUMBER;

BEGIN


   /*--------------- Business Rules Here -------------------*/
   -- Check for missing parameters
   IF (sReleaseName IS NULL) OR (nUserId IS NULL) OR (nRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! sReleaseName= '|| sReleaseName ||', nUserId='|| nUserId ||', nRtagId='|| nRtagId);

   END IF;


   -- Check for duplicate Release Names
   SELECT rt.PROJ_ID INTO ProjId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nRtagId;

   SELECT COUNT(rt.RTAG_ID) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE UPPER( rt.RTAG_NAME ) = UPPER( sReleaseName )
      AND rt.RTAG_ID != nRtagId
      AND rt.PROJ_ID = ProjId;


   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Release Name '|| sReleaseName ||' is Already Used in this Project.');
   END IF;
   /*-------------------------------------------------------*/



   -- Update release details
   UPDATE RELEASE_TAGS rt SET
   rt.RTAG_NAME = sReleaseName,
   rt.DESCRIPTION = sReleaseComments,
   rt.PARENT_RTAG_ID = nParentRtagId,
   rt.ASSOC_MASS_REF = nMASSRtagId,
   rt.CONFIG_SPEC_BRANCH = nConfigSpecBranch,
   rt.OWNER_EMAIL = sOwnerEmail,
   rt.PRODUCT_STATE_USED = cState
   WHERE rt.RTAG_ID = nRtagId;

   -- Update display Order
   UPDATE_DISPLAY_ORDER ( ProjId );

   /* Log Project Action */
   Log_Project_Action ( ProjId, 'update_release', nUserId, 'Release Name: <br>Release Comments:', nRtagId );




END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Destroy_Release ( nRtagId IN NUMBER, nUserId IN NUMBER ) IS

   RecCount NUMBER := 0;
   sReleaseId VARCHAR2(4000);
   ProjId NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nRtagId= '|| nRtagId  );
   END IF;



   -- Check for any kids
   SELECT COUNT( rt.RTAG_ID ) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE rt.PARENT_RTAG_ID = nRtagId
      AND rt.RTAG_ID != rt.PARENT_RTAG_ID;

   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Cannot destroy this release. You need to destroy its children releases first.'  );
   END IF;
   /*-------------------------------------------------------*/

   -- Clear the release contents
   Clean_Release_Contents ( nRtagId, nUserId );

   /* Log Project Action */
   SELECT rt.PROJ_ID, rt.RTAG_NAME ||'['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']' INTO ProjId, sReleaseId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nRtagId;

   Log_Project_Action ( ProjId, 'destroy_release', nUserId, sReleaseId, nRtagId );


   -- Remove Release
   DELETE
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nRtagId;



END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Import_Release_Contents ( nSourceRtagId IN NUMBER, nTargetRtagId IN NUMBER, nUserId IN NUMBER  ) IS

   sSourceLocation VARCHAR2(4000);
   sTargetLocation VARCHAR2(4000);
   ProjId NUMBER;
   cReleaseMode CHAR(1);
   RconId NUMBER;

   -- this cursor gets the source release daemon configurations, ensuring that the
   -- first record will be the master daemon, and subsequent records will be the slaves.
   CURSOR curSrcReleaseConfigs IS
    SELECT daemon_hostname, gbe_id, gbe_buildfilter
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nSourceRtagId
    ORDER BY rc.daemon_mode;
    recSrcReleaseConfigs curSrcReleaseConfigs%ROWTYPE;

    -- this cursor looks for target release daemons
   CURSOR curTgtReleaseConfigs IS
    SELECT rcon_id
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nTargetRtagId;
    recTgtReleaseConfigs curTgtReleaseConfigs%ROWTYPE;

    -- this cursor looks for target release daemon run level entries
   CURSOR curTgtReleaseConfigRunLevel IS
    SELECT current_run_level
     FROM RUN_LEVEL rl
    WHERE rl.RCON_ID = recTgtReleaseConfigs.rcon_id;
    recTgtReleaseConfigRunLevel curTgtReleaseConfigRunLevel%ROWTYPE;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nSourceRtagId IS NULL) OR (nTargetRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nSourceRtagId= '|| nSourceRtagId ||', nTargetRtagId='|| nTargetRtagId );
   END IF;

   IF (nSourceRtagId = nTargetRtagId) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Cannot import release contents from same release.' );
   END IF;


   -- Check if Target release is in OPEN mode
   SELECT rt.OFFICIAL  INTO  cReleaseMode
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nTargetRtagId;

   IF (cReleaseMode != 'N') THEN
      RAISE_APPLICATION_ERROR (-20000, 'Release must be in OPEN mode to import the contents.' );
   END IF;

   -- check that the target release's daemons are all paused before we allow an import operation
   OPEN curTgtReleaseConfigs;
   FETCH curtgtReleaseConfigs INTO recTgtReleaseConfigs;

   WHILE curTgtReleaseConfigs%FOUND
   LOOP
      OPEN curTgtReleaseConfigRunLevel;
      FETCH curTgtReleaseConfigRunLevel INTO recTgtReleaseConfigRunLevel;
      IF curTgtReleaseConfigRunLevel%FOUND THEN
         IF (recTgtReleaseConfigRunLevel.current_run_level IS NULL) OR
            (recTgtReleaseConfigRunLevel.current_run_level <> 2) THEN
            RAISE_APPLICATION_ERROR (-20000, 'Destination release daemon run levels must be paused before operation can proceed.' );
         END IF;
      ELSE
         -- we don't know what the daemon run level is so err on the side of caution
         RAISE_APPLICATION_ERROR (-20000, 'Destination release daemon run levels must be paused before operation can proceed.' );
      END IF;
      CLOSE curTgtReleaseConfigRunLevel;

      FETCH curTgtReleaseConfigs INTO recTgtReleaseConfigs;
   END LOOP;

   CLOSE curTgtReleaseConfigs;


   /*-------------------------------------------------------*/

   -- Clean target contents
   Clean_Release_Contents ( nTargetRtagId, nUserId );


   -- Import Released Area Contents
   INSERT INTO RELEASE_CONTENT ( RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE, PKG_ID, DEPRECATED_STATE )
   SELECT nTargetRtagId AS RTAG_ID,
         rc.PV_ID,
         rc.BASE_VIEW_ID,
         rc.INSERT_STAMP,
         rc.INSERTOR_ID,
         rc.PKG_STATE,
         rc.PKG_ID,
         rc.DEPRECATED_STATE
     FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nSourceRtagId;


   -- Import any Pegged Version settings from the source release
   INSERT INTO PEGGED_VERSIONS ( RTAG_ID, PV_ID )
   SELECT nTargetRtagId AS RTAG_ID,
          pegv.PV_ID
     FROM PEGGED_VERSIONS pegv
    WHERE pegv.RTAG_ID = nSourceRtagId;

   -- Import any Advisory Ripple settings from the source release
   INSERT INTO ADVISORY_RIPPLE ( RTAG_ID, PV_ID )
   SELECT nTargetRtagId AS RTAG_ID,
          avr.PV_ID
     FROM ADVISORY_RIPPLE avr
    WHERE avr.RTAG_ID = nSourceRtagId;


   --Import Release Configuration Information
   OPEN curSrcReleaseConfigs;
   FETCH curSrcReleaseConfigs INTO recSrcReleaseConfigs;

   WHILE curSrcReleaseConfigs%FOUND
   LOOP
      -- add a daemon to the target release
      PK_BUILDAPI.add_daemon( recSrcReleaseConfigs.daemon_hostname, nTargetRtagId, recSrcReleaseConfigs.gbe_id, recSrcReleaseConfigs.gbe_buildfilter );

      FETCH curSrcReleaseConfigs INTO recSrcReleaseConfigs;
   END LOOP;

   CLOSE curSrcReleaseConfigs;



   -- Import Ignore Warning states
   INSERT INTO IGNORE_WARNINGS ( RTAG_ID, PV_ID, DPV_ID )
   SELECT nTargetRtagId AS RTAG_ID,
          igw.PV_ID,
          igw.DPV_ID
     FROM IGNORE_WARNINGS igw
    WHERE igw.rtag_id = nSourceRtagId;


   /* Log Project Action */
   -- Get Source Location
   SELECT pr.PROJ_NAME ||' > '|| rt.RTAG_NAME ||' ['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']'  INTO sSourceLocation
     FROM RELEASE_TAGS rt,
           PROJECTS pr
    WHERE rt.PROJ_ID = pr.PROJ_ID
      AND rt.RTAG_ID = nSourceRtagId;

   -- Get Target Location
   SELECT pr.PROJ_NAME ||' > '|| rt.RTAG_NAME ||' ['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']'  INTO sTargetLocation
     FROM RELEASE_TAGS rt,
           PROJECTS pr
    WHERE rt.PROJ_ID = pr.PROJ_ID
      AND rt.RTAG_ID = nTargetRtagId;

   -- Get project id
   SELECT rt.PROJ_ID  INTO  ProjId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nTargetRtagId;

   Log_Project_Action ( ProjId, 'import_release_contents', nUserId, 'SOURCE: '|| sSourceLocation ||'   TARGET: '|| sTargetLocation, nTargetRtagId );
END;



/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Clean_Release_Contents ( nRtagId IN NUMBER, nUserId IN NUMBER ) IS

   RecCount NUMBER;
        rconIdList VARCHAR2(4000);

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nRtagId= '|| nRtagId  );
   END IF;


   -- Check if other release references this release
   SELECT COUNT( rl.RTAG_ID ) INTO RecCount
     FROM RELEASE_LINKS rl
    WHERE rl.REF_RTAG_ID = nRtagId;

   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'This release is referenced by other release and cannot be destroyed.'  );
   END IF;
   /*-------------------------------------------------------*/

   -- Delete Release links
   DELETE
     FROM RELEASE_LINKS rl
    WHERE rl.RTAG_ID = nRtagId;

   -- Delete ignore warning
   DELETE
     FROM IGNORE_WARNINGS iw
    WHERE iw.RTAG_ID = nRtagId;


   -- Delete Build Order cached calculations
   DELETE
     FROM BUILD_ORDER bo
    WHERE bo.RTAG_ID = nRtagId;


   -- Delete Notification History
   DELETE
     FROM NOTIFICATION_HISTORY nh
    WHERE nh.RTAG_ID = nRtagId;


   -- Delete Released Area Contents
   DELETE
     FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nRtagId;


   -- Delete Work In Progress Area Contents
   DELETE
     FROM WORK_IN_PROGRESS wip
    WHERE wip.RTAG_ID = nRtagId;


   -- Delete Pending Area Contents
   DELETE
     FROM PLANNED pl
    WHERE pl.RTAG_ID = nRtagId;

   -- Delete Deprecated Packages
   DELETE
     FROM DEPRECATED_PACKAGES dp
    WHERE dp.RTAG_ID = nRtagId;

   -- Delete Project Action Log
   DELETE
     FROM PROJECT_ACTION_LOG pal
    WHERE pal.RTAG_ID = nRtagId;

   -- Delete Do Not Ripple Contents
   DELETE
     FROM DO_NOT_RIPPLE dnr
    WHERE dnr.RTAG_ID = nRtagId;

   -- Delete Dash Board Contents
   DELETE
     FROM DASH_BOARD db
    WHERE db.RTAG_ID = nRtagId;

   -- Delete Advisory Ripple Contents
   DELETE
     FROM ADVISORY_RIPPLE adr
    WHERE adr.RTAG_ID = nRtagId;

   -- Delete Archive Action Log
   DELETE
     FROM ARCHIVE_ACTION_LOG aal
    WHERE aal.RTAG_ID = nRtagId;

   -- Delete Daemons For This Release
   FOR rcon IN (SELECT rc.RCON_ID FROM RELEASE_CONFIG rc WHERE rc.RTAG_ID = nRtagId )
   LOOP
      rconIdList := rconIdList || rcon.RCON_ID || ',';
   END LOOP;

   pk_buildapi.DELETE_DAEMON(rconIdList);

   -- Delete Release Metrics Contents
   DELETE
     FROM RELEASE_METRICS rm
    WHERE rm.RTAG_ID = nRtagId;

   -- Delete Release Configuration Contents
   DELETE
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nRtagId;

   -- Delete Pegged Version Contents
   DELETE
     FROM PEGGED_VERSIONS pegv
    WHERE pegv.RTAG_ID = nRtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PARENT_RTAG ( nRtagId IN NUMBER, nSourceRtagId IN NUMBER, cIsBranch IN CHAR )  RETURN NUMBER IS

   nSourceParentRtagId NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId IS NULL) OR (cIsBranch IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nRtagId= '|| nRtagId ||', cIsBranch= '|| cIsBranch );
   END IF;
   /*-------------------------------------------------------*/


   IF ( nSourceRtagId IS NULL ) THEN
      -- Create new on main branch
      RETURN nRtagId;

   ELSE
      -- Create from source rtag_id

      -- Find parent of Source RtagId
      SELECT rt.PARENT_RTAG_ID INTO nSourceParentRtagId
        FROM RELEASE_TAGS rt
       WHERE rt.RTAG_ID = nSourceRtagId;

      IF (UPPER(cIsBranch) = 'Y') THEN
         RETURN nSourceRtagId;
      ELSE
         IF (nSourceRtagId = nSourceParentRtagId) THEN
            RETURN nRtagId;
         ELSE
            RETURN nSourceParentRtagId;
         END IF;
      END IF;


   END IF;


END;
/*-------------------------------------------------------------------------------------------------------*/

-- PROCEDURE Get_Next_Version ( nSourceRtagId IN NUMBER,
--                       sNextVersion OUT VARCHAR2,
--                       nNextLifeCycle OUT NUMBER,
--                       nParentRtagId OUT NUMBER,
--                       nProjId IN NUMBER ) IS
--
-- SourceBranchCount NUMBER;
-- ProjRootVersion VARCHAR2(4000);
-- LastLifeCycle NUMBER;
-- ROOT_VERSION_NOT_FOUND NUMBER := -1;
-- SET_PARENT_AS_YOURSELF NUMBER := -1;
--
-- SourceProjId NUMBER;
-- SourceVersion RELEASE_TAGS.RTAG_VERSION%TYPE;
-- SourceLifeCycle RELEASE_TAGS.RTAG_LIFE_CYCLE%TYPE;
--
-- BEGIN
--    /*--------------- Business Rules Here -------------------*/
--    /*-------------------------------------------------------*/
--
--
--    BEGIN
--       -- Get Project root version
--       SELECT rt.RTAG_VERSION INTO ProjRootVersion
--         FROM RELEASE_TAGS rt
--        WHERE rt.PROJ_ID = nProjId
--          AND rt.RTAG_ID = rt.PARENT_RTAG_ID;
--
--       EXCEPTION
--       WHEN NO_DATA_FOUND THEN
--       ProjRootVersion := ROOT_VERSION_NOT_FOUND;
--    END;
--
--
--
--
--    BEGIN
--       -- Get info for source rtagid
--       SELECT rt.PROJ_ID, rt.RTAG_VERSION, rt.RTAG_LIFE_CYCLE  INTO  SourceProjId, SourceVersion, SourceLifeCycle
--         FROM RELEASE_TAGS rt
--        WHERE rt.RTAG_ID = nSourceRtagId;
--
--       EXCEPTION
--       WHEN NO_DATA_FOUND THEN
--       SourceProjId := NULL;
--       SourceVersion := NULL;
--       SourceLifeCycle := NULL;
--    END;
--
--
--    IF (nSourceRtagId IS NULL)  OR  ( SourceProjId != nProjId ) THEN
--
--       /* Blank Release Required  OR  Release imported from other project */
--
--       IF (ProjRootVersion = ROOT_VERSION_NOT_FOUND) THEN
--          /* No Releases found in the project, hence calculate next version available.  */
--
--          -- Set parent rtag
--          nParentRtagId := SET_PARENT_AS_YOURSELF;
--
--
--          BEGIN
--             -- Get Next Available Global Root Version
--             SELECT MAX( TO_NUMBER( rt.RTAG_VERSION ) )  INTO  ProjRootVersion
--               FROM RELEASE_TAGS rt
--              WHERE rt.RTAG_ID = rt.PARENT_RTAG_ID;
--
--             -- Set Next Rtag Version
--             sNextVersion := CAST( ProjRootVersion + 1 AS VARCHAR2 );
--
--             -- Restart Lifecycle
--             nNextLifeCycle := 0;
--
--
--             EXCEPTION
--             WHEN NO_DATA_FOUND THEN
--             -- Release Manager has no releases, hence start from 1
--             sNextVersion := '1';
--             nNextLifeCycle := 0;
--
--          END;
--
--
--
--       ELSE
--          /* Releases found in this project. */
--
--          SELECT qry.RTAG_ID, qry.RTAG_LIFE_CYCLE  INTO nParentRtagId, LastLifeCycle
--            FROM (
--                SELECT rt.RTAG_ID, rt.RTAG_LIFE_CYCLE
--                  FROM RELEASE_TAGS rt
--                 WHERE rt.PROJ_ID = nProjId
--                   AND rt.RTAG_VERSION = ProjRootVersion
--                 ORDER BY rt.RTAG_LIFE_CYCLE DESC
--                  ) qry
--           WHERE ROWNUM = 1;
--
--
--          -- Set same Rtag Version
--          sNextVersion := ProjRootVersion;
--
--          -- Increase Lifecycle
--          nNextLifeCycle := LastLifeCycle + 1;
--
--       END IF;
--
--
--
--    ELSE
--       /* Create Release From other release within this project */
--
--       -- Set parent id
--       nParentRtagId := nSourceRtagId;
--
--
--       -- Get number of source branches
--       SELECT COUNT(rt.RTAG_ID) INTO SourceBranchCount
--         FROM RELEASE_TAGS rt
--        WHERE rt.PROJ_ID = nProjId
--          AND rt.PARENT_RTAG_ID = nSourceRtagId;
--
--
--       IF SourceBranchCount = 0 THEN
--          /* Release is Head (i.e. Tip on its branch ) */
--
--          -- Set Next Rtag Version
--          sNextVersion := SourceVersion;
--
--          -- Increase Lifecycle
--          nNextLifeCycle := SourceLifeCycle + 1;
--
--
--       ELSIF SourceBranchCount = 1 THEN
--          /* Release IS NOT Head, but can be branched */
--
--          -- Set Next Rtag Version
--          sNextVersion := SourceVersion ||'.'|| SourceLifeCycle;
--
--          -- Reset Lifecycle to 1
--          nNextLifeCycle := 1;
--
--
--       ELSE
--          -- Limit of two branches is reached
--          RAISE_APPLICATION_ERROR (-20000, 'This release is already branched and cannot be branched again. ');
--
--       END IF;
--
--
--
--
--
--
--    END IF;
--
--
-- END;

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur ) IS

   IsBaseView CHAR(1);

BEGIN

   -- Check if the view is BASE VIEW
   SELECT vi.BASE_VIEW INTO IsBaseView
     FROM VIEWS vi
    WHERE vi.VIEW_ID = ViewId;

   IF (IsBaseView = 'Y') THEN
      -- Get Base view content
      OPEN RecordSet FOR
      SELECT DECODE ( rel.pkg_state, NULL, 0, rel.pkg_state ) AS PKG_STATE,
            rel.deprecated_state,
            pv.pv_id,
            pkg.pkg_name,
            pv.pkg_version,
            pv.dlocked,
            pv.pv_description,
            pv.BUILD_TYPE
        FROM release_content rel,
             packages pkg,
             package_versions pv
       WHERE pv.pkg_id = pkg.pkg_id
         AND rel.pv_id = pv.pv_id
         AND rel.BASE_VIEW_ID = ViewId
         AND rel.RTAG_ID = RtagId
       ORDER BY UPPER(pkg.PKG_NAME);

   ELSE

       -- Get non base view content
      OPEN RecordSet FOR
      SELECT DECODE ( rel.pkg_state, NULL, 0, rel.pkg_state ) AS PKG_STATE,
            rel.deprecated_state,
            pv.pv_id,
            pkg.pkg_name,
            pv.pkg_version,
            pv.dlocked,
            pv.pv_description,
            pv.BUILD_TYPE
        FROM release_content rel,
             packages pkg,
             package_versions pv,
            VIEW_DEF vd
       WHERE pv.pkg_id = pkg.pkg_id
         AND rel.pv_id = pv.pv_id
         AND vd.VIEW_ID = ViewId
         AND vd.PKG_ID = pv.PKG_ID
         AND rel.RTAG_ID = RtagId
       ORDER BY UPPER(pkg.PKG_NAME);

   END IF;




END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

   ReleaseLocation VARCHAR2(4000);
   sPkgVersion VARCHAR2(4000);
   nPkgId NUMBER;
   sVExt VARCHAR2(4000);
   IsPatch PACKAGE_VERSIONS.IS_PATCH%TYPE := 'N';

   -- Find package for replacement
   CURSOR curReplacePkg IS
    SELECT pv.PV_ID
     FROM RELEASE_CONTENT rc,
           PACKAGE_VERSIONS pv
    WHERE rc.PV_ID = pv.PV_ID
      AND rc.RTAG_ID = RtagId
      AND pv.PKG_ID = nPkgId
      AND NVL( pv.V_EXT, 'LINK_A_NULL' ) = NVL( sVExt, 'LINK_A_NULL' );
    recReplacePkg curReplacePkg%ROWTYPE;

BEGIN

   -- Get is_patch, pkg_id and v_ext
   SELECT pv.IS_PATCH, pv.PKG_ID, pv.V_EXT INTO IsPatch, nPkgId, sVExt
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = newPvId;


   -- Never put patch in relesed area
   IF (IsPatch != 'Y') OR (IsPatch IS NULL) THEN

      -- Try to get a package to be replaced with this new one.
      -- Use unique constraint of PKG_ID and V_EXT
      OPEN curReplacePkg;
       FETCH curReplacePkg INTO recReplacePkg;

       IF curReplacePkg%FOUND THEN
         -- Replace package
         REPLACE_PACKAGE ( newPvId, recReplacePkg.PV_ID, RtagId, UserId );

      ELSE
         -- Add new package
         INSERT INTO RELEASE_CONTENT ( RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE )
         VALUES( RtagId, newPvId, ViewId, Ora_Sysdate, UserId, 0);


          /* LOG ACTION */
         SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
           FROM PROJECTS proj,
                 RELEASE_TAGS rt
          WHERE rt.PROJ_ID = proj.PROJ_ID
            AND rt.RTAG_ID = RtagId;

         SELECT pv.PKG_VERSION INTO sPkgVersion
           FROM PACKAGE_VERSIONS pv
          WHERE pv.PV_ID = newPvId;

         Log_Action ( newPvId, 'add', UserId, 'Location: '|| ReleaseLocation );


      END IF;

      CLOSE curReplacePkg;

   END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REPLACE_PACKAGE ( newPvId IN NUMBER, oldPvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

   ReleaseLocation VARCHAR2(4000);
   sPkgVersion VARCHAR2(4000);

BEGIN

   -- Replace Package
    UPDATE RELEASE_CONTENT
       SET pv_id = newPvId,
           insert_stamp = Ora_Sysdate,
           insertor_id = UserId,
         product_state = NULL
     WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

   -- update the pegging table
   UPDATE PEGGED_VERSIONS
      SET pv_id = newPvId
     WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

   -- update the advisory_ripple table
   UPDATE ADVISORY_RIPPLE
      SET pv_id = newPvId
     WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

    /* LOG ACTION */
   SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
     FROM PROJECTS proj,
           RELEASE_TAGS rt
    WHERE rt.PROJ_ID = proj.PROJ_ID
      AND rt.RTAG_ID = RtagId;

   SELECT pv.PKG_VERSION INTO sPkgVersion
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = newPvId;

   Log_Action ( oldPvId, 'replaced_with', UserId, 'Replacing with: '|| sPkgVersion ||' at '|| ReleaseLocation );
   Log_Action ( newPvId, 'add', UserId, 'Location: '|| ReleaseLocation );

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS
   ReleaseLocation VARCHAR2(4000);

BEGIN


   -- Delete old package
   DELETE
     FROM RELEASE_CONTENT rc
    WHERE rc.PV_ID = PvId
      AND rc.RTAG_ID = RtagId;


   /* LOG ACTION */
   SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
     FROM PROJECTS proj,
          RELEASE_TAGS rt
    WHERE rt.PROJ_ID = proj.PROJ_ID
      AND rt.RTAG_ID = RtagId;

   Log_Action ( PvId, 'delete_from_released', UserId, 'Location: '|| ReleaseLocation );


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_MATCHING_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS
   ReleaseLocation VARCHAR2(4000);

   CURSOR curMatchingPackage IS
    SELECT mpv.PV_ID
     FROM RELEASE_CONTENT rc,
           PACKAGE_VERSIONS mpv,
         PACKAGE_VERSIONS pv
    WHERE rc.PV_ID = mpv.PV_ID
      AND rc.RTAG_ID = RtagId
      AND pv.PV_ID = PvId
      AND pv.PKG_ID = mpv.PKG_ID
      AND NVL( pv.V_EXT, '|LINK_A_NULL|' ) = NVL( mpv.V_EXT, '|LINK_A_NULL|' );
    recMatchingPackage curMatchingPackage%ROWTYPE;

BEGIN

   OPEN curMatchingPackage;
    FETCH curMatchingPackage INTO recMatchingPackage;

    IF curMatchingPackage%FOUND THEN
      -- Delete old package
      DELETE
        FROM RELEASE_CONTENT rc
       WHERE rc.PV_ID = recMatchingPackage.PV_ID
         AND rc.RTAG_ID = RtagId;


      /* LOG ACTION */
      SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
        FROM PROJECTS proj,
              RELEASE_TAGS rt
       WHERE rt.PROJ_ID = proj.PROJ_ID
         AND rt.RTAG_ID = RtagId;

      Log_Action ( recMatchingPackage.PV_ID, 'delete_from_released', UserId, 'Location: '|| ReleaseLocation );

   END IF;


   CLOSE curMatchingPackage;




END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER IS

   ReturnValue NUMBER;

BEGIN
   SELECT rc.BASE_VIEW_ID INTO ReturnValue
     FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = RtagId
      AND rc.PV_ID = PvId;

   RETURN ReturnValue;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE RUN_POST_ACTIONS ( PvId IN NUMBER, RtagId IN NUMBER ) IS

BEGIN
   -- Reset Ignore warnings up-the-tree
   RESET_IGNORE_WARNINGS ( TO_CHAR(PvId), RtagId );

   -- Refresh Package states
   TOUCH_RELEASE ( RtagId );

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE RUN_POST_ACTIONS_BULK ( PvId IN NUMBER ) IS
   CURSOR curReleases IS
    SELECT rc.RTAG_ID
     FROM RELEASE_CONTENT rc
    WHERE rc.PV_ID = PvId;
    recReleases curReleases%ROWTYPE;

BEGIN

   OPEN curReleases;
    FETCH curReleases INTO recReleases;

   WHILE curReleases%FOUND
   LOOP

      RUN_POST_ACTIONS ( PvId, recReleases.RTAG_ID );

      FETCH curReleases INTO recReleases;
   END LOOP;

   CLOSE curReleases;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER ) IS

BEGIN

   UPDATE RELEASE_CONTENT rc SET
   rc.BASE_VIEW_ID = NewViewId
   WHERE rc.PV_ID = PvId
     AND rc.RTAG_ID = RtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER, ProblemString OUT VARCHAR2 ) IS

   RowCount NUMBER;


   CURSOR curPackageClash IS
   SELECT pkg.PKG_NAME,
         er.*
     FROM (

           /* Get existing referenced packages */
         SELECT pv.PKG_ID,
                pv.V_EXT
           FROM RELEASE_LINKS rl,
                 RELEASE_CONTENT rc,
                 PACKAGE_VERSIONS pv
          WHERE rl.RTAG_ID = nRtagId
            AND rl.REF_RTAG_ID = rc.RTAG_ID
            AND rc.PV_ID = pv.PV_ID

            ) er,
         (

         /* Get current reference packages */
         SELECT pv.PKG_ID,
                pv.V_EXT
           FROM RELEASE_CONTENT rc,
                 PACKAGE_VERSIONS pv
          WHERE rc.RTAG_ID = nRefRtagId
            AND rc.PV_ID = pv.PV_ID

         ) cr,
         PACKAGES PKG
    WHERE er.PKG_ID = cr.PKG_ID
      AND NVL(er.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
      AND er.PKG_ID = pkg.PKG_ID;

   recPackageClash curPackageClash%ROWTYPE;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nRefRtagId = 0) OR ( nRefRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRefRtagId is not supplied. [nRefRtagId='|| nRefRtagId ||']' );
   END IF;
   /*-------------------------------------------------------*/
   ProblemString := NULL;


   -- Check if release already has references
   SELECT COUNT(rl.RTAG_ID)  INTO  RowCount
     FROM RELEASE_LINKS rl
    WHERE rl.RTAG_ID = nRtagId;


   IF RowCount > 0 THEN
      -- Found existing references

      -- Make sure there is no package clashes
      OPEN curPackageClash;
       FETCH curPackageClash INTO recPackageClash;

      IF curPackageClash%FOUND THEN

         ProblemString := ProblemString ||'Following is partial list of package already referenced from other release:'|| UTL_TCP.CRLF;

         WHILE curPackageClash%FOUND
         LOOP
            EXIT WHEN LENGTH( ProblemString || '- '|| recPackageClash.PKG_NAME ||' '|| recPackageClash.V_EXT  || UTL_TCP.CRLF ) > 200;   -- Do not allow variable overflow

            ProblemString := ProblemString || '- '|| recPackageClash.PKG_NAME ||' '|| recPackageClash.V_EXT  || UTL_TCP.CRLF;

            FETCH curPackageClash INTO recPackageClash;
         END LOOP;

      END IF;

      CLOSE curPackageClash;


   ELSE
      -- No references found, hence reference a release


      -- Remove exising package from this release to be referenced
      REMOVE_RELEASE_REFERENCE ( nRtagId, nRefRtagId);


      -- Add new linked packages to release
      INSERT INTO RELEASE_CONTENT rc (RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE)
      SELECT nRtagId,
            rc.PV_ID,
            rc.BASE_VIEW_ID,
            rc.INSERT_STAMP,
            rc.INSERTOR_ID,
            rc.PKG_STATE
        FROM RELEASE_CONTENT rc
       WHERE rc.RTAG_ID = nRefRtagId;



      -- Copy ignore warnings for referenced packages
      INSERT INTO IGNORE_WARNINGS iw (RTAG_ID, PV_ID, DPV_ID, IS_PATCH_IGNORE)
      SELECT nRtagId,
            iw.PV_ID,
            iw.DPV_ID,
            iw.IS_PATCH_IGNORE
        FROM IGNORE_WARNINGS iw,
              RELEASE_CONTENT rc
       WHERE iw.RTAG_ID = rc.RTAG_ID
         AND iw.PV_ID = rc.PV_ID
         AND rc.RTAG_ID = nRefRtagId;



      -- Reference release
      INSERT INTO RELEASE_LINKS (RTAG_ID, REF_RTAG_ID)
      VALUES ( nRtagId, nRefRtagId );


      -- Refresh Package states
      TOUCH_RELEASE ( nRtagId );

   END IF;


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER ) IS


BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nRefRtagId = 0) OR ( nRefRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRefRtagId is not supplied. [nRefRtagId='|| nRefRtagId ||']' );
   END IF;

   /*-------------------------------------------------------*/


   -- Remove ignore warnings for those packages who use referenced packages
   DELETE FROM IGNORE_WARNINGS iw
    WHERE iw.RTAG_ID = nRtagId
      AND iw.DPV_ID IN (
                        SELECT dep.DPV_ID
                       FROM (

                           /* Get referenced packages */
                           SELECT pv.PKG_ID,
                                  pv.V_EXT
                             FROM RELEASE_CONTENT rc,
                                   PACKAGE_VERSIONS pv
                            WHERE rc.RTAG_ID = nRefRtagId
                              AND rc.PV_ID = pv.PV_ID

                           ) cr,
                           (

                           /* Get all dependencies for current release */
                           SELECT DISTINCT
                                 pv.PKG_ID,
                                 pv.V_EXT,
                                 dep.DPV_ID
                             FROM RELEASE_CONTENT rc,
                                 PACKAGE_DEPENDENCIES dep,
                                 PACKAGE_VERSIONS pv
                            WHERE rc.RTAG_ID = nRtagId
                              AND rc.PV_ID = dep.PV_ID
                              AND dep.PV_ID = pv.PV_ID

                           ) dep
                      WHERE dep.PKG_ID = cr.PKG_ID
                        AND NVL(dep.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
                     );




   -- Remove ignore warnings for those package which are going to be replaced with the reference
   DELETE FROM IGNORE_WARNINGS iw
    WHERE iw.RTAG_ID = nRtagId
      AND iw.PV_ID IN (
                  SELECT pv.PV_ID
                    FROM (

                        /* Get referenced packages */
                        SELECT pv.PKG_ID,
                               pv.V_EXT
                          FROM RELEASE_CONTENT rc,
                                PACKAGE_VERSIONS pv
                         WHERE rc.RTAG_ID = nRefRtagId
                           AND rc.PV_ID = pv.PV_ID

                        ) cr,
                        RELEASE_CONTENT rc,
                        PACKAGE_VERSIONS pv
                   WHERE pv.PKG_ID = cr.PKG_ID
                     AND NVL(pv.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
                     AND rc.RTAG_ID = nRtagId
                     AND rc.PV_ID = pv.PV_ID
                  );





   -- Remove matching packages from release
   DELETE FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nRtagId
      AND rc.PV_ID IN (
                  SELECT pv.PV_ID
                    FROM (

                        /* Get referenced packages */
                        SELECT pv.PKG_ID,
                               pv.V_EXT
                          FROM RELEASE_CONTENT rc,
                                PACKAGE_VERSIONS pv
                         WHERE rc.RTAG_ID = nRefRtagId
                           AND rc.PV_ID = pv.PV_ID

                        ) cr,
                        RELEASE_CONTENT rc,
                        PACKAGE_VERSIONS pv
                   WHERE pv.PKG_ID = cr.PKG_ID
                     AND NVL(pv.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
                     AND rc.RTAG_ID = nRtagId
                     AND rc.PV_ID = pv.PV_ID
                  );





   -- Remove Reference release
   DELETE
     FROM RELEASE_LINKS rl
    WHERE rl.RTAG_ID = nRtagId
      AND rl.REF_RTAG_ID = nRefRtagId;


   -- Refresh Package states
   TOUCH_RELEASE ( nRtagId );


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CAN_USER_WRITE_TO_RELEASE ( RtagId IN NUMBER, PvId IN NUMBER, Permission IN CHAR ) IS

   cReleaseMode CHAR(1);
   cPvMode CHAR(1);

BEGIN

   -- Get Release Mode
   SELECT rt.OFFICIAL INTO cReleaseMode
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = RtagId;


   -- Get Package Mode
   SELECT pv.DLOCKED INTO cPvMode
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = PvId;

   -- Only check if package is locked
   IF (cPvMode = 'Y') THEN

      IF (cReleaseMode != 'N') AND (Permission != 'Y')
      THEN
         RAISE_APPLICATION_ERROR (-20000, 'Cannot add package to this release. Release needs to be in Open Mode.' );

      END IF;

   END IF;


END;

/*-------------------------------------------------------------------------------------------------------*/
END PK_RELEASE;
/
--------------------------------------------------------
--  DDL for Package Body PK_RMAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_RMAPI" 
IS

   /*-------------------------------------------------------------------------------------------------------*/
   FUNCTION package_dependencies (pkgname VARCHAR2, pkgversion VARCHAR2)
      RETURN typecur
   IS
      npvid     NUMBER  := 0;
      RECORDS   typecur;
   BEGIN
      BEGIN
         -- Get PV_ID --
         SELECT pv.pv_id
           INTO npvid
           FROM PACKAGES pkg, package_versions pv
          WHERE pv.pkg_id = pkg.pkg_id
            AND pkg.pkg_name = pkgname
            AND pv.pkg_version = pkgversion;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000, 'Package Not Found!');
            --WHEN OTHERS THEN
                  -- Consider logging the error and then re-raise
            RAISE;
      END;

      -- Finally get package dependencies --
      OPEN RECORDS FOR
         SELECT dpv.pv_id, dpkg.pkg_name, dpv.pkg_version
           FROM package_dependencies dep, PACKAGES dpkg, package_versions dpv
          WHERE dep.pv_id = npvid
            AND dpv.pkg_id = dpkg.pkg_id
            AND dpv.pv_id = dep.dpv_id;

      RETURN RECORDS;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION wip_iteration_package (
      projname        VARCHAR2,
      iterationname   VARCHAR2,
      pkgname         VARCHAR2
   )
      RETURN typecur
   IS
      nrtagid   NUMBER  := 0;
      RECORDS   typecur;
   BEGIN
      BEGIN
         -- Get latest rtag_id --
         SELECT rt.rtag_id
           INTO nrtagid
           FROM projects proj, release_tags rt
          WHERE rt.proj_id = proj.proj_id
            AND UPPER (proj.proj_name) = UPPER (projname)
            AND UPPER (rt.rtag_name) = UPPER (iterationname);

         IF (nrtagid IS NULL)
         THEN
            raise_application_error (-20000,
                                     'Work In Progress is Not Found!');
         END IF;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000,
                                     'Work In Progress is Not Found!');
            RAISE;
      END;

      -- Finally get package dependencies --
      OPEN RECORDS FOR
         SELECT pv.pkg_version, pv.dlocked AS is_official, pv.pkg_label,
                pv.src_path
           FROM PACKAGES pkg, package_versions pv, work_in_progress wip
          WHERE pv.pkg_id = pkg.pkg_id
            AND wip.pv_id = pv.pv_id
            AND wip.rtag_id = nrtagid
            AND pkg.pkg_name = pkgname;

      RETURN RECORDS;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION auto_make_vcsrelease (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      vcstag                   IN   VARCHAR2,
      dependenciesimportlist   IN   VARCHAR2,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      pkgid                           NUMBER;
      pvid                            NUMBER                        := 0;
      userid                          NUMBER;
      dlocked                         VARCHAR2 (20)                 := NULL;
      clonefrompvid                   NUMBER;
      ssv_mm                          package_versions.v_mm%TYPE;
      ssv_nmm                         package_versions.v_nmm%TYPE;
      ssv_ext                         package_versions.v_ext%TYPE;
      return_package_not_found        NUMBER                        := -1;
      return_package_already_exists   NUMBER                        := -2;
      return_not_approved             NUMBER                        := -3;
      return_migrated_pkg             NUMBER                        := -4;


      x_vcstypeid                     NUMBER;
      x_tag                           VARCHAR2(32);
      x_label                         VARCHAR2(60);
      x_srcpath                       VARCHAR2(2000);
      p_srcpath                       VARCHAR2(2000);

      -- Regular expression constituents
      Token         VARCHAR2(16) := '([^:]+)';  -- a token is anything except a ':' character
      Seperator     VARCHAR2(4)  := '::';       -- tokens will be seperated by '::'
      BOL           VARCHAR2(4)  := '^';
      Anything      VARCHAR2(4)  := '.*';
      ReplaceToken1 VARCHAR2(4)  := '\1';
      ReplaceToken2 VARCHAR2(4)  := '\2';
      ReplaceToken3 VARCHAR2(4)  := '\3';
      iprev_modifier_id               NUMBER;

   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pkgname IS NULL)
      THEN
         raise_application_error (-20000, 'PkgName must be supplied.');
      END IF;

      IF (newpkgversion IS NULL)
      THEN
         raise_application_error (-20000, 'PkgVersion must be supplied.');
      END IF;

      IF (vcstag IS NULL)
      THEN
         raise_application_error (-20000, 'PkgVcsTag must be supplied.');
      END IF;

      IF (isrippled IS NULL) OR (isrippled < 0) OR (isrippled > 1)
      THEN
         raise_application_error
            (-20000,
             'IsRippled must be set to 1 (Is rippled build) or 0 (Is planned build).'
            );
      END IF;

      IF (username IS NULL)
      THEN
         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Parse the PkgVcsTag
      -- Sets up
      --   x_tag, x_label, x_srcpath

       BEGIN
          -- Extract the first token - this will be the short tag name for the VCS (eg. 'CC', 'SVN', etc)
          x_tag := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Anything, ReplaceToken1);

          -- Decode the short tag
          CASE x_tag
             WHEN 'CC' THEN
                -- extract the 2nd and 3rd tokens, those being the source path and label respectively
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Token, ReplaceToken3);

                -- NOTE: if reg-expr parsing/replacement fails, the x_... variable may receive the entire input string (vcstag), so
                -- check for that error as well as the obvious zero-length string conditions.
                IF LENGTH(x_srcpath) = 0 OR LENGTH(x_label) = 0 OR x_srcpath = vcstag OR x_label = vcstag THEN
                   raise_application_error (-20000, 'VCS Tag contains insufficient or malformed data!');
                END IF;
                
                IF isSVNbyName(pkgname) > 0 THEN
                    -- Don't allow migrated packages to be released from a CC label
                    return return_migrated_pkg;
                END IF;


             WHEN 'SVN' THEN
                -- extract the 2nd token, that being the subversion tag
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Token, ReplaceToken3);

                -- NOTE: if reg-expr parsing/replacement fails, the x_... variable may receive the entire input string (vcstag), so
                -- check for that error as well as the obvious zero-length string conditions.
                IF LENGTH(x_srcpath) = 0 OR LENGTH(x_label) = 0 OR x_srcpath = vcstag OR x_label = vcstag THEN
                   raise_application_error (-20000, 'VCS Tag contains insufficient or malformed data!');
                END IF;

             WHEN 'UC' THEN
                -- nothing to extract, just assign defaults
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := 'N/A';
             ELSE
                raise_application_error (-20000, 'Unrecognised VCS Tag!');
          END CASE;
       END;

      -- Get the VCS_TYPE_ID for the version control system.
      BEGIN
         SELECT vt.vcs_type_id
         INTO x_vcstypeid
         FROM VCS_TYPE vt
         WHERE vt.tag = x_tag;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing a version control system tag (' || x_tag || ')!' );
      END;


      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000,
                                        'UserName '
                                     || username
                                     || ' is not valid or disabled.'
                                    );
      END;

/*-------------------------------------------------------*/

      -- Create package if necessary
      IF isrippled = 1
      THEN
         /* Ripple Build */
         BEGIN
            -- Make sure that package does not exist
            SELECT pv.pv_id
              INTO pvid
              FROM package_versions pv, PACKAGES pkg
             WHERE pv.pkg_id = pkg.pkg_id
               AND pkg.pkg_name = pkgname
               AND pv.pkg_version = newpkgversion;
         EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
               pvid := 0;
         END;

         IF (pvid = 0)
         THEN
            -- Split current version in parts
            split_version (newpkgversion, ssv_mm, ssv_nmm, ssv_ext);

            BEGIN
               -- Find package to be replaced with the ripple package
               IF NVL (vext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|')
               THEN
                  SELECT pv.pv_id, pv.src_path
                    INTO clonefrompvid, p_srcpath
                    FROM PACKAGES pkg, package_versions pv,
                         release_content rc
                   WHERE rc.pv_id = pv.pv_id
                     AND pv.pkg_id = pkg.pkg_id
                     AND rc.rtag_id = rtagid
                     AND pkg.pkg_name = pkgname
                     AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|');
               ELSE
                  SELECT pv.pv_id, pv.src_path
                    INTO clonefrompvid, p_srcpath
                    FROM PACKAGES pkg, package_versions pv,
                         release_content rc
                   WHERE rc.pv_id = pv.pv_id
                     AND pv.pkg_id = pkg.pkg_id
                     AND rc.rtag_id = rtagid
                     AND pkg.pkg_name = pkgname
                     AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|');
               END IF;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  raise_application_error
                                        (-20000,
                                            'Cannot get CloneFromPvId. VExt='
                                         || vext
                                         || ', RtagId='
                                         || rtagid
                                         || ', PkgName='
                                         || pkgname
                                         || ', SSV_EXT='
                                         || ssv_ext
                                        );
            END;

            IF NVL (vext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|')
            THEN
               -- Create package
               seed_package_names_versions (pkgname,
                                            newpkgversion,
                                            userid,
                                            pvid,
                                            clonefrompvid
                                           );
            ELSE
               -- Create package
               seed_package_names_versions2 (pkgname,
                                             newpkgversion,
                                             userid,
                                             pvid,
                                             clonefrompvid
                                            );
            END IF;

            -- Update Package reason for release
            UPDATE package_versions pv
               SET pv.comments = 'Rippled Build.',
                   pv.build_type = 'Y'
             WHERE pv.pv_id = pvid;
         ELSE
            -- Package already exists, it was built previously, and has just been re-built again probably due to the
            -- fact that the archive was cleaned of the original build artifacts at some point, and those artifacts
            -- are now needed once more. As such, we need to ensure that a new release note generation occurs so
            -- reset the package_versions[pvid].release_notes_info field to enable that to happen.
            UPDATE package_versions pv
               SET pv.release_notes_info = null,
                   pv.modified_stamp = ora_sysdatetime
             WHERE pv.pv_id = pvid;

            --DEVI-066151
            log_action (pvid, 'package_rebuilt', userid, 'Package Re-built...');

            RETURN return_package_already_exists;
         END IF;
      ELSE
         /* Auto build from Pending area */

         -- Find package in pending area
         BEGIN
            SELECT pv.pv_id, pv.dlocked, pv.src_path
              INTO pvid, dlocked, p_srcpath
              FROM planned pl, package_versions pv, PACKAGES pkg
             WHERE pl.pv_id = pv.pv_id
               AND pv.pkg_id = pkg.pkg_id
               AND pl.rtag_id = rtagid
               AND pkg.pkg_name = pkgname
               AND pv.dlocked = 'A'
               AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|')
               AND rownum = 1
             ORDER BY pv.modified_stamp;
         EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
               pvid := 0;
         END;

         IF (pvid = 0)
         THEN
            -- Package does not exist in pending area, hence report it
            RETURN return_package_not_found;
         ELSIF (dlocked != 'A')
         THEN
            -- Package is not approved for autobuild
            RETURN return_not_approved;
         END IF;

      END IF;

      -- Ensure Source Path does not change
      -- Do not expect the SVN development branch to change
      -- From the previous package
      IF ( x_tag = 'SVN' AND p_srcpath != x_srcpath )
      THEN
        raise_application_error (-20000, 'Source Path does not match (' || p_srcpath || ','|| x_srcpath || ')' );
      END IF;

      BEGIN
         -- Import Dependencies
         import_dependencies (pvid, dependenciesimportlist, userid);
      END;


      BEGIN
         -- Split current version in parts
         split_version (newpkgversion, ssv_mm, ssv_nmm, ssv_ext);

         -- Update Package Details
         UPDATE package_versions pv
            SET pv.pkg_version = newpkgversion,
                pv.v_ext = ssv_ext,
                pv.v_mm = ssv_mm,
                pv.v_nmm = ssv_nmm,
                pv.src_path = x_srcpath,
                pv.pkg_label = x_label,
                pv.vcs_type_id = x_vcstypeid
          WHERE pv.pv_id = pvid;
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX
         THEN
            -- Package already exists, hence cannot be used for ripple build
            RETURN return_package_already_exists;
      END;

      -- Update the is_autobuildable
      UPDATE package_versions
         SET is_autobuildable = 'Y'
       WHERE pv_id = pvid;

      -- DEVI-063601
      -- For planned builds the modifier_id shouldn't be set to buildadm.
      -- To ensure this the modifier_id is obtained so it can be restored after
      -- the function pk_environment.auto_make_release is called.
      -- This function calls, change_state, which sets the modifier_id to the
      -- specified userid, which for auto builds is buildadm.
      SELECT pv.modifier_id INTO iprev_modifier_id
      FROM package_versions pv WHERE pv.pv_id = pvid;

      -- Now release package
      pk_environment.auto_make_release (pvid,
                                        rtagid,
                                        userid,
                                        vext,
                                        ssv_ext,
                                        clonefrompvid
                                       );

      -- DEVI-063601
      -- if it is a planned build then restore the modifier_id to the previous modifier
      UPDATE package_versions pv SET pv.modifier_id = iprev_modifier_id
      WHERE pv.pv_id = pvid;

      --Now clean the PLANNED_VERSIONS table
      SELECT pkg_id
        INTO pkgid
        FROM PACKAGES
       WHERE pkg_name = pkgname;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = newpkgversion;

      RETURN pvid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE import_dependencies (
      pvid                     IN   NUMBER,
      dependenciesimportlist   IN   VARCHAR2,
      userid                   IN   NUMBER
   )
   IS
/*
|| DependenciesImportList Format:
|| "pkgA","1.0.0";"pkgB","2.0.0";
||  OR 'pkgA','1.0.0';'pkgB','2.0.0';
*/
      TYPE tdictionary IS TABLE OF VARCHAR2 (4000)
         INDEX BY VARCHAR2 (4000);

      seperator         VARCHAR2 (2)           := '||';
      pkgname           VARCHAR2 (4000);
      pkgversion        VARCHAR2 (4000);
      buildtype         VARCHAR2 (50);
      pkgid             NUMBER;
      vext              VARCHAR2 (4000);
      dpvid             NUMBER;
      slist             VARCHAR2 (4000);
      cbuildtypes       tdictionary;
      dependencyrow     NUMBER;
      sdependency       VARCHAR2 (4000);
      first_pos         VARCHAR2 (4000);
      second_pos        VARCHAR2 (4000);
      third_pos         VARCHAR2 (4000);
      forth_pos         VARCHAR2 (4000);
      citemcollection   relmgr_varchar2_tab_t  := relmgr_varchar2_tab_t ();

      CURSOR curbuildtype
      IS
         SELECT dpv.pkg_id || seperator || dpv.v_ext AS pkgid_ext,
                dep.build_type
           FROM package_dependencies dep, package_versions dpv
          WHERE dep.pv_id = pvid AND dep.dpv_id = dpv.pv_id;

      recbuildtype      curbuildtype%ROWTYPE;
   BEGIN
      slist := dependenciesimportlist;

      -- Preformat String
      IF NOT slist IS NULL
      THEN
         slist := REPLACE (slist, ' ');                      -- Remove spaces
         slist := REPLACE (slist, UTL_TCP.crlf);
         -- Remove new line and carriage-return characters
         slist := REPLACE (slist, '''', '"');             -- Replace ' with "
      END IF;

      -- Get Current Dependencies
      OPEN curbuildtype;

      FETCH curbuildtype
       INTO recbuildtype;

      WHILE curbuildtype%FOUND
      LOOP
         cbuildtypes (recbuildtype.pkgid_ext) := recbuildtype.build_type;

         FETCH curbuildtype
          INTO recbuildtype;
      END LOOP;

      CLOSE curbuildtype;

      -- Separate dependencies with ; separator
      citemcollection := in_list_varchar2 (slist, ';');

      BEGIN
         -- Remove old dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = pvid;

         -- Loop through dependencies
         FOR dependencyrow IN 1 .. citemcollection.COUNT
         LOOP
            -- Extract pkg_name and pkg_version
            sdependency := citemcollection (dependencyrow);
            first_pos := INSTR (sdependency, '"', 1, 1);
            second_pos := INSTR (sdependency, '"', 1, 2);
            third_pos := INSTR (sdependency, '"', 1, 3);
            forth_pos := INSTR (sdependency, '"', 1, 4);
            pkgname :=
               SUBSTR (sdependency,
                       (first_pos + 1),
                       (second_pos - first_pos - 1)
                      );
            pkgversion :=
               SUBSTR (sdependency,
                       (third_pos + 1),
                       (forth_pos - third_pos - 1)
                      );

            -- Dependency must exits to be linked against
            BEGIN
               SELECT pv.pv_id, pv.pkg_id, pv.v_ext
                 INTO dpvid, pkgid, vext
                 FROM package_versions pv, PACKAGES pkg
                WHERE pv.pkg_id = pkg.pkg_id
                  AND pkg.pkg_name = pkgname
                  AND pv.pkg_version = pkgversion;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  raise_application_error
                                  (-20000,
                                      'Dependency ['
                                   || pkgname
                                   || ' '
                                   || pkgversion
                                   || '] does not exist yet and cannot be used!'
                                  );
            END;

            -- Get Build Type (i.e. BuildPackageArchive or LinkPackageArchive)
            BEGIN
               buildtype := cbuildtypes (pkgid || seperator || vext);

               IF buildtype IS NULL
               THEN
                  -- Set build type to LinkPackageArchive by default
                  buildtype := 'L';
               END IF;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  buildtype := 'L';
            END;

            -- Insert Dependencies
            update_package_dependency (pvid,
                                       pkgname,
                                       pkgversion,
                                       buildtype,
                                       userid,
                                       0
                                      );
         END LOOP;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION return_last_package_version (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2
   IS
      pkgversion   VARCHAR2 (4000);
   BEGIN
      BEGIN
         SELECT pv.pkg_version
           INTO pkgversion
           FROM PACKAGES pkg, release_content rc, package_versions pv
          WHERE pv.pv_id = rc.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pkg.pkg_name = pkgname
            AND rc.rtag_id = rtagid;

         RETURN pkgversion;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION return_wip (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2
   IS
      pkgversion   VARCHAR2 (4000);
   BEGIN
      BEGIN
         SELECT pv.pkg_version
           INTO pkgversion
           FROM PACKAGES pkg, work_in_progress wip, package_versions pv
          WHERE pv.pv_id = wip.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pkg.pkg_name = pkgname
            AND wip.rtag_id = rtagid;

         IF pkgversion IS NULL
         THEN
            SELECT pv.pkg_version
              INTO pkgversion
              FROM PACKAGES pkg, planned pl, package_versions pv
             WHERE pv.pv_id = pl.pv_id
               AND pkg.pkg_id = pv.pkg_id
               AND pkg.pkg_name = pkgname
               AND pl.rtag_id = rtagid;
         END IF;

         RETURN pkgversion;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_dash_board (rtagid IN NUMBER)
   IS
      projid       NUMBER;
      projiddb     NUMBER;
      total        NUMBER;
      auto_total   NUMBER;
      rtagiddb     NUMBER;
   BEGIN
      SELECT COUNT (*)
        INTO total
        FROM release_content rc, package_versions pv
       WHERE pv.pv_id = rc.pv_id AND rc.rtag_id = rtagid;

      SELECT COUNT (*)
        INTO auto_total
        FROM release_content rc, package_versions pv
       WHERE pv.pv_id = rc.pv_id
         AND pv.is_autobuildable = 'Y'
         AND rc.rtag_id = rtagid;

      BEGIN
         SELECT rtag_id
           INTO rtagiddb
           FROM dash_board
          WHERE rtag_id = rtagid;

         SELECT proj_id
           INTO projiddb
           FROM dash_board
          WHERE rtag_id = rtagid;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            rtagiddb := '';
      END;

      IF rtagiddb IS NULL
      THEN
         SELECT proj_id
           INTO projid
           FROM release_tags
          WHERE rtag_id = rtagid;

         INSERT INTO dash_board
                     (proj_id, rtag_id, last_build_time, automated_packages,
                      total_packages
                     )
              VALUES (projid, rtagid, ora_sysdatetime, auto_total,
                      total
                     );
      ELSE
         UPDATE dash_board
            SET last_build_time = ora_sysdatetime,
                automated_packages = auto_total,
                total_packages = total
          WHERE proj_id = projiddb AND rtag_id = rtagiddb;
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION exclude_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      userid              NUMBER;
      outerrcode          NUMBER;
      pkgid               NUMBER;

      CURSOR dnr_duplicate_cur
      IS
         SELECT *
           FROM do_not_ripple
          WHERE pv_id = pvid AND rtag_id = rtagid;

      dnr_duplicate_rec   dnr_duplicate_cur%ROWTYPE;
   BEGIN
      outerrcode := -1;       -- Set default return error code to ERROR state

      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pvid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'PvId must be supplied.');
      END IF;

      IF (username IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            RETURN outerrcode;
--            raise_application_error (-20000,
--                                        'UserName '
--                                     || username
--                                     || ' is not valid or disabled.'
--                                    );
      END;

      OPEN dnr_duplicate_cur;

      FETCH dnr_duplicate_cur
       INTO dnr_duplicate_rec;

      IF dnr_duplicate_cur%FOUND
      THEN
         outerrcode := 0;
      END IF;

      IF dnr_duplicate_cur%NOTFOUND
      THEN
         /* No duplicate recordset */
         unripple_package (pvid, rtagid, userid);
         outerrcode := 0;                            -- Set return to SUCCESS
      END IF;

      CLOSE dnr_duplicate_cur;

      SELECT pkg_id
        INTO pkgid
        FROM package_versions
       WHERE pv_id = pvid;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = spkgversion;

      RETURN outerrcode;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION exclude_indirect_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2,
      rootpvid      IN   NUMBER,
      rootcause     IN   VARCHAR2,
      rootfile      IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      userid              NUMBER;
      outerrcode          NUMBER;
      pkgid               NUMBER;

      CURSOR dnr_duplicate_cur
      IS
         SELECT *
           FROM do_not_ripple
          WHERE pv_id = pvid AND rtag_id = rtagid;

      dnr_duplicate_rec   dnr_duplicate_cur%ROWTYPE;
   BEGIN
      outerrcode := -1;       -- Set default return error code to ERROR state

      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pvid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'PvId must be supplied.');
      END IF;

      IF (username IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            RETURN outerrcode;
--            raise_application_error (-20000,
--                                        'UserName '
--                                     || username
--                                     || ' is not valid or disabled.'
--                                    );
      END;

     /* No duplicate recordset */
     unripple_package_indirect (pvid, rtagid, userid, rootpvid, rootcause, rootfile);
     outerrcode := 0;                            -- Set return to SUCCESS

      SELECT pkg_id
        INTO pkgid
        FROM package_versions
       WHERE pv_id = pvid;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = spkgversion;

      RETURN outerrcode;
   END;
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE insert_abt_actionlog (rconid IN NUMBER, action IN VARCHAR2)
   IS
   BEGIN
      INSERT INTO abt_action_log
                  (rcon_id, action_datetime, action
                  )
           VALUES (rconid, ora_sysdatetime, action
                  );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION insert_package_metrics (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      metricstring             IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      citemcollection          relmgr_varchar2_tab_t  := relmgr_varchar2_tab_t ();
      lv_pvid                  NUMBER                 := 0;
      rownumber                NUMBER;
      rowcontent               VARCHAR2(4000);
      metricname               VARCHAR2(1000);
      metricvalue              VARCHAR2(4000);
      return_insert_error      NUMBER                 := -1;
      return_insert_success    NUMBER                 := 0;

      /* Metrics */
      lv_branches                 NUMBER;
      lv_branchlist               VARCHAR2(4000);
      lv_codefiles                NUMBER;
      lv_ignoredfiles             NUMBER;
      lv_directories              NUMBER;
      lv_directorydepth           NUMBER;
      lv_totalfiles               NUMBER;
      lv_makefiles                NUMBER;
      lv_blanklines               NUMBER;
      lv_codelines                NUMBER;
      lv_commentlines             NUMBER;

   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         RETURN return_insert_error;
      END IF;

      IF (pkgname IS NULL)
      THEN
         RETURN return_insert_error;
      END IF;

      IF (metricstring IS NULL)
      THEN
         RETURN return_insert_error;
      END IF;

      BEGIN
         SELECT pv.pv_id
           INTO lv_pvid
           FROM package_versions pv, packages pkg, release_content rc
          WHERE pv.pkg_id = pkg.pkg_id
            AND rc.rtag_id = rtagid
            AND pv.pv_id = rc.pv_id
            AND pkg.pkg_name = pkgname
            AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|');
      EXCEPTION
           WHEN NO_DATA_FOUND
           THEN
                lv_pvid := 0;
      END;

      citemcollection := in_list_varchar2 (metricstring, ';');

      FOR rownumber IN 1 .. citemcollection.COUNT
      LOOP
         rowcontent := citemcollection(rownumber);
         metricvalue := SUBSTR(rowcontent, (INSTR(rowcontent, '=') + 1));
         metricname := REGEXP_REPLACE(rowcontent, '=.*$', '');

         IF    metricname = 'ccbranch.count' THEN lv_branches := metricvalue;
         ELSIF metricname = 'ccbranch.list' THEN lv_branchlist := metricvalue;
         ELSIF metricname = 'code.files' THEN lv_codefiles := metricvalue;
         ELSIF metricname = 'code.ignored' THEN lv_ignoredfiles := metricvalue;
         ELSIF metricname = 'count.dir' THEN lv_directories := metricvalue;
         ELSIF metricname = 'count.dirdepth' THEN lv_directorydepth := metricvalue;
         ELSIF metricname = 'count.file' THEN lv_totalfiles := metricvalue;
         ELSIF metricname = 'count.makefile' THEN lv_makefiles := metricvalue;
         ELSIF metricname = 'lines.blank' THEN lv_blanklines := metricvalue;
         ELSIF metricname = 'lines.code' THEN lv_codelines := metricvalue;
         ELSIF metricname = 'lines.comment' THEN lv_commentlines := metricvalue;
         END IF;
      END LOOP;

      IF (lv_pvid > 0)
      THEN
         -- Delete any existing entries for this package version to makes sure our data is untainted
         DELETE FROM package_metrics pm
         WHERE pm.pv_id = lv_pvid;

         -- Insert the new data into the metrics table
         INSERT INTO package_metrics
                     (pv_id, branches, branch_list, code_files, ignored_files, directories, directory_depth,
                      total_files, makefiles, blank_lines, code_lines, comment_lines, created_stamp
                     )
              VALUES (lv_pvid, lv_branches, lv_branchlist, lv_codefiles, lv_ignoredfiles, lv_directories, lv_directorydepth,
                      lv_totalfiles, lv_makefiles, lv_blanklines, lv_codelines, lv_commentlines, ora_sysdatetime
                     );

         -- Now update the Release_Metrics Table
         update_release_metrics(rtagid);

         RETURN return_insert_success;
      ELSE
         RETURN return_insert_error;
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_release_metrics (rtagid IN NUMBER)
   IS
      lv_totalpackages       NUMBER;
      lv_autobuilt           NUMBER;
      lv_linesofcode         NUMBER;
      lv_unittested          NUMBER;
      lv_autotested          NUMBER;
      lv_numOfbranches       NUMBER;
      lv_lastbuildtime       DATE;
   BEGIN
      IF (rtagid > 0)
      THEN
         -- Get the total number of packages in this release and the number of
         -- those that are autobuilt
         SELECT COUNT (DISTINCT rc.pv_id),
                COUNT (DISTINCT autobuilt_qry.pv_id)
           INTO lv_totalpackages, lv_autobuilt
           FROM release_content rc,
                package_versions pv,
                (
                 SELECT rc.pv_id
                   FROM release_content rc,
                        package_versions pv
                  WHERE pv.is_autobuildable = 'Y'
                    AND pv.pv_id = rc.pv_id
                    AND rc.rtag_id = rtagid
                ) autobuilt_qry
          WHERE pv.pv_id = rc.pv_id
            AND rc.rtag_id = rtagid
            AND autobuilt_qry.pv_id (+) = rc.pv_id;

         -- Get the build time of the last package built in this release and the
         -- total number of lines of code
         SELECT MAX(pm.created_stamp),
                SUM(pm.code_lines)
           INTO lv_lastbuildtime, lv_linesofcode
           FROM package_metrics pm, release_content rc
          WHERE pm.pv_id = rc.pv_id
            AND rc.rtag_id = rtagid;

         -- Get the number of packages with unit tests in this release and the
         -- number of those that are autotested
         SELECT COUNT(DISTINCT ut.pv_id) INTO lv_unittested
           FROM unit_tests ut,
                release_content rc
          WHERE ut.pv_id = rc.pv_id
            AND rc.rtag_id = rtagid
        AND ut.test_types_fk != 1;

        SELECT COUNT(DISTINCT ut.pv_id) INTO lv_autotested
          FROM unit_tests ut,
               release_content rc
         WHERE ut.pv_id = rc.pv_id
           AND rc.rtag_id = rtagid
           AND ut.test_types_fk = 7;


         -- Count the number of unique branches in the packages in this release.
--         SELECT COUNT(DISTINCT branch) INTO lv_numOfbranches
--           FROM (
--                SELECT pv_id,
--                       regexp_substr(str, '[^,]+', 1, level) branch,
--                       level lv,
--                       lag(level, 1, 0) over (partition by pv_id order by level) lg
--                  FROM (
--                       SELECT pm.pv_id,
--                              ','||pm.branch_list str
--                         FROM package_metrics pm,
--                              release_content rc
--                        WHERE pm.pv_id = rc.pv_id
--                          AND rc.rtag_id = rtagid
--                       )
--                CONNECT BY regexp_substr(str, '[^,]+', 1, LEVEL) IS NOT NULL
--                )
--          WHERE lv != lg;

         UPDATE release_metrics rm
            SET rm.total_packages = lv_totalpackages,
                rm.autobuilt = lv_autobuilt,
                rm.lines_of_code = lv_linesofcode,
                rm.unit_tested = lv_unittested,
                rm.autotested = lv_autotested,
--                rm.branches = lv_numOfbranches,
                rm.last_build_time = lv_lastbuildtime
          WHERE rtag_id = rtagid;

         IF (SQL%ROWCOUNT = 0)
         THEN
            INSERT INTO release_metrics
                        (rtag_id, total_packages, autobuilt, lines_of_code, unit_tested,
                         autotested, last_build_time
                        )
                 VALUES (rtagid, lv_totalpackages, lv_autobuilt, lv_linesofcode, lv_unittested,
                         lv_autotested, lv_lastbuildtime
                        );
         END IF;
--         IF (SQL%ROWCOUNT = 0)
--         THEN
--            INSERT INTO release_metrics
--                        (rtag_id, total_packages, autobuilt, lines_of_code, unit_tested,
--                         autotested, branches, last_build_time
--                        )
--                 VALUES (rtagid, lv_totalpackages, lv_autobuilt, lv_linesofcode, lv_unittested,
--                         lv_autotested, lv_numOfbranches, lv_lastbuildtime
--                        );
--         END IF;
--      ELSE
--         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;
   END;
/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION return_vcs_tag(pvid IN NUMBER) RETURN VARCHAR2
   IS
      vcstypeid    NUMBER;
      vcstag       VARCHAR2(32);
      label        VARCHAR2(60);
      srcpath      VARCHAR2(2000);
      vcstypeid_cc NUMBER;
      vcstypeid_uc NUMBER;
   BEGIN
      -- Get the VCS_TYPE_ID for the ClearCase version control system. We do this so that we make no assumptions about
      -- what the primary key value is for the ClearCase VCS entry.
      BEGIN
         SELECT vt.vcs_type_id
         INTO vcstypeid_cc
         FROM VCS_TYPE vt
         WHERE vt.tag = 'CC';
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing compulsory CC version control system tag!');
      END;

      -- Get the VCS_TYPE_ID for the Uncontrolled version control system. We do this so that we make no assumptions about
      -- what the primary key value is for the Uncontrolled VCS entry.
      BEGIN
         SELECT vt.vcs_type_id
         INTO vcstypeid_uc
         FROM VCS_TYPE vt
         WHERE vt.tag = 'UC';
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing compulsory UC version control system tag!');
      END;

      -- Get the PKG_LABEL, SRC_PATH, VCS_TYPE_ID for the package version
      -- As additional VCS types are introduced, we may have to extend what this SELECT statement returns
      BEGIN
         SELECT pv.pkg_label, pv.src_path,
           (CASE WHEN pv.pkg_label = 'N/A' AND pv.vcs_type_id IS NULL THEN vcstypeid_uc
                 WHEN pv.vcs_type_id IS NULL THEN vcstypeid_cc
                 ELSE pv.vcs_type_id END) AS vcs_type_id
         INTO label, srcpath, vcstypeid
         FROM PACKAGE_VERSIONS pv
         WHERE pv.pv_id = pvid;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Package Version Not Found!');
      END;

      -- Get the VCS TAG for the VCS_TYPE_ID.
      BEGIN
         SELECT vt.tag
         INTO vcstag
         FROM VCS_TYPE vt
         WHERE vt.vcs_type_id = vcstypeid;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Could not get VCS Tag for the package version!');
      END;

      -- Return value depending upon which VCS Tag is being used.
      -- As additional VCS types are introduced, we have to add additional WHEN clauses
      CASE vcstag
         WHEN 'CC' THEN
            RETURN vcstag || '::' || srcpath || '::' || label;
         WHEN 'SVN' THEN
            RETURN vcstag || '::' || srcpath || '::' || label;
         ELSE
            RETURN vcstag || '::';
      END CASE;

   END;
/*-------------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------------
Name:        update_vcs_details
Description: Updates the Version Control System (vcs) details specified in the vcstag
             parameter for the specified package version.
             The specified package vcstag is parsed and split into 3 fields:
                vcs type, src path, label
             These fields are then stored for the specified pv_id in the package_versions, table.
             An action is recorded in the action log and provides information for tracking and
             for restoring the previous vcs settings if a recovery is required.
Paramters:
             ipv_id:     Package version identifier
             vcstag:     Full version control tag.
                         Examples:
                             "SVN::AUPERASVN01/DPG_SWBase/tools/trunk::daf_tools_25.1.7027.cr@1234"
                            "CC::/DPG_SWBase/tools::daf_tools_25.1.7016.cr"
             user_id:    Identifier of the user that is performing this function.
*/
PROCEDURE update_vcs_details(ipv_id IN NUMBER, vcstag IN VARCHAR2, user_id IN NUMBER)
   IS
      ivcs_type_id   NUMBER;
      svcs_type      VARCHAR2(128);
      ssrc_path      VARCHAR2(512);
      spkg_label     VARCHAR2(512);
      spattern       VARCHAR2(64);
      saction_desc   VARCHAR2(2048);
      old_vcs_type   VARCHAR2(128);
      old_src_path   VARCHAR2(512);
      old_pkg_label  VARCHAR2(512);
      old_pkg_vcstag VARCHAR2(1024);
      i              NUMBER;
      vcount         NUMBER;
   BEGIN
     -- Split vcs tag into fields: vcs type, src path, label
     -- Fields are separated by '::'
     -- e.g "CC::/DPG_SWBase/tools::daf_tools_25.1.7016.cr"
     -- The below regular expression pattern has groups to achieve this.

     spattern:= '^([^:]*)::([^:]*)(::(.*))?$';

     --As Oracle 10g does not allow REGEXP_SUBSTR to return a group,
     --REGEXP_REPLACE is used instead (Note: Oracle 11g has this enhancement).
     SELECT REGEXP_REPLACE(vcstag,spattern, '\1') INTO svcs_type  FROM DUAL;
     SELECT REGEXP_REPLACE(vcstag,spattern, '\2') INTO ssrc_path  FROM DUAL;
     SELECT REGEXP_REPLACE(vcstag,spattern, '\4') INTO spkg_label FROM DUAL;

     -- Validate vcs type
     BEGIN
       SELECT vc.vcs_type_id INTO ivcs_type_id FROM vcs_type vc WHERE UPPER(svcs_type) = UPPER(vc.tag);
     EXCEPTION
       WHEN NO_DATA_FOUND THEN
         raise_application_error (-20000, 'Invalid vcs type: ' || '"' || svcs_type || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       --RAISE;
     END;

     -- If Clearcase
     IF (ivcs_type_id = 2) THEN
       -- Validate source path
       IF NOT REGEXP_LIKE(ssrc_path,'^(\\|\/)[a-z]+[0-9a-z_\.\-\\\/ -]*$','i') THEN
         raise_application_error (-20000, 'Invalid CC src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;

       -- Validate label
       -- For clearcase the label must be specified. For subversion it is not required.
       IF NOT REGEXP_LIKE(spkg_label,'^[0-9a-z_\.\-]+$','i') THEN
         raise_application_error (-20000, 'Invalid CC label:' || '"' || spkg_label || '"' || ' for package version:' || ipv_id || ', vcstag:' || '"' || vcstag || '"');
       END IF;

     -- if Subversion
     ELSIF (ivcs_type_id = 23) THEN
       -- general validity
       -- Not as picky as the RM Data entry
       IF NOT REGEXP_LIKE(ssrc_path,'^([0-9a-z_\.\-]+)(\/([0-9a-z_\.\-]+))+$','i') THEN
         raise_application_error (-20000, 'Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;

       -- Validate Tag
       -- May be a Peg or a Label
       IF NOT REGEXP_LIKE(spkg_label,'^@?[0-9]+$','i') THEN
           IF NOT REGEXP_LIKE(spkg_label,'^[0-9a-z_\.\-]+($|@[0-9]+)','i') THEN
             raise_application_error (-20000, 'Invalid SVN tag:' || '"' || spkg_label || '"' || ' for package version:' || ipv_id || ', vcstag:' || '"' || vcstag || '"');
           END IF;
       END IF;

        -- Check for suitable ending
        IF NOT REGEXP_LIKE(ssrc_path,'(\/tags$)|(\/branches\/)|(\/trunk$)','i') THEN
            raise_application_error (-20000, 'Must end in /trunk or /tags/ or /branches/.... Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
        END IF;

       -- Check for combined use of tags, branches, trunk or repeats of each
       -- Count occurrences of /tags or /branches/ or /trunk
       vcount:=0;
       i:=1;
       WHILE i > 0 LOOP
         i:=REGEXP_INSTR(ssrc_path,'(\/tags(\/|$))|(\/branches(\/|$))|(\/trunk(\/|$))',i,1,1,'i');
         IF i > 0 THEN
           -- if found then increment count
           vcount:=vcount+1;
           i:=i-1;  -- move index back to "/"
         END IF;
       END LOOP;

       IF vcount = 0  THEN
         raise_application_error (-20000, 'Must contain exactly one of the keywords /trunk, /tags, /branches/. Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;

       IF vcount > 1  THEN
         raise_application_error (-20000, 'Combined use of /trunk, /tags, or /branches/. Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;


     END IF;

     BEGIN
       -- Get current vcs tag for specified package version
       SELECT pv.src_path, pv.pkg_label, vc.tag as vcs_type
       INTO old_src_path, old_pkg_label, old_vcs_type
       FROM package_versions pv, vcs_type vc
       WHERE pv.pv_id = ipv_id
       AND pv.vcs_type_id = vc.vcs_type_id (+);

     EXCEPTION
       WHEN NO_DATA_FOUND THEN
         raise_application_error (-20000, 'Package version not found: ' || ipv_id);
     END;

     old_pkg_vcstag:= old_vcs_type || '::' || old_src_path;
     IF (old_pkg_label IS NOT NULL) THEN
       old_pkg_vcstag:=old_pkg_vcstag || '::' || old_pkg_label;
     END IF;

     -- Create action description
     -- This description will contain the old and new tags.
     -- Its purpose is to provide information for tracking and for restoring previous vcs settings if a recovery is required.
     -- An example of the action description is below:
     --   OldTag:CC::/DPG_SWBase/tools::daf_tools_25.1.7016.cr NewTag:SVN::DPG_SWBase/tools/tags/daf_tools_25.1.7027.cr
     saction_desc:='OldTag:' || old_pkg_vcstag || ' ' || 'NewTag:' || vcstag;

     -- Store new vcs details
     UPDATE package_versions SET
       src_path = ssrc_path,
       pkg_label = spkg_label,
       vcs_type_id = ivcs_type_id
     WHERE
       pv_id = ipv_id;

     -- Store action in action log so that we can back track and also restore vcs settings if required.
     log_action (ipv_id,'VcsConversion',user_id,saction_desc);

   END update_vcs_details;

/*-------------------------------------------------------------------------------------------------------
Name:        isSVN
Description: Determine if any of the packages versions are controlled under SVN
			 Intended to be used to prevent users from releasing a package
			 that has been migrated to SVN

Paramters:	pkgid:     Package ID

Returns:	Number of versions under SVN version control
*/
      
FUNCTION isSVN( pkgid IN NUMBER )
    RETURN NUMBER
    IS
    svncount   NUMBER  := 0;
   BEGIN
        SELECT COUNT(*) INTO svncount FROM PACKAGE_VERSIONS pv WHERE pv.PKG_ID = pkgid AND pv.VCS_TYPE_ID = 23;
        RETURN (svncount);
   END;
   
/*-------------------------------------------------------------------------------------------------------
Name:        isSVNbyName
Description: Determine if any of the packages versions are controlled under SVN
			 Intended to be used to prevent users from releasing a package
			 that has been migrated to SVN

Paramters:	pkgname:	Package Name

Returns:	Number of versions under SVN version control
*/

FUNCTION isSVNbyName( pkgname IN VARCHAR2 ) 
    RETURN NUMBER
IS
   svncount   NUMBER  := 0;
   BEGIN
        SELECT COUNT(*) INTO svncount FROM PACKAGE_VERSIONS pv, PACKAGES pkg WHERE pkg.pkg_name = pkgname AND pv.PKG_ID = pkg.pkg_id AND pv.VCS_TYPE_ID = 23;
        RETURN (svncount);
   END;
   
   END;
/
--------------------------------------------------------
--  DDL for Package Body PK_WORK_IN_PROGRESS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "PK_WORK_IN_PROGRESS" IS

/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  2/May/2005
||  Body Version:   1.0
------------------------------
*/


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

	oldPvId NUMBER;
	ReleaseLocation VARCHAR2(4000);
	sLocation VARCHAR2(4000) := NULL;


BEGIN
	/*--------------- Business Rules Here -------------------*/
	/*-------------------------------------------------------*/

	BEGIN
		-- Check if Exists in "Work in progress" anywhere in the world, except "Closed mode" releases
		SELECT proj.PROJ_NAME ||' > '|| rt.RTAG_NAME  INTO sLocation
		  FROM WORK_IN_PROGRESS wip,
		  	   RELEASE_TAGS rt,
			   PROJECTS proj
		 WHERE wip.PV_ID = newPvId
		   AND wip.RTAG_ID = rt.RTAG_ID
		   AND rt.OFFICIAL != 'Y'
		   AND rt.PROJ_ID = proj.PROJ_ID;

		EXCEPTION
	    	WHEN NO_DATA_FOUND THEN
	       		sLocation := NULL;
	   
	END;	   	   



	IF (sLocation IS NULL)  THEN

		-- Add to "Work in progress"
		INSERT INTO WORK_IN_PROGRESS ( RTAG_ID, PV_ID, VIEW_ID )
		VALUES( RtagId, newPvId, ViewId );


	    /* LOG ACTION */
		SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
		  FROM PROJECTS proj,
		  	   RELEASE_TAGS rt
		 WHERE rt.PROJ_ID = proj.PROJ_ID
		   AND rt.RTAG_ID = RtagId;

		Log_Action ( newPvId, 'work_in_progress', UserId, 'Location: '|| ReleaseLocation );

	ELSE
		
		RAISE_APPLICATION_ERROR (-20000, 'This version is already in Work-In-Progress Area at '|| sLocation ||'.' );
		
	END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

	ReleaseLocation VARCHAR2(4000);

BEGIN

	/*--------------- Business Rules Here -------------------*/
	/*-------------------------------------------------------*/


	-- Get release location for logging pusposes
	SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
	  FROM PROJECTS proj,
	  	   RELEASE_TAGS rt
	 WHERE rt.PROJ_ID = proj.PROJ_ID
	   AND rt.RTAG_ID = RtagId;


	-- Delete from Work In Progress
	DELETE
	  FROM WORK_IN_PROGRESS wip
	 WHERE wip.RTAG_ID = RtagId
	   AND wip.PV_ID = PvId;

	Log_Action ( PvId, 'delete_from_wip', UserId, 'Location: '|| ReleaseLocation );




END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE_BULK ( PvIdList IN VARCHAR2, RtagId IN NUMBER, UserId IN NUMBER ) IS

	nIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
	ReleaseLocation VARCHAR2(4000);
	PvId NUMBER;

BEGIN

	/*--------------- Business Rules Here -------------------*/
	IF (PvIdList IS NULL)
	THEN
		RAISE_APPLICATION_ERROR (-20000, 'Please select at least one package.' );
	END IF;
	/*-------------------------------------------------------*/


	nIdCollector := IN_LIST_NUMBER ( PvIdList );


	-- Get release location for logging pusposes
	SELECT proj.PROJ_NAME  ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
	  FROM PROJECTS proj,
	  	   RELEASE_TAGS rt
	 WHERE rt.PROJ_ID = proj.PROJ_ID
	   AND rt.RTAG_ID = RtagId;


	FOR i IN 1..nIdCollector.COUNT
	LOOP
		PvId := nIdCollector(i);

		-- Delete from Work In Progress
		DELETE
		  FROM WORK_IN_PROGRESS wip
		 WHERE wip.RTAG_ID = RtagId
		   AND wip.PV_ID = PvId;

		Log_Action ( PvId, 'remove_from_work_in_progress', UserId, 'Location: '|| ReleaseLocation );

	END LOOP;


END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER IS

	ReturnValue NUMBER;

BEGIN
	SELECT wip.VIEW_ID INTO ReturnValue
	  FROM WORK_IN_PROGRESS wip
	 WHERE wip.RTAG_ID = RtagId
	   AND wip.PV_ID = PvId;

	RETURN ReturnValue;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur ) IS

	IsBaseView CHAR(1);
	
BEGIN

	-- Check if the view is BASE VIEW
	SELECT vi.BASE_VIEW INTO IsBaseView
	  FROM VIEWS vi
	 WHERE vi.VIEW_ID = ViewId;
	 
	IF (IsBaseView = 'Y') THEN 
		-- Get Base view content
		OPEN RecordSet FOR
		SELECT 0 AS PKG_STATE,
			   NULL AS DEPRECATED_STATE,
			   pv.pv_id, 
			   pkg.pkg_name, 
			   pv.pkg_version, 
			   pv.dlocked, 
			   pv.pv_description,
			   pv.BUILD_TYPE
		  FROM WORK_IN_PROGRESS rel,
		       packages pkg,
		       package_versions pv
		 WHERE pv.pkg_id = pkg.pkg_id
		   AND rel.pv_id = pv.pv_id
		   AND rel.VIEW_ID = ViewId
		   AND rel.RTAG_ID = RtagId
		 ORDER BY UPPER(pkg.PKG_NAME);
	 

	ELSE	 
	 
	 	-- Get non base view content
		OPEN RecordSet FOR
		SELECT 0 AS PKG_STATE,
			   NULL AS DEPRECATED_STATE,
			   pv.pv_id, 
			   pkg.pkg_name, 
			   pv.pkg_version, 
			   pv.dlocked, 
			   pv.pv_description,
			   pv.BUILD_TYPE
		  FROM WORK_IN_PROGRESS rel,
		       packages pkg,
		       package_versions pv,
			   VIEW_DEF vd
		 WHERE pv.pkg_id = pkg.pkg_id
		   AND rel.pv_id = pv.pv_id
		   AND vd.VIEW_ID = ViewId
		   AND vd.PKG_ID = pv.PKG_ID
		   AND rel.RTAG_ID = RtagId
		 ORDER BY UPPER(pkg.PKG_NAME);
	 
	 
	END IF;	 	
	

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER ) IS
	
BEGIN
	
	UPDATE WORK_IN_PROGRESS wip SET
	wip.VIEW_ID = NewViewId
	WHERE wip.PV_ID = PvId
	  AND wip.RTAG_ID = RtagId;
	
END;
/*-------------------------------------------------------------------------------------------------------*/
END PK_WORK_IN_PROGRESS;
/
--------------------------------------------------------
--  DDL for Package Body RM_ISSUES
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RM_ISSUES" AS

-- Private Implementation -----------------------------------------------------


	FUNCTION VerIsGrtrThanOrEqlToStart( XXstart IN NUMBER, XX IN NUMBER, YYstart IN NUMBER, YY IN NUMBER, ZZstart IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER
	AS

	BEGIN
		-- start boundary case
		IF ( XXstart < XX ) THEN
			RETURN 1;

		ELSIF ( XXstart = XX ) THEN

			-- need to consider YY
			IF ( YYstart < YY ) THEN
				RETURN 1;

			ELSIF ( YYstart = YY ) THEN

					-- need to consider ZZ
					IF ( ZZstart <= ZZ ) THEN
						RETURN 1;

					ELSE
						RETURN 0;
					END IF;

			ELSE
				RETURN 0;
			END IF;
		ELSE
			RETURN 0;
		END IF;
	EXCEPTION
		WHEN OTHERS THEN
			RETURN -1;
	END;


	FUNCTION VerIsLessThanOrEqlToEnd( XXend IN NUMBER, XX IN NUMBER, YYend IN NUMBER, YY IN NUMBER, ZZend IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER
	AS

	BEGIN
		-- end boundary case
		IF ( XX < XXend ) THEN
			RETURN 1;

		ELSIF ( XX = XXend ) THEN

			-- need to consider YY
			IF ( YY < YYend ) THEN
				RETURN 1;

			ELSIF ( YY = YYend ) THEN

					-- need to consider ZZ
					IF ( ZZ <= ZZend ) THEN
						RETURN 1;

					ELSE
						RETURN 0;
					END IF;
			ELSE

				RETURN 0;
			END IF;
		ELSE
			RETURN 0;
		END IF;
	EXCEPTION
		WHEN OTHERS THEN
			RETURN -1;
	END;

	/*
	-	version format:		XX.YY.ZZ.abc
	*/
	FUNCTION VersionIsBetween( version IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR ) RETURN NUMBER
	AS
		XXstart		NUMBER	:=	0;
		XXend		NUMBER	:=	0;
		XX			NUMBER	:=	0;
		YYstart		NUMBER	:=	0;
		YYend		NUMBER	:=	0;
		YY			NUMBER	:=	0;
		ZZstart		NUMBER	:=	0;
		ZZend		NUMBER	:=	0;
		ZZ			NUMBER	:=	0;
		first_dot	NUMBER	:=	0;
		second_dot	NUMBER	:=	0;
		third_dot	NUMBER	:=	0;

		ProjExtstart	VARCHAR2(10);
		ProjExtend		VARCHAR2(10);
		ProjExt			VARCHAR2(10);

	BEGIN
		-- strip the version number
		first_dot :=  INSTR(version_start, '.', 1, 1);
		second_dot :=  INSTR(version_start, '.', 1, 2);
		third_dot :=  INSTR(version_start, '.', 1, 3);

		XXstart := TO_NUMBER( SUBSTR( version_start, 1, first_dot - 1 ) );
		YYstart := TO_NUMBER( SUBSTR( version_start, first_dot + 1, second_dot - ( first_dot + 1 ) ) );
		ZZstart := TO_NUMBER( SUBSTR( version_start, second_dot + 1, third_dot - ( second_dot + 1 ) ) );
		ProjExtstart := SUBSTR( version_start, third_dot + 1, LENGTH(version_start) - third_dot );

		first_dot :=  INSTR(version_end, '.', 1, 1);
		second_dot :=  INSTR(version_end, '.', 1, 2);
		third_dot :=  INSTR(version_end, '.', 1, 3);

		XXend := TO_NUMBER( SUBSTR( version_end, 1, first_dot - 1 ) );
		YYend := TO_NUMBER( SUBSTR( version_end, first_dot + 1, second_dot - ( first_dot + 1 ) ) );
		ZZend := TO_NUMBER( SUBSTR( version_end, second_dot + 1, third_dot - ( second_dot + 1 ) ) );
		ProjExtend := SUBSTR( version_end, third_dot + 1, LENGTH(version_end) - third_dot );

		first_dot :=  INSTR(version, '.', 1, 1);
		second_dot :=  INSTR(version, '.', 1, 2);
		third_dot :=  INSTR(version, '.', 1, 3);

		XX := TO_NUMBER( SUBSTR( version, 1, first_dot - 1 ) );
		YY := TO_NUMBER( SUBSTR( version, first_dot + 1, second_dot - ( first_dot + 1 ) ) );
		ZZ := TO_NUMBER( SUBSTR( version, second_dot + 1, third_dot - ( second_dot + 1 ) ) );
		ProjExt := SUBSTR( version, third_dot + 1, LENGTH(version) - third_dot );

		-- only include versions if all project extensions are the same
		IF ( ProjExtstart = ProjExt AND ProjExt = ProjExtend ) THEN

			IF ( VerIsGrtrThanOrEqlToStart( XXstart, XX, YYstart, YY, ZZstart, ZZ ) = 1 AND VerIsLessThanOrEqlToEnd( XXend, XX, YYend, YY, ZZend, ZZ ) = 1 ) THEN
				RETURN 1;
			ELSE
				RETURN 0;
			END IF;
		ELSE
			RETURN 0;
		END IF;

	EXCEPTION
		WHEN OTHERS THEN
			RETURN -1;
	END;

	FUNCTION GetPkgId( pkgName IN VARCHAR2 ) RETURN NUMBER
	AS
	    pkg_id NUMBER;
	BEGIN
		SELECT
			p.PKG_ID
		INTO
			pkg_id
		FROM
			PACKAGES p
		WHERE
			p.PKG_NAME = pkgName;

		RETURN pkg_id;
	EXCEPTION
	    WHEN OTHERS THEN
			dbms_output.put_line('GetPkgId exception: ' || SQLERRM );
			RETURN -1;
	END;


-- Public Implementation ------------------------------------------------------

	/*
	-- Proc: AllIssues - Gets all issues for a package from dependent packages one level deep
	--
	-- INPUT PARAMETERS:
	--
	--		pkg_name  	-  	The name of the top level package to get issues for
	--		version_start	-	The start version for the comparison
	--		version_end	-	The end version for the comparison
	*/
	PROCEDURE AllIssues( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 )
	AS
		pkgId	NUMBER;
	BEGIN
		-- get pkg_id of the input package:
		pkgId := GetPkgId( pkg_name );

		OPEN vCursor FOR
		SELECT
			  pv.PKG_ID,
			  pv.PKG_VERSION,
			  pv.PV_ID,
			  i_pkg.ISS_ID,
			  ( SELECT pkg_name FROM PACKAGES WHERE pkg_id = pd.DPKG_ID ) AS DPV_NAME,
			  pd.DPKG_ID,
			  ( SELECT pkg_version FROM PACKAGE_VERSIONS WHERE pv_id = pd.DPV_ID ) AS DPV_VER,
			  pd.DPV_ID,
			  i_dpkg.ISS_ID AS ISSUE_ID
		FROM
			 PACKAGE_VERSIONS pv
							  LEFT OUTER JOIN CQ_ISSUES i_pkg ON pv.PV_ID = i_pkg.PV_ID
							  LEFT OUTER JOIN PACKAGE_DEPENDENCIES pd ON pv.PV_ID = pd.PV_ID
							  LEFT OUTER JOIN CQ_ISSUES i_dpkg ON pd.DPV_ID = i_dpkg.PV_ID
		WHERE
   			 pv.PKG_ID = pkgId
		AND
			VersionIsBetween( pv.PKG_VERSION, version_start, version_end ) = 1
		AND
			 ( i_dpkg.ISS_ID IS NOT NULL OR i_pkg.ISS_ID IS NOT NULL )
		ORDER BY
			 pv.PKG_ID,
			 pv.PV_ID,
			 pd.DPKG_ID,
			 pd.DPV_ID;
	EXCEPTION
		WHEN OTHERS THEN
			dbms_output.put_line('AllIssues exception: ' || SQLERRM );
	END;


	-- NOTE: make RM_PACKAGE_ISSUES a temporary table when tested ok

	/*
	-- Proc: LoadIssuesTable
	--
	-- Populates Package_Issues table with details of issues from all dependent packages.
	-- This will be for all package versions of the input pkg_name between the
	-- version_start and version_end.
	--
	-- INPUT PARAMETERS:
	--
	--		pkg_name  	-  	The name of the top level package to get issues for
	--		version_start	-	The start version for the comparison
	--		version_end	-	The end version for the comparison
	*/
	PROCEDURE LoadIssuesTable( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 )
	AS
		pkgId	NUMBER;

		CURSOR pack_vers_cur IS
			SELECT
				pv.PV_ID,
				pv.PKG_VERSION,
				pv.PKG_ID,
				p.PKG_NAME
			FROM
				PACKAGE_VERSIONS pv
					JOIN PACKAGES p ON pv.PKG_ID = p.PKG_ID
			WHERE
   				 pv.PKG_ID = pkgId
			AND
				VersionIsBetween( pv.PKG_VERSION, version_start, version_end ) = 1;

	BEGIN
		DELETE FROM RELEASE_MANAGER.RM_PKG_ISSUES; /*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/

		-- get the pkg_id we are finding issues for
		pkgId := GetPkgId( pkg_name );

		-- find all the top level packages we are dealing with and recursively process their issues and their dependent package issues.
		FOR pack_ver_rec IN  pack_vers_cur
		LOOP
			InsertIssuesForDepends( pack_ver_rec.PV_ID, pack_ver_rec.PKG_ID, pack_ver_rec.PKG_NAME, pack_ver_rec.PV_ID, pack_ver_rec.PKG_VERSION );
			COMMIT;
		END LOOP;

		-- The output cursor - shows the individual versions of the top level package then were reported on
		OPEN vCursor FOR
		SELECT DISTINCT ISS_ID, PKG_VERSION FROM RM_PKG_ISSUES WHERE ISS_ID IS NOT NULL; /*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/
/*removed
		SELECT
			PKG_VERSION
		FROM
			RELEASE_MANAGER.RM_PACKAGE_ISSUES;
*/


	EXCEPTION
		WHEN OTHERS THEN
			dbms_output.put_line('LoadIssuesTable exception: ' || SQLERRM );
	END;


	/*
	-- Proc: InsertIssuesForDepends
	--
	-- Used by LoadIssuesTable to recursively find issues for all dependent packages
	--
	-- INPUT PARAMETERS:
	--
	--		pvID  		-  	The package version id of the package to get issues for
	--		top_pkgID	-  	The package id of the top level package to get issues for - should be the same as pvID when called from LoadIssuesTable (different when called recursively)
	--		top_pkgName -  	The package name of the top level package
	--		top_pvID  	-  	The package version id of the top level package
	--		top_pkgVer  -  	The package version description of the top level package
	*/
	PROCEDURE InsertIssuesForDepends( pvID IN NUMBER, top_pkgID IN NUMBER, top_pkgName IN VARCHAR2, top_pvID IN NUMBER, top_pkgVer IN VARCHAR2 )
	AS
		pkgId		NUMBER;
		issCnt		NUMBER := 0;
		pkgCheck	NUMBER := 0;
		depCheck	NUMBER := 0;

		dpkgName	VARCHAR(50);
		dpkgVersion	VARCHAR(50);

		CURSOR dep_packs_cur IS
			SELECT
				DPV_ID
			FROM
				PACKAGE_DEPENDENCIES
			WHERE
				PV_ID = pvID;

	BEGIN

		-- check to see if the package has been processed previously
		SELECT
			COUNT(*)
		INTO
			pkgCheck
		FROM
			RM_PKG_ISSUES /*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/
		WHERE
			DPV_ID = pvID;

		dbms_output.put_line('pkgCheck: ' || pkgCheck );

		-- Package not already processed (no cyclic dependency) - process it
		IF ( pkgCheck = 0 ) THEN

			-- check to see if this package version has any issues assigned to it
			SELECT
				COUNT(*)
			INTO
				issCnt
			FROM
				CQ_ISSUES i
			WHERE
				i.PV_ID = pvID;

			dbms_output.put_line('issCnt: ' || issCnt );

			-- Always enter a marker row into the table even if there are no issues for the package.
			-- This allows us to pick up any cyclic dependencies.
			IF ( issCnt > 0 ) THEN
				-- get issues and insert into RM_PACKAGE_ISSUES
				/*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/

				INSERT INTO RM_PKG_ISSUES ( PKG_ID, PKG_NAME, PV_ID, PKG_VERSION, DPV_ID, DPKG_NAME, DPKG_VERSION, ISS_DB, ISS_ID )
					SELECT DISTINCT
						top_pkgID		AS PKG_ID,
						top_pkgName		AS PKG_NAME,
						top_pvID		AS PV_ID,
						top_pkgVer		AS PKG_VERSION,
						pv.PV_ID		AS DPV_ID,
						p.PKG_NAME		AS DPKG_NAME,
						pv.PKG_VERSION	AS DPKG_VERSION,
						ci.ISS_DB,
						ci.ISS_ID
					FROM
						PACKAGE_VERSIONS pv
							JOIN PACKAGES p ON pv.PKG_ID = p.PKG_ID
							JOIN CQ_ISSUES ci ON pv.PV_ID = ci.PV_ID
					WHERE
						pv.PV_ID = pvID;

			ELSE
				-- get the dpkg details - there will always be a row returned here
				SELECT
					p.PKG_NAME
				INTO
					dpkgName
				FROM
					PACKAGE_VERSIONS pv
						JOIN PACKAGES p ON pv.PKG_ID = p.PKG_ID
				WHERE
	   				 pv.PV_ID = pvID;

				SELECT
					pv.PKG_VERSION
				INTO
					dpkgVersion
				FROM
					PACKAGE_VERSIONS pv
				WHERE
	   				 pv.PV_ID = pvID;

				-- enter a marker row
				/*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/
				INSERT INTO RM_PKG_ISSUES ( PKG_ID, PKG_NAME, PV_ID, PKG_VERSION, DPV_ID, DPKG_NAME, DPKG_VERSION, ISS_DB, ISS_ID )
				VALUES (
					top_pkgID,
					top_pkgName,
					top_pvID,
					top_pkgVer,
					pvID,
					dpkgName,
					dpkgVersion,
					NULL,
					NULL );

			END IF;

			-- If this package version has dependencies then recurse
			SELECT
				COUNT(*)
			INTO
				depCheck
			FROM
				PACKAGE_DEPENDENCIES
			WHERE
				PV_ID = pvID;

			IF ( depCheck > 0 ) THEN
				-- get dependencies and call this function recursively for each one
				FOR dep_rec IN  dep_packs_cur
				LOOP
					InsertIssuesForDepends( dep_rec.DPV_ID, top_pkgID, top_pkgName, top_pvID, top_pkgVer );
				END LOOP;

			END IF;

		END IF;

	/*EXCEPTION
		WHEN OTHERS THEN
			no exception handling required
	*/
	END;

END Rm_Issues;
/
--------------------------------------------------------
--  DDL for Procedure ADD_AUTOBUILD_FAILURE_INFO
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "ADD_AUTOBUILD_FAILURE_INFO" (
   nprojid     IN   NUMBER,
   nviewid     IN   NUMBER,
   suserlist   IN   VARCHAR2
)
IS
   groupid   NUMBER;
/******************************************************************************
   NAME:       ADD_AUTOBUILD_FAILURE
   PURPOSE:

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        11/04/2006   Rupesh Solanki Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     ADD_AUTOBUILD_FAILURE
      Sysdate:         11/04/2006
      Date and Time:   11/04/2006, 9:28:28 AM, and 11/04/2006 9:28:28 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
BEGIN
   BEGIN
      SELECT group_email_id
        INTO groupid
        FROM autobuild_failure
       WHERE proj_id = nprojid AND view_id = nviewid;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         --  Create Next Sequence Id ---
         SELECT seq_group_email_id.NEXTVAL
           INTO groupid
           FROM DUAL;

         INSERT INTO autobuild_failure
                     (group_email_id, proj_id, view_id
                     )
              VALUES (groupid, nprojid, nviewid
                     );
   END;

   add_view_members (groupid, suserlist);
END add_autobuild_failure_info;
/
--------------------------------------------------------
--  DDL for Procedure ADD_COMPONENT
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "ADD_COMPONENT" ( nPvId IN RELEASE_COMPONENTS.PV_ID%TYPE,
	   	  		  						  	sFileName IN RELEASE_COMPONENTS.FILE_NAME%TYPE,
											sFilePath IN RELEASE_COMPONENTS.FILE_PATH%TYPE DEFAULT NULL,
											nByteSize IN RELEASE_COMPONENTS.BYTE_SIZE%TYPE,
											sCRCcksum IN RELEASE_COMPONENTS.CRC_CKSUM%TYPE DEFAULT NULL,
											sCRCmodcrc IN RELEASE_COMPONENTS.CRC_MODCRC%TYPE DEFAULT NULL
                                           ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */


BEGIN

	 --- Insert into RELEASE_COMPONENTS
	 INSERT INTO RELEASE_COMPONENTS ( PV_ID, FILE_NAME, FILE_PATH, BYTE_SIZE, CRC_CKSUM, CRC_MODCRC )
	 VALUES ( nPvId, sFileName, sFilePath, nByteSize, sCRCcksum, sCRCmodcrc  );




END Add_Component;
/
--------------------------------------------------------
--  DDL for Procedure ADD_PACKAGE_INTEREST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "ADD_PACKAGE_INTEREST" (nProjId IN PROJECTS.PROJ_ID%TYPE,
	   	  		  								  nPkgIdList IN VARCHAR2,
												  nUserId IN NUMBER
	   	  		  								  ) IS

/******************************************************************************
   NAME:       ADD_PACKAGE_INTEREST
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        12/05/2006  Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     ADD_PACKAGE_INTEREST
      Sysdate:         12/05/2006
      Date and Time:   12/05/2006, 9:11:12 AM, and 12/05/2006 9:11:12 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   npkgidcollector   relmgr_number_tab_t := relmgr_number_tab_t ();
   nPkgId NUMBER;
BEGIN

	 npkgidcollector := in_list_number2 (nPkgIdList);
	 
	FOR i IN 1..npkgidcollector.COUNT
	LOOP
		nPkgId := npkgidcollector(i);

	 --- Insert into PACKAGE_INTEREST TABLE
	 INSERT INTO PACKAGE_INTEREST (PROJ_ID, PKG_ID, USER_ID)
	 VALUES(nProjId, nPkgId, nUserId);
	END LOOP;	 
	 

END ADD_PACKAGE_INTEREST;
/
--------------------------------------------------------
--  DDL for Procedure ADD_PACKAGE_INTEREST_TEST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "ADD_PACKAGE_INTEREST_TEST" (nProjId IN PROJECTS.PROJ_ID%TYPE,
	   	  		  								  nPkgIdList IN VARCHAR2,
												  nUserId IN NUMBER
	   	  		  								  ) IS

/******************************************************************************
   NAME:       ADD_PACKAGE_INTEREST
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        12/05/2006  Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     ADD_PACKAGE_INTEREST
      Sysdate:         12/05/2006
      Date and Time:   12/05/2006, 9:11:12 AM, and 12/05/2006 9:11:12 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   npkgidcollector   relmgr_number_tab_t := relmgr_number_tab_t ();
   nPkgId NUMBER;
BEGIN

	 npkgidcollector := in_list_number2 (nPkgIdList);
	 
	FOR i IN 1..npkgidcollector.COUNT
	LOOP
		nPkgId := npkgidcollector(i);

	 --- Insert into PACKAGE_INTEREST TABLE
	 INSERT INTO PACKAGE_INTEREST (PROJ_ID, PKG_ID, USER_ID)
	 VALUES(nProjId, nPkgId, nUserId);
	END LOOP;	 
	 

END ADD_PACKAGE_INTEREST_TEST;
/
--------------------------------------------------------
--  DDL for Procedure ADD_RUNTIME_DEPENDENCY
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "ADD_RUNTIME_DEPENDENCY" ( NNpv_id IN NUMBER,
                                                     SSrtd_name IN PACKAGES.pkg_name%TYPE,
                                                     SSrtd_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
                                                     NNuser_id IN NUMBER
                                                    ) IS
/* ---------------------------------------------------------------------------
    Version: 3.1
   --------------------------------------------------------------------------- */

    retRTD_ID NUMBER;

	CURSOR rtd_cur IS
        SELECT rtd_id FROM runtime_dependencies WHERE pv_id = NNpv_id AND rtd_id = retRTD_ID;
    rtd_rec rtd_cur%ROWTYPE;

BEGIN
    --- Seed database with package_name and version if required ---
    Seed_Package_Names_Versions ( SSrtd_name, SSrtd_version, NNuser_id, retRTD_ID );

	OPEN rtd_cur;
    FETCH rtd_cur INTO rtd_rec;

    IF rtd_cur%NOTFOUND
    THEN
		/* Make sure it does not exists already as runtime dependency */

		--- Add new Runtime Dependency ---
	    INSERT INTO runtime_dependencies ( pv_id, rtd_id, mod_date, mod_user )
	    VALUES (  NNpv_id, retRTD_ID, ORA_SYSDATE , NNuser_id );

    	/* LOG ACTION */
        Log_Action ( NNpv_id, 'runtime_add', NNuser_id,
    			     'Runtime package: '|| SSrtd_name ||' '|| SSrtd_version );

	END IF;


END Add_Runtime_Dependency;
/
--------------------------------------------------------
--  DDL for Procedure ADD_VIEW_MEMBERS
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "ADD_VIEW_MEMBERS" (nGroupId IN NUMBER, sUserList IN VARCHAR2) IS

/******************************************************************************
   NAME:       ADD_VIEW_MEMBERS
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        11/04/2006          1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     ADD_VIEW_MEMBERS
      Sysdate:         11/04/2006
      Date and Time:   11/04/2006, 9:52:58 AM, and 11/04/2006 9:52:58 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
CURSOR user_cur IS
	SELECT u.USER_ID
	  FROM USERS u
	 WHERE u.USER_ID IN (
	 	   			   	SELECT * 
						  FROM THE ( SELECT CAST( IN_LIST_NUMBER( sUserList ) AS RELMGR_NUMBER_TAB_t ) FROM dual ) 
						);
user_rec user_cur%ROWTYPE;


BEGIN

	 OPEN user_cur;
	 FETCH user_cur INTO user_rec;
	 
	 WHILE user_cur%FOUND
	 LOOP
	 	 INSERT INTO MEMBERS_GROUP (GROUP_EMAIL_ID, USER_ID)
	 	 VALUES ( nGroupId, user_rec.USER_ID);
	 	 
	 	 FETCH user_cur INTO user_rec;	 
	 END LOOP;	 
	 	 
		 
		 
END ADD_VIEW_MEMBERS;
/
--------------------------------------------------------
--  DDL for Procedure BASIC_CLONE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "BASIC_CLONE" ( nFROMpv_id IN NUMBER,
                        nTOpv_id IN NUMBER,
                        nRtag_id IN NUMBER,
                        nUser_id IN NUMBER,
                        nTOpkg_id IN NUMBER DEFAULT NULL,
                        enumISSUES_STATE_IMPORTED IN NUMBER DEFAULT NULL ) IS

   FromVersion PACKAGE_VERSIONS.PKG_VERSION%TYPE;
   major NUMBER;
   minor NUMBER;
   patch NUMBER;
   buildn NUMBER;
   from_vcs_type_id NUMBER;
BEGIN
------------------------------ Version Control System ------------------------------------------
   SELECT vcs_type_id
      INTO from_vcs_type_id
      FROM package_versions WHERE pv_id = nFROMpv_id;

   UPDATE package_versions
      SET vcs_type_id = from_vcs_type_id
      WHERE pv_id = nTOpv_id;
------------------------------------- Limits ---------------------------------------------------
   select major_limit, minor_limit, patch_limit, build_number_limit
   into major, minor, patch, buildn
   from package_versions where pv_id=nFROMpv_id;
    UPDATE package_versions SET
           major_limit = major,
           minor_limit = minor,
           patch_limit = patch,
           build_number_limit = buildn
     WHERE PV_ID = nTOpv_id;
------------------------------------- Clone Dependencies ---------------------------------------------------
   IF NOT nRtag_id IS NULL
   THEN
      -- Auto Update Dependencies --
      INSERT INTO PACKAGE_DEPENDENCIES
           SELECT nTOpv_id AS pv_id,
                  DECODE(nUser_id,
                         frc.modifier_id,
                         frc.pv_id,
                         DECODE(frc.dlocked,
                                'Y',
                                frc.pv_id,
                                dep.dpv_id)
                         ) AS dpv_id,
                  nTOpkg_id AS pkg_id,
                  dep.dpkg_id,
                  dep.build_type,
                  dep.display_order
             FROM PACKAGE_DEPENDENCIES dep,
                  PACKAGE_VERSIONS pv,
                  (
                  /* Full Release Contents used for reference*/
                  SELECT rpv.pv_id, rpv.pkg_id, NVL(rpv.v_ext, '|LINK_A_NULL|') AS v_ext, rpv.modifier_id, rpv.dlocked
                  FROM RELEASE_CONTENT rel, PACKAGE_VERSIONS rpv
                  WHERE rel.pv_id = rpv.pv_id AND rtag_id = nRtag_id
                  ) frc
            WHERE dep.pv_id = nFROMpv_id
              AND dep.dpv_id = pv.pv_id
              AND pv.pkg_id = frc.pkg_id(+)
              AND NVL(pv.v_ext, '|LINK_A_NULL|') = frc.v_ext(+);
   ELSE
      -- Clone Dependencies --
      INSERT INTO PACKAGE_DEPENDENCIES
           SELECT nTOpv_id         AS pv_id,
                  dep.dpv_id,
                  nTOpkg_id        AS pkg_id,
                  dep.dpkg_id,
                  dep.build_type,
                  dep.display_order
             FROM PACKAGE_DEPENDENCIES dep
            WHERE dep.pv_id = nFROMpv_id;

   END IF;

----------------------------------------- Clone Issues -------------------------------------------------------
   IF enumISSUES_STATE_IMPORTED IS NULL
   THEN
        /* All Issues */
       INSERT INTO CQ_ISSUES ( pv_id, iss_db, iss_id, iss_state, mod_date, notes )
            SELECT nTOpv_id AS pv_id, iss_db, iss_id, iss_state, mod_date, notes
              FROM CQ_ISSUES
             WHERE pv_id = nFROMpv_id;
   ELSE
       /* Outstanding Issues Only */
       INSERT INTO CQ_ISSUES ( pv_id, iss_db, iss_id, iss_state, mod_date, notes )
            SELECT nTOpv_id AS pv_id, iss_db, iss_id, iss_state, mod_date, notes
              FROM CQ_ISSUES
             WHERE pv_id = nFROMpv_id
               AND iss_state = enumISSUES_STATE_IMPORTED;
   END IF;

------------------------------------ Clone Runtime Dependencies -----------------------------------------------
   INSERT INTO RUNTIME_DEPENDENCIES (pv_id, rtd_id, rtd_url, rtd_comments, mod_date, mod_user)
       SELECT nTOpv_id AS pv_id, rtd_id, rtd_url, rtd_comments, mod_date, mod_user
       FROM RUNTIME_DEPENDENCIES WHERE pv_id = nFROMpv_id;

--------------------------------------- Clone Additional Notes ------------------------------------------------
   INSERT INTO ADDITIONAL_NOTES ( NOTE_ID, PV_ID, NOTE_TITLE, NOTE_BODY, MOD_DATE, MOD_USER )
        SELECT an.NOTE_ID,
               nTOpv_id AS PV_ID,
               an.NOTE_TITLE,
               an.NOTE_BODY,
               an.MOD_DATE,
               an.MOD_USER
          FROM ADDITIONAL_NOTES an
         WHERE an.PV_ID = nFROMpv_id;

-------------------------------------------- Clone Unit Tests -------------------------------------------------
   -- Clone only Automatic unit tests --
   INSERT INTO UNIT_TESTS (
                           TEST_ID,
                           PV_ID,
                           TEST_TYPES_FK,
                           TEST_SUMMARY,
                           COMPLETION_DATE,
                           COMPLETED_BY,
                           RESULTS_URL,
                           RESULTS_ATTACHMENT_NAME,
                           NUMOF_TEST
                          )
        SELECT ut.TEST_ID,
               nTOpv_id AS PV_ID,
               ut.TEST_TYPES_FK,
               ut.TEST_SUMMARY,
               Ora_Sysdate AS COMPLETION_DATE,
               nUser_id AS COMPLETED_BY,
               ut.RESULTS_URL,
               ut.RESULTS_ATTACHMENT_NAME,
               ut.NUMOF_TEST
          FROM UNIT_TESTS ut
         WHERE ut.PV_ID = nFROMpv_id
           AND ut.TEST_TYPES_FK IN ( 5, 7 );

    -- Clone only Interactive Unit Tests --
    INSERT INTO UNIT_TESTS (
                            TEST_ID,
                            PV_ID,
                            TEST_TYPES_FK,
                            TEST_SUMMARY
                           )
       SELECT ut.TEST_ID,
              nTOpv_id AS PV_ID,
              ut.TEST_TYPES_FK,
              ut.TEST_SUMMARY
         FROM UNIT_TESTS ut
        WHERE ut.PV_ID = nFROMpv_id
          AND ut.TEST_TYPES_FK IN (6);

-------------------------------------------- Clone Package Documents ------------------------------------------
   INSERT INTO PACKAGE_DOCUMENTS ( PV_ID, TEST_ID, DOC_NUM, DOC_ID, IS_LATEST )
        SELECT nTOpv_id AS PV_ID,
               pd.test_id,
               pd.doc_num,
               pd.doc_id,
               pd.IS_LATEST
          FROM PACKAGE_DOCUMENTS pd
         WHERE pd.PV_ID = nFROMpv_id;

-------------------------------------------- Clone Build Environments -----------------------------------------
    INSERT INTO PACKAGE_BUILD_ENV ( PV_ID, BE_ID, BUILD_TYPE )
    SELECT nTOpv_id AS PV_ID,
           pkgbe.BE_ID,
           pkgbe.BUILD_TYPE
      FROM PACKAGE_BUILD_ENV pkgbe
     WHERE pkgbe.PV_ID = nFROMpv_id;
---------------------------------------------Clone Package Build Info------------------------------------------
    INSERT INTO PACKAGE_BUILD_INFO (PV_ID, BM_ID, BSA_ID)
    SELECT nTOpv_id AS PV_ID,
           pkgbinfo.BM_ID,
           pkgbinfo.BSA_ID
      FROM PACKAGE_BUILD_INFO pkgbinfo
     WHERE pkgbinfo.PV_ID = nFROMpv_id;
---------------------------------------------Clone Package Version Processes-----------------------------------
    INSERT INTO PACKAGE_PROCESSES ( PV_ID, PROC_ID )
    SELECT nTOpv_id AS PV_ID,
           pp.PROC_ID
      FROM PACKAGE_PROCESSES pp
     WHERE pp.PV_ID = nFROMpv_id;
---------------------------------------------Clone Licencing Associations-----------------------------------
    PK_LICENCING.CLONE_LICENCING(nFROMpv_id, nTOpv_id, nUser_id);
---------------------------------------------------------------------------------------------------------------

    /* LOG ACTION */
    SELECT pv.PKG_VERSION INTO FromVersion
      FROM PACKAGE_VERSIONS pv
     WHERE pv.PV_ID = nFROMpv_id;

    Log_Action ( nTOpv_id, 'clone_from', nUser_id,
                 'Details cloned from: '|| FromVersion );

---------------------------------------------------------------------------------------------------------------

END Basic_Clone;
/
--------------------------------------------------------
--  DDL for Procedure BUILD_TREE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "BUILD_TREE" ( nRtag_id IN NUMBER,
	   	  		  					     retSessionNum OUT NUMBER ) IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */
    rowCnt 			NUMBER := 0;						-- Iterations counter
    iteration 		NUMBER := 1;                  -- Maximum number of iterations allowed.
    maxIterations 	NUMBER := 50;      	  	-- This will prevent infinite loops if cyrcular dependencies are found
	UP_THE_TREE 	CONSTANT NUMBER DEFAULT 1;
	DOWN_THE_TREE 	CONSTANT NUMBER DEFAULT -1;
    sessionNum 		NUMBER;
	levelNum		NUMBER;
	
BEGIN
    SELECT SEQ_session_num.nextval INTO sessionNum FROM DUAL;
	
	/*
	||	   Start UP THE TREE
	*/
	
	
	/* Packages with no dependencies */    
    INSERT INTO TEMP_TREE_BROWSE (SESSION_NUM, LEVEL_NUM, DIRECTION, PV_ID, PKG_ID, V_EXT )
		SELECT sessionNum AS SESSION_NUM,
			   iteration AS LEVEL_NUM,
			   UP_THE_TREE AS DIRECTION,
			   rc.pv_id, pv.pkg_id, pv.v_ext
		  FROM release_content rc,
		  	   package_versions pv
		 WHERE rc.rtag_id = nRtag_id
		   AND rc.pv_id = pv.pv_id
		 MINUS
		SELECT sessionNum AS SESSION_NUM, 
			   iteration AS LEVEL_NUM,
			   UP_THE_TREE AS DIRECTION,
			   dep.pv_id, pv.pkg_id, pv.v_ext
		  FROM package_dependencies dep,
		  	   package_versions pv
		 WHERE dep.pv_id IN ( SELECT pv_id FROM release_content WHERE rtag_id = nRtag_id )
		   AND dep.pv_id = pv.pv_id;
		   
		   
	/* Browse UP the build tree */	   
	iteration := iteration + 1;
    LOOP
        
		INSERT INTO TEMP_TREE_BROWSE (SESSION_NUM, LEVEL_NUM, DIRECTION, PV_ID, PKG_ID, V_EXT )
			SELECT DISTINCT 
			       sessionNum AS SESSION_NUM,
			       iteration AS LEVEL_NUM,
				   UP_THE_TREE AS DIRECTION, 
				   rdep.pv_id, rdep.pkg_id, rdep.v_ext
			  FROM (  
			        SELECT dep.pv_id, pv.pkg_id, pv.v_ext, dep.dpv_id, dpv.pkg_id AS dpkg_id, dpv.v_ext AS dv_ext
			          FROM package_dependencies dep,
			               release_content rc,
						   package_versions pv,
						   package_versions dpv
			         WHERE dep.pv_id = rc.pv_id
			           AND rc.rtag_id = nRtag_id
					   AND dep.pv_id = pv.pv_id
					   AND dep.dpv_id = dpv.pv_id
					) rdep,
					temp_tree_browse ttb
			 WHERE rdep.dpkg_id  = ttb.pkg_id
			   AND NVL(rdep.dv_ext ,'|LINK_A_NULL|') = NVL(ttb.v_ext,'|LINK_A_NULL|')
			   AND ttb.SESSION_NUM = sessionNum
			   AND ttb.LEVEL_NUM = iteration - 1	
			MINUS
			/* Packages with all depencencies NOT matched */  
			SELECT DISTINCT 
			       sessionNum AS SESSION_NUM,
			       iteration AS LEVEL_NUM, 
				   UP_THE_TREE AS DIRECTION,
				   rdep.pv_id, rdep.pkg_id, rdep.v_ext
			  FROM (  
			        SELECT dep.pv_id, pv.pkg_id, pv.v_ext, dep.dpv_id, dpv.pkg_id AS dpkg_id, dpv.v_ext AS dv_ext
			          FROM package_dependencies dep,
			               release_content rc,
						   package_versions pv,
						   package_versions dpv
			         WHERE dep.pv_id = rc.pv_id
			           AND rc.rtag_id = nRtag_id
					   AND dep.pv_id = pv.pv_id
					   AND dep.dpv_id = dpv.pv_id
					) rdep,
					(
					 SELECT tb.*
					   FROM temp_tree_browse tb
					  WHERE tb.SESSION_NUM = sessionNum
					) ttb
			 WHERE rdep.dpkg_id  = ttb.pkg_id (+)
			   AND NVL(rdep.dv_ext ,'|LINK_A_NULL|') = NVL(ttb.v_ext (+),'|LINK_A_NULL|')
			   AND ttb.SESSION_NUM IS NULL;
		
		rowCnt := SQL%ROWCOUNT;
		IF rowCnt > 0 THEN
           iteration := iteration + 1;
		END IF;
        EXIT WHEN (rowCnt < 1) OR (iteration > maxIterations);
    END LOOP;
	
	/*---------------------------------------------------------------------------------------------------------------------*/
	
	/*     Check for unresolved dependencies
	||  
	*/
	/* UNRESOLVED */
	 SELECT COUNT(*) INTO rowCnt
	   FROM (
			 SELECT pv.pv_id, pv.pkg_id, pv.v_ext
			  FROM release_content rc,
			  	   package_versions pv
			 WHERE rc.rtag_id = nRtag_id
			   AND rc.pv_id = pv.pv_id	   
			MINUS
			SELECT ttb.pv_id, ttb.pkg_id, ttb.v_ext
			  FROM temp_tree_browse ttb
			 WHERE ttb.session_num = sessionNum
			);
				
	 
			  
	 IF rowCnt > 0 
	 THEN
	 	 /*     Circular dependencies detected.
		 ||     Try to resolve build order from the top now.
		 ||		Start DOWN THE TREE
		 */
		 
		iteration := 0; 
		 /* Top Level packages */	
		INSERT INTO TEMP_TREE_BROWSE (SESSION_NUM, LEVEL_NUM, DIRECTION, PV_ID, PKG_ID, V_EXT )	   
			SELECT sessionNum AS SESSION_NUM,
			       iteration AS LEVEL_NUM,
				   DOWN_THE_TREE AS DIRECTION,
				   pv.pv_id, pv.pkg_id, pv.v_ext
			  FROM (		   
					/* Packages no one depends on ( Top level packages )*/
					( 
					/* All parents*/ 
					SELECT pv.pkg_id, pv.v_ext
			          FROM package_dependencies dep,
			               release_content rc,
						   package_versions pv
			         WHERE dep.pv_id = rc.pv_id
			           AND rc.rtag_id = nRtag_id
					   AND dep.pv_id = pv.pv_id
					 MINUS
					 /* All children */
					SELECT dpv.pkg_id, dpv.v_ext
			          FROM package_dependencies dep,
			               release_content rc,
						   package_versions dpv
			         WHERE dep.pv_id = rc.pv_id
			           AND rc.rtag_id = nRtag_id
					   AND dep.dpv_id = dpv.pv_id
					 ) 
					 MINUS
					/* Packages with resolved dependencies from UP THE TREE */ 
					SELECT ttb.pkg_id, ttb.v_ext
					  FROM temp_tree_browse ttb
					 WHERE ttb.session_num = sessionNum
				  ) tpkg,
				  package_versions pv,
				  release_content rc
			WHERE rc.rtag_id = nRtag_id
			  AND rc.pv_id = pv.pv_id
			  AND tpkg.pkg_id = pv.pkg_id
			  AND NVL(tpkg.v_ext,'|LINK_A_NULL|') = NVL(pv.v_ext,'|LINK_A_NULL|');
		
		
		 /* Keep taking packages which no one depende on */			  
		 iteration := iteration - 1;  
		 LOOP	  
			   INSERT INTO TEMP_TREE_BROWSE (SESSION_NUM, LEVEL_NUM, DIRECTION, PV_ID, PKG_ID, V_EXT )
					SELECT sessionNum AS SESSION_NUM,
					       iteration AS LEVEL_NUM,
					       DOWN_THE_TREE AS DIRECTION,
					       pv.pv_id, pv.pkg_id, pv.v_ext
					  FROM (		   
					 	/* All Unresolved */
					 	(
					 	SELECT pv.pkg_id, pv.v_ext
					 	  FROM release_content rc,
					 	  	   package_versions pv
					 	 WHERE rc.rtag_id = nRtag_id
					 	   AND rc.pv_id = pv.pv_id	   
					 	MINUS
					 	SELECT ttb.pkg_id, ttb.v_ext
					 	  FROM temp_tree_browse ttb
					 	 WHERE ttb.session_num = sessionNum
					 	)
					 	 MINUS
					 	(  
					 	 /* Children of Unresolved */  
					 	SELECT dpv.pkg_id, dpv.V_EXT
					 	  FROM (
					 			SELECT pv.pv_id, pv.pkg_id, pv.v_ext
					 			  FROM release_content rc,
					 			  	   package_versions pv
					 			 WHERE rc.rtag_id = nRtag_id
					 			   AND rc.pv_id = pv.pv_id	   
					 			MINUS
					 			SELECT ttb.pv_id, ttb.pkg_id, ttb.v_ext
					 			  FROM temp_tree_browse ttb
					 			 WHERE ttb.session_num = sessionNum
					 		   ) unr,
					 		   package_dependencies dep,
					 		   package_versions dpv
					 	 WHERE unr.pv_id = dep.pv_id
					 	   AND dep.dpv_id = dpv.pv_id
					 	 )  
					   ) tpkg,
					   package_versions pv,
					   release_content rc
					WHERE rc.rtag_id = nRtag_id
					  AND rc.pv_id = pv.pv_id
					  AND tpkg.pkg_id = pv.pkg_id
					  AND NVL(tpkg.v_ext,'|LINK_A_NULL|') = NVL(pv.v_ext,'|LINK_A_NULL|');
					  
            rowCnt := SQL%ROWCOUNT;
        	IF rowCnt > 0 THEN
	           iteration := iteration - 1;
			END IF;
            EXIT WHEN (rowCnt < 1);
     	END LOOP;
		
	 END IF;
	 
	 
	/*---------------------------------------------------------------------------------------------------------------------*/
	
	/* 
	|| 	 Save results from temp table
	*/	
	/* Clean up build_order table */
	DELETE FROM BUILD_ORDER WHERE rtag_id = nRtag_id;
	
	/* Save UP THE TREE */
	INSERT INTO BUILD_ORDER ( RTAG_ID, STEP_NUM, PV_ID )
		SELECT nRtag_id AS rtag_id,
			   ttb.level_num AS step_num, 
			   ttb.PV_ID
		  FROM temp_tree_browse ttb
		 WHERE ttb.session_num = sessionNum
		   AND ttb.direction = UP_THE_TREE;	
		   
	/*Get last step_num */
	SELECT MAX(ttb.level_num) + 1 INTO levelNum
	FROM temp_tree_browse ttb WHERE ttb.session_num = sessionNum AND ttb.DIRECTION = UP_THE_TREE;
	
	/* UNRESOLVED */
	 SELECT COUNT(*) INTO rowCnt
	   FROM (
			 SELECT pv.pv_id, pv.pkg_id, pv.v_ext
			  FROM release_content rc,
			  	   package_versions pv
			 WHERE rc.rtag_id = nRtag_id
			   AND rc.pv_id = pv.pv_id	   
			MINUS
			SELECT ttb.pv_id, ttb.pkg_id, ttb.v_ext
			  FROM temp_tree_browse ttb
			 WHERE ttb.session_num = sessionNum
			);
	
			
	IF rowCnt > 0
	THEN
		/* Save unresolved packages */
 		INSERT INTO BUILD_ORDER ( RTAG_ID, STEP_NUM, PV_ID, UNRESOLVED )
		    SELECT  nRtag_id AS rtag_id,
				    levelNum AS step_num, 
				    upv.PV_ID,
					'Y' AS UNRESOLVED
			   FROM (
					 SELECT pv.pv_id, pv.pkg_id, pv.v_ext
					  FROM release_content rc,
					  	   package_versions pv
					 WHERE rc.rtag_id = nRtag_id
					   AND rc.pv_id = pv.pv_id	   
					MINUS
					SELECT ttb.pv_id, ttb.pkg_id, ttb.v_ext
					  FROM temp_tree_browse ttb
					 WHERE ttb.session_num = sessionNum
					) upv;
	END IF;	
			
	/* Save DOWN THE TREE */
	levelNum := 1000;
	INSERT INTO BUILD_ORDER ( RTAG_ID, STEP_NUM, PV_ID )
		SELECT nRtag_id AS rtag_id,
			   levelNum + ttb.level_num  AS step_num, 
			   ttb.PV_ID
		  FROM temp_tree_browse ttb
		 WHERE ttb.session_num = sessionNum
		   AND ttb.direction = DOWN_THE_TREE;
	
	
	/*---------------------------------------------------------------------------------------------------------------------*/
	
	/* Clean up temp table */
	DELETE FROM TEMP_TREE_BROWSE WHERE session_num = sessionNum;
	
	retSessionNum := sessionNum;
END Build_Tree;
/
--------------------------------------------------------
--  DDL for Procedure CHANGE_PACKAGE_STATE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CHANGE_PACKAGE_STATE" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
											 nRtagId IN RELEASE_TAGS.RTAG_ID%TYPE ) IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

BEGIN

    -- Unlock Package
    UPDATE RELEASE_CONTENT rc SET
    	rc.PKG_STATE = 0
    WHERE rc.PV_ID = nPvId
	AND rc.RTAG_ID = nRtagId;

    /* LOG ACTION */
   /*	Log_Action ( nPvId, 'unlock_package', nUserId );*/

END Change_Package_State;
/
--------------------------------------------------------
--  DDL for Procedure CHANGE_RELEASE_MODE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CHANGE_RELEASE_MODE" ( nModeCode IN NUMBER, nRtagId IN NUMBER, UserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

	cMode CHAR(1) := NULL;  
	nProjId NUMBER; 

BEGIN
	 

	/*
	Author: Rupesh Solanki
	Modified: 24th October 2006
	Reason: Added the archive mode state into Release Manager 
	||	1 - Open Mode
	||	2 - Restrictive Mode
	||	3 - Closed Mode
	||	4 - CCB Mode
	||	5 - Archive Mode
	*/	
	-- Get project Id
	SELECT rt.PROJ_ID INTO nProjId
	  FROM RELEASE_TAGS rt
	 WHERE rt.RTAG_ID = nRtagId; 
	
	IF nModeCode = 1 THEN
		-- Open Mode
		cMode := 'N';
		
		/* LOG ACTION */
   		Log_Project_Action ( nProjId, 'set_to_open_mode', UserId, 'Release is set to Open Mode', nRtagId );
		
	ELSIF nModeCode = 2 THEN
		-- Restrictive Mode
		cMode := 'R';
		
		/* LOG ACTION */
   		Log_Project_Action ( nProjId, 'set_to_restrictive_mode', UserId, 'Release is set to Restrictive Mode', nRtagId );
		
	ELSIF nModeCode = 3 THEN
		-- Closed Mode
		cMode := 'Y';
		
		/* LOG ACTION */
   		Log_Project_Action ( nProjId, 'set_to_closed_mode', UserId, 'Release is set to Closed Mode', nRtagId  );

	ELSIF nModeCode = 4 THEN
		-- CCB Mode
		cMode := 'C';
		
		/* LOG ACTION */
   		Log_Project_Action ( nProjId, 'set_to_ccb_mode', UserId, 'Release is set to CCB Mode', nRtagId  );
	
	ELSIF nModeCode = 5 THEN
		-- Archive Mode
		cMode := 'A';
		
		/* LOG ACTION */
   		Log_Project_Action ( nProjId, 'set_to_archive_mode', UserId, 'Release is set to Archive Mode', nRtagId  );	
				
		
	END IF;
	
	
	
	-- Now update table
	IF NOT cMode IS NULL THEN
		UPDATE RELEASE_TAGS rt SET
		rt.OFFICIAL = cMode
		WHERE rt.RTAG_ID = nRtagId;
		
	END IF;


END CHANGE_RELEASE_MODE;
/
--------------------------------------------------------
--  DDL for Procedure CHECK_NEW_PATCHES
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CHECK_NEW_PATCHES" (
   nrtagid   IN   release_content.rtag_id%TYPE
)
IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */
BEGIN
   /*--------------- Business Rules Here -------------------*/
   /*IF nRtagId NOT IN (SELECT RTAG_ID FROM RELEASE_TAGS ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Please contact the person in charge of Release Manager now.' );
   END IF

   /*-------------------------------------------------------*/
   UPDATE release_content rc
      SET rc.pkg_state = 5                          -- enumPKG_STATE_NEW_PATCH
    WHERE rc.pv_id IN (
             SELECT prod.pv_id
               FROM (SELECT   pp.pv_id AS orig_parent_id,
                              COUNT (*) AS num_of_patches
                         FROM release_content rc, package_patches pp
                        WHERE rc.pv_id = pp.pv_id AND rc.rtag_id = nrtagid
                     GROUP BY pp.pv_id) orig,
                    (SELECT   prodpp.pv_id, pp.pv_id AS parent_id,
                              COUNT (*) AS num_of_patches
                         FROM release_content rc,
                              package_patches pp,
                              package_dependencies dep,
                              package_versions pv,
                              package_patches prodpp
                        WHERE rc.pv_id = pp.pv_id
                          AND rc.rtag_id = nrtagid
                          AND pp.patch_id = dep.dpv_id
                          AND dep.pv_id = pv.pv_id
                          AND pv.is_patch = 'Y'
                          AND pv.dlocked = 'Y'
                          AND prodpp.patch_id = dep.pv_id
                     GROUP BY prodpp.pv_id, pp.pv_id) prod,
                    release_content rc
              WHERE orig.orig_parent_id = prod.pv_id
                AND orig.num_of_patches != prod.num_of_patches
                AND rc.rtag_id = nrtagid
                AND rc.pv_id = prod.pv_id
                AND rc.pkg_state = 0
             UNION
             SELECT   prodpp.pv_id
                 FROM release_content rc,
                      package_patches pp,
                      package_dependencies dep,
                      package_versions pv,
                      package_patches prodpp
                WHERE rc.pv_id = pp.pv_id
                  AND rc.rtag_id = nrtagid
                  AND pp.patch_id = dep.dpv_id
                  AND dep.pv_id = pv.pv_id
                  AND pv.is_patch = 'Y'
                  AND pv.dlocked = 'Y'
                  AND prodpp.patch_id = dep.pv_id
             GROUP BY prodpp.pv_id, pp.pv_id
             MINUS
             SELECT   pp.pv_id
                 FROM release_content rc, package_patches pp
                WHERE rc.pv_id = pp.pv_id AND rc.rtag_id = nrtagid
             GROUP BY pp.pv_id);
END check_new_patches;
/
--------------------------------------------------------
--  DDL for Procedure CLEAN_ADVISORY_RIPPLE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CLEAN_ADVISORY_RIPPLE" (nrtagid IN NUMBER)
IS
/******************************************************************************
   NAME:       clean_advisory_ripple

   PURPOSE:    To delete entries from the advisory_ripple table based upon
               an RTAG_ID only

               This is a tidy-up operation performed against the advisory_ripple
               table, ensuring that the table does not have rtag_id/pv_id
               combinations that cannot be found in the release's wip/pending/release
               tabs.

******************************************************************************/
BEGIN
   -- Delete any invalid rtag_id/pv_id combination from the advisory_ripple table.
   -- An invalid rtag_id/pv_id combination is one that cannot be found in the
   -- work_in_progress, planned, or release_content table.
   -- NOTE: Planned operations that represent pending additive/subtractive merge
   -- operations are ignored because they have not been approved yet and so
   -- cannot be said to be "in the release".
   DELETE FROM advisory_ripple
         WHERE rtag_id = nrtagid
           AND pv_id not in
               ((SELECT pv_id FROM release_content WHERE rtag_id = nrtagid)
                 UNION
                (SELECT pv_id FROM work_in_progress WHERE rtag_id = nrtagid)
                 UNION
                (SELECT pv_id FROM planned WHERE rtag_id = nrtagid AND (operation is null OR operation = 'R'))
               );
END clean_advisory_ripple;
/
--------------------------------------------------------
--  DDL for Procedure CLEAN_DO_NOT_RIPPLE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CLEAN_DO_NOT_RIPPLE" (nrtagid IN NUMBER)
IS
/******************************************************************************
   NAME:       clean_do_not_ripple

   PURPOSE:    To delete entries from the do_not_ripple table based upon
               an RTAG_ID only

               This is a tidy-up operation performed against the do_not_ripple
               table, ensuring that the table does not have rtag_id/pv_id
               combinations that cannot be found in the release's wip/pending/release
               tabs.

******************************************************************************/
BEGIN
   -- Delete any invalid rtag_id/pv_id combination from the do_not_ripple table.
   -- An invalid rtag_id/pv_id combination is one that cannot be found in the
   -- work_in_progress, planned, or release_content table.
   -- NOTE: Planned operations that represent pending additive/subtractive merge
   -- operations are ignored because they have not been approved yet and so
   -- cannot be said to be "in the release".
   DELETE FROM do_not_ripple
         WHERE rtag_id = nrtagid
           AND pv_id not in
               ((SELECT pv_id FROM release_content WHERE rtag_id = nrtagid)
                 UNION
                (SELECT pv_id FROM work_in_progress WHERE rtag_id = nrtagid)
                 UNION
                (SELECT pv_id FROM planned WHERE rtag_id = nrtagid AND (operation is null OR operation = 'R'))
               );
END clean_do_not_ripple;
/
--------------------------------------------------------
--  DDL for Procedure CLEAR_ADVISORY_RIPPLE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CLEAR_ADVISORY_RIPPLE" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
	   	  		  							   nRtagId IN RELEASE_TAGS.RTAG_ID%TYPE,
											 nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

BEGIN

    -- Clear Advisory Ripple Package
    DELETE FROM ADVISORY_RIPPLE
	WHERE PV_ID = nPvId
	AND RTAG_ID = nRtagId;

    /* LOG ACTION */
   	Log_Action ( nPvId, 'clear_advisory_ripple', nUserId );
	
	/*Rebuild_Environment(nRtagId);*/

END Clear_Advisory_Ripple;
/
--------------------------------------------------------
--  DDL for Procedure CLONED_PACKAGE_PROCESSES
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CLONED_PACKAGE_PROCESSES" 
IS

proc_id NUMBER;
/******************************************************************************
   NAME:       DELETE_DO_NOT_RIPPLE
   PURPOSE:    TO DELETE ENTRIES FROM THE DO_NOT_RIPPLE TABLE WHEN A PACKAGE
               IS RELEASED

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        21/04/2006  Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     DELETE_DO_NOT_RIPPLE
      Sysdate:         21/04/2006
      Date and Time:   21/04/2006, 3:21:55 PM, and 21/04/2006 3:21:55 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   CURSOR ripple_cur
   IS
      select distinct proc_id, prod_id from deployment_manager.processes_config;

   ripple_rec   ripple_cur%ROWTYPE;
BEGIN
   OPEN ripple_cur;

   FETCH ripple_cur
    INTO ripple_rec;

   WHILE ripple_cur%FOUND
   LOOP
   

   
insert into package_processes (PROC_ID, PV_ID) 
values( ripple_rec.proc_id, ripple_rec.prod_id);

      FETCH ripple_cur
       INTO ripple_rec;
   END LOOP;
END CLONED_PACKAGE_PROCESSES;
/
--------------------------------------------------------
--  DDL for Procedure CLONED_PROCESSES
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "CLONED_PROCESSES" 
IS

proc_id NUMBER;
/******************************************************************************
   NAME:       DELETE_DO_NOT_RIPPLE
   PURPOSE:    TO DELETE ENTRIES FROM THE DO_NOT_RIPPLE TABLE WHEN A PACKAGE
               IS RELEASED

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        21/04/2006  Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     DELETE_DO_NOT_RIPPLE
      Sysdate:         21/04/2006
      Date and Time:   21/04/2006, 3:21:55 PM, and 21/04/2006 3:21:55 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   CURSOR ripple_cur
   IS
      select distinct pkg_health_tag, cmd_interface, pkg_owner, is_interface from deployment_manager.processes_config;

   ripple_rec   ripple_cur%ROWTYPE;
BEGIN
   OPEN ripple_cur;

   FETCH ripple_cur
    INTO ripple_rec;

   WHILE ripple_cur%FOUND
   LOOP
   
   select deployment_manager.seq_proc_id.nextval into proc_id from dual;
   
insert into processes (PROC_ID, PROC_NAME, RUN_AS, PKG_OWNER, IS_INTERFACE) 
values(proc_id, ripple_rec.pkg_health_tag, ripple_rec.cmd_interface, ripple_rec.pkg_owner, ripple_rec.is_interface);

      FETCH ripple_cur
       INTO ripple_rec;
   END LOOP;
END CLONED_PROCESSES;
/
--------------------------------------------------------
--  DDL for Procedure DELETE_AUTOBUILD_FAILURE_INFO
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "DELETE_AUTOBUILD_FAILURE_INFO" 
IS
/******************************************************************************
   NAME:       DELETE_AUTOBUILD_FAILURE_INFO
   PURPOSE:

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        2/06/2006    Rupesh Solanki      1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     DELETE_AUTOBUILD_FAILURE_INFO
      Sysdate:         2/06/2006
      Date and Time:   2/06/2006, 8:44:25 AM, and 2/06/2006 8:44:25 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
BEGIN
   DELETE FROM autobuild_failure
         WHERE group_email_id NOT IN (SELECT group_email_id
                                        FROM members_group);
END delete_autobuild_failure_info;
/
--------------------------------------------------------
--  DDL for Procedure DEPLOY_TO_RELEASE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "DEPLOY_TO_RELEASE" IS

/******************************************************************************
   

******************************************************************************/

	CURSOR curInfo IS
    SELECT DISTINCT
        qry.DPV_ID
     FROM (
             SELECT dep.*,
                    LEVEL AS LEVEL_NUM
               FROM PACKAGE_DEPENDENCIES dep
             START WITH dep.PV_ID IN ( 
                        
                        69124,63479,60048,49566,49562,54351,63560,54360,46053,59753,97060,97061,100883,78236,75241,92371,92372,105682,135506,127204,135615,136498,137571,61534,76540,96787,133102,96770,96771,116692,133768,61537,88935,110216,96797,69469,98123,111626,96802,100289,97233,97623,135801,69700,77808,43026,77809,43027,100825,126854,105589,96405,102105,133770,134408,91177,91179,96822,96824,48031,78965,78936,78935,79114,76620,125164,61804,96826,61977,67592,72594,134415,135804,65097,64850,64851,64879,64881,64882,64884,67612,67613,67614,67615,68501,68502,68503,68516,68518,68519,68521,71974,68659,69764,68662,68661,68757,69765,69766,69767,71975,71976,71977,71978,71979,71980,75149,71982,71983,75153,75158,71986,75160,75161,75162,72418,72419,71987,71988,71990,75164,72420,72421,72423,72424,72425,75165,75181,75182,83285,75184,75201,75220,75240,75260,75280,75242,76320,75320,76340,76321,82031,76341,76342,76344,76345,76806,76350,76810,76811,76360,76361,76362,76380,76637,76638,76639,76647,76649,76812,76650,78261,76815,77603,76818,76846,76847,76848,76849,77604,77606,77016,77607,77608,77609,78518,77671,77610,78519,78520,78205,78206,77795,78262,78263,78666,78521,78669,78767,78768,78770,78771,82032,79471,78772,82033,80856,80210,80898,82449,80211,80212,80214,80215,80216,80611,80217,82034,82035,80749,80750,82036,94266,82037,82038,82039,82040,82041,82042,82043,82044,82045,82046,82450,82296,82297,82451,82047,82298,82299,82300,82452,82453,82454,82455,82456,82457,82769,82458,82459,82770,82460,82461,82771,83286,85069,83543,83544,83287,85070,84959,85071,85072,84960,85073,85074,84975,85194,85075,85195,85196,85197,85198,85199,94267,85231,85237,94268,94269,94270,94271,94273,94274,94275,94276,94277,94278,94279,94280,94281,94282,94283,94284,94285,94286,94287,94288,94289,94290,94291,94292,94293,94294,94295,94296,94297,94298,94299,94300,94301,94302,94303,94304,94305,94306,94307,94308,94309,94310,94311,94312,94313,94314,94315,94316,94634,94317,94635,97035,94319,94320,94636,94637,94322,96536,96552,96554,96555,96556,96568,96569,96570,96571,96572,96573,96574,96575,96576,96577,96578,96579,96580,96581,96582,96583,96584,96585,96586,96818,97435,96819,96820,97599,97436,97437,97438,97439,97440,97434,97723,97640,97641,97642,97724,97725,97729,97743,97825,98097,98098,98099,98100,97999,98049,98101,98102,98103,99506,98268,98207,99507,99508,99509,99159,99510,99511,99512,102883,99513,99514,100243,99515,99880,99562,99563,99676,99677,99678,99881,99882,99883,99884,100244,100245,100623,100247,100624,100625,100626,100885,100719,100886,100887,100888,100889,100890,100990,100991,101301,101603,110065,101605,102180,102627,102181,102182,102183,102184,102185,102186,102187,102188,102189,102190,102191,104378,102192,104379,102193,102379,102380,102381,102884,102410,102411,102628,102465,102629,102630,102885,102886,102887,104380,104381,104382,104383,104384,104385,104387,110063,104389,106409,104561,104594,104660,105088,105089,105090,105091,105093,105097,105673,105768,106410,109314,106173,110064,137890,106433,106960,109080,111665,122015,110954,116763,110066,116764,110123,111867,110713,116765,111666,116869,111667,111668,116766,116767,115142,115143,121477,113924,114594,116768,115144,116769,115170,115172,115171,115644,120042,120043,116092,116870,116871,118382,116872,116876,120044,118026,119364,121485,120045,120416,121478,120417,122016,124577,129495,123602,123600,124578,124579,124580,124581,124784,125238,127096,127097,129496,129497,128036,128415,129498,129499,129914,130063,130064,130680,130681,131333,131488,133886,132219,132477,132478,133887,136537,136552,136538,136539,136540,136553,136554,136555,137869,85076,80857,62418,64889,64890,64891,64893,68666,68667,68668,68670,68671,68672,68673,72019,72020,72023,72024,72227,77745,77746,77747,77748,77749,77750,77751,77798,78773,80751,82464,82465,83288,92874,92875,92876,92877,92878,94122,94123,96290,96882,96883,97554,97514,97726,98008,98009,98051,99193,100248,99608,100249,100250,100670,100671,100672,101059,101061,101607,102194,102195,102412,102413,102633,104390,104391,106421,104560,104595,105767,106174,106426,109081,122017,137851,110712,116873,115145,115146,114597,115645,116095,120046,123551,122018,124584,124585,129500,129501,129502,128417,129503,129915,130066,131487,133897,133882,133883,136559,85078,100673,63475,78264,78265,78266,78267,78775,80753,94118,94119,94120,94121,96888,100251,100252,102631,102590,102632,65229,43366,69139,132551,59764,127129,101196,96830,61535,105433,96833,96835,96839,83795,77723,126868,99146,70188,117523,117524,117525,99237,100854,100855,137314,137315,96868,138232,138233,69709,96907,130854,119208,69520,124772,96878,60049,47875,70354,59371,54558,59849,33893,43087,43134,33894,60054,24345,49563,49558,97474,84982,31770,30950,49926,60050,52670,59846,59891,30966,59744,61988,59745,59881,59746,59741,47449,59747,64101,63480,63562,105382,105383,60052,48955,49561,49556,47401,65896,65906,65909,65985,108670,68697,68698,59754,59752,59751,62526,59805,59799,66981,46050,59756,46044,59806,46051,59807,82290,66980,59808,46046,61536,88834,70260,111081,105409,66093,66095,66094,47440,65778,59750,56748,99152,78409
                        
                        ) 
 			CONNECT BY PRIOR dep.DPV_ID = dep.PV_ID
 		) qry,
 		PACKAGES pkg,
		PACKAGE_VERSIONS pv
 	 WHERE qry.PV_ID = pv.PV_ID AND pv.PKG_ID = pkg.PKG_ID
         and (pv.is_patch is null or pv.is_patch = 'N');
    recInfo curInfo%ROWTYPE;
	
	
BEGIN

	OPEN curInfo;
    FETCH curInfo INTO recInfo;
	
	WHILE curInfo%FOUND
	LOOP

	insert into release_content(RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE)
    VALUES(8027, recInfo.dpv_id, 7, ora_sysdatetime, 0, 0);
    
    FETCH curInfo INTO recInfo;
		
	END LOOP;

	CLOSE curInfo;




END DEPLOY_TO_RELEASE; 
/
--------------------------------------------------------
--  DDL for Procedure DEPRECATE_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "DEPRECATE_PACKAGE" (nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
	   	  		  							   nRtagId IN DEPRECATED_PACKAGES.RTAG_ID%TYPE,
	   	  		  							   nPkgId IN DEPRECATED_PACKAGES.PKG_ID%TYPE,
											   sComments IN DEPRECATED_PACKAGES.COMMENTS%TYPE,
											   nUserId IN NUMBER) IS
ext VARCHAR2(50);



											   
BEGIN

	--Extract the package version extension
	SELECT V_EXT into ext
	FROM PACKAGE_VERSIONS
	WHERE PV_ID = nPvId; 
	
    -- Deprecate Package
    INSERT INTO DEPRECATED_PACKAGES (RTAG_ID, PKG_ID, COMMENTS, V_EXT)
	VALUES (nRtagId, nPkgId, sComments, ext);
	
	IF ext IS NOT NULL THEN
	   UPDATE RELEASE_CONTENT 
	   SET PKG_ID = nPkgId, DEPRECATED_STATE = 6
	   WHERE RTAG_ID = nRtagId
	   AND PV_ID IN (SELECT PV.PV_ID 
		   	  	  	FROM PACKAGE_VERSIONS PV, PACKAGES PKG
				  	WHERE PKG.PKG_ID = PV.PKG_ID
				  	AND PV.V_EXT = ext
				  	AND PKG.PKG_ID = nPkgId
				 	);						
	ELSE
	   UPDATE RELEASE_CONTENT 
	   SET PKG_ID = nPkgId, DEPRECATED_STATE = 6
	   WHERE RTAG_ID = nRtagId
	   AND PV_ID IN (SELECT PV.PV_ID 
		   	  	  	FROM PACKAGE_VERSIONS PV, PACKAGES PKG
				  	WHERE PKG.PKG_ID = PV.PKG_ID
				  	AND PV.V_EXT IS NULL
				  	AND PKG.PKG_ID = nPkgId
				 	);
	END IF;
				 
	UPDATE RELEASE_CONTENT
	SET PKG_ID = nPkgId, DEPRECATED_STATE = 7
	WHERE RTAG_ID = nRtagId
	AND PV_ID IN (		   SELECT DISTINCT
 	 		  	 		   qry.PV_ID
						        FROM (
								 	  SELECT dep.*,
									  LEVEL AS LEVEL_NUM
									  FROM PACKAGE_DEPENDENCIES dep 
 								START WITH dep.DPV_ID IN ( nPvId ) 
								CONNECT BY PRIOR dep.PV_ID = dep.DPV_ID
 								) qry,
								PACKAGES pkg,
								PACKAGE_VERSIONS pv,
								RELEASE_CONTENT rc
						 	 WHERE qry.PV_ID = pv.PV_ID AND pv.PKG_ID = pkg.PKG_ID
							 AND rc.RTAG_ID = nRtagId AND rc.PV_ID = qry.PV_ID
							 AND rc.DEPRECATED_STATE IS NULL
				 );			 

    /* LOG ACTION */
   	/*Log_Action ( nPkgId, 'deprecated_package', nUserId );*/
	

END Deprecate_Package;
/
--------------------------------------------------------
--  DDL for Procedure DT_DROPUSEROBJECTBYID
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "DT_DROPUSEROBJECTBYID" ( PARAM_ID IN NUMBER ) AS BEGIN DELETE FROM MICROSOFTDTPROPERTIES WHERE OBJECTID = PARAM_ID; END DT_DROPUSEROBJECTBYID;
/
--------------------------------------------------------
--  DDL for Procedure DT_SETPROPERTYBYID
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "DT_SETPROPERTYBYID" ( PARAM_ID   IN NUMBER, PARAM_PROPERTY IN VARCHAR2, PARAM_VALUE  IN VARCHAR2, PARAM_LVALUE  IN LONG RAW ) AS BEGIN DECLARE X NUMBER(40); BEGIN SELECT COUNT(*) INTO X FROM MICROSOFTDTPROPERTIES WHERE OBJECTID=PARAM_ID AND PROPERTY=PARAM_PROPERTY; IF X = 0 THEN INSERT INTO MICROSOFTDTPROPERTIES (ID, PROPERTY, OBJECTID, VALUE, LVALUE, VERSION) VALUES (MICROSOFTSEQDTPROPERTIES.NEXTVAL, PARAM_PROPERTY, PARAM_ID, PARAM_VALUE, PARAM_LVALUE, 0); ELSE UPDATE MICROSOFTDTPROPERTIES SET VALUE=PARAM_VALUE, LVALUE=PARAM_LVALUE, VERSION=VERSION+1 WHERE OBJECTID=PARAM_ID AND PROPERTY=PARAM_PROPERTY; END IF; END; END DT_SETPROPERTYBYID;
/
--------------------------------------------------------
--  DDL for Procedure IGNORE_DEPENDENCY_WARNINGS
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "IGNORE_DEPENDENCY_WARNINGS" ( nRtagId IN IGNORE_WARNINGS.RTAG_ID%TYPE,
                                                         nPvId IN IGNORE_WARNINGS.PV_ID%TYPE,
                                                         sIgnoreIdList IN VARCHAR2,
                                                         bDoPatchIgnore IN BOOLEAN DEFAULT FALSE,
                                                         nUserId IN NUMBER DEFAULT NULL ) IS
/* ---------------------------------------------------------------------------
    Updates the ignore warnings table - this is really two functions in one.

    1) One function updates the table based on a list of dependent PV_IDs and a parent PV_ID
       and is called from the RM website's SetIgnoreWarnings() function after a user changes
       the ignore warnings checkboxes and submits the form.
       This can (at time of writing this) only be done within releases that are not build
       daemon enabled. The ignore warnings feature is a feature we would like to see the end
       of in an ideal world.
       The SetIgnoreWarnings() website function now calls Touch_Release so there is no need to
       do so in this stored procedure, thereby making this stored procedure much more precise in
       that it only updates the ignore_warnings table (action log table too although that is just
       a log and doesn't affect any subsequent business rules behaviour) and it cares nothing
       about website presentation layer states, etc.

    2) The other function updates the table for out of sync dependencies that have in fact
       been satisfied by patches made to some other product in the release.
       This seems to be a seldom used feature in current projects.
       It is probably the most often taken path through this function given that it occurs when
       this function is called from Rebuild_Environment, and that is called in many circumstances
       from the RM website whenever the seems to be a possibility that the state of a package
       in a release might have changed and therefore affects the state of other packages in
       that same release.

    Parameter Usage:
                        when called from    | when called from
                        Rebuild_Environment | SetIgnoreWarnings()
                        stored procedure.   | in the Website
      --------------------------------------+----------------------------
      nRtagId           RTAG_ID             | RTAG_ID
      nPvId             NULL                | PV_ID
      sIgnoreIdList     NULL                | list of dependent PV_ID's
      bDoPatchIgnore    TRUE                | FALSE
      nUserId           NULL                | current user ID
   --------------------------------------------------------------------------- */

oIgnoreIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
ReleaseLocation VARCHAR2(4000);
ActionTypeId NUMBER;

BEGIN

   IF (NOT bDoPatchIgnore) THEN
      /* Manual Ignore Warnings - this execution path is the one taken when called from SetIgnoreWarnings() in the Website
      */
      oIgnoreIdCollector := IN_LIST_NUMBER ( sIgnoreIdList );


      /* Log Action */
      -- Get Release Location
      SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
        FROM PROJECTS proj,
             RELEASE_TAGS rt
       WHERE rt.PROJ_ID = proj.PROJ_ID
         AND rt.RTAG_ID = nRtagId;

      -- Get Action Type Id for IGNORE_ON
      SELECT act.ACTTYPE_ID INTO ActionTypeId
        FROM ACTION_TYPE act
       WHERE act.NAME = 'ignore_on';

      -- Get Ignored (Current MINUS Old)
      INSERT INTO ACTION_LOG ( USER_ID, ACTION_DATETIME, PV_ID, DESCRIPTION, ACTTYPE_ID )
      SELECT nUserId, ORA_SYSDATETIME, nPvId, pkg.PKG_NAME ||' '|| rpv.PKG_VERSION ||' at '|| ReleaseLocation, ActionTypeId
        FROM (
              SELECT TO_NUMBER(nRtagId) AS RTAG_ID, TO_NUMBER(nPvId), pv.PV_ID AS DPV_ID
                FROM PACKAGE_VERSIONS pv
               WHERE pv.PV_ID IN ( SELECT * FROM TABLE ( CAST ( oIgnoreIdCollector AS RELMGR_NUMBER_TAB_t ) ) )
              MINUS
              SELECT igw.RTAG_ID, igw.PV_ID, igw.DPV_ID
                FROM IGNORE_WARNINGS igw
               WHERE igw.RTAG_ID = nRtagId
                 AND igw.PV_ID = nPvId
             ) qry,
             PACKAGE_VERSIONS pv,
             PACKAGES pkg,
             RELEASE_CONTENT rc,
             PACKAGE_VERSIONS rpv
       WHERE pv.PKG_ID = pkg.PKG_ID
         AND rc.RTAG_ID = nRtagId
         AND rc.PV_ID = rpv.PV_ID
         AND rpv.PKG_ID = pv.PKG_ID
         AND NVL( rpv.V_EXT, 'LINK_A_NULL' ) = NVL( pv.V_EXT, 'LINK_A_NULL' )
         AND qry.DPV_ID = pv.PV_ID;


      -- Get Action Type Id for IGNORE_OFF
      SELECT act.ACTTYPE_ID INTO ActionTypeId
        FROM ACTION_TYPE act
       WHERE act.NAME = 'ignore_off';

      -- Get UnIgnored (Old MINUS Current)
      INSERT INTO ACTION_LOG ( USER_ID, ACTION_DATETIME, PV_ID, DESCRIPTION, ACTTYPE_ID )
      SELECT nUserId, ORA_SYSDATETIME, nPvId, pkg.PKG_NAME ||' '|| rpv.PKG_VERSION ||' at '|| ReleaseLocation, ActionTypeId
        FROM (
              SELECT igw.RTAG_ID, igw.PV_ID, igw.DPV_ID
                FROM IGNORE_WARNINGS igw
               WHERE igw.RTAG_ID = nRtagId
                 AND igw.PV_ID = nPvId
              MINUS
              SELECT TO_NUMBER(nRtagId) AS RTAG_ID, TO_NUMBER(nPvId), pv.PV_ID AS DPV_ID
                FROM PACKAGE_VERSIONS pv
               WHERE pv.PV_ID IN ( SELECT * FROM TABLE ( CAST ( oIgnoreIdCollector AS RELMGR_NUMBER_TAB_t ) ) )
             ) qry,
             PACKAGE_VERSIONS pv,
             PACKAGES pkg,
             RELEASE_CONTENT rc,
             PACKAGE_VERSIONS rpv
       WHERE pv.PKG_ID = pkg.PKG_ID
         AND rc.RTAG_ID = nRtagId
         AND rc.PV_ID = rpv.PV_ID
         AND rpv.PKG_ID = pv.PKG_ID
         AND NVL( rpv.V_EXT, 'LINK_A_NULL' ) = NVL( pv.V_EXT, 'LINK_A_NULL' )
         AND qry.DPV_ID = pv.PV_ID;


      -- Delete Current Ignore Warnings
      DELETE
        FROM IGNORE_WARNINGS igw
       WHERE igw.RTAG_ID = nRtagId
         AND igw.PV_ID = nPvId
         AND igw.IS_PATCH_IGNORE IS NULL;


      IF (oIgnoreIdCollector.COUNT > 0) THEN
         -- Insert Ignore Warnings
         INSERT INTO IGNORE_WARNINGS igw ( RTAG_ID, PV_ID, DPV_ID )
         SELECT nRtagId,
                nPvId,
                pv.PV_ID AS DPV_ID
           FROM PACKAGE_VERSIONS pv
          WHERE pv.PV_ID IN ( SELECT * FROM TABLE ( CAST ( oIgnoreIdCollector AS RELMGR_NUMBER_TAB_t ) ) );
      END IF;

   ELSE
      /* Patch Ignore Warnings - this execution path is the one taken when called from the Rebuild_Environment stored procedure */

      -- Delete Current Patch Ignore Warnings
      DELETE
        FROM IGNORE_WARNINGS igw
       WHERE igw.RTAG_ID = nRtagId
         AND igw.IS_PATCH_IGNORE = 'Y';


      -- Delete Manual Ignores that need to be Patch Ignores
      DELETE
        FROM IGNORE_WARNINGS igw
       WHERE ( RTAG_ID, PV_ID, DPV_ID ) IN
             (
              SELECT DISTINCT
                     nRtagId,
                     err.PV_ID,
                     err.ERR_DPV AS DPV_ID
               FROM  (
                      /* Full Release Contents used for reference*/
                      SELECT rpv.PV_ID, rpv.pkg_id, NVL(rpv.v_ext, '|LINK_A_NULL|') AS v_ext
                        FROM release_content rel, package_versions rpv
                       WHERE rel.pv_id = rpv.pv_id
                         AND rtag_id = nRtagId
                     ) frc,
                     (
                      /* DPV_IDs not fount in release*/
                      SELECT dep.pv_id, dep.dpv_id AS err_dpv
                        FROM package_dependencies dep
                       WHERE dep.pv_id IN ( SELECT pv_id FROM release_content WHERE rtag_id = nRtagId )
                         AND NOT dep.dpv_id IN ( SELECT pv_id FROM release_content WHERE rtag_id = nRtagId )
                     ) err,
                     (
                      SELECT DISTINCT pp.PV_ID, dep.DPV_ID
                        FROM PACKAGE_PATCHES pp,
                             PACKAGE_DEPENDENCIES dep,
                             RELEASE_CONTENT rc
                       WHERE rc.RTAG_ID = nRtagId
                         AND rc.PV_ID = pp.PV_ID
                         AND dep.PV_ID = pp.PATCH_ID
                     ) pp,
                     package_versions errpkg,
                     package_versions errpv
               WHERE err.err_dpv = errpv.pv_id
                 AND errpv.pkg_id = frc.pkg_id(+)
                 AND NVL(errpv.v_ext, '|LINK_A_NULL|') = frc.v_ext(+)
                 AND err.pv_id = errpkg.pv_id
                 AND err.PV_ID = pp.PV_ID
                 AND frc.PV_ID = pp.DPV_ID
             );

      /*
      ---------------------------------------------------
      --  Make sure that select statement above and below are same
      ---------------------------------------------------
      */

      -- Insert Patch Ignores
      INSERT INTO IGNORE_WARNINGS igw ( RTAG_ID, PV_ID, DPV_ID, IS_PATCH_IGNORE )
      SELECT DISTINCT
             nRtagId,
             err.PV_ID,
             err.ERR_DPV AS DPV_ID,
             'Y'
        FROM (
              /* Full Release Contents used for reference*/
              SELECT rpv.PV_ID, rpv.pkg_id, NVL(rpv.v_ext, '|LINK_A_NULL|') AS v_ext
                FROM release_content rel, package_versions rpv
               WHERE rel.pv_id = rpv.pv_id
                 AND rtag_id = nRtagId
             ) frc,
             (
               /* DPV_IDs not fount in release*/
               SELECT dep.pv_id, dep.dpv_id AS err_dpv
                 FROM package_dependencies dep
                WHERE dep.pv_id IN ( SELECT pv_id FROM release_content WHERE rtag_id = nRtagId )
                  AND NOT dep.dpv_id IN ( SELECT pv_id FROM release_content WHERE rtag_id = nRtagId )
             ) err,
             (
              SELECT DISTINCT pp.PV_ID, dep.DPV_ID
                FROM PACKAGE_PATCHES pp,
                     PACKAGE_DEPENDENCIES dep,
                     RELEASE_CONTENT rc
               WHERE rc.RTAG_ID = nRtagId
                 AND rc.PV_ID = pp.PV_ID
                 AND dep.PV_ID = pp.PATCH_ID
             ) pp,
             package_versions errpkg,
             package_versions errpv
       WHERE err.err_dpv = errpv.pv_id
         AND errpv.pkg_id = frc.pkg_id(+)
         AND NVL(errpv.v_ext, '|LINK_A_NULL|') = frc.v_ext(+)
         AND err.pv_id = errpkg.pv_id
         AND err.PV_ID = pp.PV_ID
         AND frc.PV_ID = pp.DPV_ID;

    END IF;

END Ignore_Dependency_Warnings;
/
--------------------------------------------------------
--  DDL for Procedure INSERT_INTO_PACKAGE_BUILD_INFO
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "INSERT_INTO_PACKAGE_BUILD_INFO" IS

/******************************************************************************
   NAME:       INSERT_INTO_PACKAGE_BUILD_INFO
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        6/12/2006          1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     INSERT_INTO_PACKAGE_BUILD_INFO
      Sysdate:         6/12/2006
      Date and Time:   6/12/2006, 1:53:40 PM, and 6/12/2006 1:53:40 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/

	CURSOR curInfo IS
    SELECT PV_ID
	FROM PACKAGE_BUILD_ENV
	WHERE BE_ID IN (11, 12);
    recInfo curInfo%ROWTYPE;
	
	
BEGIN

	OPEN curInfo;
    FETCH curInfo INTO recInfo;
	
	WHILE curInfo%FOUND
	LOOP

		INSERT INTO PACKAGE_BUILD_INFO ( PV_ID, BM_ID, BSA_ID )
		VALUES( recInfo.PV_ID, 2, 5);
		
		UPDATE PACKAGE_VERSIONS SET BS_ID = 2 WHERE PV_ID = recInfo.PV_ID;
		
		FETCH curInfo INTO recInfo;
		
	END LOOP;

	CLOSE curInfo;




END INSERT_INTO_PACKAGE_BUILD_INFO;
/
--------------------------------------------------------
--  DDL for Procedure INSERT_MULTIPLE_STICKY_NOTES
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "INSERT_MULTIPLE_STICKY_NOTES" IS

/******************************************************************************
   NAME:       INSERT_MULTIPLE_STICKY_NOTES
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        6/12/2006          1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     INSERT_MULTIPLE_STICKY_NOTES
      Sysdate:         6/12/2006
      Date and Time:   6/12/2006, 1:53:40 PM, and 6/12/2006 1:53:40 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/

	CURSOR curInfo IS
    SELECT PV_ID
	FROM PACKAGE_BUILD_ENV
	WHERE BE_ID IN (11, 12);
    recInfo curInfo%ROWTYPE;
	
	
BEGIN

	OPEN curInfo;
    FETCH curInfo INTO recInfo;
	
	WHILE curInfo%FOUND
	LOOP

		INSERT INTO NOTE_MANAGER ( NID, LAST_USER, LAST_DATE, DESCRIPTION )
		VALUES( recInfo.PV_ID, 'awehalle', ORA_SYSDATETIME, '' );
		
		FETCH curInfo INTO recInfo;
		
	END LOOP;

	CLOSE curInfo;




END INSERT_MULTIPLE_STICKY_NOTES;
/
--------------------------------------------------------
--  DDL for Procedure LEVEL_N_CONFLICTS
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LEVEL_N_CONFLICTS" (
   nnrtag_id       IN       NUMBER,
   nnsession_num   IN       NUMBER,
   nnrowcnt        OUT      NUMBER,
   nniteration     IN       NUMBER
)
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.1
   --------------------------------------------------------------------------- */
   previteration   NUMBER := nniteration - 1;
BEGIN
   /* ---------  LEVEL 1 CONFILCTS -----------
   || Following states are used:
   || 0 -> NOT FOUND
   || 1 -> MAJOR
   || 2 -> MINOR MINOR
   */
   INSERT INTO temp_env_states
      SELECT DISTINCT nnsession_num AS session_num, nniteration AS level_num,
                      pv.pv_id, pv.pkg_id, pv.v_ext,
                      DECODE (tes.tes_state, 2, 2, 1) AS MESSAGE
                 FROM package_dependencies dep,
                      package_versions dpv,
                      package_versions pv,
                      release_content rel,
                      temp_env_states tes
                WHERE rel.pv_id = dep.pv_id
                  AND rel.rtag_id = nnrtag_id
                  AND dep.pv_id = pv.pv_id
                  AND dep.dpv_id = dpv.pv_id
                  AND dpv.pkg_id = tes.pkg_id
                  AND NVL (dpv.v_ext, '|LINK_A_NULL|') =
                                              NVL (tes.v_ext, '|LINK_A_NULL|')
                  AND tes.session_num = nnsession_num
                  AND tes.level_num = previteration
                  AND (dep.pv_id, dep.dpv_id) IN 
                                                   /* Remove packages listed in IGNORE_WARNINGS table and
                                                 || packages already stored in Temp Table.
                                                 */
                      (
                         SELECT pd.pv_id, pd.dpv_id
                           FROM package_dependencies pd, release_content rc
                          WHERE pd.pv_id = rc.pv_id AND rc.rtag_id = nnrtag_id
                         --AND pd.pv_id NOT IN ( SELECT pv_id FROM temp_env_states WHERE session_num = NNsession_num AND level_num > 5 )
                         MINUS
                         SELECT igw.pv_id, igw.dpv_id
                           FROM ignore_warnings igw
                          WHERE igw.rtag_id = nnrtag_id);

   nnrowcnt := SQL%ROWCOUNT;
END level_n_conflicts;
/
--------------------------------------------------------
--  DDL for Procedure LEVEL_ONE_CONFLICTS
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LEVEL_ONE_CONFLICTS" (
   nnrtag_id       IN   NUMBER,
   nnsession_num   IN   NUMBER
)
IS
BEGIN
   /* ---------  LEVEL 1 CONFILCTS -----------
   || Following states are used:
   || 0 -> NOT FOUND
   || 1 -> MAJOR
   || 2 -> MINOR MINOR
   */
   INSERT INTO temp_env_states
      SELECT DISTINCT nnsession_num AS session_num, 1 AS level_num,
                      err.pv_id, errpkg.pkg_id, errpkg.v_ext,
                      DECODE (frc.v_nmm,
                              NULL, 0,
                              errpv.v_nmm, DECODE (frc.v_mm,
                                                   errpv.v_mm, NULL,
                                                   2
                                                  ),
                              1
                             ) AS MESSAGE
                 FROM (
                       /* Full Release Contents used for reference*/
                        SELECT rel.rtag_id, rpv.pv_id, rpv.pkg_id,
                                NVL (rpv.v_ext, '|LINK_A_NULL|') AS v_ext,
                                rpv.pkg_version, rpv.v_nmm, rpv.v_mm,
                                (SELECT COUNT(*)
                                   FROM ADVISORY_RIPPLE avr
                                  WHERE avr.rtag_id = rel.rtag_id
                                    AND avr.pv_id = rel.pv_id
                                ) AS IsAvr
                          FROM release_content rel,
                                package_versions rpv
                          WHERE rel.pv_id = rpv.pv_id
                             AND rtag_id = nnrtag_id
                      ) frc,

                      (
                       /* DPV_IDs not found in release (excluding those from pegged versions whose dependencies will not
                          necessarily be satisfied in the release) */
                       SELECT dep.pv_id, dep.dpv_id AS err_dpv
                         FROM package_dependencies dep,
                              package_versions dep_dpv
                        WHERE dep.dpv_id = dep_dpv.pv_id
                          AND dep.pv_id IN (SELECT pv_id FROM release_content WHERE rtag_id = nnrtag_id)
                          AND NOT dep.pv_id IN (SELECT pegv.pv_id FROM PEGGED_VERSIONS pegv WHERE pegv.rtag_id = nnrtag_id)
                          AND NOT dep.dpv_id IN (SELECT pv_id FROM release_content WHERE rtag_id = nnrtag_id)
                       MINUS
                       /* MINUS Dependencies to be ignored */
                       SELECT igw.pv_id, igw.dpv_id AS err_dpv
                         FROM ignore_warnings igw,
                              package_versions igw_dpv
                        WHERE igw.dpv_id = igw_dpv.pv_id
                          AND igw.rtag_id = nnrtag_id
                      ) err,
                      package_versions errpkg,
                      package_versions errpv
                WHERE err.err_dpv = errpv.pv_id
                  AND errpv.pkg_id = frc.pkg_id(+)
                  AND NVL (errpv.v_ext, '|LINK_A_NULL|') = frc.v_ext(+)
                  AND err.pv_id = errpkg.pv_id
                  AND frc.IsAvr = 0;
END level_one_conflicts;
/
--------------------------------------------------------
--  DDL for Procedure LOCK_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LOCK_PACKAGE" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
											 nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

BEGIN

    -- Lock Package
    UPDATE PACKAGE_VERSIONS pv SET
    	pv.DLOCKED = 'Y'
    WHERE pv.PV_ID = nPvId;

    /* LOG ACTION */
   	Log_Action ( nPvId, 'lock_package', nUserId );

END Lock_Package;
/
--------------------------------------------------------
--  DDL for Procedure LOG_ACTION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LOG_ACTION" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
										 enumActionTypeName IN ACTION_TYPE.NAME%TYPE,
                                         nUserId IN ACTION_LOG.USER_ID%TYPE,
										 sAdditionalComments IN ACTION_LOG.DESCRIPTION%TYPE DEFAULT NULL  ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

    ActionTypeId NUMBER;

BEGIN

    -- Get Action Type FK
    SELECT act.ACTTYPE_ID INTO ActionTypeId
      FROM ACTION_TYPE act
     WHERE act.NAME = enumActionTypeName;


    INSERT INTO ACTION_LOG ( USER_ID, ACTION_DATETIME, PV_ID, DESCRIPTION, ACTTYPE_ID )
    VALUES ( nUserId, ORA_SYSDATETIME, nPvId, sAdditionalComments, ActionTypeId );


END Log_Action;
/
--------------------------------------------------------
--  DDL for Procedure LOG_ACTION_BULK
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LOG_ACTION_BULK" ( nPvIdList IN VARCHAR2,
										 	  enumActionTypeName IN ACTION_TYPE.NAME%TYPE,
                                         	  nUserId IN ACTION_LOG.USER_ID%TYPE,
										 	  sAdditionalComments IN ACTION_LOG.DESCRIPTION%TYPE DEFAULT NULL  ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

    ActionTypeId NUMBER;
    oPvIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

BEGIN

    oPvIdCollector := IN_LIST_NUMBER ( nPvIdList );

    -- Get Action Type FK
    SELECT act.ACTTYPE_ID INTO ActionTypeId
      FROM ACTION_TYPE act
     WHERE act.NAME = enumActionTypeName;

    -- Log Action
    INSERT INTO ACTION_LOG ( USER_ID, ACTION_DATETIME, PV_ID, DESCRIPTION, ACTTYPE_ID )
    SELECT nUserId,
    	   ORA_SYSDATETIME,
           pv.PV_ID,
           sAdditionalComments,
           ActionTypeId
      FROM PACKAGE_VERSIONS pv
     WHERE pv.PV_ID IN ( SELECT * FROM TABLE ( CAST ( oPvIdCollector AS RELMGR_NUMBER_TAB_t ) ) );


END Log_Action_Bulk;
/
--------------------------------------------------------
--  DDL for Procedure LOG_DAEMON_ACTION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LOG_DAEMON_ACTION" ( nRconId IN NUMBER,
												 enumActionTypeName IN VARCHAR2,
		                                         nUserId IN NUMBER,
												 sAdditionalComments IN VARCHAR2 DEFAULT NULL  ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

    ActionTypeId NUMBER;

BEGIN

    -- Get Action Type FK
    SELECT act.ACTTYPE_ID INTO ActionTypeId
      FROM ACTION_TYPE act
     WHERE act.NAME = enumActionTypeName;


    INSERT INTO DAEMON_ACTION_LOG
    VALUES ( nUserId, ORA_SYSDATETIME, nRconId, sAdditionalComments, ActionTypeId );


END Log_Daemon_Action;
/
--------------------------------------------------------
--  DDL for Procedure LOG_PROJECT_ACTION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "LOG_PROJECT_ACTION" ( nProjId IN NUMBER,
												 enumActionTypeName IN VARCHAR2,
		                                         nUserId IN NUMBER,
												 sAdditionalComments IN VARCHAR2 DEFAULT NULL,
												 nRtagId IN NUMBER  ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

    ActionTypeId NUMBER;

BEGIN

    -- Get Action Type FK
    SELECT act.ACTTYPE_ID INTO ActionTypeId
      FROM ACTION_TYPE act
     WHERE act.NAME = enumActionTypeName;


    INSERT INTO PROJECT_ACTION_LOG ( USER_ID, ACTION_DATETIME, PROJ_ID, DESCRIPTION, ACTTYPE_ID, RTAG_ID)
    VALUES ( nUserId, ORA_SYSDATETIME, nProjId, sAdditionalComments, ActionTypeId, nRtagId);


END Log_Project_Action;
/
--------------------------------------------------------
--  DDL for Procedure NEW_ADDITIONAL_NOTE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "NEW_ADDITIONAL_NOTE" ( pnPv_id IN NUMBER,
                                                  psNote_title IN ADDITIONAL_NOTES.NOTE_TITLE%TYPE,
                                                  psNote_body IN ADDITIONAL_NOTES.NOTE_BODY%TYPE,
                                                  pnUser_id IN NUMBER,
                                                  outErrCode OUT NUMBER
                                                 ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    newID NUMBER;

	CURSOR an_duplicate_cur IS
        SELECT note_id
          FROM ADDITIONAL_NOTES
         WHERE pv_id = pnPv_id
           AND note_title = psNote_title;
    an_duplicate_rec an_duplicate_cur%ROWTYPE;

BEGIN
	outErrCode := -1;		-- Set default return error code to ERROR state

	OPEN an_duplicate_cur;
    FETCH an_duplicate_cur INTO an_duplicate_rec;

    IF an_duplicate_cur%NOTFOUND
    THEN
		/* No duplicate titles */
		-- Get new ID --
    	SELECT SEQ_ADDITIONAL_NOTES.NEXTVAL INTO newID FROM DUAL;

		--- Add Additional Note ---
	    INSERT INTO ADDITIONAL_NOTES ( note_id, pv_id, note_title, note_body, mod_date, mod_user  )
	    VALUES (  newID, pnPv_id, psNote_title, psNote_body, Ora_Sysdate, pnUser_id );
		outErrCode := 0;		-- Set return to SUCCESS
	END IF;

	CLOSE an_duplicate_cur;
END New_Additional_Note;
/
--------------------------------------------------------
--  DDL for Procedure NEW_PACKAGE_NAME
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "NEW_PACKAGE_NAME" ( SSpkg_name IN PACKAGES.pkg_name%TYPE,
                                               retPKG_ID OUT NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    CURSOR packages_cur IS
        SELECT pkg.pkg_id
          FROM packages pkg
         WHERE pkg.pkg_name = SSpkg_name;
    packages_rec packages_cur%ROWTYPE;


BEGIN

    /* ---------------------------------------------------- */
    /* Find if package name exists                          */
    /* ---------------------------------------------------- */

    OPEN packages_cur;
    FETCH packages_cur INTO packages_rec;

    IF packages_cur%NOTFOUND
    THEN
        -- Create new pkg_name --
        SELECT SEQ_PKG_ID.nextval INTO retPKG_ID FROM DUAL;

        INSERT INTO packages ( pkg_id, pkg_name )
        VALUES ( retPKG_ID, SSpkg_name );

    ELSE
        retPKG_ID := packages_rec.pkg_id;

    END IF;


    CLOSE packages_cur;

END New_Package_Name;
/
--------------------------------------------------------
--  DDL for Procedure NEW_PATCH
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "NEW_PATCH" ( SSpatch_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
 	   	  		  					  	NNparent_id IN NUMBER,
                                        sPatchIdList IN VARCHAR2,
										NNuser_id IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.5
   --------------------------------------------------------------------------- */

    patchPv_id    NUMBER;
	parPkg_id	  NUMBER;
    LastInstallOrder NUMBER;
    isPatchDlocked PACKAGE_VERSIONS.DLOCKED%TYPE;
    SSV_MM PACKAGE_VERSIONS.V_MM%TYPE;
    SSV_NMM PACKAGE_VERSIONS.V_NMM%TYPE;
    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;
	oPatchDepCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

	CURSOR parent_cur IS
        SELECT pv.*, pkg.pkg_name
          FROM package_versions pv,
		       packages pkg
         WHERE pv.pv_id = NNparent_id
		   AND pv.pkg_id = pkg.pkg_id;
    parent_rec parent_cur%ROWTYPE;

    CURSOR patch_cur IS
        SELECT pv.*, pg.pkg_name
          FROM package_versions pv,
		       packages pg
         WHERE pv.pkg_id = parPkg_id
		   AND pv.pkg_version = SSpatch_version
		   AND pv.pkg_id = pg.pkg_id;
    patch_rec patch_cur%ROWTYPE;

	CURSOR releases_cur IS
        SELECT rc.pv_id
		  FROM release_content rc
		 WHERE rc.pv_id = patch_rec.pv_id;
    releases_rec releases_cur%ROWTYPE;


BEGIN

	-- Get Last Install Order
    SELECT Count(*) INTO LastInstallOrder
	  FROM PACKAGE_PATCHES pp
	 WHERE pp.PV_ID = NNparent_id;


    -- Get parent details
	OPEN parent_cur;
    FETCH parent_cur INTO parent_rec;
	parPkg_id := parent_rec.pkg_id;


	-- Find if patch exists in database
    OPEN patch_cur;
    FETCH patch_cur INTO patch_rec;


    -- Parent must be official
    IF parent_rec.dlocked = 'Y' THEN

	    IF patch_cur%NOTFOUND
	    THEN
        	isPatchDlocked := 'N';

	        -- Create new patch version --
	        SELECT SEQ_PV_ID.nextval INTO patchPv_id FROM DUAL;


	        Split_version ( SSpatch_version, SSV_MM, SSV_NMM, SSV_EXT );

	        INSERT INTO package_versions ( pv_id, pkg_id, pkg_version, dlocked, created_stamp, creator_id, modified_stamp, modifier_id, V_MM, V_NMM, V_EXT, src_path, pv_description, owner_id, is_patch, LAST_PV_ID, bs_id, is_autobuildable, ripple_field )
				   VALUES (
						   patchPv_id,
	                       parPkg_id,
	                       SSpatch_version,
	                       isPatchDlocked,
	                       ORA_SYSDATE,
	                       NNuser_id,
	                       ORA_SYSDATETIME,
	                       NNuser_id,
	                       SSV_MM,
	                       SSV_NMM,
	                       SSV_EXT,
	                       parent_rec.src_path,
	                       'This is a patch to ' || parent_rec.pkg_name || ' ' || parent_rec.pkg_version,
	                       NNuser_id,
						   'Y',
                           patchPv_id,
						   parent_rec.bs_id,
						   parent_rec.is_autobuildable,
						   parent_rec.ripple_field
						   
						   );

			INSERT INTO package_patches ( pv_id, patch_id, INSTALL_ORDER )
		    	   ( SELECT NNparent_id AS pv_id,
				            pv.pv_id AS patch_id,
	                        LastInstallOrder + 1 AS INSTALL_ORDER
				       FROM package_versions pv
					  WHERE pv.pv_id = patchPv_id
					    AND pv.is_patch = 'Y' );

	        /* LOG ACTION */
            Log_Action ( patchPv_id, 'new_version', NNuser_id,
        			     'Patch version created: '|| SSpatch_version );

        	Log_Action ( NNparent_id, 'patch_add', NNuser_id,
        			     'New patch created and attached: '|| SSpatch_version );


	    ELSE

		    patchPv_id := patch_rec.pv_id;
	    	isPatchDlocked := patch_rec.dlocked;

			-- Find if pv_id exists in release content (i.e. it cannot be a patch)
		    OPEN releases_cur;
		    FETCH releases_cur INTO releases_rec;

			IF releases_cur%NOTFOUND
	   		THEN
				-- This pv_id is trully a patch, hence add Y to column IS_PATCH
				UPDATE package_versions SET
					   is_patch = 'Y'
					   WHERE pv_id = patchPv_id;

				INSERT INTO package_patches ( pv_id, patch_id, INSTALL_ORDER )
			    	   ( SELECT NNparent_id AS pv_id,
					            pv.pv_id AS patch_id,
	                            LastInstallOrder + 1 AS INSTALL_ORDER
					       FROM package_versions pv
						  WHERE pv.pv_id = patchPv_id
						    AND pv.is_patch = 'Y' );

			END IF;

			CLOSE releases_cur;

            /* LOG ACTION */
        	Log_Action ( NNparent_id, 'patch_add', NNuser_id,
        			     'Patch version was found and attached: '|| SSpatch_version );

	    END IF;




    END IF;



    /* Create Patch Dependencies */
    oPatchDepCollector := IN_LIST_NUMBER ( sPatchIdList );


    -- Make sure patch is unofficial before altering its dependencies
    IF (oPatchDepCollector.COUNT > 0) AND (isPatchDlocked = 'N') THEN
    	-- Delete Existing Dependencies
        DELETE
          FROM PACKAGE_DEPENDENCIES dep
         WHERE dep.PV_ID = patchPv_id;


        -- Insert new dependencies
        INSERT INTO PACKAGE_DEPENDENCIES ( PV_ID, DPV_ID, PKG_ID, DPKG_ID, BUILD_TYPE )
        SELECT patchPv_id AS PV_ID,
        	   pv.PV_ID AS DPV_ID,
               parPkg_id AS PKG_ID,
               pv.PKG_ID AS DPKG_ID,
               'L' AS BUILD_TYPE
          FROM PACKAGE_VERSIONS pv
         WHERE pv.PV_ID IN ( SELECT * FROM TABLE ( CAST ( oPatchDepCollector AS RELMGR_NUMBER_TAB_t ) ) );


    END IF;


    CLOSE parent_cur;
    CLOSE patch_cur;
END New_Patch;
/
--------------------------------------------------------
--  DDL for Procedure NEW_UNIT_TEST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "NEW_UNIT_TEST" ( nPv_id IN NUMBER,
                                            nTestTypeId IN UNIT_TESTS.TEST_TYPES_FK%TYPE,
                                            sTest_summary IN UNIT_TESTS.TEST_SUMMARY%TYPE,
                                            sNumOfTest IN UNIT_TESTS.NUMOF_TEST%TYPE,
                                            sDpkg_path IN VARCHAR2,
                                            sResults IN VARCHAR2,
                                            sCompletion_date IN VARCHAR2,
                                            nCompleted_by IN NUMBER,
											enumTEST_TYPE_AUTOMATIC IN NUMBER,
											enumTEST_TYPE_NOT_DONE IN NUMBER,
											outFileName OUT VARCHAR2
                                           ) IS
/* ---------------------------------------------------------------------------
    Version: 3.2.0
   --------------------------------------------------------------------------- */

   	FILENAME_PREFIX CONSTANT VARCHAR2(50) := 'RM_UNIT_TEST';

    newID NUMBER;
    ResultsURL UNIT_TESTS.RESULTS_URL%TYPE DEFAULT NULL;
    ResultsAttachment UNIT_TESTS.RESULTS_ATTACHMENT_NAME%TYPE DEFAULT NULL;

BEGIN

	-- Get new ID --
   	SELECT SEQ_UNIT_TESTS.NEXTVAL INTO newID FROM DUAL;

       IF nTestTypeId = enumTEST_TYPE_AUTOMATIC THEN
       	ResultsURL := sResults;
       ELSE
       	IF (sResults <> '') OR ( NOT sResults IS NULL ) THEN
        	outFileName := FILENAME_PREFIX || newID ||'_'|| sResults;
    		ResultsAttachment := sDpkg_path || '/' || outFileName;
           END IF;
       END IF;

	-- Remove NOT_DONE entry if exists
	DELETE FROM UNIT_TESTS
	 WHERE pv_id = nPv_id
	   AND test_types_fk = enumTEST_TYPE_NOT_DONE;

	--- Add Additional Note ---
    INSERT INTO UNIT_TESTS ( TEST_ID,
								PV_ID,
								TEST_TYPES_FK,
								TEST_SUMMARY,
								COMPLETION_DATE,
								COMPLETED_BY,
								RESULTS_URL,
								RESULTS_ATTACHMENT_NAME,
								NUMOF_TEST )
    VALUES (
       	newID,
           nPv_id,
           nTestTypeId,
           sTest_summary,
           TO_DATE( sCompletion_date,'DD/MM/YYYY' ),
           nCompleted_by,
           ResultsURL,
           ResultsAttachment,
		   sNumOfTest );

END New_Unit_Test;
/
--------------------------------------------------------
--  DDL for Procedure NEW_VERSION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "NEW_VERSION" ( NNorig_pv_id IN NUMBER,
                                          SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE DEFAULT NULL,
                                          NNsetto_pv_id IN NUMBER DEFAULT NULL,
                                          NNrtag_id IN NUMBER,
                                          NNuser_id IN NUMBER,
                                          enumISSUES_STATE_IMPORTED IN NUMBER,
                                          retPv_id OUT NUMBER ) IS
										  
										  
  TO BE REMOVED   !!!										  
										  
										  
										  
										  
/* ---------------------------------------------------------------------------
    Version: 3.3
   --------------------------------------------------------------------------- */

    ReleaseLocation VARCHAR2(4000);
    origPkg_id PACKAGE_VERSIONS.pkg_id%TYPE;
    origDlocked PACKAGE_VERSIONS.dlocked%TYPE;
    SSV_MM PACKAGE_VERSIONS.V_MM%TYPE;
    SSV_NMM PACKAGE_VERSIONS.V_NMM%TYPE;
    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;
    nIssuesTypes NUMBER;

    CURSOR package_versions_cur IS
        SELECT pv.pv_id, pv.is_patch
          FROM PACKAGE_VERSIONS pv
         WHERE pv.pkg_version = SSpkg_version
           AND pv.pkg_id IN ( SELECT DISTINCT origpv.pkg_id FROM PACKAGE_VERSIONS origpv WHERE origpv.pv_id = NNorig_pv_id );
    package_versions_rec package_versions_cur%ROWTYPE;

    CURSOR clone_package_versions_cur IS
        SELECT DISTINCT pkg_id, dlocked FROM PACKAGE_VERSIONS WHERE pv_id = NNorig_pv_id;
    clone_package_versions_rec clone_package_versions_cur%ROWTYPE;

BEGIN
	IF NNsetto_pv_id IS NULL
    THEN
		-- SetToPv_id is not supplied, hence proceed.

	    /* ---------------------------------------------------- */
	    /* Find id package_version exists                       */
	    /* ---------------------------------------------------- */

	    OPEN package_versions_cur;
	    FETCH package_versions_cur INTO package_versions_rec;

	    IF package_versions_cur%NOTFOUND
	    THEN
	        SELECT SEQ_PV_ID.NEXTVAL INTO retPv_id FROM DUAL;
	        Split_Version ( SSpkg_version, SSV_MM, SSV_NMM, SSV_EXT );

	        OPEN clone_package_versions_cur;
	        FETCH clone_package_versions_cur INTO clone_package_versions_rec;
	        origPkg_id := clone_package_versions_rec.pkg_id;
	        origDlocked := clone_package_versions_rec.dlocked;
	        CLOSE clone_package_versions_cur;

	        -- Clone Package Version Details --
	        INSERT INTO PACKAGE_VERSIONS ( pv_id, pkg_id, pkg_version, dlocked, created_stamp, creator_id, modified_stamp, modifier_id, V_MM, V_NMM, V_EXT,
	                                       src_path, pv_description, PV_OVERVIEW, LAST_PV_ID, owner_id, IS_DEPLOYABLE, IS_BUILD_ENV_REQUIRED )
	            SELECT retPv_id         AS pv_id,
	                   origPkg_id       AS pkg_id,
	                   SSpkg_version    AS pkg_version,
	                   'N'              AS dlocked,
	                   Ora_Sysdate      AS created_stamp,
	                   NNuser_id        AS creator_id,
	                   Ora_Sysdatetime  AS modified_stamp,
	                   NNuser_id        AS modifier_id,
	                   SSV_MM           AS V_MM,
	                   SSV_NMM          AS V_NMM,
	                   SSV_EXT          AS V_EXT,
	                   pv.src_path,
	                   pv.pv_description,
                       pv.PV_OVERVIEW,
                       NNorig_pv_id 	AS LAST_PV_ID,
	                   pv.owner_id,
					   pv.IS_DEPLOYABLE,
					   pv.IS_BUILD_ENV_REQUIRED
	              FROM PACKAGE_VERSIONS pv
	             WHERE pv.pv_id = NNorig_pv_id;


	        -- Set Issues Type for cloning ---
	        IF origDlocked = 'Y'
	        THEN
            	nIssuesTypes := enumISSUES_STATE_IMPORTED;
	        ELSE
            	nIssuesTypes := NULL;
	        END IF;

			Basic_Clone ( NNorig_pv_id, retPv_id, NNrtag_id, NNuser_id, origPkg_id, nIssuesTypes );



	    ELSE
	        retPv_id := package_versions_rec.pv_id;

	    END IF;

        CLOSE package_versions_cur;

	ELSE
    	retPv_id := NNsetto_pv_id;
    END IF;


    /* ---------------------------------------------------- */
    /* Insert into Release Contents (EXCLUDE PATCHES)       */
    /* ---------------------------------------------------- */
	IF (package_versions_rec.is_patch != 'Y') OR (package_versions_rec.is_patch IS NULL) THEN
	    UPDATE RELEASE_CONTENT
	       SET pv_id = retPv_id,
	           insert_stamp = Ora_Sysdate,
	           insertor_id = NNuser_id
	     WHERE rtag_id = NNrtag_id
	       AND pv_id = NNorig_pv_id;

        /* LOG ACTION */
        SELECT proj.PROJ_NAME ||' / '|| vt.VTREE_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
		  FROM PROJECTS proj,
		  	   VTREES vt,
		       RELEASE_TAGS rt
		 WHERE rt.VTREE_ID = vt.VTREE_ID
		   AND vt.PROJ_ID = proj.PROJ_ID
		   AND rt.RTAG_ID = NNrtag_id;

        Log_Action ( NNorig_pv_id, 'replaced_with', NNuser_id, 'Replacing version: '|| SSpkg_version ||' at '|| ReleaseLocation );
   		Log_Action ( retPv_id, 'add', NNuser_id, 'Location: '|| ReleaseLocation );

	END IF;


END New_Version;
/
--------------------------------------------------------
--  DDL for Procedure OLE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "OLE" 
IS retval VARCHAR2(40);   
BEGIN   retval := RELEASE_MANAGER.Pk_Rmapi.RETURN_WIP ( 'daf_br_applets', 2362 ) 
DBMS_OUTPUT.PUT_LINE(retval);
/
--------------------------------------------------------
--  DDL for Procedure PAOLO_BUILD_TREE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "PAOLO_BUILD_TREE" ( nRtag_id IN NUMBER ) IS

    sessionNumber NUMBER := 0;
    iteration NUMBER := 1; 
    rowCnt NUMBER := 0;
    maxIterations 	NUMBER := 50;
	
BEGIN
	
   
    INSERT INTO TEMP_TREE_BROWSE ( SESSION_NUM, LEVEL_NUM, PV_ID )
    SELECT sessionNumber, iteration, rc.PV_ID
      FROM RELEASE_CONTENT rc
     WHERE rc.RTAG_ID = nRtag_id;
     
    iteration := iteration + 1;
    LOOP
        
        INSERT INTO TEMP_TREE_BROWSE ( SESSION_NUM, LEVEL_NUM, PV_ID )
		SELECT sessionNumber,     
               iteration,
               dep.DPV_ID
          FROM TEMP_TREE_BROWSE ttb,
               PACKAGE_DEPENDENCIES dep
         WHERE dep.PV_ID = ttb.PV_ID 
           AND ttb.LEVEL_NUM = iteration - 1 
           
         MINUS  
         
        SELECT sessionNumber, iteration, ttb.PV_ID
          FROM TEMP_TREE_BROWSE ttb;   
          
          
         
		
		rowCnt := SQL%ROWCOUNT;
		IF rowCnt > 0 THEN
           iteration := iteration + 1;
		END IF;
        EXIT WHEN (rowCnt < 1) OR (iteration > maxIterations);
    END LOOP; 
    
END PAOLO_Build_Tree;
/
--------------------------------------------------------
--  DDL for Procedure REBUILD_ENVIRONMENT
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REBUILD_ENVIRONMENT" ( NNrtag_id IN NUMBER ) IS

/* ---------------------------------------------------------------------------
    Version: 3.3
   --------------------------------------------------------------------------- */
    rowCnt NUMBER := 0;
    iteration NUMBER := 2;          -- Iterations counter
    maxIterations NUMBER := 50;    -- Maximum number of iterations allowed.
                                    -- This will prevent infinite loops if cyrcular dependencies are found
    sessionNum NUMBER;
BEGIN
    SELECT SEQ_session_num.nextval INTO sessionNum FROM DUAL;


    -- Redo Patch Ignore warnings
    Ignore_Dependency_Warnings ( NNrtag_id, NULL, NULL, TRUE );


    Level_One_Conflicts ( NNrtag_id, sessionNum );
	
    LOOP
        Level_N_Conflicts ( NNrtag_id, sessionNum, rowCnt, iteration );
        iteration := iteration + 1;
        EXIT WHEN (rowCnt < 1) OR (iteration > maxIterations);
    END LOOP;

    Update_Package_States ( NNrtag_id, sessionNum );

    DELETE FROM temp_env_states WHERE temp_env_states.session_num = sessionNum;

    -- Flag Packages with New Patches Available
    Check_New_Patches ( NNrtag_id );
	
	Clean_Do_Not_Ripple( NNrtag_id );


	/* Circular Dependency Flag */
    /*
	IF iteration > maxIterations
	THEN
		UPDATE release_tags SET
		   	   circular_dependency = 'Y'
		 WHERE rtag_id = NNrtag_id;
	ELSE
		UPDATE release_tags SET
		   	   circular_dependency = NULL
		 WHERE rtag_id = NNrtag_id;
	END IF;
    */
END Rebuild_Environment;
/
--------------------------------------------------------
--  DDL for Procedure RELEASE_MANAGER_MAILOUT
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "RELEASE_MANAGER_MAILOUT" (
  sender      IN VARCHAR2,
  recipient   IN VARCHAR2,
  ccrecipient IN VARCHAR2,
  subject     IN VARCHAR2,
  message     IN VARCHAR2
  ) IS

  crlf VARCHAR2(2):= UTL_TCP.CRLF;
  connection utl_smtp.connection;
  mailhost VARCHAR2(30) := 'aupera03.aupera.erggroup.com';
  header VARCHAR2(1000);

BEGIN

  --
  -- Start the connection.
  --
  connection := utl_smtp.open_connection(mailhost,25);

  header:= 'Date: '||TO_CHAR(SYSDATE,'dd Mon yy hh24:mi:ss')||crlf||
     'From: '||sender||''||crlf||
  'Subject: '||subject||crlf||
       'To: '||recipient||crlf||
       'CC: '||ccrecipient;

  --
  -- Handshake with the SMTP server
  --
  utl_smtp.helo(connection, mailhost);
  utl_smtp.mail(connection, sender);
  utl_smtp.rcpt(connection, recipient);
  utl_smtp.rcpt(connection, ccrecipient);
  utl_smtp.open_data(connection);
  --
  -- Write the header
  --
  utl_smtp.write_data(connection, header);
  --
  -- The crlf is required to distinguish that what comes next is not simply part of the header..
  --
  utl_smtp.write_data(connection, crlf ||message);
  utl_smtp.close_data(connection);
  utl_smtp.quit(connection);

EXCEPTION
  WHEN UTL_SMTP.INVALID_OPERATION THEN
    dbms_output.put_line(' Invalid Operation in SMTP transaction.');
  WHEN UTL_SMTP.TRANSIENT_ERROR THEN
    dbms_output.put_line(' Temporary problems with sending email - try again later.');
  WHEN UTL_SMTP.PERMANENT_ERROR THEN
    dbms_output.put_line(' Errors in code for SMTP transaction.');

END RELEASE_MANAGER_MAILOUT;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_COMPONENTS
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_COMPONENTS" ( nPvId IN RELEASE_COMPONENTS.PV_ID%TYPE ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */


BEGIN

	 --- Delete From RELEASE_COMPONENTS
	 DELETE FROM RELEASE_COMPONENTS
	 WHERE PV_ID = nPvId;

END Remove_Components;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_DOCUMENT
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_DOCUMENT" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
											  nDocId IN PACKAGE_DOCUMENTS.DOC_ID%TYPE,
                                              nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

   DocNumber PACKAGE_DOCUMENTS.DOC_NUM%TYPE;

BEGIN

	-- Get Doc Num
    SELECT pd.DOC_NUM INTO DocNumber
      FROM PACKAGE_DOCUMENTS pd
     WHERE pd.PV_ID = nPvId
       AND pd.DOC_ID = nDocId;


	-- Delete Document
    DELETE
      FROM PACKAGE_DOCUMENTS pd
     WHERE pd.PV_ID = nPvId
       AND pd.DOC_ID = nDocId;


    /* LOG ACTION */
   	Log_Action ( nPvId, 'document_remove', nUserId,
   			     'Document number: '|| DocNumber );


END Remove_Document;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_PACKAGE_INTEREST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_PACKAGE_INTEREST" (nProjId IN PROJECTS.PROJ_ID%TYPE,
	   	  		  								  	nPkgId IN PACKAGES.PKG_ID%TYPE,
												  	nUserId IN NUMBER
	   	  		  									) IS

/******************************************************************************
   NAME:       REMOVE_PACKAGE_INTEREST
   PURPOSE:    To remove interest in a given package per project

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        12/05/2006  Rupesh Solanki      1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     REMOVE_PACKAGE_INTEREST
      Sysdate:         12/05/2006
      Date and Time:   12/05/2006, 11:28:50 AM, and 12/05/2006 11:28:50 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
BEGIN

	 --Delete from PACKAGE_INTEREST
	 DELETE FROM PACKAGE_INTEREST
	 WHERE PROJ_ID = nProjId
	 AND PKG_ID = nPkgId
	 AND USER_ID = nUserId;
	 
END REMOVE_PACKAGE_INTEREST;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_PATCH
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_PATCH" ( nPatchId IN PACKAGE_PATCHES.PATCH_ID%TYPE,
										   nPvId IN PACKAGE_PATCHES.PV_ID%TYPE,
                                           nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

PatchVersion PACKAGE_VERSIONS.PKG_VERSION%TYPE;

CURSOR curPatch IS
	SELECT pp.PV_ID,
		   pp.PATCH_ID,
	       ROWNUM AS NEW_INSTALL_ORDER
	  FROM PACKAGE_PATCHES pp
	 WHERE pp.PV_ID = nPvId
	ORDER BY pp.INSTALL_ORDER;
recPatch curPatch%ROWTYPE;

BEGIN

	 -- Delete Patch
     DELETE
       FROM PACKAGE_PATCHES pp
      WHERE pp.PV_ID = nPvId
        AND pp.PATCH_ID = nPatchId;


	-- Redo Install Order
    OPEN curPatch;
	FETCH curPatch INTO recPatch;

	WHILE curPatch%FOUND
	LOOP

		UPDATE PACKAGE_PATCHES pp SET
			pp.INSTALL_ORDER = recPatch.NEW_INSTALL_ORDER
		WHERE pp.PV_ID = nPvId
		  AND pp.PATCH_ID = recPatch.PATCH_ID;

		FETCH curPatch INTO recPatch;
	END LOOP;

	CLOSE curPatch;




    /* LOG ACTION */
    SELECT pv.PKG_VERSION INTO PatchVersion
      FROM PACKAGE_VERSIONS pv
     WHERE pv.PV_ID = nPatchId;

   	Log_Action ( nPvId, 'patch_remove', nUserId,
   			     'Version: '|| PatchVersion );

END Remove_Patch;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_PROJECT_VIEW_OWNER
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_PROJECT_VIEW_OWNER" (nProjId IN NUMBER,
	   	  		  						 			  nViewId IN NUMBER,
										 			  sUserIdList IN VARCHAR2,
										 			  nUserId IN NUMBER ) IS

GroupId NUMBER;													  
										 
									 

/******************************************************************************
   NAME:       UPDATE_VIEW
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           		Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        10/04/2006     Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     UPDATE_VIEW
      Sysdate:         10/04/2006
      Date and Time:   10/04/2006, 1:55:19 PM, and 10/04/2006 1:55:19 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/

BEGIN
	 SELECT GROUP_EMAIL_ID into GroupId
	 FROM AUTOBUILD_FAILURE
	 WHERE PROJ_ID = nProjId
	 AND VIEW_ID = nViewId;
	 
	 DELETE FROM MEMBERS_GROUP
	 WHERE GROUP_EMAIL_ID = GroupId
	 AND USER_ID IN (
	 SELECT * FROM THE ( SELECT CAST( IN_LIST_NUMBER( sUserIdList ) AS RELMGR_NUMBER_TAB_t ) FROM dual ) 
	 );
	

	
END REMOVE_PROJECT_VIEW_OWNER;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_RELEASE_CONTENT
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_RELEASE_CONTENT" ( sPvIdList IN VARCHAR2,
													 sNotPvIdList IN VARCHAR2,
                                                     nRTagId IN RELEASE_CONTENT.RTAG_ID%TYPE ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

oPvIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
oNotPvIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

BEGIN
	oPvIdCollector := IN_LIST_NUMBER ( sPvIdList );
    oNotPvIdCollector := IN_LIST_NUMBER ( sNotPvIdList );

    -- Delete From Release Content
    DELETE
      FROM RELEASE_CONTENT
	 WHERE rtag_id = nRTagId
	   AND pv_id IN ( SELECT * FROM TABLE ( CAST ( oPvIdCollector AS RELMGR_NUMBER_TAB_t ) ) )
	   AND NOT pv_id IN ( SELECT * FROM TABLE ( CAST ( oNotPvIdCollector AS RELMGR_NUMBER_TAB_t ) ) );



END Remove_Release_Content;
/
--------------------------------------------------------
--  DDL for Procedure REMOVE_RUNTIME
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "REMOVE_RUNTIME" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
											 nRuntimeId IN RUNTIME_DEPENDENCIES.RTD_ID%TYPE,
                                             nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

   RuntimeDependency VARCHAR2(4000);

BEGIN

	-- Get Runtime dependency
    SELECT pkg.PKG_NAME ||' '|| pv.PKG_VERSION  INTO RuntimeDependency
	  FROM RUNTIME_DEPENDENCIES rtd,
	  	   PACKAGES pkg,
	       PACKAGE_VERSIONS pv
	 WHERE rtd.PV_ID = nPvId
	   AND pv.PKG_ID = pkg.PKG_ID
	   AND rtd.RTD_ID = pv.PV_ID
	   AND rtd.RTD_ID = nRuntimeId;


	-- Delete Document
    DELETE
      FROM RUNTIME_DEPENDENCIES rtd
     WHERE rtd.PV_ID = nPvId
       AND rtd.RTD_ID = nRuntimeId;


    /* LOG ACTION */
   	Log_Action ( nPvId, 'runtime_remove', nUserId,
   			     'Runtime package: '|| RuntimeDependency );


END Remove_Runtime;
/
--------------------------------------------------------
--  DDL for Procedure RENAME_PACKAGE_VERSION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "RENAME_PACKAGE_VERSION" ( NNpv_id IN NUMBER,
                                                     SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
													 cBuildType IN CHAR,
                                                     NNuser_id IN NUMBER,
                                                     errMessage OUT VARCHAR2 ) IS
/* ---------------------------------------------------------------------------
    Version: 3.2
   --------------------------------------------------------------------------- */

    sPackageVersion VARCHAR2(4000);
	sLabel VARCHAR2(4000) := NULL;
    OldPkgVersion PACKAGE_VERSIONS.PKG_VERSION%TYPE;

    SSV_MM PACKAGE_VERSIONS.V_MM%TYPE;
    SSV_NMM PACKAGE_VERSIONS.V_NMM%TYPE;
    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;

    CURSOR package_versions_cur IS
        SELECT pv_id
     	  FROM package_versions
     	 WHERE pkg_id IN ( SELECT pkg_id FROM package_versions WHERE pv_id = NNpv_id )
     	   AND pkg_version = SSpkg_version;
    package_versions_rec package_versions_cur%ROWTYPE;


BEGIN

    /* ---------------------------------------------------- */
    /* Find if package_version exists                       */
    /* ---------------------------------------------------- */

	errMessage := NULL;


	-- Get previous version
	SELECT pv.PKG_VERSION INTO OldPkgVersion
      FROM PACKAGE_VERSIONS pv
     WHERE pv.PV_ID = NNpv_id;


	sPackageVersion := SSpkg_version;


	IF OldPkgVersion != sPackageVersion THEN

	    OPEN package_versions_cur;
	    FETCH package_versions_cur INTO package_versions_rec;

	    IF package_versions_cur%NOTFOUND
	    THEN

			-- Split current version in parts
	    	Split_Version ( SSpkg_version, SSV_MM, SSV_NMM, SSV_EXT );


		    -- Automated built config
			IF (cBuildType = 'A') THEN
				sPackageVersion := '('|| NNpv_id ||')'|| SSV_EXT;	-- Make sure that version is still unique
			END IF;


	        -- Packge version not found, hence rename it.
	        UPDATE package_versions
	           SET pkg_version = sPackageVersion,
	               v_mm = SSV_MM,
	               v_nmm = SSV_NMM,
	               v_ext = SSV_EXT,
	               modified_stamp = ORA_SYSDATETIME,
	               modifier_id = NNuser_id,
				   build_type = cBuildType,
				   pkg_label = NULL
	         WHERE pv_id = NNpv_id;


			IF (cBuildType = 'A') THEN
				sLabel := GET_AUTOMATED_LABEL( NNpv_id );
				UPDATE PACKAGE_VERSIONS pv SET
					pv.PKG_LABEL = sLabel
		         WHERE pv_id = NNpv_id;
			END IF;

			/* LOG ACTION */
	      	Log_Action ( NNpv_id, 'rename', NNuser_id, 'From '|| OldPkgVersion ||' to '|| SSpkg_version );

	    ELSE
	        -- Package version exists. Cannot proceed.
	        errMessage := 'enum_MSG_VERSION_EXISTS';

	    END IF;

	    CLOSE package_versions_cur;

	END IF;




END Rename_Package_Version;
/
--------------------------------------------------------
--  DDL for Procedure RESET_IGNORE_WARNINGS
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "RESET_IGNORE_WARNINGS" ( sPvIdList IN VARCHAR2,
                                                    nRTagId IN RELEASE_CONTENT.RTAG_ID%TYPE ) IS
/* ---------------------------------------------------------------------------
    Version: 5.0
   --------------------------------------------------------------------------- */

oPvIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

BEGIN
	oPvIdCollector := IN_LIST_NUMBER ( sPvIdList );

    -- Remove Ignore Warnings
     DELETE
       FROM ignore_warnings
	  WHERE (rtag_id, pv_id, dpv_id) IN
	     (
	      SELECT igw.rtag_id, igw.pv_id, igw.dpv_id
	        FROM ignore_warnings igw,
	             package_versions dpv,
	             package_versions pv
	       WHERE igw.dpv_id = dpv.pv_id
	         AND igw.rtag_id = nRTagId
	         AND dpv.pkg_id = pv.pkg_id
	         AND NVL(dpv.v_ext,'|LINK_A_NULL|') = NVL(pv.v_ext,'|LINK_A_NULL|')
	         AND pv.pv_id IN ( SELECT * FROM TABLE ( CAST ( oPvIdCollector AS RELMGR_NUMBER_TAB_t ) ) )
         );

END Reset_Ignore_Warnings;
/
--------------------------------------------------------
--  DDL for Procedure RIPPLE_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "RIPPLE_PACKAGE" (
        sPvIdList IN VARCHAR2,
        nRtagId IN RELEASE_TAGS.RTAG_ID%TYPE,
        nUserId IN NUMBER
    ) IS
/* ---------------------------------------------------------------------------
    Version: 4.1
   --------------------------------------------------------------------------- */

BEGIN

    IF (sPvIdList IS NULL) THEN
        RAISE_APPLICATION_ERROR (-20000, 'Please select at least one package.' );
    END IF;

    -- Ripple Package
    DELETE FROM DO_NOT_RIPPLE
    WHERE RTAG_ID = nRtagId
    AND PV_ID IN (
        SELECT *
        FROM THE (
            SELECT CAST( IN_LIST_NUMBER( sPvIdList )
            AS RELMGR_NUMBER_TAB_t )
            FROM DUAL
        )
    );

    /* LOG ACTION */
    Log_Action_Bulk ( sPvIdList, 'ripple_package', nUserId );

END Ripple_Package;
/
--------------------------------------------------------
--  DDL for Procedure SEED_PACKAGE_NAMES_VERSIONS
--------------------------------------------------------

CREATE OR REPLACE PROCEDURE "SEED_PACKAGE_NAMES_VERSIONS" ( SSpkg_name IN PACKAGES.pkg_name%TYPE,
                                                          SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
                                                          NNuser_id IN NUMBER,
                                                          retPV_ID OUT NUMBER,
                                                          nCloneFromPvId IN NUMBER DEFAULT NULL,
                                                          nBuildType IN CHAR DEFAULT 'M',
                                                          nChangeType IN CHAR DEFAULT 'F') IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

    parPkg_id   NUMBER;
    parPv_id    NUMBER;
    cloneFrom_pv_id NUMBER;
    SSV_MM PACKAGE_VERSIONS.V_MM%TYPE;
    SSV_NMM PACKAGE_VERSIONS.V_NMM%TYPE;
    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;
    spackageversion VARCHAR2 (4000);
    
    CURSOR packages_cur IS
        SELECT pkg_id FROM PACKAGES
        WHERE pkg_name = SSpkg_name;
    packages_rec packages_cur%ROWTYPE;

    CURSOR package_versions_cur IS
        SELECT pv_id FROM PACKAGE_VERSIONS
        WHERE pkg_id = parPkg_id
        AND pkg_version = SSpkg_version;
    package_versions_rec package_versions_cur%ROWTYPE;

    CURSOR clone_package_versions_cur IS
        SELECT MAX(pv_id) AS pv_id
          FROM PACKAGE_VERSIONS
         WHERE pkg_id = parPkg_id
           AND NVL(v_ext,'LINK_A_NULL') = NVL(SSV_EXT,'LINK_A_NULL');
    clone_package_versions_rec clone_package_versions_cur%ROWTYPE;

BEGIN
    /* -------------------------------------------- */
    /* Find if pkg_name exists and seed if required */
    /* -------------------------------------------- */
    OPEN packages_cur;
    FETCH packages_cur INTO packages_rec;

    IF packages_cur%NOTFOUND
    THEN
        /* INSERT into packages table */
        SELECT SEQ_PKG_ID.NEXTVAL INTO parPkg_id FROM DUAL;
        INSERT INTO PACKAGES ( pkg_id, pkg_name ) VALUES ( parPkg_id, SSpkg_name );

    ELSE
        parPkg_id := packages_rec.pkg_id;

    END IF;

    CLOSE packages_cur;


    /* ---------------------------------------------------- */
    /* Find if package_version exists and seed if required  */
    /* ---------------------------------------------------- */
    OPEN package_versions_cur;
    FETCH package_versions_cur INTO package_versions_rec;

    IF package_versions_cur%NOTFOUND
    THEN
        SELECT SEQ_PV_ID.NEXTVAL INTO parPv_id FROM DUAL;

        /* Generate automated version Number */
        Split_Version ( SSpkg_version, SSV_MM, SSV_NMM, SSV_EXT );
        spackageversion := SSpkg_version;
                
        IF ( nBuildType = 'A' )
        THEN
            spackageversion := '(' || parPv_id || ')' || SSV_EXT;
        END If;
        
        /* LOG ACTION */
        Log_Action ( parPv_id, 'new_version', NNuser_id,
                     'New package version: '|| spackageversion );

        
        /* Find similar pkg_name + ext to clone from */
        OPEN clone_package_versions_cur;
        FETCH clone_package_versions_cur INTO clone_package_versions_rec;


        IF NOT clone_package_versions_rec.pv_id IS NULL
        THEN
            /* CLONE details from similar version  OR  from nCloneFromPvId */
            IF ( NOT nCloneFromPvId IS NULL) THEN
                cloneFrom_pv_id := nCloneFromPvId;
            ELSE
                cloneFrom_pv_id := clone_package_versions_rec.pv_id;
            END IF;

            -- Clone Package Version Details --
            INSERT INTO PACKAGE_VERSIONS ( pv_id, pkg_id, pkg_version, dlocked, created_stamp, creator_id, modified_stamp, modifier_id, V_MM, V_NMM, V_EXT,
                                           src_path, pv_description, PV_OVERVIEW, LAST_PV_ID, owner_id, BUILD_TYPE, IS_BUILD_ENV_REQUIRED, bs_id, is_autobuildable, is_deployable, ripple_field,change_type  )
                SELECT parPv_id         AS pv_id,
                       parPkg_id        AS pkg_id,
                       spackageversion  AS pkg_version,
                       'N'              AS dlocked,
                       Ora_Sysdate      AS created_stamp,
                       NNuser_id        AS creator_id,
                       Ora_Sysdatetime  AS modified_stamp,
                       NNuser_id        AS modifier_id,
                       SSV_MM           AS V_MM,
                       SSV_NMM          AS V_NMM,
                       SSV_EXT          AS V_EXT,
                       pv.src_path,
                       pv.pv_description,
                       pv.PV_OVERVIEW,
                       cloneFrom_pv_id  AS LAST_PV_ID,
                       pv.owner_id,
                       nBuildType       AS BUILD_TYPE,
                       pv.IS_BUILD_ENV_REQUIRED,
                       pv.BS_ID,
                       pv.is_autobuildable,
                       pv.IS_DEPLOYABLE, 
                       pv.ripple_field,
                       nChangeType       AS change_type
                  FROM PACKAGE_VERSIONS pv
                 WHERE pv.pv_id = cloneFrom_pv_id;

            Basic_Clone ( cloneFrom_pv_id, parPv_id, NULL, NNuser_id, parPkg_id, 0 );

        ELSE
            /* BRAND NEW version + ext */
            INSERT INTO PACKAGE_VERSIONS ( pv_id, pkg_id, pkg_version, dlocked, created_stamp, creator_id, modified_stamp, modifier_id, V_MM, V_NMM, V_EXT, owner_id, LAST_PV_ID, BUILD_TYPE, ripple_field, change_type )
            VALUES (
                    parPv_id,
                    parPkg_id,
                    spackageversion,
                    'N',
                    Ora_Sysdate,
                    NNuser_id,
                    Ora_Sysdatetime,
                    NNuser_id,
                    SSV_MM,
                    SSV_NMM,
                    SSV_EXT,
                    NNuser_id,
                    parPv_id,
                    nBuildType,
                    'b',
                    nChangeType
                   );

        END IF;

        CLOSE clone_package_versions_cur;
        retPV_ID := parPv_id;

    ELSE
        retPV_ID := package_versions_rec.pv_id;

    END IF;

    CLOSE package_versions_cur;

END Seed_Package_Names_Versions;
/

--------------------------------------------------------
--  DDL for Procedure SEED_PACKAGE_NAMES_VERSIONS2
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SEED_PACKAGE_NAMES_VERSIONS2" ( SSpkg_name IN PACKAGES.pkg_name%TYPE,
                                                          SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
                                                          NNuser_id IN NUMBER,
                                                          retPV_ID OUT NUMBER,
														  nCloneFromPvId IN NUMBER DEFAULT NULL ) IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

    parPkg_id   NUMBER;
    parPv_id    NUMBER;
    cloneFrom_pv_id NUMBER;
    SSV_MM PACKAGE_VERSIONS.V_MM%TYPE;
    SSV_NMM PACKAGE_VERSIONS.V_NMM%TYPE;
    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;

    CURSOR packages_cur IS
        SELECT pkg_id FROM PACKAGES
        WHERE pkg_name = SSpkg_name;
    packages_rec packages_cur%ROWTYPE;

    CURSOR package_versions_cur IS
        SELECT pv_id FROM PACKAGE_VERSIONS
        WHERE pkg_id = parPkg_id
        AND pkg_version = SSpkg_version;
    package_versions_rec package_versions_cur%ROWTYPE;

    CURSOR clone_package_versions_cur IS
        SELECT MAX(pv_id) AS pv_id
          FROM PACKAGE_VERSIONS
         WHERE pkg_id = parPkg_id
           AND NVL(v_ext,'LINK_A_NULL') = NVL(SSV_EXT,'LINK_A_NULL');
    clone_package_versions_rec clone_package_versions_cur%ROWTYPE;

BEGIN
    /* -------------------------------------------- */
    /* Find if pkg_name exists and seed if required */
    /* -------------------------------------------- */
    OPEN packages_cur;
    FETCH packages_cur INTO packages_rec;

    IF packages_cur%NOTFOUND
    THEN
        /* INSERT into packages table */
        SELECT SEQ_PKG_ID.NEXTVAL INTO parPkg_id FROM DUAL;
        INSERT INTO PACKAGES ( pkg_id, pkg_name ) VALUES ( parPkg_id, SSpkg_name );

    ELSE
        parPkg_id := packages_rec.pkg_id;

    END IF;

    CLOSE packages_cur;



    /* ---------------------------------------------------- */
    /* Find if package_version exists and seed if required  */
    /* ---------------------------------------------------- */
    OPEN package_versions_cur;
    FETCH package_versions_cur INTO package_versions_rec;

    IF package_versions_cur%NOTFOUND
    THEN
        SELECT SEQ_PV_ID.NEXTVAL INTO parPv_id FROM DUAL;

        /* LOG ACTION */
        Log_Action ( parPv_id, 'new_version', NNuser_id,
        			 'New package version: '|| SSpkg_version );

        Split_Version ( SSpkg_version, SSV_MM, SSV_NMM, SSV_EXT );





            /* CLONE details from similar version  OR  from nCloneFromPvId */
			IF ( NOT nCloneFromPvId IS NULL) THEN
            	cloneFrom_pv_id := nCloneFromPvId;
			ELSE
				cloneFrom_pv_id := clone_package_versions_rec.pv_id;
			END IF;

            -- Clone Package Version Details --
            INSERT INTO PACKAGE_VERSIONS ( pv_id, pkg_id, pkg_version, dlocked, created_stamp, creator_id, modified_stamp, modifier_id, V_MM, V_NMM, V_EXT,
                                           src_path, pv_description, PV_OVERVIEW, LAST_PV_ID, owner_id, BUILD_TYPE, IS_BUILD_ENV_REQUIRED, bs_id, is_autobuildable, is_deployable, ripple_field )
                SELECT parPv_id         AS pv_id,
                       parPkg_id        AS pkg_id,
                       SSpkg_version    AS pkg_version,
                       'N'              AS dlocked,
                       Ora_Sysdate      AS created_stamp,
                       NNuser_id        AS creator_id,
                       Ora_Sysdatetime  AS modified_stamp,
                       NNuser_id        AS modifier_id,
                       SSV_MM           AS V_MM,
                       SSV_NMM          AS V_NMM,
                       SSV_EXT          AS V_EXT,
                       pv.src_path,
                       pv.pv_description,
                       pv.PV_OVERVIEW,
                       cloneFrom_pv_id 	AS LAST_PV_ID,
                       pv.owner_id,
					   pv.BUILD_TYPE,
					   pv.IS_BUILD_ENV_REQUIRED,
					   pv.bs_id,
					   pv.is_autobuildable,
					   pv.IS_DEPLOYABLE,
					   pv.ripple_field
                  FROM PACKAGE_VERSIONS pv
                 WHERE pv.pv_id = cloneFrom_pv_id;

            Basic_Clone ( cloneFrom_pv_id, parPv_id, NULL, NNuser_id, parPkg_id, 0 );

        retPV_ID := parPv_id;

    ELSE
        retPV_ID := package_versions_rec.pv_id;

    END IF;

    CLOSE package_versions_cur;




END Seed_Package_Names_Versions2;
/
--------------------------------------------------------
--  DDL for Procedure SET_ADVISORY_RIPPLE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SET_ADVISORY_RIPPLE" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
	   	  		  							   nRtagId IN RELEASE_TAGS.RTAG_ID%TYPE,
											 nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 4.0
   --------------------------------------------------------------------------- */

BEGIN

    -- Set Advisory Ripple Package
    INSERT INTO ADVISORY_RIPPLE (RTAG_ID, PV_ID)
	VALUES (nRtagId, nPvId);

    /* LOG ACTION */
   	Log_Action ( nPvId, 'set_advisory_ripple', nUserId );
	
	/*Rebuild_Environment(nRtagId);*/

END Set_Advisory_Ripple;
/
--------------------------------------------------------
--  DDL for Procedure SET_PACKAGE_BUILD_ENV
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SET_PACKAGE_BUILD_ENV" ( nPvId IN PACKAGE_BUILD_ENV.PV_ID%TYPE,
	   	  		  								  	sBuildEnvIdList IN VARCHAR2 ) IS
/* ---------------------------------------------------------------------------
    Last Modified: Rupesh Solanki
	Version: 3.0.1
   --------------------------------------------------------------------------- */


BEGIN

   -- Delete Current Build Env settings
   DELETE FROM PACKAGE_BUILD_ENV
   WHERE pv_id = nPvId;
   
   -- Delet Current Package Build Info Settings
   DELETE FROM PACKAGE_BUILD_INFO
   WHERE pv_id = nPvId;

   -- Reset flag to N
   UPDATE PACKAGE_VERSIONS SET
	   IS_BUILD_ENV_REQUIRED = 'N'
   WHERE PV_ID = nPvId;


   -- Set new Build Env
   IF NOT sBuildEnvIdList IS NULL THEN
   	  -- Insert into PACKAGE_BUILD_ENV
      INSERT INTO PACKAGE_BUILD_ENV ( PV_ID, BE_ID )
	  SELECT nPvId AS PV_ID,
	  		 be.BE_ID
	    FROM BUILD_ENVIRONMENTS be
	   WHERE be.BE_ID IN (
	   		 		  	   SELECT *
					   	     FROM THE ( SELECT CAST( IN_LIST_NUMBER( sBuildEnvIdList ) AS RELMGR_NUMBER_TAB_t ) FROM dual )
	   		 		  	 );
						 
   	  -- Insert into PACKAGE_BUILD_INFO
      INSERT INTO PACKAGE_BUILD_INFO ( PV_ID, BM_ID )
	  SELECT nPvId AS PV_ID,
	  		 be.BM_ID
	    FROM BUILD_MACHINES be
	   WHERE be.BM_ID IN (
	   		 		  	   SELECT *
					   	     FROM THE ( SELECT CAST( IN_LIST_NUMBER( sBuildEnvIdList ) AS RELMGR_NUMBER_TAB_t ) FROM dual )
	   		 		  	 );						 

	   -- Set flag to Y
	   UPDATE PACKAGE_VERSIONS SET
		   IS_BUILD_ENV_REQUIRED = 'Y'
	   WHERE PV_ID = nPvId;

   END IF;


END Set_Package_Build_Env;
/
--------------------------------------------------------
--  DDL for Procedure SET_PACKAGE_BUILD_ENV_TEMP
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SET_PACKAGE_BUILD_ENV_TEMP" ( nPvId IN PACKAGE_BUILD_ENV.PV_ID%TYPE,
	   	  		  								  	   	 sBuildEnvIdList IN VARCHAR2,
														 nBuildStandard IN PACKAGE_VERSIONS.BS_ID%TYPE 
														 ) IS
/* ---------------------------------------------------------------------------
    Last Modified: Rupesh Solanki
	Version: 3.0.1
   --------------------------------------------------------------------------- */
   
   nBsCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();   
   BsId NUMBER;
   HackBsId NUMBER;


BEGIN

   nBsCollector := IN_LIST_NUMBER ( sBuildEnvIdList );

   -- Delete Current Build Env settings
   DELETE FROM PACKAGE_BUILD_ENV
   WHERE pv_id = nPvId;
   
   -- Delet Current Package Build Info Settings
   DELETE FROM PACKAGE_BUILD_INFO
   WHERE pv_id = nPvId;

   -- Reset flag to N
   UPDATE PACKAGE_VERSIONS SET
	   IS_BUILD_ENV_REQUIRED = 'N'
   WHERE PV_ID = nPvId;


   -- Set new Build Env
   IF NOT sBuildEnvIdList IS NULL THEN
	FOR i IN 1..nBsCollector.COUNT
	LOOP   
	
	BsId := nBsCollector(i);
	
	IF nBuildStandard = 2 THEN
	   IF BsId = 1 THEN
	   	  HackBsId := 11;
	   ELSE
	   	  HackBsId := 12;
	   END IF;
	   
   	  -- Insert into PACKAGE_BUILD_ENV
      INSERT INTO PACKAGE_BUILD_ENV ( PV_ID, BE_ID )
	  SELECT nPvId AS PV_ID,
	  		 be.BE_ID
	    FROM BUILD_ENVIRONMENTS be
	   WHERE be.BE_ID IN ( HackBsId );
						 
   	  -- Insert into PACKAGE_BUILD_INFO
      INSERT INTO PACKAGE_BUILD_INFO ( PV_ID, BM_ID )
	  SELECT nPvId AS PV_ID,
	  		 be.BM_ID
	    FROM BUILD_MACHINES be
	   WHERE be.BM_ID IN ( BsId );						 

	   -- Set flag to Y
	   UPDATE PACKAGE_VERSIONS SET
		   IS_BUILD_ENV_REQUIRED = 'Y'
	   WHERE PV_ID = nPvId;	
	
	
	ELSE
	
   	  -- Insert into PACKAGE_BUILD_ENV
      INSERT INTO PACKAGE_BUILD_ENV ( PV_ID, BE_ID )
	  SELECT nPvId AS PV_ID,
	  		 be.BE_ID
	    FROM BUILD_ENVIRONMENTS be
	   WHERE be.BE_ID IN ( BsId );
						 
   	  -- Insert into PACKAGE_BUILD_INFO
      INSERT INTO PACKAGE_BUILD_INFO ( PV_ID, BM_ID )
	  SELECT nPvId AS PV_ID,
	  		 be.BM_ID
	    FROM BUILD_MACHINES be
	   WHERE be.BM_ID IN ( BsId );						 

	   -- Set flag to Y
	   UPDATE PACKAGE_VERSIONS SET
		   IS_BUILD_ENV_REQUIRED = 'Y'
	   WHERE PV_ID = nPvId;
	   
	END IF;  
	   
	   
	END LOOP;	   

   END IF;


END Set_Package_Build_Env_Temp;
/
--------------------------------------------------------
--  DDL for Procedure SET_TO_AUTOBUILDABLE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SET_TO_AUTOBUILDABLE" (
   nrtagid     IN   NUMBER,
   spvidlist   IN   VARCHAR2
)
IS
/******************************************************************************
   NAME:       SET_TO_AUTOBUILDABLE
   PURPOSE:

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        15/12/2006   Rupesh Solanki       1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     SET_TO_AUTOBUILDABLE
      Sysdate:         15/12/2006
      Date and Time:   15/12/2006, 11:42:29 AM, and 15/12/2006 11:42:29 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   npvidcollector   relmgr_number_tab_t := relmgr_number_tab_t ();
   PvId NUMBER;
BEGIN

   npvidcollector := in_list_number2 (spvidlist);
   
   UPDATE package_versions
      SET is_autobuildable = 'N'
    WHERE pv_id IN (SELECT pv_id
                      FROM release_content
                     WHERE rtag_id = nrtagid);

  
   
   	FOR i IN 1..npvidcollector.COUNT
	LOOP
		PvId := npvidcollector(i);

		UPDATE package_versions
		set is_autobuildable = 'Y'
		where pv_id = PvId;

	END LOOP;
   
   
END set_to_autobuildable;
/
--------------------------------------------------------
--  DDL for Procedure SHIFT_INSTALL_ORDER
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SHIFT_INSTALL_ORDER" ( nPatchId IN PACKAGE_PATCHES.PATCH_ID%TYPE,
												  nPvId IN PACKAGE_PATCHES.PV_ID%TYPE,
                                                  nToInstallOrder IN PACKAGE_PATCHES.INSTALL_ORDER%TYPE ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

currInstallOrder NUMBER;
FromInstallOrder NUMBER;

BEGIN

	 -- Get Current Install Order
     SELECT pp.INSTALL_ORDER INTO currInstallOrder
       FROM PACKAGE_PATCHES pp
      WHERE pp.PV_ID = nPvId
        AND pp.PATCH_ID = nPatchId;


	 IF currInstallOrder > nToInstallOrder
	 THEN

		FromInstallOrder := nToInstallOrder;

	    -- Shift others Up
		UPDATE PACKAGE_PATCHES pp SET
			   pp.INSTALL_ORDER = pp.INSTALL_ORDER + 1
		 WHERE pp.PV_ID = nPvId
           AND pp.PATCH_ID != nPatchId
		   AND pp.INSTALL_ORDER BETWEEN  FromInstallOrder  AND  currInstallOrder - 1;


	 ELSIF currInstallOrder < nToInstallOrder
	 THEN

		FromInstallOrder := currInstallOrder + 1;

		-- Shift others Down
        UPDATE PACKAGE_PATCHES pp SET
			   pp.INSTALL_ORDER = pp.INSTALL_ORDER - 1
		 WHERE pp.PV_ID = nPvId
           AND pp.PATCH_ID != nPatchId
		   AND pp.INSTALL_ORDER BETWEEN  FromInstallOrder  AND  nToInstallOrder;

	 END IF;


	 -- Move Patch to new install order
     UPDATE PACKAGE_PATCHES pp SET
		    pp.INSTALL_ORDER = nToInstallOrder
	  WHERE pp.PV_ID = nPvId
	    AND pp.PATCH_ID = nPatchId;


END Shift_Install_Order;
/
--------------------------------------------------------
--  DDL for Procedure SPLIT_VERSION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SPLIT_VERSION" ( SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
                                            SSV_MM OUT PACKAGE_VERSIONS.V_MM%TYPE,
                                            SSV_NMM OUT PACKAGE_VERSIONS.V_NMM%TYPE,
                                            SSV_EXT OUT PACKAGE_VERSIONS.V_EXT%TYPE  ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    TYPE VERSION_COMPONENTS_TYPE IS TABLE OF VARCHAR2(50)
        INDEX BY BINARY_INTEGER;

    version_components VERSION_COMPONENTS_TYPE;
    lastDot NUMBER := 0;
    currDot NUMBER := 0;

BEGIN
    currDot := INSTR ( SSpkg_version, '.', -1 );      -- Find 1st dot from the right

    IF ( currDot > 0 )
    THEN
        -- YES dot separator found --
        SSV_EXT := GET_V_EXT( SSpkg_version );

        IF NOT SSV_EXT IS NULL
        THEN
            lastDot := currDot;
            currDot := INSTR ( SSpkg_version, '.', -1, 2 );   -- Find 2nd dot from the right

            IF ( currDot > 0 )
            THEN
                -- XXXX.M.E
                SSV_MM := SUBSTR ( SSpkg_version, currDot + 1, lastDot - currDot - 1);
                SSV_NMM := SUBSTR ( SSpkg_version, 0, currDot ) || SSV_EXT;
            ELSE
                -- XXXX.E
                SSV_MM := NULL;
                SSV_NMM := SSpkg_version;
            END IF;

        ELSE
            -- XXXX.M
            SSV_MM := SUBSTR ( SSpkg_version, currDot + 1, LENGTH(SSpkg_version) - currDot );
            SSV_NMM := SUBSTR ( SSpkg_version, 0, currDot );

        END IF;

    ELSE
        -- NO dot separator found --
        -- XXXXXX
        SSV_MM  := NULL;
        SSV_NMM := SSpkg_version;
        SSV_EXT := NULL;

    END IF;

END Split_Version;
/
--------------------------------------------------------
--  DDL for Procedure SWITCH_REPRODUCIBLE_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SWITCH_REPRODUCIBLE_PACKAGE" (nPvId IN NUMBER, nUserId IN NUMBER)IS
Auto CHAR;
/******************************************************************************
   NAME:       SWITCH_REPRODUCIBLE_PACKAGE
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        14/12/2006   Rupesh Solanki       1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     SWITCH_REPRODUCIBLE_PACKAGE
      Sysdate:         14/12/2006
      Date and Time:   14/12/2006, 11:35:15 AM, and 14/12/2006 11:35:15 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
BEGIN

	 SELECT IS_AUTOBUILDABLE into Auto
	 FROM PACKAGE_VERSIONS 
	 WHERE PV_ID = nPvId;

	 IF Auto = 'N' Then
	 
	 	UPDATE PACKAGE_VERSIONS
	 	SET IS_AUTOBUILDABLE = 'Y'
	 	WHERE PV_ID = nPvId;
	 
	 
	 	/* LOG ACTION */
   		Log_Action ( nPvId, 'reproducible_package', nUserId );	 
	 
	 Else
	 	 
		 UPDATE PACKAGE_VERSIONS
		 SET IS_AUTOBUILDABLE = 'N'
		 WHERE PV_ID = nPvId;
	 	 
	 
	 	 /* LOG ACTION */
   	 	 Log_Action ( nPvId, 'unreproducible_package', nUserId );	 
	 
	 End If;
	 
	 

	




END SWITCH_REPRODUCIBLE_PACKAGE;
/
--------------------------------------------------------
--  DDL for Procedure SYNC_PROJECTS_NEW_VERSION
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "SYNC_PROJECTS_NEW_VERSION" ( nPv_id 				IN NUMBER,
														  sSyncRtagsInList		IN VARCHAR2,
				                                          nUser_id 				IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

	CURSOR sync_rtags_cur IS
        SELECT rc.RTAG_ID, rc.BASE_VIEW_ID, pv.pv_id
		  FROM release_content rc,
		  	   package_versions pv,
		       package_versions opv
		 WHERE rc.pv_id = pv.pv_id
		   AND opv.pkg_id = pv.pkg_id
		   AND NVL(opv.v_ext, '|LINK_A_NULL|') = NVL(pv.v_ext, '|LINK_A_NULL|')
		   AND opv.pv_id = nPv_id
		   AND rtag_id IN ( SELECT *
		   	   		   	      FROM THE (
					   	   		   	    SELECT CAST( IN_LIST_NUMBER( sSyncRtagsInList ) AS RELMGR_NUMBER_TAB_t )
					       		   	    FROM dual
									   )
						  );
    sync_rtags_rec sync_rtags_cur%ROWTYPE;

BEGIN

	OPEN sync_rtags_cur;
	FETCH sync_rtags_cur INTO sync_rtags_rec;

	WHILE sync_rtags_cur%FOUND
	LOOP
		DELETE FROM RELEASE_CONTENT
		 WHERE rtag_id = sync_rtags_rec.rtag_id
	       AND pv_id = sync_rtags_rec.pv_id;

		INSERT INTO RELEASE_CONTENT ( RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE )
	   		   VALUES ( sync_rtags_rec.rtag_id,
		       		  	nPv_id,
						sync_rtags_rec.BASE_VIEW_ID,
	           			Ora_Sysdate,
	           			nUser_id,
						0
	      	   		   );

-- 		UPDATE RELEASE_CONTENT
-- 	       SET pv_id = nPv_id,
-- 	           insert_stamp = Ora_Sysdate,
-- 	           insertor_id = nUser_id
-- 	     WHERE rtag_id = sync_rtags_rec.rtag_id
-- 	       AND pv_id = sync_rtags_rec.pv_id;

		FETCH sync_rtags_cur INTO sync_rtags_rec;
	END LOOP;

	CLOSE sync_rtags_cur;

END Sync_Projects_New_Version;
/
--------------------------------------------------------
--  DDL for Procedure TEST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "TEST" 
IS

proc_id NUMBER;
/******************************************************************************
   NAME:       DELETE_DO_NOT_RIPPLE
   PURPOSE:    TO DELETE ENTRIES FROM THE DO_NOT_RIPPLE TABLE WHEN A PACKAGE
               IS RELEASED

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        21/04/2006  Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     DELETE_DO_NOT_RIPPLE
      Sysdate:         21/04/2006
      Date and Time:   21/04/2006, 3:21:55 PM, and 21/04/2006 3:21:55 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   CURSOR ripple_cur
   IS
      select distinct pkg_health_tag, cmd_interface, pkg_owner, is_interface from deployment_manager.processes_config;

   ripple_rec   ripple_cur%ROWTYPE;
BEGIN
   OPEN ripple_cur;

   FETCH ripple_cur
    INTO ripple_rec;

   WHILE ripple_cur%FOUND
   LOOP
   
   select deployment_manager.seq_proc_id.nextval into proc_id from dual;
   
insert into processes (PROC_ID, PROC_NAME, RUN_AS, PKG_OWNER, IS_INTERFACE) 
values(proc_id, ripple_rec.pkg_health_tag, ripple_rec.cmd_interface, ripple_rec.pkg_owner, ripple_rec.is_interface);

      FETCH ripple_cur
       INTO ripple_rec;
   END LOOP;
END test;
/
--------------------------------------------------------
--  DDL for Procedure TEST_MARCO
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "TEST_MARCO" IS
/******************************************************************************
   NAME:       TEST_MARCO
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        2/03/2007          1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     TEST_MARCO
      Sysdate:         2/03/2007
      Date and Time:   2/03/2007, 3:11:11 PM, and 2/03/2007 3:11:11 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/

parPv_id    NUMBER;
parPkg_id   NUMBER;
    SSV_MM PACKAGE_VERSIONS.V_MM%TYPE;
    SSV_NMM PACKAGE_VERSIONS.V_NMM%TYPE;
    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;
BEGIN

SELECT SEQ_PV_ID.NEXTVAL INTO parPv_id FROM DUAL;

        /* LOG ACTION */
        Log_Action ( parPv_id, 'new_version', 3764,
        			 'New package version: '|| parPv_id || '.' );

        Split_Version ( parPv_id || '.', SSV_MM, SSV_NMM, SSV_EXT );
		
     -- Clone Package Version Details --
            INSERT INTO PACKAGE_VERSIONS ( pv_id, pkg_id, pkg_version, dlocked, created_stamp, creator_id, modified_stamp, modifier_id, V_MM, V_NMM, V_EXT,
                                           src_path, pv_description, PV_OVERVIEW, LAST_PV_ID, owner_id, BUILD_TYPE, IS_BUILD_ENV_REQUIRED, bs_id, is_autobuildable, is_deployable )
                SELECT parPv_id         AS pv_id,
                       pv.pkg_id        AS pkg_id,
                       parPv_id || '.'    AS pkg_version,
                       'N'              AS dlocked,
                       Ora_Sysdate      AS created_stamp,
                       3764        AS creator_id,
                       Ora_Sysdatetime  AS modified_stamp,
                       3764        AS modifier_id,
                       SSV_MM          AS V_MM,
                       SSV_NMM         AS V_NMM,
                       SSV_EXT          AS V_EXT,
                       pv.src_path,
                       pv.pv_description,
                       pv.PV_OVERVIEW,
                       112982 	AS LAST_PV_ID,
                       pv.owner_id,
					   pv.BUILD_TYPE,
					   pv.IS_BUILD_ENV_REQUIRED,
					   pv.bs_id,
					   pv.is_autobuildable,
					   pv.IS_DEPLOYABLE
                  FROM PACKAGE_VERSIONS pv
                 WHERE pv.pv_id = 112982;		
		
Basic_Clone ( 112982, parPv_id, NULL, 3764, 22325, 0 );


END TEST_MARCO;
/
--------------------------------------------------------
--  DDL for Procedure TOUCH_RELEASE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "TOUCH_RELEASE" ( nRtagId IN RELEASE_TAGS.RTAG_ID%TYPE ) IS
/* ---------------------------------------------------------------------------
    The purpose of this procedure is to flag in the database that the specified
    release has changed to an extent that the procedure Rebuild_Environment
    should be called at the next opportunity in order that the package state
    icons are all re-evaluated.
    The package state icons are controlled using the pkg_state column in the
    release_content table, and Rebuild_Environment updates that column.
    It will be through user action in the website that Rebuild_Environment will
    be called, for example:
      a) when setting/clearing ignore warnings checkboxes
      b) when someone opens a page upon a rtag/pvid and rebuild_en flag is set
      c) when someone opens the build order report form
      d) when someone modifies dependencies of a package
      + other scenarios (?)
   --------------------------------------------------------------------------- */
BEGIN
   -- Touch Release for Rebuild
   UPDATE RELEASE_TAGS rt SET
          rt.REBUILD_ENV = 'Y',
          rt.REBUILD_STAMP = 0
    WHERE rt.RTAG_ID = nRtagId;

END Touch_Release;
/
--------------------------------------------------------
--  DDL for Procedure TOUCH_RELEASE_BULK
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "TOUCH_RELEASE_BULK" ( nRtagIdList IN VARCHAR2 ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0
   --------------------------------------------------------------------------- */

oRTagIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

BEGIN
	 oRTagIdCollector := IN_LIST_NUMBER ( nRtagIdList );

	 -- Touch Release for Rebuild
     UPDATE RELEASE_TAGS rt SET
     	rt.REBUILD_ENV = 'Y',
        rt.REBUILD_STAMP = 0
      WHERE rt.RTAG_ID IN ( SELECT * FROM TABLE ( CAST ( oRTagIdCollector AS RELMGR_NUMBER_TAB_t ) ) );


END Touch_Release_Bulk;
/
--------------------------------------------------------
--  DDL for Procedure TO_INSERT_VTREE_ID
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "TO_INSERT_VTREE_ID" IS

/******************************************************************************
   NAME:       TO_INSERT_VTREE_ID
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        2/02/2007          1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     TO_INSERT_VTREE_ID
      Sysdate:         2/02/2007
      Date and Time:   2/02/2007, 8:42:56 AM, and 2/02/2007 8:42:56 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
VTreeId NUMBER;																			  																	   


	CURSOR curInfo IS
    SELECT RTAG_ID
	FROM RELEASE_TAGS
	WHERE VTREE_ID IS NULL;
    recInfo curInfo%ROWTYPE;
	
	
BEGIN

	OPEN curInfo;
    FETCH curInfo INTO recInfo;
	
	WHILE curInfo%FOUND
	LOOP
		SELECT SEQ_VTREE_ID.nextval INTO VTreeId FROM DUAL;

		UPDATE RELEASE_TAGS
		SET VTREE_ID = VTreeId
		WHERE RTAG_ID = recInfo.RTAG_ID;

		FETCH curInfo INTO recInfo;
	END LOOP;

	CLOSE curInfo;

END TO_INSERT_VTREE_ID;
/
--------------------------------------------------------
--  DDL for Procedure UNDEPRECATE_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UNDEPRECATE_PACKAGE" (nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
	   	  		  								 nRtagId IN DEPRECATED_PACKAGES.RTAG_ID%TYPE,
	   	  		  							   	 nPkgId IN DEPRECATED_PACKAGES.PKG_ID%TYPE,
											   	 nUserId IN NUMBER) IS
												 
ext VARCHAR2(50);
PvIdList VARCHAR2(32767);
nIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
PvId NUMBER;
sComments VARCHAR2(32767);
												 
BEGIN



	--Extract the package extension
	SELECT V_EXT into ext 
	FROM PACKAGE_VERSIONS 
	WHERE PV_ID = nPvId;
	 
	--SELECT COMMENTS into sComments 
	--FROM DEPRECATED_PACKAGES
	--WHERE RTAG_ID = nRtagId
	--AND V_EXT = ext
	--AND PKG_ID = nPkgId;
	
	--SELECT PV_ID into PvIdList FROM
	--RELEASE_CONTENT WHERE RTAG_ID = nRtagId
	--AND PKG_STATE = 6
	--AND PV_ID NOT IN nPvId;


	IF ext IS NOT NULL THEN
       -- Undeprecate Package
       DELETE FROM DEPRECATED_PACKAGES 
	   WHERE RTAG_ID = nRtagId 
	   AND PKG_ID = nPkgId
	   AND V_EXT = ext;	

		UPDATE RELEASE_CONTENT 
		SET PKG_ID = NULL, DEPRECATED_STATE = NULL
		WHERE RTAG_ID = nRtagId
		AND PV_ID IN (SELECT PV.PV_ID 
				  	  FROM PACKAGE_VERSIONS PV, PACKAGES PKG
					  WHERE PKG.PKG_ID = PV.PKG_ID
					  AND PKG.PKG_ID = nPkgId
					  AND PV.V_EXT = ext
					  UNION
					  SELECT DISTINCT
	 	 		  	 		   qry.PV_ID
							        FROM (
									 	  SELECT dep.*,
										  LEVEL AS LEVEL_NUM
										  FROM PACKAGE_DEPENDENCIES dep
	 								START WITH dep.DPV_ID IN ( nPvId )
									--AND dep.DPV_ID NOT IN ( SELECT PV_ID FROM RELEASE_CONTENT WHERE RTAG_ID = nRtagId AND PKG_STATE = 6 )
									CONNECT BY PRIOR dep.PV_ID = dep.DPV_ID
	 								) qry,
									PACKAGES pkg,
									PACKAGE_VERSIONS pv,
									RELEASE_CONTENT rc
							 	 WHERE qry.PV_ID = pv.PV_ID AND pv.PKG_ID = pkg.PKG_ID
								 AND rc.RTAG_ID = nRtagId AND rc.PV_ID = qry.PV_ID
								 
					 );	 
		   
	ELSE
       -- Undeprecate Package
       DELETE FROM DEPRECATED_PACKAGES 
	   WHERE RTAG_ID = nRtagId 
	   AND PKG_ID = nPkgId
	   AND V_EXT IS NULL;	
	   
		UPDATE RELEASE_CONTENT 
		SET PKG_ID = NULL, DEPRECATED_STATE = NULL
		WHERE RTAG_ID = nRtagId
		AND PV_ID IN (SELECT PV.PV_ID 
				  	  FROM PACKAGE_VERSIONS PV, PACKAGES PKG
					  WHERE PKG.PKG_ID = PV.PKG_ID
					  AND PKG.PKG_ID = nPkgId
					  AND PV.V_EXT IS NULL
					  UNION
					  SELECT DISTINCT
	 	 		  	 		   qry.PV_ID
							        FROM (
									 	  SELECT dep.*,
										  LEVEL AS LEVEL_NUM
										  FROM PACKAGE_DEPENDENCIES dep
	 								START WITH dep.DPV_ID IN ( nPvId )
									--AND dep.DPV_ID NOT IN ( SELECT PV_ID FROM RELEASE_CONTENT WHERE RTAG_ID = nRtagId AND PKG_STATE = 6 )
									CONNECT BY PRIOR dep.PV_ID = dep.DPV_ID
	 								) qry,
									PACKAGES pkg,
									PACKAGE_VERSIONS pv,
									RELEASE_CONTENT rc
							 	 WHERE qry.PV_ID = pv.PV_ID AND pv.PKG_ID = pkg.PKG_ID
								 AND rc.RTAG_ID = nRtagId AND rc.PV_ID = qry.PV_ID
								 
					 );	 	   
	
	END IF;
	
	--IF PvIdList IS NOT NULL THEN
	
	 --  nIdCollector := IN_LIST_NUMBER ( PvIdList );
	
	 --  FOR i IN 1..nIdCollector.COUNT
	 --  LOOP
	--	   PvId := nIdCollector(i);
		

		
	--		Deprecate_Package (nPvId, nRtagId, nPkgId, sComments, nUserId );
	--		END LOOP;
	--END IF;
	
	Rebuild_environment(nRtagId);			 
				 
				 									 

END Undeprecate_Package;
/
--------------------------------------------------------
--  DDL for Procedure UNLOCK_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UNLOCK_PACKAGE" ( nPvId IN PACKAGE_VERSIONS.PV_ID%TYPE,
											 nUserId IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Author: Rupesh Solanki
	
	Version: 4.0
   --------------------------------------------------------------------------- */
   STATE CHAR;
   
BEGIN
	 
	SELECT DLOCKED INTO STATE
	FROM PACKAGE_VERSIONS
	WHERE PV_ID = nPvId; 

	IF STATE = 'A' THEN --It was made official for autobuilds
		-- Unlock Package
		UPDATE PACKAGE_VERSIONS pv SET
		pv.DLOCKED = 'P'
		WHERE pv.PV_ID = nPvId;	
	ELSE
		-- Unlock Package
		UPDATE PACKAGE_VERSIONS pv SET
		pv.DLOCKED = 'N'
		WHERE pv.PV_ID = nPvId;	
	
	END IF;	   

    /* LOG ACTION */
   	Log_Action ( nPvId, 'unlock_package', nUserId );

END Unlock_Package;
/
--------------------------------------------------------
--  DDL for Procedure UNRIPPLE_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UNRIPPLE_PACKAGE" (
        sPvIdList IN VARCHAR2,
        nRtagId IN RELEASE_TAGS.RTAG_ID%TYPE,
        nUserId IN NUMBER
    ) IS
/* ---------------------------------------------------------------------------
    Version: 4.1
   --------------------------------------------------------------------------- */

    oPvIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

BEGIN

    IF (sPvIdList IS NULL) THEN
        RAISE_APPLICATION_ERROR (-20000, 'Please select at least one package.' );
    END IF;

    oPvIdCollector := IN_LIST_NUMBER ( sPvIdList );

    -- UnRipple Package
    INSERT INTO DO_NOT_RIPPLE ( RTAG_ID, PV_ID )
    SELECT nRtagId, pv.PV_ID
    FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID IN (
        SELECT *
        FROM TABLE (
            CAST ( oPvIdCollector AS RELMGR_NUMBER_TAB_t )
        )
    );
    
    /* LOG ACTION */
    Log_Action_Bulk ( sPvIdList, 'unripple_package', nUserId );

END UnRipple_Package;
/
--------------------------------------------------------
--  DDL for Procedure UNRIPPLE_PACKAGE_INDIRECT
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UNRIPPLE_PACKAGE_INDIRECT" (
        nPvId IN NUMBER,
        nRtagId IN NUMBER,
        nUserId IN NUMBER,
        nrootCausePvId IN NUMBER,
        srootCause IN VARCHAR2,
        srootFile IN VARCHAR2
    ) IS
    ReleaseLocation VARCHAR2(4000);
BEGIN

    -- UnRipple Package
    delete from do_not_ripple where rtag_id=nRtagId and pv_id=nPvId;
    INSERT INTO DO_NOT_RIPPLE ( RTAG_ID, PV_ID, ROOT_PV_ID, ROOT_CAUSE, ROOT_FILE ) values (nRtagId, nPvId, nrootCausePvId, srootCause, srootFile);

    /* LOG ACTION */
   SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
              FROM PROJECTS proj,
                   RELEASE_TAGS rt
             WHERE rt.RTAG_ID = nRtagId
               AND rt.PROJ_ID = proj.PROJ_ID;

    /* LOG ACTION */
    Log_Action ( nPvId, 'unripple_package', nUserId, 'Location: '|| ReleaseLocation );

END UnRipple_Package_Indirect;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_ADDITIONAL_NOTE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_ADDITIONAL_NOTE" ( pnNote_id IN NUMBER,
													 pnPv_id IN NUMBER,
                                                     psNote_title IN ADDITIONAL_NOTES.NOTE_TITLE%TYPE,
                                                     psNote_body IN ADDITIONAL_NOTES.NOTE_BODY%TYPE,
                                                     pnUser_id IN NUMBER,
                                                     outErrCode OUT NUMBER
                                                    ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.1
   --------------------------------------------------------------------------- */

    newID NUMBER;

    /* Disallow duplicate Note Titles */
	CURSOR an_duplicate_cur IS
        SELECT COUNT(*) AS cnt_note
          FROM ADDITIONAL_NOTES
         WHERE pv_id = pnPv_id
           AND note_id != pnNote_id
           AND note_title = psNote_title;
    an_duplicate_rec an_duplicate_cur%ROWTYPE;

BEGIN
	outErrCode := -1;		-- Set default return error code to ERROR state

	OPEN an_duplicate_cur;
    FETCH an_duplicate_cur INTO an_duplicate_rec;

    IF an_duplicate_rec.cnt_note < 1
    THEN
		--- Update Additional Note ---
	    UPDATE ADDITIONAL_NOTES SET
		       note_title = psNote_title,
		       note_body = psNote_body,
		       mod_date = Ora_Sysdate,
		       mod_user = pnUser_id
         WHERE note_id = pnNote_id
           AND pv_id = pnPv_id;
		outErrCode := 0;		-- Set return to SUCCESS
	END IF;

	CLOSE an_duplicate_cur;
END Update_Additional_Note;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_DEPRECATION_STATE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_DEPRECATION_STATE" (nnrtag_id IN NUMBER) AS

recno NUMBER;

CURSOR deprecate_cur IS

SELECT rc.pv_id
FROM release_content rc
WHERE rtag_id = nnrtag_id
 AND deprecated_state IN(7);

deprecate_rec deprecate_cur % rowtype;

BEGIN

  OPEN deprecate_cur;

  FETCH deprecate_cur
  INTO deprecate_rec;

  WHILE deprecate_cur % FOUND
  LOOP

    SELECT COUNT(*)
    INTO recno
    FROM package_dependencies pd,
      release_content rc
    WHERE pd.pv_id = deprecate_rec.pv_id
     AND rc.pv_id = pd.dpv_id
     AND rc.rtag_id = nnrtag_id
     AND rc.deprecated_state IN(6,   7);

    IF recno = 0 THEN

      UPDATE release_content
      SET pkg_id = NULL, deprecated_state = NULL
      WHERE pv_id = deprecate_rec.pv_id
       AND rtag_id = nnrtag_id;

    END IF;

    FETCH deprecate_cur
    INTO deprecate_rec;
  END LOOP;

END;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_MISC_VIEW
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_MISC_VIEW" IS
/******************************************************************************
   NAME:       UPDATE_MISC_VIEW
   PURPOSE:    

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        16/03/2007          1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     UPDATE_MISC_VIEW
      Sysdate:         16/03/2007
      Date and Time:   16/03/2007, 8:56:29 AM, and 16/03/2007 8:56:29 AM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   CURSOR view_cur /*Create a record set to store the ripple data*/
   IS
   	 SELECT pkg.pkg_id, rc.base_view_id 
	 FROM package_versions pv, packages pkg, release_content rc
	 where rc.rtag_id = 2362
	 and rc.pv_id = pv.pv_id
	 and pv.pkg_id = pkg.pkg_id;
   view_rec   view_cur%ROWTYPE;



BEGIN
   OPEN view_cur;

   FETCH view_cur
    INTO view_rec;

   WHILE view_cur%FOUND
   LOOP

	   
	   update release_content
	   set base_view_id = view_rec.base_view_id
	   where rtag_id = 8027
	   and pv_id IN 
	   (
	   	select pv.pv_id from release_content rc, package_versions pv
		where rc.rtag_id = 8027
		and pv.pv_id = rc.pv_id
		and pv.pkg_id = view_rec.pkg_id 
	  
	   );
	  
	   

	   
	   
	   
	   
   	   

   FETCH view_cur
   		 INTO view_rec;
   END LOOP;	 





END UPDATE_MISC_VIEW; 
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_PACKAGE_DEPENDENCY
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_PACKAGE_DEPENDENCY" ( NNpv_id IN NUMBER,
                                                        SSdep_name IN PACKAGES.pkg_name%TYPE,
                                                        SSdep_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
                                                        CCbuild_type IN PACKAGE_DEPENDENCIES.build_type%TYPE,
                                                        NNuser_id IN NUMBER,
                                                        NNdelete_old_dependency IN NUMBER
                                                       ) IS
/* ---------------------------------------------------------------------------
    Version: 3.3
   --------------------------------------------------------------------------- */

    retPV_ID NUMBER;
    SSV_EXT PACKAGE_VERSIONS.v_ext%TYPE;
	DepIsPatch	PACKAGE_VERSIONS.is_patch%TYPE;
    PvIsPatch	PACKAGE_VERSIONS.is_patch%TYPE;
    NNpkg_id NUMBER;
    NNdpkg_id NUMBER;

BEGIN
    --- Seed database with package_name and version if required ---
    Seed_Package_Names_Versions ( SSdep_name, SSdep_version, NNuser_id, retPV_ID );

    -- get v_ext,pkg_id of current dependency
    SELECT v_ext, pkg_id, is_patch INTO SSV_EXT, NNdpkg_id, DepIsPatch
      FROM PACKAGE_VERSIONS
     WHERE pv_id = retPV_ID;

    -- get pkg_id of parent package
    SELECT pkg_id, is_patch INTO NNpkg_id, PvIsPatch
      FROM PACKAGE_VERSIONS
     WHERE pv_id = NNpv_id;


	IF ( (PvIsPatch IS NULL) AND (DepIsPatch IS NULL) ) OR
    	( (PvIsPatch IS NOT NULL) )THEN

	    IF NNdelete_old_dependency = 1 THEN
	        /* Used for CUSTOM dependency add/edit */

	        --- Remove old dependency ---
            IF (PvIsPatch IS NULL) THEN
            	-- Do it for Packages
		        DELETE FROM PACKAGE_DEPENDENCIES
		         WHERE ( pv_id, dpv_id, pkg_id, dpkg_id, build_type, display_order ) IN
		            (
		            SELECT dep.*
		              FROM PACKAGE_DEPENDENCIES dep,
		                   PACKAGE_VERSIONS dpv,
		                   PACKAGE_VERSIONS pv
		             WHERE dep.dpv_id = dpv.pv_id
		               AND dep.pv_id = NNpv_id
		               AND pv.pv_id = retPV_ID
		               AND dpv.pkg_id = pv.pkg_id
		               AND NVL(dpv.v_ext, '|LINK_A_NULL|') = NVL(SSV_EXT, '|LINK_A_NULL|')
		            );
            ELSE
            	-- Do it for Patches
                DELETE FROM PACKAGE_DEPENDENCIES
		         WHERE ( pv_id, dpv_id, pkg_id, dpkg_id, build_type, display_order ) IN
		            (
		            SELECT dep.*
		              FROM PACKAGE_DEPENDENCIES dep
		             WHERE dep.dpv_id = retPV_ID
		               AND dep.pv_id = NNpv_id
		            );
			END IF;

	    END IF;

	    /* NOTE: for JATS, ANTS dependency update, it is expected that all dependencies are removed. */

	    --- Add new dependency ---
	    INSERT INTO PACKAGE_DEPENDENCIES ( pv_id, dpv_id, pkg_id, dpkg_id, build_type )
	    VALUES ( NNpv_id, retPV_ID, NNpkg_id, NNdpkg_id, CCbuild_type );

	END IF;

END Update_Package_Dependency;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_PACKAGE_STATES
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_PACKAGE_STATES" ( NNrtag_id IN NUMBER,
                                                    NNsession_num IN NUMBER ) IS
/* =============  STATE RULES =================== */
/*
   MNR   MRR   MN   MR    |   pkg_state
   ------------------------------------
    0     0     0     0   |      OK
    0     0     0     1   |      MAJOR
    0     0     1     0   |      MINOR
    0     0     1     1   |      MAJOR
   ------------------------------------
    0     1     0     0   |      MAJOR_READY
    0     1     0     1   |      MAJOR
    0     1     1     0   |      MAJOR
    0     1     1     1   |      MAJOR
   ------------------------------------
    1     0     0     0   |      MINOR_READY
    1     0     0     1   |      MAJOR
    1     0     1     0   |      MINOR
    1     0     1     1   |      MAJOR
   ------------------------------------
    1     1     0     0   |      MAJOR_READY
    1     1     0     1   |      MAJOR
    1     1     1     0   |      MAJOR
    1     1     1     1   |      MAJOR
   ------------------------------------
*/
BEGIN
    /*----------------------------------------------
    ||              MINOR READY
    */----------------------------------------------

    UPDATE release_content
       SET pkg_state = 4
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
           FROM temp_env_states
           WHERE session_num = NNsession_num
             AND level_num = 1
             AND tes_state = 2
           );

    /*----------------------------------------------
    ||              MAJOR READY
    */----------------------------------------------
    UPDATE release_content
       SET pkg_state = 3
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
           FROM temp_env_states
           WHERE session_num = NNsession_num
             AND level_num = 1
             AND tes_state IN (0,1)
           );

    /*----------------------------------------------
    ||                MINOR
    */----------------------------------------------
    UPDATE release_content
       SET pkg_state = 2
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
            FROM temp_env_states
            WHERE session_num = NNsession_num
              AND level_num >= 2
              AND tes_state = 2
            MINUS
           SELECT pv_id
             FROM release_content
            WHERE rtag_id = NNrtag_id
              AND pkg_state = 3
           );

    /*----------------------------------------------
    ||                MAJOR
    */----------------------------------------------
    UPDATE release_content
       SET pkg_state = 1
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
           FROM temp_env_states
           WHERE session_num = NNsession_num
             AND level_num >= 2
             AND tes_state IN (0,1)
           /* MAJOR EXCEPTION - When package has Major Ready and Minor */
           UNION
           SELECT DISTINCT tes.pv_id
           FROM temp_env_states tes,
                release_content rc
           WHERE tes.session_num = NNsession_num
             AND tes.level_num >= 2
             AND tes.tes_state = 2
             AND rtag_id = NNrtag_id
             AND rc.pv_id = tes.pv_id
             AND rc.pkg_state = 3
           );

    /*----------------------------------------------
    ||                 OK
    */----------------------------------------------
    UPDATE release_content
       SET pkg_state = 0
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT rc.pv_id
             FROM release_content rc
            WHERE rc.rtag_id = NNrtag_id
              AND NOT rc.pv_id IN
                    (
                     SELECT DISTINCT pv_id
                     FROM temp_env_states WHERE session_num = NNsession_num
                    )
           );

      Update_Deprecation_State (NNrtag_id);

    /*----------------------------------------------
    ||              PEGGED VERSIONS DEPENDENT
    */----------------------------------------------
    UPDATE release_content
       SET pkg_state = 10
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
           FROM pegged_versions pegv
           WHERE pegv.rtag_id = NNrtag_id
           );

    /*----------------------------------------------
    ||              ADVISORY RIPPLE
    */----------------------------------------------
    UPDATE release_content
       SET pkg_state = 8
     WHERE rtag_id = NNrtag_id
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
           FROM advisory_ripple ar
           WHERE ar.rtag_id = NNrtag_id
           )
       AND pv_id IN
           (
           SELECT DISTINCT pv_id
           FROM release_content rc
           WHERE rc.rtag_id = NNrtag_id
           );

END Update_Package_States;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_PROCESSES
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_PROCESSES" 
IS

proc_id NUMBER;
/******************************************************************************
   NAME:       DELETE_DO_NOT_RIPPLE
   PURPOSE:    TO DELETE ENTRIES FROM THE DO_NOT_RIPPLE TABLE WHEN A PACKAGE
               IS RELEASED

   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0        21/04/2006  Rupesh Solanki     1. Created this procedure.

   NOTES:

   Automatically available Auto Replace Keywords:
      Object Name:     DELETE_DO_NOT_RIPPLE
      Sysdate:         21/04/2006
      Date and Time:   21/04/2006, 3:21:55 PM, and 21/04/2006 3:21:55 PM
      Username:         (set in TOAD Options, Procedure Editor)
      Table Name:       (set in the "New PL/SQL Object" dialog)

******************************************************************************/
   CURSOR ripple_cur
   IS
      select proc_id,  proc_name, run_as, pkg_owner, is_interface from processes;

   ripple_rec   ripple_cur%ROWTYPE;
BEGIN
   OPEN ripple_cur;

   FETCH ripple_cur
    INTO ripple_rec;

   WHILE ripple_cur%FOUND
   LOOP
   

update deployment_manager.processes_config 
set proc_id = ripple_rec.proc_id
where pkg_health_tag = ripple_rec.proc_name
and cmd_interface IS NULL
and pkg_owner IS NULL
and is_interface IS NULL; 
   

      FETCH ripple_cur
       INTO ripple_rec;
   END LOOP;
END UPDATE_PROCESSES;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_RUNTIME_DEPENDENCY
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_RUNTIME_DEPENDENCY" ( NNpv_id IN RUNTIME_DEPENDENCIES.pv_id%TYPE,
				   	  		  						    NNrtd_id IN RUNTIME_DEPENDENCIES.rtd_id%TYPE,
				   	  		  						    SSrtd_version IN PACKAGE_VERSIONS.pkg_version%TYPE,
													    SSrtd_url IN RUNTIME_DEPENDENCIES.rtd_url%TYPE,
													    SSrtd_comments IN RUNTIME_DEPENDENCIES.rtd_comments%TYPE,
													    NNuser_id IN NUMBER ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.1
   --------------------------------------------------------------------------- */

    retRTD_ID	NUMBER;
	CURSOR rtd_cur IS
	    SELECT pv.pkg_version, pkg.pkg_name
		  FROM runtime_dependencies rtd,
		       package_versions pv,
			   packages pkg
		 WHERE rtd.rtd_id = pv.pv_id
		   AND pv.pkg_id = pkg.pkg_id
		   AND rtd.pv_id = NNpv_id
		   AND rtd.rtd_id = NNrtd_id;
	   rtd_rec rtd_cur%ROWTYPE;

	CURSOR old_rtd_cur IS
	    SELECT pv.pv_id
		  FROM package_versions pv
		 WHERE pv.pkg_id IN ( SELECT rtdpv.pkg_id
		 	   			 	    FROM package_versions rtdpv
							   WHERE rtdpv.pv_id = NNrtd_id )
		   AND pv.pkg_version = SSrtd_version;
	old_rtd_rec old_rtd_cur%ROWTYPE;


BEGIN

    -- Get current runtime dependency details
	OPEN rtd_cur;
    FETCH rtd_cur INTO rtd_rec;




	IF rtd_rec.pkg_version != SSrtd_version THEN
           -- Version has changed, hence create new runtime dependency --
	    /* NOTE: You must create new version as updating just a version will affect
		        all packages using this runtime dependency and user does not expect that.
		        It is safer to create new version */
		OPEN old_rtd_cur;
		FETCH old_rtd_cur INTO old_rtd_rec;


		IF old_rtd_cur%NOTFOUND
		THEN
			-- Version not found, hence Create New version --
    		Seed_Package_Names_Versions ( rtd_rec.pkg_name, SSrtd_version, NNuser_id, retRTD_ID );

			-- Update runtime dependency table --
			UPDATE runtime_dependencies SET
				   rtd_id = retRTD_ID,
				   rtd_url = SSrtd_url,
				   rtd_comments = SSrtd_comments
			 WHERE pv_id = NNpv_id
			   AND rtd_id = NNrtd_id;

		ELSE
			-- Update runtime dependency table --
			UPDATE runtime_dependencies SET
				   rtd_id = old_rtd_rec.pv_id,
				   rtd_url = SSrtd_url,
				   rtd_comments = SSrtd_comments
			 WHERE pv_id = NNpv_id
			   AND rtd_id = NNrtd_id;

		END IF;


		CLOSE old_rtd_cur;

	ELSE
		--  Version has not changed, hence update everithing except	version --
		UPDATE runtime_dependencies SET
			   rtd_url = SSrtd_url,
			   rtd_comments = SSrtd_comments
		 WHERE pv_id = NNpv_id
		   AND rtd_id = NNrtd_id;



	END IF;


	CLOSE rtd_cur;

END Update_Runtime_Dependency;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_UNIT_TEST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_UNIT_TEST" ( nTest_id IN NUMBER,
	   	  		  							   nTestTypeId IN UNIT_TESTS.TEST_TYPES_FK%TYPE,  	
											   nPv_id IN NUMBER,
											   nUserId IN NUMBER,
	                                           sTest_summary IN UNIT_TESTS.TEST_SUMMARY%TYPE,
											   sNumof_test IN UNIT_TESTS.NUMOF_TEST%TYPE,
	                                           sCompletion_date IN VARCHAR2,
											   sDpkg_path IN VARCHAR2,
											   enumTEST_TYPE_AUTOMATIC IN NUMBER,
											   sResults IN VARCHAR2,
											   outFileName OUT VARCHAR2
                                              ) IS
/* ---------------------------------------------------------------------------
    Version: 3.1.0
   --------------------------------------------------------------------------- */
   
   	FILENAME_PREFIX CONSTANT VARCHAR2(50) := 'RM_UNIT_TEST';

    ResultsURL UNIT_TESTS.RESULTS_URL%TYPE DEFAULT NULL;
    ResultsAttachment UNIT_TESTS.RESULTS_ATTACHMENT_NAME%TYPE DEFAULT NULL;


BEGIN

       IF nTestTypeId = enumTEST_TYPE_AUTOMATIC THEN
       	ResultsURL := sResults;
       ELSE
       	IF (sResults <> '') OR ( NOT sResults IS NULL ) THEN
        	outFileName := FILENAME_PREFIX || nTest_id ||'_'|| sResults;
    		ResultsAttachment := sDpkg_path || '/' || outFileName;
           END IF;
       END IF;

	--- Update Unit Test ---
    UPDATE UNIT_TESTS SET
           TEST_SUMMARY = sTest_summary,
		   NUMOF_TEST = sNumof_test,
           COMPLETION_DATE = TO_DATE( sCompletion_date,'DD/MM/YYYY' ),
		   COMPLETED_BY = nUserId,
		   RESULTS_URL = ResultsURL,
		   RESULTS_ATTACHMENT_NAME = ResultsAttachment
     WHERE TEST_ID = nTest_id
       AND PV_ID = nPv_id;

END Update_Unit_Test;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_UNIT_TEST_ACCEPTANCE
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_UNIT_TEST_ACCEPTANCE" ( pnTest_id IN NUMBER,
														  pnPv_id IN NUMBER,
					                                      sAccepted IN UNIT_TESTS.TEST_ACCEPTED%TYPE,
														  sAcceptanceDate IN VARCHAR2,
														  sAcceptedBy IN NUMBER,
					                                      sReviewComments IN UNIT_TESTS.REVIEW_COMMENTS%TYPE,
														  cUpdateAcceptedStateOnly IN CHAR
					                                     ) IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */



BEGIN
	IF cUpdateAcceptedStateOnly = 'Y'
	THEN
		--- Update Accepted State Only ---
		IF ( sAccepted IS NULL )
		THEN
			-- Clear alleptance
			UPDATE UNIT_TESTS SET
		           TEST_ACCEPTED = NULL,
		           ACCEPTANCE_DATE = NULL,
				   ACCEPTED_BY = NULL,
				   REVIEW_COMMENTS = NULL
		     WHERE TEST_ID = pnTest_id
		       AND PV_ID = pnPv_id;

	    ELSE
			UPDATE UNIT_TESTS SET
		           TEST_ACCEPTED = sAccepted,
		           ACCEPTANCE_DATE = TO_DATE( sAcceptanceDate,'DD/MM/YYYY' ),
				   ACCEPTED_BY = sAcceptedBy
		     WHERE TEST_ID = pnTest_id
		       AND PV_ID = pnPv_id;

		END IF;


	ELSE
		--- Update Unit Test Acceptance ---
	    UPDATE UNIT_TESTS SET
	           TEST_ACCEPTED = sAccepted,
			   REVIEW_COMMENTS = sReviewComments,
	           ACCEPTANCE_DATE = TO_DATE( sAcceptanceDate,'DD/MM/YYYY' ),
			   ACCEPTED_BY = sAcceptedBy
	     WHERE TEST_ID = pnTest_id
	       AND PV_ID = pnPv_id;

	END IF;

END Update_Unit_Test_Acceptance;
/
--------------------------------------------------------
--  DDL for Procedure UPDATE_UNIT_TEST_TEST
--------------------------------------------------------

  CREATE OR REPLACE PROCEDURE "UPDATE_UNIT_TEST_TEST" ( nTest_id IN NUMBER,
	   	  		  							   nTestTypeId IN UNIT_TESTS.TEST_TYPES_FK%TYPE,  	
											   nPv_id IN NUMBER,
											   nUserId IN NUMBER,
	                                           sTest_summary IN UNIT_TESTS.TEST_SUMMARY%TYPE,
											   sNumof_test IN UNIT_TESTS.NUMOF_TEST%TYPE,
	                                           sCompletion_date IN VARCHAR2,
											   sDpkg_path IN VARCHAR2,
											   enumTEST_TYPE_AUTOMATIC IN NUMBER,
											   sResults IN VARCHAR2,
											   outFileName OUT VARCHAR2
                                              ) IS
/* ---------------------------------------------------------------------------
    Version: 3.1.0
   --------------------------------------------------------------------------- */
   
   	FILENAME_PREFIX CONSTANT VARCHAR2(50) := 'RM_UNIT_TEST';

    ResultsURL UNIT_TESTS.RESULTS_URL%TYPE DEFAULT NULL;
    ResultsAttachment UNIT_TESTS.RESULTS_ATTACHMENT_NAME%TYPE DEFAULT NULL;


BEGIN

       IF nTestTypeId = enumTEST_TYPE_AUTOMATIC THEN
       	ResultsURL := sResults;
       ELSE
       	IF (sResults <> '') OR ( NOT sResults IS NULL ) THEN
        	outFileName := FILENAME_PREFIX || nTest_id ||'_'|| sResults;
    		ResultsAttachment := sDpkg_path || '/' || outFileName;
           END IF;
       END IF;

       /*	IF (sResults <> '') OR ( NOT sResults IS NULL ) THEN
        	outFileName := FILENAME_PREFIX || newID ||'_'|| sResults;
    		sResults_url:= 'doc' || '/' || 
			;
        END IF;*/
	--- Update Unit Test ---
    UPDATE UNIT_TESTS SET
           TEST_SUMMARY = sTest_summary,
		   NUMOF_TEST = sNumof_test,
           COMPLETION_DATE = TO_DATE( sCompletion_date,'DD/MM/YYYY' ),
		   COMPLETED_BY = nUserId,
		   RESULTS_URL = ResultsURL,
		   RESULTS_ATTACHMENT_NAME = ResultsAttachment
     WHERE TEST_ID = nTest_id
       AND PV_ID = nPv_id;

END Update_Unit_Test_Test;
/