CREATE PACKAGE BODY "RELEASE_MANAGER"."PK_RMAPI_TEST" 
IS
/*
------------------------------
||  Last Modified:  Rupesh Solanki
||  Modified Date:  11 September 2006
||  Body Version:   2.0
------------------------------
*/

   /*-------------------------------------------------------------------------------------------------------*/
   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_release (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      label                    IN   VARCHAR2,
      dependenciesimportlist   IN   VARCHAR2,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      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;
   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 (label IS NULL)
      THEN
         raise_application_error (-20000, 'Label 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;

      -- 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 thie ripple package
               IF vext = ssv_ext
               THEN
                  SELECT pv.pv_id
                    INTO clonefrompvid
                    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 pv.v_ext = ssv_ext;
               ELSE
                  SELECT pv.pv_id
                    INTO clonefrompvid
                    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 pv.v_ext = vext;
               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 vext = ssv_ext
            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, hence cannot be used for ripple build
            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
              INTO pvid, dlocked
              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|');
         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;

      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.pkg_label = label
          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;	  

      -- Now release package
      pk_environment.auto_make_release (pvid,
                                        rtagid,
                                        userid,
                                        vext,
                                        ssv_ext,
                                        clonefrompvid
                                       );
									   							  									   									  					   
									   									   
      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_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;
   
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CQ_TEST IS

  INPUT NUMBER(8,2);
  RESULT VARCHAR2(50);
BEGIN
  INPUT := 33558440;
  RESULT := dbo.sp_RM_getIssueDetails@DEVI(INPUT);
  INSERT INTO CQ_TEST (ID) VALUES (RESULT);


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;
   
   
/*-------------------------------------------------------------------------------------------------------*/   
END pk_rmapi_test;
/
ALTER PACKAGE "RELEASE_MANAGER"."PK_RMAPI_TEST" 
  COMPILE BODY 
    PLSQL_OPTIMIZE_LEVEL=  2
    PLSQL_CODE_TYPE=  INTERPRETED
    PLSQL_DEBUG=  FALSE
 REUSE SETTINGS TIMESTAMP '2007-02-06 11:21:54'
/
