-- https://www.phpmyadmin.net
--




--
-- Database: `vidyalkh_app`
--
CREATE DATABASE IF NOT EXISTS `vidyalkh_app` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
USE `vidyalkh_app`;

DELIMITER $$
--
-- Procedures
--
DROP PROCEDURE IF EXISTS `sample_test`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sample_test`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_exam_master_json';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_json_str text;
	declare l_json_str_len int;
	declare l_json_substr text;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count tinyint(3);
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';
	declare l_insert_sql_str text default 'insert into exam_master(
				ay_id, 
				inst_id, 
				exam_mst_id, 
				standard_id, 
				division_id, 
				group_type, 
				group_id, 
				gradeset_mst_id, 
				evaluation_type, 
				exam_cat_id, 
				exam_term, 
				exam_name, 
				exam_start_date, 
				exam_end_date, 
				exam_weightage, 
				is_system_def, 
				status, 
				status_desc, 
				created_by ) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text; 
	declare cur_json_template cursor for 
		select col_name from json_template_master where tbl_name = 'exam_master' order by col_pos; 
	declare continue handler for not found set l_looping_done = true; 
	declare exit handler for sqlexception 
		begin   
			rollback; 
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,err_desc, err_type, err_severity, created_by)  
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);  
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = ''; 
			open cur_json_template;  
				cursor_loop: loop 
					fetch cur_json_template into l_template_col_name; 
					if l_looping_done then 
					  leave cursor_loop; 
					end if; 
					set l_separator_idx = instr(l_json_str, l_template_col_name) + length(l_template_col_name) + l_json_key_val_sep_len;  
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);   
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);  
					if (l_template_col_name = 'exam_mst_id') THEN 
						set l_template_col_value = fn_sequence_generator('EXAM_MASTER'); 
					else 
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);  
					end if; 
 					set l_template_col_value = concat(l_single_quot_const, l_template_col_value,l_single_quot_const);  
					set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part,l_template_col_value); 
					set l_json_str = l_json_substr; 
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1; 
				set l_looping_done = false; 
				if length(trim(l_insert_val_str_full)) > 0 then        
					set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start,l_insert_val_str_part, l_val_str_end, ',');
				else
					set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part,l_val_str_end, ',');
				end if; 
				set l_insert_val_str_part = ''; 
				set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '('); 
				insert into proc_error_logs values ('sp_ins_exam_master_json','l_insert_val_str_full',l_insert_val_str_full) ;
			close cur_json_template; 
		end while; 
		set l_insert_sql_str = concat(l_insert_sql_str, substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1)); 
 		start transaction;    
			set l_routine_block = 'before execute immediate';   
			call sp_execute_immediate (l_insert_sql_str);        
		commit;  
	set out_err_code = l_err_code;  
	set out_err_desc = l_err_desc; 
END$$

DROP PROCEDURE IF EXISTS `sp_activate_new_institute`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_activate_new_institute`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_activate_new_institute';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_is_active tinyint(1) default 0;
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                    err_desc, err_type, err_severity, created_by) 
             values (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                    'ERROR', 0, in_created_by);
        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
          #donothing             
       end; 
       when 'U' then          
          begin
             set l_routine_block = 'update'; 
                	update institution_master Set is_active=in_is_active, updated_by = in_created_by, updated_on = NOW()
                   where inst_id=in_inst_id and is_deleted = 0 ;  
         end;    
       end case;
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_calculate_student_score_in_bulk`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_calculate_student_score_in_bulk`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_student_ids` VARCHAR(255), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_calculate_student_score_in_bulk';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_student_category int default 0;
  declare l_consession_category int default 0;
  declare l_prev_school_board int default 0;
  declare l_disability int default 0;
  declare l_f_edu_qual_degree int default 0;
  declare l_f_occupation int default 0;
  declare l_f_income_bracket int default 0;
  declare l_m_edu_qual_degree int default 0;
  declare l_m_occupation int default 0;
  declare l_m_income_bracket int default 0;
  declare l_father_id int;
  declare l_mother_id int;
  declare l_student_score int;
  DECLARE a INT Default 0 ;
  DECLARE in_student_id VARCHAR(255);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                    err_desc, err_type, err_severity, created_by) 
             values (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                    'ERROR', 0, in_created_by);
        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;
    start transaction;
   simple_loop: LOOP
			         SET a=a+1;
			         SET in_student_id=SPLIT_STR(in_student_ids,',',a);
			         IF in_student_id='' THEN
			            LEAVE simple_loop;
			         END IF;
          select contact_id_1 INTO l_father_id from student_master 
          where inst_id=in_inst_id
          AND ay_id=in_ay_id AND is_active=1 AND is_deleted=0
          AND student_id=in_student_id;
          select contact_id_2 INTO l_mother_id from student_master 
          where inst_id=in_inst_id
          AND ay_id=in_ay_id AND is_active=1 AND is_deleted=0
          AND student_id=in_student_id;
          select sasc.score INTO l_student_category from student_master sm 
          JOIN stud_admissiom_score_master sasc ON sm.student_category=sasc.data_key 
            and sasc.data_type='STUD_CATEGORY_TYPE'
            and sasc.category='STUD_CATEGORY_TYPE'
          where sm.inst_id=sasc.inst_id
          AND sm.ay_id=sasc.ay_id 
          AND sm.is_deleted=sasc.is_deleted
          AND sm.is_active=sasc.is_active 
          AND sm.is_active=1 
          AND sm.is_deleted=0
          AND sm.inst_id=in_inst_id
          AND sm.ay_id=in_ay_id 
          AND sm.student_id=in_student_id;
          select sasc.score INTO l_consession_category from student_master sm 
          JOIN stud_admissiom_score_master sasc ON sm.consession_category=sasc.data_key 
            and sasc.data_type='STUD_CONCESSION_CATEGORY' 
            and sasc.category='STUD_CONCESSION_CATEGORY'
      where sm.inst_id=sasc.inst_id
          AND sm.ay_id=sasc.ay_id 
          AND sm.is_deleted=sasc.is_deleted
          AND sm.is_active=sasc.is_active 
          AND sm.is_active=1 
          AND sm.is_deleted=0
          AND sm.inst_id=in_inst_id
          AND sm.ay_id=in_ay_id 
          AND sm.student_id=in_student_id;
          select sasc.score INTO l_prev_school_board from student_master sm 
          JOIN stud_admissiom_score_master sasc ON sm.prev_school_board=sasc.data_key 
            and sasc.data_type='CURRICULUM_TYPE'
            and sasc.category='PREVIOUS_SCHOOL_BOARD'
         where sm.inst_id=sasc.inst_id
          AND sm.ay_id=sasc.ay_id 
          AND sm.is_deleted=sasc.is_deleted
          AND sm.is_active=sasc.is_active 
          AND sm.is_active=1 
          AND sm.is_deleted=0
          AND sm.inst_id=in_inst_id
          AND sm.ay_id=in_ay_id 
          AND sm.student_id=in_student_id;
          select sasc.score INTO l_disability from student_master sm 
          JOIN stud_admissiom_score_master sasc ON sm.disability=sasc.data_key 
            and sasc.data_type='STUD_DISABILITY_TYPE'
            and sasc.category='STUD_DISABILITY_TYPE'
         where sm.inst_id=sasc.inst_id
          AND sm.ay_id=sasc.ay_id 
          AND sm.is_deleted=sasc.is_deleted
          AND sm.is_active=sasc.is_active 
          AND sm.is_active=1 
          AND sm.is_deleted=0
          AND sm.inst_id=in_inst_id
          AND sm.ay_id=in_ay_id 
          AND sm.student_id=in_student_id;
          select sasc.score INTO l_f_edu_qual_degree from parent_master pm 
          JOIN stud_admissiom_score_master sasc ON pm.edu_qual_degree=sasc.data_key 
            and sasc.data_type='EDU_QUALIFICATION'
            and sasc.category='FATHER_QUALIFICATION'
          where pm.inst_id=sasc.inst_id
          AND pm.is_deleted=sasc.is_deleted
          AND pm.is_active=sasc.is_active 
          AND pm.is_active=1 
          AND pm.is_deleted=0
          AND pm.inst_id=in_inst_id
          AND pm.parent_id=l_father_id;
          select sasc.score INTO l_f_occupation from parent_master pm 
          JOIN stud_admissiom_score_master sasc ON pm.occupation=sasc.data_key 
            and sasc.data_type='OCCUPATION'
            and sasc.category='FATHER_OCCUPATION'
         where pm.inst_id=sasc.inst_id
          AND pm.is_deleted=sasc.is_deleted
          AND pm.is_active=sasc.is_active 
          AND pm.is_active=1 
          AND pm.is_deleted=0
          AND pm.inst_id=in_inst_id
          AND pm.parent_id=l_father_id;
          select sasc.score INTO l_f_income_bracket from parent_master pm 
          JOIN stud_admissiom_score_master sasc ON pm.income_bracket=sasc.data_key 
            and sasc.data_type='INCOME_BRACKET'
            and sasc.category='FATHER_INCOME_BRACKET'
          where pm.inst_id=sasc.inst_id
          AND pm.is_deleted=sasc.is_deleted
          AND pm.is_active=sasc.is_active 
          AND pm.is_active=1 
          AND pm.is_deleted=0
          AND pm.inst_id=in_inst_id
          AND pm.parent_id=l_father_id;
          select sasc.score INTO l_m_edu_qual_degree from parent_master pm 
          JOIN stud_admissiom_score_master sasc ON pm.edu_qual_degree=sasc.data_key 
          and sasc.data_type='EDU_QUALIFICATION'
            and sasc.category='MOTHER_QUALIFICATION'
          where pm.inst_id=sasc.inst_id
         AND pm.is_deleted=sasc.is_deleted
          AND pm.is_active=sasc.is_active 
          AND pm.is_active=1 
          AND pm.is_deleted=0
          AND pm.inst_id=in_inst_id
          AND pm.parent_id=l_mother_id;
          select sasc.score INTO l_m_occupation from parent_master pm 
          JOIN stud_admissiom_score_master sasc ON pm.occupation=sasc.data_key 
          and sasc.data_type='OCCUPATION'
            and sasc.category='MOTHER_OCCUPATION'
          where pm.inst_id=sasc.inst_id
          AND pm.is_deleted=sasc.is_deleted
          AND pm.is_active=sasc.is_active 
          AND pm.is_active=1 
          AND pm.is_deleted=0
          AND pm.inst_id=in_inst_id
          AND pm.parent_id=l_mother_id;
          select sasc.score INTO l_m_income_bracket from parent_master pm 
          JOIN stud_admissiom_score_master sasc ON pm.income_bracket=sasc.data_key 
          and sasc.data_type='INCOME_BRACKET'
            and sasc.category='MOTHER_INCOME_BRACKET'
          where pm.inst_id=sasc.inst_id
         AND pm.is_deleted=sasc.is_deleted
          AND pm.is_active=sasc.is_active 
          AND pm.is_active=1 
          AND pm.is_deleted=0
          AND pm.inst_id=in_inst_id
          AND pm.parent_id=l_mother_id;
           Set l_student_score=l_student_category + l_consession_category + l_prev_school_board+
              l_disability + l_f_edu_qual_degree + l_f_occupation + l_f_income_bracket + 
              l_m_edu_qual_degree + l_m_occupation + l_m_income_bracket;
          Update student_master set student_admission_score=l_student_score 
          where inst_id=in_inst_id and ay_id=in_ay_id and student_id=in_student_id
                  and is_active=1 and is_deleted=0;
     END LOOP simple_loop;
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_custom_seq_generator`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_custom_seq_generator`(IN `in_inst_id` SMALLINT(5), IN `in_entity_name` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_initiator_id` VARCHAR(25), OUT `out_custom_seq_num` VARCHAR(50))
BEGIN
  declare l_routine_name varchar(50) default 'sp_custom_seq_generator';
  declare l_routine_block varchar(25) default 'start work';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_curs_1_loop_done int default false;
  declare l_curs_2_loop_done int default false;
  declare l_param_count tinyint(2) default 0; 
  declare l_separator_char char(1);
  declare l_seq_pattern varchar(50); 
  declare l_operation_code varchar(10); 
  declare l_seq_current_num mediumint(8); 
  declare l_separator_idx int default 1;
  declare l_token varchar(25); 
  declare l_inst_abbr varchar(25);  
  declare l_inst_br_abbr varchar(25);  
  declare l_custom_seq_num varchar(100) default ''; 
  declare cur_seq_gen_master cursor for 
  select param_count, trim(seperator_char), trim(op_code), trim(seq_pattern), seq_current_num
  from sequence_generator_master 
  where entity_id = trim(in_entity_name) and inst_id = in_inst_id and is_active = 1
  and is_deleted = 0;
  declare cur_inst_seq_params cursor for 
  select trim(inst_abbr), trim(inst_br_abbr)
  from institution_sequence_params
  where inst_id = in_inst_id and is_active = 1 and is_deleted = 0;
  declare continue handler for not found set l_curs_1_loop_done = true, 
    l_curs_2_loop_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_initiator_id);
      set out_custom_seq_num = '';
		end;
    open cur_seq_gen_master;
    open cur_inst_seq_params;
    cursor_loop_1: loop
      fetch cur_inst_seq_params into l_inst_abbr, l_inst_br_abbr;
      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Inside Cursor 1', l_inst_abbr);
      set l_curs_1_loop_done = true;
      if l_curs_1_loop_done then
        leave cursor_loop_1;
      end if;
    end loop;
    close cur_inst_seq_params;
    cursor_loop_2: loop
      fetch cur_seq_gen_master into l_param_count, l_separator_char, l_operation_code, l_seq_pattern, 
        l_seq_current_num;
      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Inside Cursor 2', l_param_count);
      if l_curs_2_loop_done then
        leave cursor_loop_2;
      end if;
      while (l_param_count > 0) do
        set l_routine_block = 'inside while loop';
        set l_separator_idx = instr(l_seq_pattern, l_separator_char);
        set l_token = substring(l_seq_pattern, 1, l_separator_idx - 1);
        set l_seq_pattern = substring(l_seq_pattern, l_separator_idx + 1, 
          length(l_seq_pattern));
        #insert into proc_error_logs (routine_name, label_name, sql_log)
        #values(l_routine_name, l_routine_block, l_token);
        case l_token
          when '{INST_ABBR}' THEN
            begin
              if length(l_inst_abbr) > 0 then
                set l_custom_seq_num = concat(l_custom_seq_num, l_separator_char, l_inst_abbr);
              end if;
            end;
          when '{INST_BR}' THEN
            begin            
              if length(l_inst_br_abbr) > 0 then
                set l_custom_seq_num = concat(l_custom_seq_num, l_separator_char, l_inst_br_abbr);
              end if;
            end;
          when '{AY_ID}' THEN
            begin            
              if length(in_ay_id) > 0 then
                set l_custom_seq_num = concat(l_custom_seq_num, l_separator_char, in_ay_id);
              end if;
            end;
          when '{OP_CODE}' THEN
            begin            
              if length(l_operation_code) > 0 then
                set l_custom_seq_num = concat(l_custom_seq_num, l_separator_char, l_operation_code);
              end if;
            end;
          when '{DD-MON}' THEN
            begin            
              set l_custom_seq_num = concat(l_custom_seq_num, l_separator_char, day(current_date()));
            end;
        end case;
        set l_param_count = l_param_count - 1;
        set l_separator_idx = 0;
      end while;
    end loop;
    close cur_seq_gen_master;
    start transaction;
      begin
        select seq_current_num into l_seq_current_num from sequence_generator_master 
        where entity_id = trim(in_entity_name) and inst_id = in_inst_id and is_active = 1
        and is_deleted = 0 for update;
        #insert into proc_error_logs (routine_name, label_name, sql_log)
        #values(l_routine_name, 'Seed : ', l_seq_current_num);
        set l_seq_current_num = l_seq_current_num + 1;
        set l_custom_seq_num = concat(l_custom_seq_num, l_separator_char, l_seq_current_num);
        set l_custom_seq_num = substring(l_custom_seq_num, 2, length(l_custom_seq_num));
        #insert into proc_error_logs (routine_name, label_name, sql_log)
        #values(l_routine_name, 'Value : ', l_custom_seq_num);
        update sequence_generator_master set seq_current_num = l_seq_current_num, 
          updated_by = trim(in_initiator_id), updated_on = now()
        where entity_id = in_entity_name and inst_id = in_inst_id and is_active = 1
          and is_deleted = 0;
      end; 
    commit;      
    set out_custom_seq_num = l_custom_seq_num; 
END$$

DROP PROCEDURE IF EXISTS `sp_del_appl_data_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_appl_data_master`(IN `in_data_type` VARCHAR(100), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
		declare l_routine_name varchar(50) default 'sp_del_appl_data_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  appl_data_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where is_deleted =0 and inst_id = in_inst_id and data_type=in_data_type;
             if(in_inst_id=0)then
                  	update  appl_data_master set valid_to = NOW(), updated_by = in_created_by, 
                      updated_on = NOW(), is_deleted = 1
                    where is_deleted =0 and data_type=in_data_type;
              end if;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_appl_license_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_appl_license_master`(IN `in_fy_id` CHAR(7), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_appl_license_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update appl_license_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where fy_id=in_fy_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_appl_txn_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_appl_txn_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_txn_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
		declare l_routine_name varchar(50) default 'sp_del_appl_txn_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  appl_txn_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where is_deleted =0 and inst_id = in_inst_id and txn_id=in_txn_id and ay_id=in_ay_id;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_book_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_book_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_book_id` MEDIUMINT(8), IN `in_curriculum_type` VARCHAR(4), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_book_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          	update book_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where book_id = in_book_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id and curriculum_type=in_curriculum_type;
          end;    
    commit;
   set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_class_subject_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_class_subject_map`(IN `in_class_id` VARCHAR(25), IN `in_subject_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_class_subject_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update class_subject_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where subject_id=in_subject_id and class_id=in_class_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_contracts_and_renewals`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_contracts_and_renewals`(IN `in_con_renewal_id` VARCHAR(7), 
  IN `in_ay_id` CHAR(7), 
  IN `in_inst_id` SMALLINT(5), 
  IN `in_created_by` VARCHAR(20), 
  OUT `out_err_code` CHAR(5), 
  OUT `out_err_desc` TEXT)
    NO SQL
BEGIN
  declare l_routine_name varchar(50) default 'sp_del_contracts_and_renewals';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
      begin
          	update  contract_and_renewal set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where con_renewal_id=in_con_renewal_id and is_deleted = 0 and 
             ay_id = in_ay_id 	and inst_id = in_inst_id; 
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_custom_group_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_custom_group_details`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_custom_group_mst_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

   declare l_routine_name varchar(50) default 'sp_del_custom_group_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	 begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
          begin
          	update custom_group_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where custom_group_mst_id = in_custom_group_mst_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id ;

          end;    
      
    
    commit;
   set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_department_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_department_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_dept_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_department_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          	update department_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where dept_id = in_dept_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id ;
          end;    
    commit;
   set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_division_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_division_master`(IN `in_division_id` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_del_division_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  division_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id and division_id=in_division_id;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_email_template_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_email_template_master`(IN `in_id` INT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_del_email_template_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  email_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id and id=in_id;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_employee_attendance_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_employee_attendance_dtl_json`(IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_employee_attendance_dtl_json';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update emp_attendance_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where attendance_mst_id = in_attendance_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end; 
           begin
          		update emp_attendance_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where attendance_mst_id = in_attendance_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_employee_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_employee_master`(IN `in_emp_id` VARCHAR(20), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_employee_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update   employee_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  emp_id=in_emp_id  and is_active = 'Y'  
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_emp_bank_account_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_emp_bank_account_details`(IN `in_emp_attendance_id` VARCHAR(25), IN `in_emp_id` VARCHAR(25), IN `in_file_upload_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_emp_bank_account_details';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update emp_bank_account_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  emp_id=in_emp_id and branch_id=in_branch_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_emp_dept_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_emp_dept_map`(IN `in_emp_id` VARCHAR(25), IN `in_dept_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_emp_dept_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update emp_dept_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  emp_id=in_emp_id and dept_id=in_dept_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_emp_leave_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_emp_leave_details`(IN `in_emp_leave_id` MEDIUMINT(8), IN `in_emp_id` MEDIUMINT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_emp_leave_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update emp_leave_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where emp_leave_id = in_emp_leave_id and emp_id = in_emp_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end; 
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_emp_subject_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_emp_subject_map`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_emp_sub_map_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_del_emp_subject_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          	update  emp_subject_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where emp_sub_map_id=in_emp_sub_map_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id; 
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_event_participant_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_event_participant_map`(IN `in_event_id` VARCHAR(25), IN `in_participant_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_event_participant_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  event_participant_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where event_id=in_event_id and participant_id=in_participant_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_fee_structure_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_fee_structure_details`(IN `in_inst_id` CHAR(15), IN `in_fee_struct_mst_id` VARCHAR(25), IN `in_acct_head_id` VARCHAR(25), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2), OUT `out_err_desc` TEXT)
    NO SQL
begin 
	declare v_routine_name varchar(50) default 'sp_del_fee_structure_details'; 
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction; 
          begin
          	update fee_structure_details 
				set valid_to = NOW(), 
					updated_by = in_created_by,  
					updated_on = NOW(), 
					is_active = '1' , 
					is_deleted = '1' 
            where 	fee_struct_mst_id = in_fee_struct_mst_id 
					and acct_head_id = in_acct_head_id 
					and is_active = '1' 
					and is_deleted = '0'  
					and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_fee_structure_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_fee_structure_master`(IN `in_inst_id` CHAR(15), IN `in_fee_struct_mst_id` VARCHAR(25), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2), OUT `out_err_desc` TEXT)
    NO SQL
begin 
	declare v_routine_name varchar(50) default 'sp_del_fee_structure_master'; 
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction; 
		begin
          	update fee_structure_master
				set valid_to = NOW(), 
					updated_by = in_created_by,  
					updated_on = NOW(), 
					is_active = '1' , 
					is_deleted = '1' 
            where 	fee_struct_mst_id = in_fee_struct_mst_id  
					and is_active = '1' 
					and is_deleted = '0'  
					and inst_id = in_inst_id; 
			update fee_structure_details 
				set valid_to = NOW(), 
					updated_by = in_created_by,  
					updated_on = NOW(), 
					is_active = '1' , 
					is_deleted = '1' 
            where 	fee_struct_mst_id = in_fee_struct_mst_id  
					and is_active = '1' 
					and is_deleted = '0'  
					and inst_id = in_inst_id; 
		end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_file_upload_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_file_upload_details`(IN `in_file_upload_id` VARCHAR(25), IN `in_class_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_file_upload_details';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  file_upload_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where file_upload_id=in_file_upload_id and class_id=in_class_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_grade_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_grade_details`(IN `in_inst_id` SMALLINT(5), IN `in_ay_id` CHAR(7), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_gradeset_dtl_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
    declare l_routine_name varchar(50) default 'sp_del_grade_details';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
  declare exit handler for sqlexception
     begin
     rollback;
     get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
   start transaction;
         begin
             update  gradeset_details set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where gradeset_dtl_id=in_gradeset_dtl_id and is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id;
         end;    
   commit;
 set out_err_code = l_err_code;
 set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_grade_set_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_grade_set_master`(IN `in_inst_id` SMALLINT(5), IN `in_ay_id` CHAR(7), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
    declare l_routine_name varchar(50) default 'sp_del_grade_set_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
  declare exit handler for sqlexception
     begin
     rollback;
     get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
   start transaction;
         begin
             update  gradeset_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where gradeset_mst_id=in_gradeset_mst_id and is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id;
         end;    
   commit;
 set out_err_code = l_err_code;
 set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_holiday_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_holiday_master`(IN `in_holiday_id` INT(10), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_holiday_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  holiday_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where holiday_id=in_holiday_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_house_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_house_master`(IN `in_house_id` TINYINT(2), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(0), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
		declare l_routine_name varchar(50) default 'sp_del_house_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  house_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted =1
            where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id and house_id=in_house_id;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_id_generator_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_id_generator_master`(IN `in_id_category` VARCHAR(10), IN `in_id_cycle` VARCHAR(10), IN `in_id_prefix` VARCHAR(15), IN `in_id_seperator` VARCHAR(15), IN `in_id_start_from` VARCHAR(50), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_id_generator_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update id_generator_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where id_category=in_id_category and id_cycle=in_id_cycle and id_prefix=in_id_prefix and 
              id_seperator=in_id_seperator and id_starts_from=in_id_starts_from and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_information_posts_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_information_posts_details`(IN `in_post_id` MEDIUMINT(5), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_information_posts_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update  information_posts set  updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where post_id = in_post_id   and is_deleted = 0 
            	and inst_id = in_inst_id;
          end; 
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_institution_config`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_institution_config`(IN `in_fy_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_institution_config';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  institution_config set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where fy_id=in_fy_id and is_active = 'Y'  
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_institution_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_institution_master`(IN `in_inst_id` CHAR(15), IN `in_org_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_institution_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  institution_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where inst_id=in_inst_id and org_id=in_org_id and is_active = 'Y';  
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_inventory_issuedItem`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_inventory_issuedItem`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_user_id` MEDIUMINT(8), IN `in_issue_mst_id` MEDIUMINT(8), IN `in_issue_dtl_id` MEDIUMINT(8), IN `in_inventory_dept_id` MEDIUMINT(8), IN `in_item_id` MEDIUMINT(8), IN `in_quantity` DECIMAL(7,2), IN `in_amount` BIGINT(50), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_rowCount` MEDIUMINT(8), IN `in_issueItemCount` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_del_inventory_issuedItem';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	 begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
          begin
-- all rows selected
          if(in_rowCount = in_issueItemCount)then
          	update  inventory_issue_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where issue_mst_id=in_issue_mst_id and party_id = in_user_id 
              and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id and inventory_dept_id=in_inventory_dept_id
             and is_active=1; 
            
            update  inventory_user_pocket_history set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where issue_mst_id = in_issue_mst_id and user_id = in_user_id and is_active=1 
              AND is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id
            AND transcation_type='DR';
      -- if one rows selected           
          else
              update  inventory_issue_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), total_amount = total_amount-in_amount
            where issue_mst_id=in_issue_mst_id and party_id = in_user_id 
              and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id and inventory_dept_id=in_inventory_dept_id
             and is_active=1;

            update  inventory_user_pocket_history set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), balance =balance-in_amount
            where issue_mst_id = in_issue_mst_id and user_id = in_user_id and is_active=1 
              AND is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id
            AND transcation_type='DR';

          end if;

            	update   inventory_issue_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where issue_dtl_id = in_issue_dtl_id and in_item_id=in_item_id AND
                is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id
               and is_active=1;
              
              update  inventory_pocket_money set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), balance = balance +in_amount
            where user_id = in_user_id  and ay_id = in_ay_id 
            	and inst_id = in_inst_id and is_active=1 and  is_deleted = 0;

            update  inventory_stock_balance set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), quantity = quantity+in_quantity
            where item_id = in_item_id and is_active=1 AND
                is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id;

             

            INSERT INTO  audit_history(ay_id, inst_id, comment_type,main_id,
               sub_id,comment,created_by, updated_by, is_active) 
            VALUES(in_ay_id,in_inst_id,'Delete inventory issued item',in_issue_mst_id, 
              in_user_id, 'Update all issue item table of inventory',
              in_created_by, in_created_by, in_is_active);
              

          end;    

    commit;
   set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_library_book`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_library_book`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_book_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), IN `in_lib_acct_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_del_library_book';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	 begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
          begin
          	update library_book_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where book_id = in_book_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id and lib_acct_id=in_lib_acct_id;

            	update  library_book_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where book_id = in_book_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;

          end;    
      
  
    commit;
   set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_news_posts_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_news_posts_details`(IN `in_post_id` MEDIUMINT(5), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_news_posts_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update  news_posts set  updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where post_id = in_post_id   and is_deleted = 0 
            	and inst_id = in_inst_id;
          end; 
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_notif_temp_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_notif_temp_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notif_template_id` MEDIUMINT(8), IN `in_web_template_id` MEDIUMINT(8), IN `in_mail_template_id` MEDIUMINT(8), IN `in_app_template_id` MEDIUMINT(8), IN `in_sms_template_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
BEGIN

  declare l_routine_name varchar(50) default 'sp_del_notif_temp_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);

  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id,inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id,in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
    
      begin
          	update  notification_config set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where notif_template_id=in_notif_template_id and is_deleted = 0 and inst_id = in_inst_id; 
          
            update  notif_web_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where web_template_id=in_web_template_id and is_deleted = 0 and inst_id = in_inst_id;

            update  notif_email_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where mail_template_id=in_mail_template_id and is_deleted = 0 and inst_id = in_inst_id;

            update  notif_app_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where app_template_id=in_app_template_id and is_deleted = 0 and inst_id = in_inst_id;

            update  notif_sms_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where sms_template_id=in_sms_template_id and is_deleted = 0 and inst_id = in_inst_id;

            if(in_inst_id=0)then

              update  notification_config set valid_to = NOW(), updated_by = in_created_by, 
                updated_on = NOW(), is_deleted = 1 
              where notif_template_id=in_notif_template_id and is_deleted = 0; 
            
              update  notif_web_template_master set valid_to = NOW(), updated_by = in_created_by, 
                updated_on = NOW(), is_deleted = 1 
              where web_template_id=in_web_template_id and is_deleted = 0;
  
              update  notif_email_template_master set valid_to = NOW(), updated_by = in_created_by, 
                updated_on = NOW(), is_deleted = 1 
              where mail_template_id=in_mail_template_id and is_deleted = 0;
  
              update  notif_app_template_master set valid_to = NOW(), updated_by = in_created_by, 
                updated_on = NOW(), is_deleted = 1 
              where app_template_id=in_app_template_id and is_deleted = 0;
  
              update  notif_sms_template_master set valid_to = NOW(), updated_by = in_created_by, 
                updated_on = NOW(), is_deleted = 1 
              where sms_template_id=in_sms_template_id and is_deleted = 0;   

            end if;
          end;    
      
    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_organization_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_organization_master`(IN `in_org_id` SMALLINT(5), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
		declare l_routine_name varchar(50) default 'sp_del_organization_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        ('', '', l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_updated_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  organization_master set valid_to = NOW(), updated_by = in_updated_by, 
              updated_on = NOW(), is_deleted =1
            where is_deleted = 0 and org_id=in_org_id;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_parent_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_parent_master`(IN `in_parent_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_parent_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  parent_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where parent_id=in_parent_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_qams_asset_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_qams_asset_master`(IN `in_inst_id` SMALLINT(5), IN `in_asset_id` VARCHAR(7), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
BEGIN

  declare l_routine_name varchar(50) default 'sp_del_qams_asset_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
    
      begin
          	update  qams_asset_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where asset_id=in_asset_id and is_deleted = 0 
            	and inst_id = in_inst_id; 
          
          end;    
      
    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_role_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_role_master`(IN `in_role_id` VARCHAR(20), IN `in_parent_id` VARCHAR(20), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_role_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update role_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where role_id=in_role_id and parent_id=in_parent_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_school_document_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_school_document_details`(IN `in_document_upload_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_del_school_document_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
      
          begin
          		update  school_document_details set  updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where document_upload_id = in_document_upload_id   and is_deleted = 0 
            	and inst_id = in_inst_id and ay_id=in_ay_id;
          
          end; 
          
      
    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_del_sms_template_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_sms_template_master`(IN `in_txn_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_sms_template_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  sms_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  txn_id=in_txn_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_standard_division_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_standard_division_map`(IN `in_std_div_map_id` MEDIUMINT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_del_standard_division_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update standard_division_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id 
              and std_div_map_id=in_std_div_map_id ;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_standard_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_standard_master`(IN `in_standard_id` CHAR(2), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_del_standard_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
          begin
          	update  standard_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id and standard_id=in_standard_id;
          end;    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_student_assignment_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_student_assignment_details`(IN `in_student_id` VARCHAR(25), IN `in_assignment_id` VARCHAR(25), IN `in_class_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_student_assignment_details';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update student_assignment_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where student_id=in_student_id and assignment_id=in_assignment_id and class_id=in_class_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_student_elective_subject_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_student_elective_subject_map`(IN `in_student_id` VARCHAR(25), IN `in_subject_id` VARCHAR(25), IN `in_class_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_student_elective_subject_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  student_elective_subject_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  student_id=in_student_id  and subject_id=in_subject_id and 	class_id=in_class_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_student_leave_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_student_leave_details`(IN `in_leave_id` MEDIUMINT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
   declare l_routine_name varchar(50) default 'sp_del_student_leave_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update student_leave_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where leave_id = in_leave_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end; 
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_student_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_student_master`(IN `in_class_id` VARCHAR(25), IN `in_student_id` VARCHAR(25), IN `in_file_upload_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_student_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  student_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where student_id=in_student_id and class_id=in_class_id and file_upload_id=in_file_upload_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_student_previous_institutions`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_student_previous_institutions`(IN `in_standard_id` VARCHAR(25), IN `in_student_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_student_previous_institutions';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update student_previous_institutions set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where standard_id=in_standard_id  and student_id=in_student_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_stud_admission_stage_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_stud_admission_stage_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stage_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
 declare l_routine_name varchar(50) default 'sp_del_stud_admission_stage_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';            
 declare l_routine_block varchar(15);
  declare exit handler for sqlexception
     begin
     rollback;
     get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
   start transaction;
         begin
             update  admission_stage_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id and stage_id=in_stage_id;
         end;    
   commit;
 set out_err_code = l_err_code;
 set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_stud_admission_status_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_stud_admission_status_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_status_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
    declare l_routine_name varchar(50) default 'sp_del_stud_admission_status_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
  declare exit handler for sqlexception
     begin
     rollback;
     get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
   start transaction;
         begin
             update  admission_stage_status_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id and status_id=in_status_id;
         end;    
   commit;
 set out_err_code = l_err_code;
 set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_stud_assignment_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_stud_assignment_dtl_json`(IN `in_assignment_mst_id` MEDIUMINT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_stud_assignment_dtl_json';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update student_assignment_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where assignment_mst_id = in_assignment_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end; 
           begin
          		update  student_assignment_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where assignment_mst_id = in_assignment_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_stud_attendance_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_stud_attendance_dtl_json`(IN `in_ay_id` CHAR(7), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_stud_attendance_dtl_json';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update student_attendance_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where attendance_mst_id = in_attendance_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end; 
           begin
          		update student_attendance_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where attendance_mst_id = in_attendance_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_stud_homework_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_stud_homework_master`(IN `in_stud_hw_mst_id` MEDIUMINT(8), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_del_stud_homework_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          		update student_homework_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where stud_hw_mst_id = in_stud_hw_mst_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end; 
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_subject_book_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_subject_book_map`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_book_map_id` MEDIUMINT(8), IN `in_curriculum_type` VARCHAR(4), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_del_subject_book_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          	update  subject_book_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where  sub_book_map_id = in_sub_book_map_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_subject_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_subject_master`(IN `in_subject_id` VARCHAR(7), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
BEGIN
  declare l_routine_name varchar(50) default 'sp_del_subject_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
      begin
          	update  subject_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where subject_id=in_subject_id and is_deleted = 0 and 
             ay_id = in_ay_id 	and inst_id = in_inst_id; 
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_subject_standard_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_subject_standard_map`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_std_map_id` CHAR(6), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
BEGIN
  declare l_routine_name varchar(50) default 'sp_del_subject_standard_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
      begin
          update  subject_standard_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where   sub_std_map_id = in_sub_std_map_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_subject_structure_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_subject_structure_map`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_curriculum_type` VARCHAR(4), IN `in_sub_struct_map_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_del_subject_structure_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
      begin	
            update  subject_structure_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where   sub_struct_map_id = in_sub_struct_map_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id and curriculum_type=in_curriculum_type; 
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_subject_syllabus_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_subject_syllabus_map`(IN `in_sub_std_map_id` CHAR(7), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_del_subject_syllabus_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
       set l_routine_block = 'Delete';
          begin
          	update  subject_syllabus_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where sub_std_map_id=in_sub_std_map_id and 
                   is_deleted = 0 and ay_id = in_ay_id 
            	     and inst_id = in_inst_id; 
          end;    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_timeslot_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_timeslot_master`(IN `in_timeslot_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_timeslot_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  timeslot_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where timeslot_id=in_timeslot_id
                     and is_active = 'Y' and ay_id = in_ay_id 
            	     and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_timetable_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_timetable_master`(IN `in_timetable_id` VARCHAR(25), IN `in_class_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_timetable_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  timetable_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where timetable_id=in_timetable_id and class_id=in_class_id
                     and is_active = 'Y' and ay_id = in_ay_id 
            	     and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_timetable_period_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_timetable_period_map`(IN `in_timetable_period_id` VARCHAR(25), IN `in_timetable_id` VARCHAR(25), IN `in_timeslot_id` VARCHAR(25), IN `in_weekday_id` VARCHAR(25), IN `in_subject_id` VARCHAR(25), IN `in_emp_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_timetable_period_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  timetable_period_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where timetable_period_id=in_timetable_period_id and timetable_id=in_timetable_id 
                        and timeslot_id=in_timeslot_id and weekday_id=in_weekday_id and subject_id=in_subject_id and emp_id=in_emp_id
                        and is_active = 'Y' and ay_id = in_ay_id 
            	          and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_trans_route_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_trans_route_master`(IN `in_route_id` SMALLINT(5), IN `in_inst_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
BEGIN

  declare l_routine_name varchar(50) default 'sp_del_trans_route_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
    
      begin
          	update  trans_route_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where route_id=in_route_id and is_deleted = 0 
            	and inst_id = in_inst_id; 
          
          end;    
      
    
    commit;
   set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_del_trans_vehicle_driver_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_trans_vehicle_driver_map`(IN `in_vehicle_driver_map_id` MEDIUMINT(8), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

   declare l_routine_name varchar(50) default 'sp_del_trans_vehicle_driver_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
    	
  declare exit handler for sqlexception
	 begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        ('', in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
       set l_routine_block = 'Delete';
          begin
          		update  trans_vehicle_driver_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where vehicle_driver_map_id=in_vehicle_driver_map_id and is_deleted = 0 and inst_id = in_inst_id; 

          end;    
      
    commit;
   set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_del_txn_alert_config`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_txn_alert_config`(IN `in_txn_id` VARCHAR(25), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_del_txn_alert_config';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
          begin
          	update  txn_alert_config set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where txn_id=in_txn_id
                  and is_active = 'Y' and ay_id = in_ay_id 
            	    and inst_id = in_inst_id; 
          end;    
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_del_video_posts_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_del_video_posts_details`(IN `in_video_id` MEDIUMINT(5), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

       
  declare l_routine_name varchar(50) default 'sp_del_video_posts_details';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
       
 declare exit handler for sqlexception
      begin
     rollback;
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
      set l_routine_block = 'Delete';
     
         begin
                 update  video_posts set  updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where video_id = in_video_id   and is_deleted = 0
               and inst_id = in_inst_id and is_active=1;
         
         end;
         
     
   
   commit;
  set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_execute_immediate`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_execute_immediate`(IN `in_sql_str` TEXT)
begin
  set @l_sql_str = trim(in_sql_str);
  prepare l_execute_stmt from @l_sql_str;
  execute l_execute_stmt;
  deallocate prepare l_execute_stmt;   
  commit;
end$$

DROP PROCEDURE IF EXISTS `sp_final_setup_migration`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_final_setup_migration`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_current_ay` CHAR(7), IN `in_next_ay` CHAR(7), IN `in_next_to_next_ay` CHAR(7), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_final_setup_migration';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_is_active tinyint(1) default 0;
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                    err_desc, err_type, err_severity, created_by) 
             values (in_current_ay, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                    'ERROR', 0, in_created_by);
        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
       when 'M' then          
          begin
             set l_routine_block = 'Migration'; 
             
              
              #gradeset_master data 
 
              Delete from gradeset_master where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO gradeset_master(ay_id, inst_id, gradeset_mst_id ,curriculum_type, grading_system,
               gradeset_name, gradeset_display_name, gradeset_abbr, is_system_def, created_by, updated_by)
                select in_next_ay, in_inst_id,gradeset_mst_id ,curriculum_type, grading_system,
              gradeset_name, gradeset_display_name, gradeset_abbr, is_system_def, in_created_by, in_created_by
                 from gradeset_master where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #gradeset_details data 

              Delete from gradeset_details where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO gradeset_details(ay_id, inst_id, gradeset_mst_id ,gradeset_dtl_id, grade_name,
               grade_desc, grade_abbr, score_range_from , score_range_to,grade_points, grade_pos,
                created_by, updated_by)
                  select in_next_ay, in_inst_id, gradeset_mst_id ,gradeset_dtl_id, grade_name,
               grade_desc, grade_abbr, score_range_from , score_range_to,grade_points, grade_pos,
                    in_created_by, in_created_by
                  from gradeset_details where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #subject_master data

              Delete from subject_master where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO subject_master(ay_id, inst_id, curriculum_type, grading_system, subject_id, 
                subject_name, subject_display_name, subject_desc, subject_abbr, subject_group_name, 
                is_system_def, valid_from, valid_to, created_by, created_on, updated_by, updated_on, 
                is_active, is_deleted) 
              select in_next_ay, inst_id, curriculum_type, grading_system, subject_id, 
                subject_name, subject_display_name, subject_desc, subject_abbr, subject_group_name, 
                is_system_def, now(), valid_to, created_by, now(), updated_by, now(), 
                is_active, is_deleted
              from subject_master where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #subject_standard_map data
              Delete from subject_standard_map where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

               INSERT INTO subject_standard_map(ay_id, inst_id, sub_std_map_id, curriculum_type, grading_system, 
                  standard_id, division_id, group_type, group_id, subject_id, 
                  subject_type_id, subject_category_id, gradeset_mst_id, evaluation_type,
                   subject_level, max_weekly_classes, credit_hours, is_mandatory, exam_type, 
                  is_book_based, is_consecutive_preferred, is_system_def, valid_from, valid_to,
                   created_by, created_on, updated_by, updated_on, is_active, is_deleted) 
              select in_next_ay, inst_id, sub_std_map_id, curriculum_type, grading_system, 
                  standard_id, division_id, group_type, group_id, subject_id, 
                  subject_type_id, subject_category_id, gradeset_mst_id, evaluation_type,
                   subject_level, max_weekly_classes, credit_hours, is_mandatory, exam_type, 
                  is_book_based, is_consecutive_preferred, is_system_def, now(), valid_to,
                  created_by, now(), updated_by, now(), 
                is_active, is_deleted
              from subject_standard_map where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #subject_structure_map data
              Delete from subject_structure_map where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

               INSERT INTO subject_structure_map(ay_id, inst_id, sub_struct_map_id, sub_std_map_id, 
                curriculum_type, grading_system, standard_id, division_id, group_type, group_id, subject_id, parent_id, 
                subject_level, subject_pos, is_system_def, time_table_enabled, exam_enabled, homework_enabled, 
                valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted) 
              select in_next_ay, inst_id,sub_struct_map_id, sub_std_map_id, 
                curriculum_type, grading_system, standard_id, division_id, group_type, group_id, subject_id, parent_id, 
                subject_level, subject_pos, is_system_def, time_table_enabled, exam_enabled, homework_enabled,
                now(), valid_to,created_by, now(), updated_by, now(), is_active, is_deleted
              from subject_structure_map where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #subject_package_master data
              Delete from subject_package_master where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO subject_package_master(ay_id, inst_id, standard_id, package_id, package_name,
                package_display_name, package_desc, 
                valid_from, valid_to,created_by, created_on, updated_by, updated_on, is_active, is_deleted) 
              select in_next_ay, inst_id, standard_id, package_id, package_name,
                package_display_name,package_desc,
                now(), valid_to,created_by, now(), updated_by, now(), is_active, is_deleted
              from subject_package_master where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #book_master data
              Delete from book_master where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO book_master(ay_id, inst_id, book_id, curriculum_type, grading_system, 
                standard_id, book_type, book_name, book_display_name, 
                book_desc, book_abbr, publisher_name, is_system_def,
                valid_from, valid_to,created_by, created_on, updated_by, updated_on, is_active, is_deleted) 
              select in_next_ay, inst_id, book_id, curriculum_type, grading_system, 
                standard_id, book_type, book_name, book_display_name, 
                book_desc, book_abbr, publisher_name, is_system_def,
                now(), valid_to,created_by, now(), updated_by, now(), is_active, is_deleted
              from book_master where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #book_chapter_map data
              Delete from book_chapter_map where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO book_chapter_map(ay_id, inst_id, book_chpt_map_id, curriculum_type, book_id, chapter_type,
                chapter_num, chapter_name, chapter_desc, chapter_abbr, is_system_def,
                valid_from, valid_to,created_by, created_on, updated_by, updated_on, is_active, is_deleted) 
              select in_next_ay, inst_id, book_chpt_map_id, curriculum_type, book_id, chapter_type,
                chapter_num, chapter_name, chapter_desc, chapter_abbr, is_system_def,
                now(), valid_to,created_by, now(), updated_by, now(), is_active, is_deleted
              from book_chapter_map where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

               #emp_subject_map data
              Delete from emp_subject_map where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              #institution_sub_config data
              Delete from institution_sub_config where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

              INSERT INTO institution_sub_config(ay_id, inst_id, config_name, config_value, created_by, updated_by) 
              select in_next_ay, inst_id, config_name, config_value, created_by, updated_by
              from institution_sub_config where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;
      end;    

      when 'Y' then          
      begin
         set l_routine_block = 'Year Migration'; 

          Delete from institution_config where ay_id = in_next_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;
          
          # institution_config data
           INSERT INTO institution_config (ay_id, inst_id, inst_type, edu_board, fy_start_date, fy_end_date, ay_start_date, 
           ay_end_date, current_ay, next_ay, attendance_type, first_day_of_week, weekly_holiday, date_format, currency_code, 
           class_display_format, instruction_mode, grading_system, terms_per_year, enrollment_num_gen_mode, enrollment_num_gen_id, 
           stud_num_gen_mode, stud_num_gen_id, emp_num_gen_mode, emp_num_gen_id, admission_num_gen_mode, admission_num_gen_id,
	        demand_num_gen_mode,  demand_num_gen_id, pmt_rcpt_num_gen_mode, pmt_rcpt_num_gen_id, sms_override,sms_sender_id,
           web_theme_id, app_theme_id, inst_house_flag, records_per_page, created_by, updated_by, is_active,
            lib_book_num_gen_mode,lib_book_num_gen_id, online_payment_enabled,force_stop_notifications,inst_sms_master_stop,
            app_inactive_days_sms_override,inst_sms_credit_value,is_group_homework,is_stu_picture_upload,is_stu_profile_update,
           is_emp_picture_upload, is_emp_profile_update, stud_name_format, stud_name_case, emp_name_format, emp_name_case) 
           select in_next_ay, in_inst_id, inst_type, edu_board, DATE_ADD(fy_start_date, INTERVAL 1 YEAR),
            DATE_ADD(fy_end_date, INTERVAL 1 YEAR), DATE_ADD(ay_start_date, INTERVAL 1 YEAR), 
           DATE_ADD(ay_end_date, INTERVAL 1 YEAR), in_next_ay, in_next_to_next_ay, attendance_type, first_day_of_week, weekly_holiday, date_format, currency_code, 
           class_display_format, instruction_mode, grading_system, terms_per_year, enrollment_num_gen_mode, enrollment_num_gen_id, 
           stud_num_gen_mode, stud_num_gen_id, emp_num_gen_mode, emp_num_gen_id, admission_num_gen_mode, admission_num_gen_id, 
	        demand_num_gen_mode,  demand_num_gen_id, pmt_rcpt_num_gen_mode, pmt_rcpt_num_gen_id, sms_override,sms_sender_id,
           web_theme_id, app_theme_id, inst_house_flag, records_per_page, in_created_by,in_created_by,is_active,
            lib_book_num_gen_mode,lib_book_num_gen_id, online_payment_enabled,force_stop_notifications,inst_sms_master_stop,
            app_inactive_days_sms_override,inst_sms_credit_value,is_group_homework,is_stu_picture_upload,is_stu_profile_update,
           is_emp_picture_upload, is_emp_profile_update, stud_name_format, stud_name_case, emp_name_format, emp_name_case
             from institution_config where ay_id = in_current_ay and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;


          update institution_config set is_active=0 where inst_id = in_inst_id and ay_id=in_current_ay
                   and is_deleted = 0 and is_active=1;

          update appl_data_master set data_value=in_next_ay where data_type = 'GLOBAL_VARIABLES' 
            and data_key='MIGRATION_DONE_FOR_YEAR' and inst_id = in_inst_id
                   and is_deleted = 0 and is_active=1;

         
       end;
    end case; 
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_emp_RFID_code_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_emp_RFID_code_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_add_emp_RFID_code_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO user_device_map(ay_id,inst_id,device_reg_id,
    user_id,user_type, is_active, created_by, updated_by,RFID_code ) VALUES';

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'user_device_map' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;

  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';

    
    

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      
      

      if (l_template_col_name = 'dept_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('DEPARTMENT_MASTER');
               
              end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    
    

    close cur_json_template;

  end while;

  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  
  
  
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
      
                   call sp_execute_immediate (l_insert_sql_str); 

              
        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

           update department_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and dept_id = in_dept_id
            and is_deleted = 0;
                   
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_add_head_master_account`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_head_master_account`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_acct_head_id` SMALLINT(5), IN `in_parent_id` SMALLINT(5), IN `in_acct_head_name` VARCHAR(50), IN `in_acct_head_type` CHAR(2), IN `in_acct_head_category` CHAR(3), IN `in_acct_head_abbr` VARCHAR(50), IN `in_acct_head_desc` VARCHAR(50), IN `in_acct_head_level` VARCHAR(50), IN `in_is_system_def` TINYINT(1), IN `in_is_discountable` TINYINT(1), IN `in_is_waivable` TINYINT(1), IN `in_is_taxable` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_add_head_master_account';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_acc_head_id mediumint(8);
 declare l_looping_done int default false;
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
            set l_acc_head_id = fn_sequence_generator('ADD_ACCOUNT_HEAD_MASTER');
            set l_routine_block = 'insert';
       if(in_acct_head_level ='0') then
           insert into account_head_master (ay_id, inst_id,acct_head_id,parent_id,
                   acct_head_level,acct_head_category,acct_head_type,acct_head_name,
                   acct_head_display_name,acct_head_desc,acct_head_abbr,is_system_def,
                   is_discountable,is_waivable,is_taxable,is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,l_acc_head_id,l_acc_head_id,in_acct_head_level,
                 in_acct_head_category,in_acct_head_type,in_acct_head_name,
                 in_acct_head_name,in_acct_head_desc,in_acct_head_abbr,in_is_system_def,
                 in_is_discountable,in_is_waivable,in_is_taxable,in_is_active,
                  in_created_by, in_created_by);
          else
             insert into account_head_master (ay_id, inst_id,acct_head_id,parent_id,
                       acct_head_level,acct_head_category,acct_head_type,acct_head_name,
                       acct_head_display_name,acct_head_desc,acct_head_abbr,is_system_def,
                       is_discountable,is_waivable,is_taxable,is_active,created_by,updated_by) 
                                            
               values(in_ay_id, in_inst_id,l_acc_head_id,in_parent_id,in_acct_head_level,
                     in_acct_head_category,in_acct_head_type,in_acct_head_name,
                     in_acct_head_name,in_acct_head_desc,in_acct_head_abbr,in_is_system_def,
                     in_is_discountable,in_is_waivable,in_is_taxable,in_is_active,
                      in_created_by, in_created_by);
         end if;
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update  account_head_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where acct_head_id = in_acct_head_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

            insert into account_head_master (ay_id, inst_id,acct_head_id,parent_id,
                   acct_head_level,acct_head_category,acct_head_type,acct_head_name,
                   acct_head_display_name,acct_head_desc,acct_head_abbr,is_system_def,
                   is_discountable,is_waivable,is_taxable,is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,in_acct_head_id,in_parent_id,in_acct_head_level,
                 in_acct_head_category,in_acct_head_type,in_acct_head_name,
                 in_acct_head_name,in_acct_head_desc,in_acct_head_abbr,in_is_system_def,
                 in_is_discountable,in_is_waivable,in_is_taxable,in_is_active,
                  in_created_by, in_created_by);
        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_invoice_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_invoice_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_invoice_mst_id` MEDIUMINT(8), IN `in_invoice_dtl_id` MEDIUMINT(8), IN `in_amount` BIGINT(50), IN `in_tax` BIGINT(50), IN `in_total_amount` BIGINT(50), IN `in_due_date` DATE, IN `in_installment_remark` VARCHAR(50), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_invoice_dtl_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_add_invoice_details';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_invoice_mst_id mediumint(8);
  declare l_party_type varchar(20);
  declare l_invoice_dtl_id mediumint(8);

  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
            set l_invoice_dtl_id = fn_sequence_generator('FIN_INVOICE_DETAILS');
            set out_invoice_dtl_id=l_invoice_dtl_id;
            set l_routine_block = 'insert';
       
           insert into fin_invoice_details (ay_id, inst_id,invoice_mst_id,invoice_dtl_id,
                   installment_remark,amount,tax,total_amount,due_date
                   ,is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,in_invoice_mst_id,l_invoice_dtl_id,
                 in_installment_remark,in_amount,in_tax,in_total_amount,
                 in_due_date,in_is_active,in_created_by, in_created_by);
             
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update  fin_account_heads_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where acc_head_mst_id = in_acc_head_mst_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

            insert into   fin_account_heads_master (ay_id, inst_id,acc_head_mst_id,
                   account_head_name,account_head_type,parent,is_default_transcation,
                   is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,in_acc_head_mst_id,in_account_head_name,
                 in_account_head_type,in_parent,in_is_default_transcation,
                 in_is_active,in_created_by, in_created_by);
        end; 
         
     end case;
   
   commit;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_invoice_dtl_id = out_invoice_dtl_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_add_issued_book`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_issued_book`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_member_id` MEDIUMINT(8), IN `in_book_id` SMALLINT(8), IN `in_book_code` VARCHAR(20), IN `in_member_type` VARCHAR(10), IN `in_issue_date` DATE, IN `in_return_date` DATE, IN `in_returned_date` DATE, IN `in_book_status` VARCHAR(20), IN `in_fine_amount` BIGINT(20), IN `in_book_renew_count` SMALLINT(5), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_lib_acct_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_add_issued_book';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_request_id mediumint(8);
  declare l_inst_count bigint(50);
 declare l_book_copies int(20);

  declare exit handler for sqlexception
	  begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

       insert into db_error_log( inst_id, routine_name, routine_block, err_code, 
                   err_desc, err_type, err_severity, created_by) 
        values 
             ( in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
      case in_dml_mode 
        when 'I' then
          begin
            
           set l_routine_block = 'insert';
          if(in_book_status="ISSUED")then
              insert into library_book_issue(ay_id,inst_id,lib_acct_id,member_id,
                          book_code,member_type,issue_date,
                      return_date,book_status,is_active,created_by,updated_by) 
              values(in_ay_id,in_inst_id,in_lib_acct_id,in_member_id,in_book_code,
                        in_member_type,in_issue_date,
                      in_return_date,in_book_status,in_is_active,in_created_by,in_created_by);
          end IF;
              
          if(in_book_status="RENEWED")then
                         
 
            if(in_book_renew_count<=1)then
               set in_book_status ="ISSUED";
            else
               set in_book_status="RENEWED";
            end IF;
            	update library_book_issue set valid_to = NOW(), updated_by = in_created_by, updated_on = NOW(),
                is_active = 0,book_status=in_book_status
               where book_code=in_book_code  and is_deleted = 0 and ay_id = in_ay_id 
                 and inst_id = in_inst_id and lib_acct_id=in_lib_acct_id and is_active=1;

              insert into library_book_issue(ay_id,inst_id,lib_acct_id,member_id,book_code,member_type,issue_date,
                  return_date,book_status,book_renew_count,is_active,created_by,updated_by) 
              values(in_ay_id,in_inst_id,in_lib_acct_id,in_member_id,in_book_code,in_member_type,in_issue_date,
                  in_return_date,"RENEWED",in_book_renew_count,in_is_active,in_created_by,in_created_by);

           end IF;

--             	update library_book_issue set valid_to = NOW(), updated_by = in_created_by, updated_on = NOW(),
--                 book_renew_count=in_book_renew_count
--                where book_code=in_book_code  and is_deleted = 0 and ay_id = in_ay_id 
--                  and inst_id = in_inst_id ;
          end;      
          when 'U' then          
          begin
             set l_routine_block = 'update';   

            	update library_book_issue set valid_to = NOW(), updated_by = in_created_by, updated_on = NOW(),
                is_active =0  
               where book_code=in_book_code  and is_deleted = 0 and ay_id = in_ay_id 
                 and inst_id = in_inst_id and lib_acct_id=in_lib_acct_id;

             insert into library_book_issue(ay_id,inst_id,lib_acct_id,member_id,book_code,member_type,issue_date,
                  return_date,returned_date,book_status,book_renew_count,is_active,created_by,updated_by) 
              values(in_ay_id,in_inst_id,in_lib_acct_id,in_member_id,in_book_code,in_member_type,in_issue_date,
                  in_return_date,in_returned_date,in_book_status,in_book_renew_count,in_is_active,in_created_by,in_created_by);

         
      end;    	   
      end case;
    
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_new_bank_account`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_new_bank_account`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_bank_id` SMALLINT(8), IN `in_bank_name` VARCHAR(50), IN `in_bank_display_name` VARCHAR(100), IN `in_branch` VARCHAR(50), IN `in_account_no` VARCHAR(20), IN `in_ifsc_code` VARCHAR(20), IN `in_address` VARCHAR(100), IN `in_bank_contact_no` VARCHAR(15), IN `in_status` SMALLINT(5), IN `in_party_id` VARCHAR(10), IN `in_party_type` VARCHAR(20), IN `in_bank_holder` VARCHAR(50), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_add_new_bank_account';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
  declare l_bank_id mediumint(8);
 declare l_looping_done int default false;
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
            set l_bank_id = fn_sequence_generator('ADD_BANK_ACCOUNT');
            set l_routine_block = 'insert';
       
           insert into fin_bank_account_master (ay_id, inst_id,bank_id,bank_name,
                   bank_display_name,branch,account_no,ifsc_code,address,status,
                   party_id,party_type,bank_holder,is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,l_bank_id,in_bank_name,in_bank_display_name,
                 in_branch,in_account_no,in_ifsc_code,in_address,in_status,in_party_id,
                 in_party_type,in_bank_holder,in_is_active,in_created_by, in_created_by);
             
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update fin_bank_account_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where bank_id = in_bank_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

            insert into fin_bank_account_master (ay_id, inst_id,bank_id,bank_name,branch,
                       bank_display_name,account_no,ifsc_code,address,status,party_id,
                       party_type,is_active,created_by,updated_by)     
           values(in_ay_id, in_inst_id,in_bank_id,in_bank_name,in_branch,
               in_bank_display_name,in_account_no,in_ifsc_code,in_address,in_status,in_party_id,
                  in_party_type,in_is_active,in_created_by, in_created_by);
        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_new_billing_account`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_new_billing_account`(
 IN in_dml_mode CHAR(1),
 IN in_ay_id CHAR(7),
 IN in_inst_id SMALLINT(8),
 IN in_fin_acct_id 	mediumint(8),
 IN in_sequence_entity_id varchar(30), 
 IN in_sequence_entity_mode varchar(10), 
 IN in_acct_name varchar(50), 
 IN in_acct_display_name varchar(50), 
 IN in_acct_short_name varchar(50),
 IN in_address varchar(250),
 IN in_pan_card_no varchar(20),
 IN in_gst_reg_no VARCHAR(20),
 IN in_razorpay_acct_no VARCHAR(20),
 IN in_logo_path VARCHAR(200),
 IN in_is_default tinyint(1),
 IN in_seq_gen_mst_id mediumint(8),
 IN in_is_active tinyint(1),
 IN in_created_by VARCHAR(20),
 IN in_payment_seq_gen_mst_id mediumint(8),
 IN in_payment_sequence_entity_id varchar(30),
 OUT out_err_code CHAR(5),
 OUT out_err_desc TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_add_new_billing_account';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_looping_done int default false;

 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
          
          set l_routine_block = 'insert';
--         Insert  payment sequence entity_id
           insert into sequence_generator_master (ay_id,inst_id,seq_gen_mst_id,entity_id,
                   reset_freq,param_count,seperator_char,op_code,seq_pattern,
                   seq_seed_num,seq_current_num,is_active,created_by,updated_by) 
                                        
          values(in_ay_id,in_inst_id,in_payment_seq_gen_mst_id,in_payment_sequence_entity_id,
                  'MLY','0','/','PMT','',
                  '0','0',in_is_active,in_created_by,in_created_by);
           
--         Insert  expense sequence entity_id
          insert into sequence_generator_master (ay_id,inst_id,seq_gen_mst_id,entity_id,
                   reset_freq,param_count,seperator_char,op_code,seq_pattern,
                   seq_seed_num,seq_current_num,is_active,created_by,updated_by) 
                                        
          values(in_ay_id,in_inst_id,in_seq_gen_mst_id,in_sequence_entity_id,
                  'YLY','0','/','EXP','',
                  '0','0',in_is_active,in_created_by,in_created_by); 

           insert into fin_accounts (ay_id,inst_id,fin_acct_id,
                   sequence_entity_id,payment_sequence_entity_id,sequence_entity_mode,
                   acct_name,acct_display_name,acct_short_name,address,
                   pan_card_no,gst_reg_no,logo_path,is_default,
                   is_active,created_by,updated_by,razorpay_acct_no) 
                                         
           values(in_ay_id,in_inst_id,in_fin_acct_id,in_sequence_entity_id,
                  in_payment_sequence_entity_id,in_sequence_entity_mode ,in_acct_name,
                  in_acct_display_name,in_acct_short_name,in_address,in_pan_card_no,in_gst_reg_no,
                  in_logo_path,in_is_default,in_is_active,in_created_by,in_created_by,in_razorpay_acct_no);
                   
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update fin_accounts set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
             where fin_acct_id = in_fin_acct_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

           insert into fin_accounts (ay_id,inst_id,fin_acct_id,
                   sequence_entity_id,payment_sequence_entity_id,sequence_entity_mode,acct_name,acct_display_name,
                   acct_short_name,address,pan_card_no,gst_reg_no,logo_path,is_default,
                   is_active,created_by,updated_by,razorpay_acct_no) 
                                         
           values(in_ay_id,in_inst_id,in_fin_acct_id,in_sequence_entity_id,in_payment_sequence_entity_id,
                  in_sequence_entity_mode,in_acct_name,in_acct_display_name,
                  in_acct_short_name,in_address,in_pan_card_no,in_gst_reg_no,
                  in_logo_path,in_is_default,in_is_active,in_created_by,in_created_by,in_razorpay_acct_no);

        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_new_library_account`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_new_library_account`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_lib_acct_id` MEDIUMINT(8), IN `in_acct_name` VARCHAR(50), IN `in_acct_display_name` VARCHAR(50), IN `in_acct_abbr` VARCHAR(30), IN `in_logo_path` VARCHAR(200), IN `in_is_default` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_add_new_library_account';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_looping_done int default false;
 declare l_lib_acct_id mediumint(8);
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
          
          set l_routine_block = 'insert';
          set l_lib_acct_id = fn_sequence_generator('ADD_LIB_ACCOUNT');
           insert into library_accounts (ay_id,inst_id,lib_acct_id,
                   acct_name,acct_display_name,acct_abbr,logo_path,is_default,
                   is_active,created_by,updated_by) 
                                         
           values(in_ay_id,in_inst_id,l_lib_acct_id,in_acct_name,in_acct_display_name,
                  in_acct_abbr,in_logo_path,in_is_default,
                  in_is_active,in_created_by,in_created_by);
                   
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update library_accounts set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
             where lib_acct_id = in_lib_acct_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

           insert into library_accounts (ay_id,inst_id,lib_acct_id,
                   acct_name,acct_display_name,acct_abbr,logo_path,is_default,
                   is_active,created_by,updated_by) 
                                         
           values(in_ay_id,in_inst_id,in_lib_acct_id,in_acct_name,in_acct_display_name,
                  in_acct_abbr,in_logo_path,in_is_default,
                  in_is_active,in_created_by,in_created_by);

        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_new_library_book`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_new_library_book`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_book_id` SMALLINT(8), IN `in_book_code` VARCHAR(20), IN `in_book_title` VARCHAR(100), IN `in_book_author` VARCHAR(20), IN `in_isbn_no` VARCHAR(20), IN `in_book_type` VARCHAR(20), IN `in_book_edition` VARCHAR(50), IN `in_publication` VARCHAR(50), IN `in_no_of_copies` INT(20), IN `in_per_book_price` INT(20), IN `in_rack_type` VARCHAR(20), IN `in_rack_no` INT(10), IN `in_book_arrival_date` DATE, IN `in_lib_book_num_gen_mode` VARCHAR(10), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_lib_acct_id` MEDIUMINT(8), IN `in_book_entry_date` DATE, IN `in_language` VARCHAR(50), IN `in_book_category` VARCHAR(100), IN `in_accession_no` VARCHAR(20), IN `in_place_of_publication` VARCHAR(20), IN `in_year_of_publication` SMALLINT(5), IN `in_pages` BIGINT(20), IN `in_binding` VARCHAR(20), IN `in_source` VARCHAR(50), IN `in_bill_no` MEDIUMINT(8), IN `in_bill_date` DATE, IN `in_book_condition` VARCHAR(50), IN `in_remark` VARCHAR(50), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_book_id` MEDIUMINT(8))
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_add_new_library_book';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_looping_done int default false;
 declare l_book_id mediumint(8);
 declare l_book_code_num varchar(20);
 declare l_bookcode varchar(20); 
 declare l_book_arrival_date date;
      
  declare cur_book_master cursor for 
  select book_code,book_arrival_date
    from library_book_details 
    where book_id=in_book_id and inst_id=in_inst_id and is_deleted=0;

 declare continue handler for not found set l_looping_done = true;
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
           If(in_book_id='')then
              set l_book_id = fn_sequence_generator('ADD_BOOK');
              set l_routine_block = 'insert';
       
              insert into library_book_master (ay_id,inst_id,book_id,ISBN_no,book_title,book_author,
                           book_type,no_of_copies,is_active,created_by, updated_by,
                           lib_acct_id,book_entry_date,book_category,language,bill_no,bill_date)                              
              values(in_ay_id,in_inst_id,l_book_id,in_isbn_no,in_book_title,in_book_author,in_book_type,
                     in_no_of_copies,in_is_active,in_created_by, in_created_by,
                     in_lib_acct_id,in_book_entry_date,in_book_category,in_language,in_bill_no,in_bill_date);
  
              set l_count=1;

              while(in_no_of_copies>=l_count)do
          
                 set l_book_code_num =in_book_code;
                  IF ( in_lib_book_num_gen_mode='Y' AND length(trim(in_book_code)) = 0 ) THEN 
        					    call sp_custom_seq_generator(in_inst_id,'LIB_BOOK_NUM',in_ay_id,in_created_by,l_book_code_num) ;
                     IF length(trim(l_book_code_num)) = 0 THEN
        					     SIGNAL SQLSTATE '10012' 
        					   SET MESSAGE_TEXT = 'An error occurred while generating Book Code';
                     END IF;
        	        END IF;

                 insert into  library_book_details (ay_id, inst_id,book_id,book_code,publication,book_edition,per_book_price,
                          rack_type,rack_no,book_arrival_date,is_active,created_by,updated_by,
                  accession_no,place_of_publication,year_of_publication,pages,binding,source,
                   book_condition,remark) 
                                              
                 values(in_ay_id, in_inst_id,l_book_id,l_book_code_num,in_publication,in_book_edition, in_per_book_price,
                        in_rack_type,in_rack_no,in_book_arrival_date,in_is_active,in_created_by, in_created_by,
                  in_accession_no,in_place_of_publication,in_year_of_publication,in_pages,in_binding,
                   in_source,in_book_condition,in_remark);
                   
                set l_count=l_count+1;
              end while; 

        ELSE

            insert into  library_book_master (ay_id,inst_id,book_id,ISBN_no,book_title,book_author,
                         book_type,no_of_copies,is_active,created_by, updated_by,lib_acct_id,
                          book_entry_date,book_category,language,bill_no,bill_date)                              
            values(in_ay_id,in_inst_id,in_book_id,in_isbn_no,in_book_title,in_book_author,in_book_type,
                   in_no_of_copies,in_is_active,in_created_by, in_created_by,in_lib_acct_id,in_book_entry_date,
                   in_book_category,in_language,in_bill_no,in_bill_date);
  
          
            set l_count=1;
          while(in_no_of_copies>=l_count)do
          
            set l_book_code_num =in_book_code;
            IF ( in_lib_book_num_gen_mode='Y' AND length(trim(in_book_code)) = 0 ) THEN 
  					    call sp_custom_seq_generator(in_inst_id,'LIB_BOOK_NUM',in_ay_id,in_created_by,l_book_code_num) ;
               IF length(trim(l_book_code_num)) = 0 THEN
  					     SIGNAL SQLSTATE '10012' 
  					   SET MESSAGE_TEXT = 'An error occurred while generating Book Code';
               END IF;
  	        END IF;
             insert into  library_book_details (ay_id, inst_id,book_id,book_code,publication,book_edition,per_book_price,
                      rack_type,rack_no,book_arrival_date,is_active,created_by,updated_by,
              accession_no,place_of_publication,year_of_publication,pages,binding,source,
              book_condition,remark) 
                                          
             values(in_ay_id, in_inst_id,in_book_id,l_book_code_num,in_publication,in_book_edition, in_per_book_price,
                    in_rack_type,in_rack_no,in_book_arrival_date,in_is_active,in_created_by, in_created_by,
              in_accession_no,in_place_of_publication,in_year_of_publication,in_pages,in_binding,
              in_source,in_book_condition,in_remark);
               
            set l_count=l_count+1;

         end while; 
      END IF;
     
--           remove extra space between two words
     update library_book_master set book_title = replace(in_book_title, '  ', ' ')
     where inst_id = in_inst_id and book_id=l_book_id and is_active=1 and is_deleted=0;

      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
          update library_book_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where book_id = in_book_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

             insert into  library_book_master (ay_id,inst_id,book_id,ISBN_no,book_title,book_author,
                         book_type,no_of_copies,is_active,created_by, updated_by,lib_acct_id,
                          book_entry_date,book_category,language,bill_no,bill_date)                              
            values(in_ay_id,in_inst_id,in_book_id,in_isbn_no,in_book_title,in_book_author,in_book_type,
                   in_no_of_copies,in_is_active,in_created_by, in_created_by,in_lib_acct_id,in_book_entry_date,
                   in_book_category,in_language,in_bill_no,in_bill_date);
  

       open cur_book_master;
        cursor_loop_new:loop
        fetch cur_book_master into l_bookcode,l_book_arrival_date;
         if l_looping_done then
             leave cursor_loop_new;
         end if;

       update library_book_details set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1 
           where book_id = in_book_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id and book_code=l_bookcode;
       insert into  library_book_details (ay_id,inst_id,book_id,book_code,publication,book_edition,per_book_price,
                    rack_type,rack_no,book_arrival_date,is_active,created_by,updated_by,
          accession_no,place_of_publication,year_of_publication,pages,binding,source,
                   book_condition,remark) 
                                        
        values(in_ay_id, in_inst_id,in_book_id,l_bookcode,in_publication,in_book_edition, in_per_book_price,
                  in_rack_type,in_rack_no,l_book_arrival_date,in_is_active,in_created_by, in_created_by,
          in_accession_no,in_place_of_publication,in_year_of_publication,in_pages,in_binding,
              in_source,in_book_condition,in_remark);
             
--            update library_book_details set valid_to = NOW(), updated_by = in_created_by,
--              updated_on = NOW(),publication=in_publication,book_edition=in_book_edition,
--              per_book_price=in_per_book_price,rack_type=in_rack_type,rack_no=in_rack_no,
--              book_arrival_date=in_book_arrival_date
--            where book_id = in_book_id  and is_deleted = 0 and ay_id = in_ay_id
--                  and inst_id = in_inst_id;
     end loop;  
        end; 

--           remove extra space between two words
         update library_book_master set book_title = replace(in_book_title, '  ', ' ')
         where inst_id = in_inst_id and book_id=in_book_id and is_active=1 and is_deleted=0;
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_book_id=l_book_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_new_party_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_new_party_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_party_id` VARCHAR(10), IN `in_party_name` VARCHAR(50), IN `in_party_type` VARCHAR(50), IN `in_address` VARCHAR(100), IN `in_party_contact_no` VARCHAR(15), IN `in_pan_card_no` VARCHAR(20), IN `in_gst_reg_no` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_add_new_party_details';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
  declare l_party_id varchar(10);
 declare l_looping_done int default false;
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
          
            set l_party_id = fn_sequence_generator('ADD_PARTY_MASTER');
            set l_routine_block = 'insert';
       
           insert into  fin_party_master (ay_id, inst_id,party_id,party_name,
                   party_type,address,party_contact_no,pan_card_no,gst_reg_no,
                   is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,l_party_id,in_party_name,in_party_type,
                 in_address,in_party_contact_no,in_pan_card_no,in_gst_reg_no,
                 in_is_active,in_created_by, in_created_by);
             
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update fin_party_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where party_id = in_party_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

          insert into fin_party_master (ay_id, inst_id,party_id,party_name,
                   party_type,address,party_contact_no,pan_card_no,gst_reg_no,
                   is_active,created_by,updated_by)                        
           values(in_ay_id, in_inst_id,in_party_id,in_party_name,in_party_type,
                 in_address,in_party_contact_no,in_pan_card_no,in_gst_reg_no,
                 in_is_active,in_created_by, in_created_by);
        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_new_user_in_group`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_new_user_in_group`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_custom_group_mst_id` MEDIUMINT(8), IN `in_custom_group_dtl_id` MEDIUMINT(8), IN `in_group_name` VARCHAR(100), IN `in_group_desc` VARCHAR(100), IN `in_group_abbr` VARCHAR(50), IN `in_group_expiry_date` DATE, IN `in_group_category` VARCHAR(50), IN `in_status` VARCHAR(20), IN `in_insert_row_count` MEDIUMINT(3), IN `in_json_str` TEXT, IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_add_new_user_in_group';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_package_id int;
  declare l_custom_group_mst_id int;

  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO custom_group_details(inst_id, custom_group_mst_id,
    custom_group_dtl_id, user_id,group_title,user_type, is_active, created_by, updated_by,is_admin,group_type,group_ids) VALUES'; 

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'custom_group_details' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;


   case in_dml_mode 
    when 'I' then
      begin
--         set l_order_id = fn_sequence_generator('SUBJECT_PACKAGE_MASTER');
         set l_custom_group_mst_id = fn_sequence_generator('GROUP_MASTER');
      end;

    when 'U' then
      begin
        set l_custom_group_mst_id = in_custom_group_mst_id;
      
      end;
  end case;

  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      if (l_template_col_name = 'custom_group_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('GROUP_DETAILS');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('GROUP_DETAILS');
              
              end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'custom_group_mst_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_custom_group_mst_id;
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    close cur_json_template;

  end while;

  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';

              INSERT INTO custom_group_master(ay_id, inst_id, custom_group_mst_id, group_name, 
              group_desc, group_abbr,group_expiry_date,group_category,status,created_by, updated_by, is_active) 
              VALUES (in_ay_id, in_inst_id, l_custom_group_mst_id, in_group_name, 
              in_group_desc,in_group_abbr,in_group_expiry_date,in_group_category,in_status,
              in_created_by, in_created_by, in_is_active);
                    
              call sp_execute_immediate (l_insert_sql_str); 

        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

       update custom_group_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1
          where ay_id = in_ay_id and inst_id = in_inst_id and custom_group_mst_id = in_custom_group_mst_id
            and is_deleted = 0;
      
      INSERT INTO custom_group_master(ay_id, inst_id, custom_group_mst_id, group_name, 
              group_desc, group_abbr,group_expiry_date,group_category,status,created_by, updated_by, is_active) 
              VALUES (in_ay_id, in_inst_id, in_custom_group_mst_id, in_group_name, 
              in_group_desc,in_group_abbr,in_group_expiry_date,in_group_category,in_status,
              in_created_by, in_created_by, in_is_active);

      update custom_group_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1
          where  inst_id = in_inst_id and custom_group_mst_id = in_custom_group_mst_id
            and is_deleted = 0;

       call sp_execute_immediate (l_insert_sql_str); 
      
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
 

END$$

DROP PROCEDURE IF EXISTS `sp_ins_add_order_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_order_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_order_master_id` MEDIUMINT(8), IN `in_order_detail_id` MEDIUMINT(8), IN `in_order_name` VARCHAR(100), IN `in_order_desc` VARCHAR(20), IN `in_order_status` VARCHAR(20), IN `in_order_date` DATE, IN `in_is_active` TINYINT(1), IN `in_insert_row_count` MEDIUMINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_inventory_dept_id` MEDIUMINT(8), IN `in_fulfil_status` VARCHAR(20), IN `in_total_amount` BIGINT(50), IN `in_stock_row_count` MEDIUMINT(3), IN `in_stockBalance_json` TEXT, IN `in_party_id` MEDIUMINT(8), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_order_master_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_add_order_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_stock_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_stock_row_count tinyint(3);
  declare l_package_id int;
  declare l_order_master_id int;

  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO inventory_order_details(ay_id, inst_id, order_master_id,
    order_detail_id, item_id,order_quantity,unit, is_active, created_by, updated_by,
    received_quantity,recived_item_rate,received_amount) VALUES'; 

  declare l_insert_sql_str_stock text default 'INSERT INTO inventory_stock_balance(ay_id,inst_id, 
    inventory_dept_id,order_master_id,item_id, quantity,is_active,
    created_by,updated_by) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'inventory_order_details' 
  order by col_pos;

  declare cur_json_stock cursor for 
  select col_name from json_template_master 
  where tbl_name = 'inventory_stock_balance' 
  order by col_pos;
  
  declare continue handler for not found set l_looping_done = true;
 
  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;


   case in_dml_mode 
    when 'I' then
      begin

         set l_order_master_id = fn_sequence_generator('INVENTORY_ORDER_MASTER');
      end;

    when 'U' then
      begin
        set l_order_master_id = in_order_master_id;
      
      end;
  end case;

  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      if (l_template_col_name = 'order_detail_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('INVENTORY_ORDER_DETAILS');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('INVENTORY_ORDER_DETAILS');
              
              end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'order_master_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_order_master_id;
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    close cur_json_template;

  end while;

  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));



-- Inventory stock balance_Json


  set l_json_str = '';
  set l_json_substr = '';
  set l_json_str_len = 0;
  set l_looping_done = false;
  set l_separator_idx = 1;
  set l_template_col_name = '';
  set l_template_col_value = '';
  set l_insert_val_str_part = '';
  set l_insert_val_str_full = '';

   set l_stock_row_count = in_stock_row_count;
  set l_json_str = trim(in_stockBalance_json);
  set l_json_str_len = length(l_json_str);

  while (l_stock_row_count > 0) do
    set l_routine_block = 'inside while loop';

    set l_insert_val_str_part = '';

    open cur_json_stock;

    cursor_loop: loop
      fetch cur_json_stock into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      
        
      if (l_template_col_name = 'order_master_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_order_master_id;
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_stock_row_count = l_stock_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    close cur_json_stock;


  end while;

  set l_insert_sql_str_stock = concat(l_insert_sql_str_stock, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
-- End of Inventory Stock balance_json


  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';

          INSERT INTO inventory_order_master(ay_id,inst_id,order_master_id,inventory_dept_id,
          order_name,order_desc, order_date,order_status,created_by, updated_by, is_active,party_id) 
          VALUES (in_ay_id, in_inst_id, l_order_master_id,in_inventory_dept_id,in_order_name, 
          in_order_desc,in_order_date,in_order_status,
          in_created_by, in_created_by, in_is_active,in_party_id);
                
          call sp_execute_immediate (l_insert_sql_str); 
          call sp_execute_immediate (l_insert_sql_str_stock); 

        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

          update inventory_order_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and order_master_id = in_order_master_id
            and is_deleted = 0 and inventory_dept_id=in_inventory_dept_id;

          INSERT INTO inventory_order_master(ay_id, inst_id, order_master_id,inventory_dept_id,order_name, 
           order_desc,total_amount,order_date,order_status,fulfil_status,created_by, updated_by, is_active,
            party_id) 
          VALUES (in_ay_id, in_inst_id, in_order_master_id,in_inventory_dept_id,in_order_name, 
           in_order_desc,in_total_amount,in_order_date,in_order_status,in_fulfil_status,
           in_created_by, in_created_by, in_is_active,in_party_id);
                    
           set l_routine_block = 'before execute immediate';
      
           update inventory_order_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
           
           where ay_id = in_ay_id and inst_id = in_inst_id and order_master_id = in_order_master_id
            and is_deleted = 0;

          call sp_execute_immediate (l_insert_sql_str); 
           
        
          delete from inventory_stock_balance 
            where ay_id = in_ay_id and inst_id = in_inst_id and order_master_id = in_order_master_id
            and is_deleted = 0; 
            call sp_execute_immediate (l_insert_sql_str_stock);    
                
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_order_master_id = l_order_master_id;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_add_sms_credit`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_sms_credit`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sms_credit_id` MEDIUMINT(8), IN `in_sms_credit_no` BIGINT(50), IN `in_rate` BIGINT(30), IN `in_amount` BIGINT(50), IN `in_payment_type` VARCHAR(30), IN `in_bank_account_no` BIGINT(30), IN `in_bank_name` VARCHAR(50), IN `in_remark` VARCHAR(500), IN `in_credit_date` DATE, IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_gst_rate` DECIMAL(3,2), IN `in_gst_amount` BIGINT(30), IN `in_total_amount` BIGINT(50), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_add_sms_credit';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_request_id mediumint(8);
  declare l_sms_credit_id mediumint(8);
  declare l_sms_credit_no bigint(50);
  declare l_sms_credit_balance bigint(50); 	
  declare l_sms_credit_balance1 bigint(50); 	
  declare l_sms_balance bigint(50);
  declare l_sms_credit bigint(50);	
  declare l_new_sms_balance bigint(50); 
  declare l_Available_SMSBalance text;
  declare l_sms_credit_count bigint(50);
declare l_inst_count bigint(50);

declare l_sms bigint(50);

  declare exit handler for sqlexception
	  begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

       insert into db_error_log( inst_id, routine_name, routine_block, err_code, 
                   err_desc, err_type, err_severity, created_by) 
        values 
             ( in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
      case in_dml_mode 
        when 'I' then
          begin
              set in_sms_credit_id = fn_sequence_generator('ADD_SMS_CREDIT');
           set l_routine_block = 'insert';

              insert into sms_credit_history(sms_credit_id,ay_id,inst_id,sms_credit_no,rate,amount,payment_type,bank_account_no,
                      bank_name,remark,credit_date,is_active,created_by,updated_by,
                      gst_rate,gst_amount,total_amount) 
              values(in_sms_credit_id,in_ay_id,in_inst_id,in_sms_credit_no,in_rate,in_amount,in_payment_type,in_bank_account_no,
                      in_bank_name,in_remark,in_credit_date,in_is_active,in_created_by,in_created_by,
                      in_gst_rate,in_gst_amount,in_total_amount);
        
        
              SELECT count(inst_id) INTO l_inst_count from sms_credit_status 
              where inst_id=in_inst_id and is_deleted=0 and is_active=1;

        IF(l_inst_count=0) THEN
            select (sms_credit_balance) INTO l_sms_balance from sms_credit_status 
            where inst_id=0 and is_active=1 and is_deleted=0 ;
            set l_new_sms_balance=l_sms_balance-in_sms_credit_no;

            update  sms_credit_status set valid_to = NOW(), updated_by = in_created_by, 
                    updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_new_sms_balance
            where is_deleted = 0 and inst_id = 0;
   
--              if institute does not assign intially sms credit balance    
              IF(in_payment_type='CAMPAIGN_ACCOUNT_TRANSFER')THEN
 
                  set l_sms_credit_balance1=0-in_sms_credit_no;
                  insert into sms_credit_status(ay_id,inst_id,sms_credit_balance,rate,is_active,created_by,updated_by)
                 values(in_ay_id,in_inst_id,l_sms_credit_balance1,in_rate,in_is_active,in_created_by,in_created_by);
                
             else
                insert into sms_credit_status(inst_id,sms_credit_balance,rate,is_active,created_by,updated_by)
                values(in_inst_id,in_sms_credit_no,in_rate,in_is_active,in_created_by,in_created_by);
              END IF;
          
        ELSE IF(in_inst_id=0) THEN
--         vidyalekha itself add balance

              select (sms_credit_balance) INTO l_sms_balance from sms_credit_status 
              where inst_id=0 and is_active=1 and is_deleted=0 ;
              set l_new_sms_balance=l_sms_balance+in_sms_credit_no;

--                 IF(in_sms_credit_no > l_sms_balance) THEN
--                     set l_Available_SMSBalance = 'SMS Balance is Low. Please Check!! ';
--                     SIGNAL SQLSTATE '10001' 
--                     SET MESSAGE_TEXT =l_Available_SMSBalance;
--                 END IF; 

                    update  sms_credit_status set valid_to = NOW(), updated_by = in_created_by, 
                    updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_new_sms_balance
                    where is_deleted = 0 and inst_id = 0;

            ELSE
              select (sms_credit_balance) INTO l_sms_balance from sms_credit_status 
              where inst_id=0 and is_active=1 and is_deleted=0 ;
              set l_new_sms_balance=l_sms_balance-in_sms_credit_no;
-- 
--                  IF(in_sms_credit_no > l_sms_balance) THEN
--                     set l_Available_SMSBalance = 'SMS Balance is Low. Please Check!! ';
--                     SIGNAL SQLSTATE '10001' 
--                     SET MESSAGE_TEXT =l_Available_SMSBalance;
--                 END IF; 

              update  sms_credit_status set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_new_sms_balance
              where is_deleted = 0 and inst_id = 0;

              IF(in_payment_type='CAMPAIGN_ACCOUNT_TRANSFER')THEN

                  select (sms_credit_balance) INTO l_sms_credit_no from sms_credit_status 
                  where inst_id=in_inst_id and is_active=1 and is_deleted=0 ;

--                   if sms balance is in minus
                 if(l_sms_credit_no<0)then
                     set l_sms_credit_balance=(l_sms_credit_no)-(-in_sms_credit_no);
                 else
                     set l_sms_credit_balance=l_sms_credit_no-in_sms_credit_no;
                 END IF;
                 
                 update  sms_credit_status set valid_to = NOW(), updated_by = in_created_by, 
                  updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_sms_credit_balance,rate=in_rate
                  where is_deleted = 0 and inst_id = in_inst_id;
    
              ELSE
    
                    select (sms_credit_balance) INTO l_sms_credit_no from sms_credit_status 
                  where inst_id=in_inst_id and is_active=1 and is_deleted=0 ;
                  
    
                  set l_sms_credit_balance=l_sms_credit_no+in_sms_credit_no;
    
                  update  sms_credit_status set valid_to = NOW(), updated_by = in_created_by, 
                  updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_sms_credit_balance,rate=in_rate
                  where is_deleted = 0 and inst_id = in_inst_id;

             END IF;

          END IF;
        END IF;

          end;      	   
      end case;
    
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_add_stud_RFID_code_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_add_stud_RFID_code_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_class_id` CHAR(8), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_add_stud_RFID_code_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_student_count bigint(20);
  declare l_user_count bigint(20);

  declare l_insert_sql_str text default 'INSERT INTO user_device_map(ay_id,inst_id,device_reg_id,
    user_id, user_type, is_active, created_by, updated_by,RFID_code ) VALUES';

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'user_device_map' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;

  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';


    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);


      if (l_template_col_name = 'user_map_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('ADD_STUDENT_RFID');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('DEPARTMENT_MASTER');
               
              end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
 

    close cur_json_template;

  end while;

  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  
  
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
      
                  call sp_execute_immediate (l_insert_sql_str); 

                  SELECT count(sm.student_id)  INTO l_student_count 
                                   from student_master as sm  join
                                  (SELECT * FROM user_device_map 
                                   where inst_id=in_inst_id AND ay_id=in_ay_id AND is_active=1 AND is_deleted=0)as udm
                                   on sm.student_id=udm.user_id  
                                   where  sm.ay_id=in_ay_id
                                   AND sm.inst_id=in_inst_id
                                   AND sm.class_id=in_class_id
                                   AND sm.is_active=1 
                                   AND sm.is_deleted=0;

                  SELECT count(student_id) INTO l_user_count from student_master 
                  where inst_id=in_inst_id and ay_id=in_ay_id 
                        and class_id=in_class_id and is_active=1 and is_deleted=0;

                  IF(l_student_count=l_user_count) THEN
                      
                      update  class_master set valid_to = NOW(), updated_by = in_created_by, 
                        updated_on = NOW(), is_deleted = 0 , RFID_updated=1, is_active=1, class_id=in_class_id
                     where  is_deleted = 0 and ay_id=in_ay_id and inst_id = in_inst_id and class_id=in_class_id
                           and is_active=1;
               
                  END IF;
        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

           update department_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and dept_id = in_dept_id
            and is_deleted = 0;
                   
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_admin_in_temp_emp_Master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_admin_in_temp_emp_Master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_user_id` MEDIUMINT(8), IN `in_login_name` VARCHAR(50), IN `in_password` VARCHAR(60), IN `in_mobile_phone_1` VARCHAR(20), IN `in_email_main` VARCHAR(50), IN `in_emp_status` VARCHAR(20), IN `in_bulk_upload_status` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin                                                          
                      
	 declare l_routine_name varchar(50) default 'sp_ins_admin_in_temp_emp_Master';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
    declare l_emp_id mediumint(8);
    declare l_emp_num varchar(50);
	 declare t_emp_num varchar(50);
declare l_user_id mediumint(8);
  declare exit handler for sqlexception
	  begin
      rollback;
      
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

      insert into db_error_log( inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        ( in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_dml_mode 
        
        when 'I' then
          begin
       
 set l_routine_block = 'insert_user_master';
     
         INSERT INTO temp_user_employee_master(ay_id, inst_id, emp_id, login_name, password, mobile_phone_main, 
          email_main, emp_status, bulk_upload_status, notification_status, created_by, updated_by,
          is_active, is_deleted) 
          VALUES ('', in_inst_id, in_user_id, in_login_name, in_password, in_mobile_phone_1, 
          in_email_main, in_emp_status, 100, 0, in_created_by, in_created_by,
          '1', 0);
             
          end;
          
           when 'U' then
          begin
          set l_routine_block = 'insert_user_master';
                
  	    	update temp_user_employee_master set login_name=in_login_name , password=in_password,
            mobile_phone_main=in_mobile_phone_1
            where  emp_id=in_user_id  and is_deleted = '0' and inst_id = in_inst_id;
        end; 
      end case;
    
    commit;
    
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_admission_fee_config`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_admission_fee_config`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_standard_id` CHAR(2), IN `in_stage_id` MEDIUMINT(8), IN `in_admission_fee_type` VARCHAR(10), IN `in_old_fees_id` MEDIUMINT(8), IN `in_fees_id` MEDIUMINT(8), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
 declare l_routine_name varchar(50) default 'sp_ins_admission_fee_config';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare l_subject_book_map_id mediumint(8);      
 declare exit handler for sqlexception
     begin
     rollback;
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
   start transaction;
     case in_dml_mode
        when 'U' then
     set l_routine_block = 'update';      
         begin
             update  admission_fees_config set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where fees_id = in_old_fees_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id and standard_id = in_standard_id;
            insert into  admission_fees_config(ay_id, inst_id,standard_id,stage_id,
             admission_fee_type, fees_id,is_active,created_by, updated_by)
           values(in_ay_id, in_inst_id, in_standard_id, in_stage_id,in_admission_fee_type, in_fees_id,
             in_is_active,in_created_by, in_created_by);
    end;    
     end case;
   commit;
    set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_admission_fee_config_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_admission_fee_config_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_admission_fee_config_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';   
  declare l_err_desc text default '';                 
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'INSERT INTO admission_fees_config(ay_id,inst_id,
    standard_id,stage_id,admission_fee_type,fees_id,is_active, created_by, updated_by ) VALUES';
    declare l_insert_val_str_part text;
    declare l_insert_val_str_full text;
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'admission_fees_config' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
      begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
    close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
         update admission_fees_config set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id AND category=in_category AND data_type=in_data_type
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_data_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_data_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_ay_id` VARCHAR(7), IN `in_data_type` VARCHAR(25), IN `in_data_key` VARCHAR(25), IN `in_data_value` VARCHAR(50), IN `in_data_desc` VARCHAR(100), IN `in_data_abbr` VARCHAR(15), IN `in_data_pos` TINYINT(3), IN `in_is_editable` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_appl_data_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            set l_routine_block = 'insert';
            insert into appl_data_master (inst_id,ay_id, data_type ,data_key,data_value,
               data_desc,data_abbr,data_pos,is_editable,created_by, updated_by) 	 						
            values(in_inst_id,in_ay_id,in_data_type ,in_data_key,in_data_value,in_data_desc,
              in_data_abbr,in_data_pos,in_is_editable,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
            set l_routine_block = 'update';
            update appl_data_master set valid_to = NOW(), updated_by = in_created_by,updated_on = NOW(), is_deleted = 1 
            where data_type = in_data_type 
            and data_key=in_data_key
            and is_deleted = 0
            and ay_id = in_ay_id 
            and inst_id = in_inst_id;
          insert into appl_data_master (inst_id,ay_id, data_type ,data_key,data_value,
               data_desc,data_abbr,data_pos,is_editable,created_by, updated_by) 	 						
            values(in_inst_id,in_ay_id,in_data_type ,in_data_key,in_data_value,in_data_desc,
              in_data_abbr,in_data_pos,in_is_editable,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_data_master_all_inst`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_data_master_all_inst`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_data_type` VARCHAR(100), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
declare l_routine_name varchar(50) default 'sp_ins_appl_data_master_all_inst';
declare l_err_code char(5) default '00000';
declare l_err_desc text default '';        
declare l_routine_block varchar(15);
declare l_looping_done int default false;
declare l_inst_id smallint(5) default 0; 
declare l_delete_flag tinyint(1) default 0;      

declare cur_appl_data_mst cursor for 
  select inst_id,is_deleted
  from appl_data_master where inst_id!='-1' and inst_id!='0' and is_active=1 and is_deleted=0 group by inst_id;


 declare continue handler for not found set l_looping_done = true;
declare exit handler for sqlexception
    begin
    rollback;
    
    get diagnostics condition 1
      l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

    insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
      err_desc, err_type, err_severity, created_by) 
    values 
      ("", in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
      'ERROR', 0, in_created_by);

    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

       end;
open cur_appl_data_mst;

  cursor_loop_new:loop
     fetch cur_appl_data_mst into l_inst_id, l_delete_flag;
         if l_looping_done then
             leave cursor_loop_new;
         end if;
      
  start transaction;
  
    case in_dml_mode 
      when 'I' then
        begin
          set l_routine_block = 'insert';
            if(in_inst_id=0)then
    
               INSERT INTO appl_data_master(ay_id, inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                 created_by, updated_by)
                    select '', l_inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                      in_created_by, in_created_by
                    from appl_data_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1 and data_type=in_data_type;

            end if;
        end;    

        when 'U' then
    
        begin
          set l_routine_block = 'update';

          if(in_inst_id=0)then

              update appl_data_master set valid_to = now(), updated_by = in_created_by, 
                updated_on = now(), is_deleted = 1 
               where inst_id = l_inst_id and data_type = in_data_type 
--                 and is_system_def=1
               and is_deleted = 0;

           
               INSERT INTO appl_data_master(ay_id, inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                 created_by, updated_by)
                    select '', l_inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                      in_created_by, in_created_by
                    from appl_data_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1 and data_type=in_data_type;

           end if;    
        end;    

    end case;
    end loop;
  commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_data_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_data_master_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_data_type` VARCHAR(100), IN `in_is_editable` TINYINT(1), IN `in_is_validations` TINYINT(1), IN `in_is_notification` TINYINT(1), IN `in_is_system_def` TINYINT(1), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_appl_data_master_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO appl_data_master(ay_id, inst_id, data_type, data_key,
    data_value, data_desc, data_abbr, data_pos, is_system_def,is_editable, is_active, created_by, updated_by ,
    is_validations, is_notification) VALUES'; 

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'appl_data_master' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;

  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';

    
    

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      
      

     
      set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
     

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    
    

    close cur_json_template;

  end while;

  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  
  
  
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
      
              call sp_execute_immediate (l_insert_sql_str); 
              if(in_inst_id=0)then
                CALL sp_ins_appl_data_master_all_inst('I', in_inst_id, in_data_type, in_created_by, l_err_code, l_err_desc); 
              end if;
        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

      
          update appl_data_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and data_type = in_data_type
            and is_deleted = 0 ;
                   
         update appl_data_master set valid_to = now(), updated_by = in_created_by, 
                   updated_on = now(), is_system_def = in_is_system_def ,is_editable = in_is_editable ,
                   is_validations = in_is_validations ,is_system_def = in_is_notification 
                   where data_type = in_data_type
                  and is_deleted = 0 ;

          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);  
          
           if(in_inst_id=0 AND in_is_system_def=1)then
             
                CALL sp_ins_appl_data_master_all_inst('U', in_inst_id, in_data_type, in_created_by, l_err_code, l_err_desc);       
             
           end if;
          
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_data_master_replicate_to_all_inst`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_data_master_replicate_to_all_inst`(
  IN `in_dml_mode` CHAR(1),
  IN `in_inst_id` SMALLINT(5),
  IN `in_data_type` VARCHAR(100),
  IN `in_data_key` VARCHAR(100),
  IN `in_created_by` VARCHAR(20),
  OUT `out_err_code` CHAR(5), 
  OUT `out_err_desc` TEXT)
BEGIN
declare l_routine_name varchar(50) default 'sp_ins_appl_data_master_replicate_to_all_inst';
declare l_err_code char(5) default '00000';
declare l_err_desc text default '';        
declare l_routine_block varchar(15);
declare l_looping_done int default false;
declare l_inst_id smallint(5) default 0; 
declare l_delete_flag tinyint(1) default 0; 
declare l_is_updated_by_institute tinyint(1);     

declare cur_appl_data_mst cursor for 
  select inst_id,is_deleted
  from institution_master where inst_id!='-1' and inst_id!='0' and is_deleted=0 group by inst_id;


 declare continue handler for not found set l_looping_done = true;
declare exit handler for sqlexception
    begin
    rollback;
    
    get diagnostics condition 1
      l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

    insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
      err_desc, err_type, err_severity, created_by) 
    values 
      ("", in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
      'ERROR', 0, in_created_by);

    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

       end;
open cur_appl_data_mst;

  cursor_loop_new:loop
     fetch cur_appl_data_mst into l_inst_id, l_delete_flag;
         if l_looping_done then
             leave cursor_loop_new;
         end if;
      
  start transaction;
  
    case in_dml_mode 
      when 'I' then
        begin
          set l_routine_block = 'insert';
            select is_updated_by_institute INTO l_is_updated_by_institute
              FROM appl_data_master
              where inst_id = l_inst_id and 
              data_type = in_data_type and is_active=1 and is_deleted=0  
              order by is_updated_by_institute DESC LIMIT 1;   

--              AND (l_is_updated_by_institute = 0 OR l_is_updated_by_institute='')
             if(in_inst_id=0)then

               INSERT INTO appl_data_master(ay_id, inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                 created_by, updated_by)
                    select '', l_inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                      in_created_by, in_created_by
                    from appl_data_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1 and data_type=in_data_type
                         and data_key=in_data_key ;

--                insert into  appl_data_master (ay_id, inst_id, data_type ,data_key, data_value,
--                  data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
--                 created_by, updated_by)                              
--               values('', l_inst_id,in_data_type,in_data_key,'asa',
--               '','','','','','','', in_created_by, in_created_by);

            end if;
        end;    

        when 'U' then
    
        begin
          set l_routine_block = 'update';

          select is_updated_by_institute INTO l_is_updated_by_institute
              FROM appl_data_master
              where inst_id = l_inst_id and 
              data_type = in_data_type and is_active=1 and is_deleted=0 
               order by is_updated_by_institute DESC LIMIT 1;   

		  if(in_inst_id = 0 AND l_is_updated_by_institute = 0)then

              update appl_data_master set valid_to = now(), updated_by = in_created_by, 
                updated_on = now(), is_deleted = 1 
               where inst_id = l_inst_id and data_type = in_data_type
               and data_key = in_data_key
               and is_deleted = 0;

           
               INSERT INTO appl_data_master(ay_id, inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                  created_by, updated_by)
                    select '', l_inst_id, data_type ,data_key, data_value,
                 data_desc, data_abbr, data_pos, is_system_def, is_editable,is_validations,is_notification,
                     in_created_by, in_created_by
                    from appl_data_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1 and data_type=in_data_type
                         and data_key=in_data_key ;

           end if;    
        end;    

    end case;
    end loop;
  commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_data_notif_templates_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_data_notif_templates_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_data_type` VARCHAR(25), IN `in_data_key` VARCHAR(25), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_appl_data_notif_templates_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'INSERT INTO appl_data_notif_templates (ay_id, inst_id, data_type,
    data_key, subject, message_body, is_active, created_by, updated_by) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'appl_data_notif_templates' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);
      set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Close Cursor', l_insert_val_str_full);
    close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'Before Close Cursor', l_insert_sql_str);
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
          update appl_data_notif_templates set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and data_type=in_data_type
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);  
        commit;
      end;
      when 'S' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
          update appl_data_notif_templates set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and data_type=in_data_type and data_key=in_data_key
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);  
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_license_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_license_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` CHAR(15), IN `in_fy_id` CHAR(7), IN `in_ay_id` CHAR(7), IN `in_is_current_ay` CHAR(1), IN `in_is_next_ay` CHAR(1), IN `in_grace_period` TINYINT(3), IN `in_grace_start_date` DATE, IN `in_grace_end_date` DATE, IN `in_free_period` TINYINT(3), IN `in_free_start_date` DATE, IN `in_free_end_date` DATE, IN `in_is_license_expired` CHAR(1), IN `in_is_license_renewed` CHAR(1), IN `in_renewal_date` DATE, IN `in_license_start_date` DATE, IN `in_license_end_date` DATE, IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_appl_license_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into   appl_license_master( inst_id,fy_id, ay_id,is_current_ay,is_next_ay,grace_period, 
               	grace_start_date,grace_end_date,free_period,free_start_date,free_end_date,is_license_expired,is_license_renewed, 
                renewal_date,license_start_date,license_end_date,created_by, updated_by) 
            values(in_inst_id,in_fy_id, in_ay_id,in_is_current_ay,in_is_next_ay,in_grace_period, 
                  	in_grace_start_date,in_grace_end_date,in_free_period,in_free_start_date,in_free_end_date,
                    in_is_license_expired,in_is_license_renewed, in_renewal_date,in_license_start_date,in_license_end_date,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update  appl_license_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  is_active = 'Y' and ay_id = in_ay_id and fy_id=in_fy_id 
            	and inst_id = in_inst_id;
           insert into   appl_license_master( inst_id,fy_id, ay_id,is_current_ay,is_next_ay,grace_period, 
               	grace_start_date,grace_end_date,free_period,free_start_date,free_end_date,is_license_expired,is_license_renewed, 
                renewal_date,license_start_date,license_end_date,created_by, updated_by) 
            values(in_inst_id,in_fy_id, in_ay_id,in_is_current_ay,in_is_next_ay,in_grace_period, 
                  	in_grace_start_date,in_grace_end_date,in_free_period,in_free_start_date,in_free_end_date,
                    in_is_license_expired,in_is_license_renewed, in_renewal_date,in_license_start_date,in_license_end_date,in_created_by, in_created_by);
     end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_location_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_location_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_location_id` VARCHAR(25), IN `in_parent_id` VARCHAR(25), IN `in_location_name` VARCHAR(25), IN `in_location_abbr` VARCHAR(10), IN `in_location_type` VARCHAR(10), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_appl_location_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  appl_location_master (ay_id,inst_id,location_id, parent_id,location_name,location_abbr, 
               	location_type,created_by, updated_by) 	 						
            values(in_ay_id,in_inst_id,in_location_id, in_parent_id,in_location_name,in_location_abbr, 
               	in_location_type,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update appl_location_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where parent_id = in_parent_id and location_id=in_location_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
                insert into  appl_location_master (ay_id,inst_id,location_id, parent_id,location_name,location_abbr, 
               	location_type,created_by, updated_by) 	 						
            values(in_ay_id,in_inst_id,in_location_id, in_parent_id,in_location_name,in_location_abbr, 
               	in_location_type,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_appl_txn_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_appl_txn_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_ay_id` CHAR(7), IN `in_txn_id` MEDIUMINT(8), IN `in_parent_id` INT(3), IN `in_txn_type` ENUM('M','S','T'), IN `in_txn_name` VARCHAR(25), IN `in_txn_abbr` VARCHAR(20), IN `in_route_url` VARCHAR(100), IN `in_icon_class` VARCHAR(40), IN `in_txn_desc` VARCHAR(25), IN `in_txn_lvl` TINYINT(1), IN `in_txn_seq` INT(3), IN `in_is_menu_txn` TINYINT(1), IN `in_is_blacked_out` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
declare l_routine_name varchar(50) default 'sp_ins_appl_txn_master';
declare l_err_code char(5) default '00000';
declare l_err_desc text default '';        
declare l_routine_block varchar(15);
declare l_looping_done int default false;
declare l_inst_id smallint(5) default 0; 
declare l_delete_flag tinyint(1) default 0;      
declare cur_appl_txn_mst cursor for 
select inst_id,is_deleted
 from appl_txn_master where inst_id!='-1' and is_active=1 and is_deleted=0 group by inst_id;
 declare continue handler for not found set l_looping_done = true;
declare exit handler for sqlexception
    begin
    rollback;
    get diagnostics condition 1
      l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
    insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
      err_desc, err_type, err_severity, created_by) 
    values 
      ("", in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
      'ERROR', 0, in_created_by);
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
       end;
open cur_appl_txn_mst;
  cursor_loop: loop
     fetch cur_appl_txn_mst into l_inst_id, l_delete_flag;
         if l_looping_done then
             leave cursor_loop;
         end if;
  start transaction;
    case in_dml_mode 
      when 'I' then
        begin
          set l_routine_block = 'insert';
         if(in_inst_id=0)then
              insert into appl_txn_master (ay_id,inst_id, txn_id, parent_id, txn_type, txn_name, txn_abbr, route_url, icon_class, txn_desc,
                txn_lvl, txn_seq, is_menu_txn, is_blacked_out,is_active, created_by,updated_by)                              
              values(in_ay_id,l_inst_id, in_txn_id, in_parent_id, in_txn_type, in_txn_name, in_txn_abbr, in_route_url, in_icon_class, in_txn_desc,
                in_txn_lvl, in_txn_seq, in_is_menu_txn, in_is_blacked_out,in_is_active, in_created_by,in_created_by);
              -- CALL sp_ins_role_txn_map_user_entitlements(in_ay_id, in_inst_id, in_role_id, in_created_by, l_err_code, l_err_desc); 
         End IF; 
        end;    
        when 'U' then
        begin
          set l_routine_block = 'update';
          update appl_txn_master set valid_to = NOW(), updated_by = in_created_by,updated_on = NOW(), is_deleted = 1 
          where txn_id = in_txn_id 
          and is_deleted = 0
          and inst_id = l_inst_id;
          insert into appl_txn_master (ay_id,inst_id, txn_id, parent_id, txn_type, txn_name, txn_abbr, route_url, icon_class, txn_desc,
                txn_lvl, txn_seq, is_menu_txn, is_blacked_out,is_active, created_by,updated_by)                              
              values(in_ay_id,l_inst_id, in_txn_id, in_parent_id, in_txn_type, in_txn_name, in_txn_abbr, in_route_url, in_icon_class, in_txn_desc,
                in_txn_lvl, in_txn_seq, in_is_menu_txn, in_is_blacked_out,in_is_active, in_created_by,in_created_by);
        end;    
    end case;
    end loop;
  commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_assign_user_access`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_assign_user_access`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_user_id` MEDIUMINT(8), IN `in_module_acct_id` MEDIUMINT(8), IN `in_module_name` VARCHAR(50), IN `in_is_create_allowed` CHAR(1), IN `in_is_read_allowed` CHAR(1), IN `in_is_update_allowed` CHAR(1), IN `in_is_delete_allowed` CHAR(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_assign_user_access';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_user_count mediumint(8);
 declare l_looping_done int default false;
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
          
          set l_routine_block = 'insert';
         
          SELECT count(user_id) INTO l_user_count from module_user_master 
              WHERE inst_id=in_inst_id AND user_id=in_user_id AND module_acct_id=in_module_acct_id
           and module_name=in_module_name AND is_deleted=0 and is_active=1;
        
          IF(l_user_count=0) THEN
             INSERT INTO  module_user_master (ay_id,inst_id,user_id,module_acct_id,module_name,
                     is_create_allowed,is_read_allowed,is_update_allowed,is_delete_allowed,
                     is_active,created_by,updated_by) 
                                           
             values(in_ay_id,in_inst_id,in_user_id,in_module_acct_id,in_module_name,
                    in_is_create_allowed,in_is_read_allowed,in_is_update_allowed,
                    in_is_delete_allowed,in_is_active,in_created_by,in_created_by);
          ElSE
           
            UPDATE module_user_master set is_create_allowed=in_is_create_allowed,
                is_read_allowed=in_is_read_allowed,is_update_allowed=in_is_update_allowed,
                is_delete_allowed=in_is_delete_allowed,valid_to = NOW(), updated_by = in_created_by,
               updated_on = NOW()
            WHERE inst_id=in_inst_id AND user_id=in_user_id AND module_acct_id=in_module_acct_id
                 AND module_name=in_module_name AND is_deleted=0 AND is_active=1;
    
          END IF;
                          
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update lib_accounts set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
             where lib_acct_id = in_lib_acct_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

           insert into lib_accounts (ay_id,inst_id,lib_acct_id,
                   acct_name,acct_display_name,acct_abbr,logo_path,is_default,
                   account_date,is_active,created_by,updated_by) 
                                         
           values(in_ay_id,in_inst_id,in_lib_acct_id,in_acct_name,in_acct_display_name,
                  in_acct_abbr,in_logo_path,in_is_default,in_account_date,
                  in_is_active,in_created_by,in_created_by);

        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_bank_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_bank_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_bank_id` VARCHAR(25), IN `in_bank_type` VARCHAR(15), IN `in_bank_name` VARCHAR(25), IN `in_bank_abbr` VARCHAR(10), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_bank_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into bank_master (ay_id, inst_id, bank_id, bank_type, bank_name, 
               bank_abbr, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_bank_id, in_bank_type, in_bank_name, 
              in_bank_abbr, in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update bank_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where bank_id = in_bank_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into bank_master(ay_id, inst_id, bank_id, bank_type,	bank_name, 
              bank_abbr, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_bank_id, in_bank_type, in_bank_name, 
              in_bank_abbr, in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_biomatric_attendance`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_biomatric_attendance`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_biomatric_attendance';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'INSERT INTO  biomatric_attendance_details( ay_id,
                                       inst_id, 
									  file_upload_id,
									   employee_code, 
									   	user_name,
									   company, 
									   	department, 
									   		category, 
									   degination,
									   	grade, 
									   		team, 
									   shift, 
									   		in_time, 
									   		out_time, 
									   duration,
									   	late_by, early_by,
                                       status,
									   punch_records,
									   overtime,
									   attendance_type,
									   created_by, 
									   updated_by,
									   is_active,
									   biometric_att_date,device_id,device_type,device_log_id,bio_type_id) VALUES';
    declare l_insert_val_str_part text;
    declare l_insert_val_str_full text;
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'biomatric_attendance_details' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
      begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
            set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
                  
         
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
            close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
      
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
      
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
          
                   
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_biomatric_attendance_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_biomatric_attendance_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_file_upload_id` MEDIUMINT(8), IN `in_biometric_att_date` DATE, IN `in_employee_code` VARCHAR(20), IN `in_insert_row_count_mst` TINYINT(3), IN `in_insert_row_count_dtl` TINYINT(3), IN `in_json_str_mst` TEXT, IN `in_json_str_dtl` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_biomatric_attendance_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default ''; 
  declare l_attendance_mst_id mediumint(8);   
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '\'';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO  biomatric_attendance_details (
                                       ay_id,
                                       inst_id, 
									  file_upload_id,
									   employee_code, 
									   	user_name,
									   company, 
									   	department, 
									   		category, 
									   degination,
									   	grade, 
									   		team, 
									   shift, 
									   		in_time, 
									   		out_time, 
									   duration,
									   	late_by, early_by,
                                       status,
									   punch_records,
									   overtime,
									   attendance_type,
									   created_by, 
									   updated_by,
									   is_active,
									   biometric_att_date) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO biomatric_attendance_master (
                    ay_id, 
                           inst_id,
						   file_upload_id,
						   total_record,
						  
						   attendance_type, 
						   created_by, 
						   updated_by, 
						   is_active) VALUES'; 
  declare l_insert_val_str_part text;
  declare l_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'biomatric_attendance_master' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'biomatric_attendance_details' 
  order by col_pos;
  
  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
          err_desc, err_type, err_severity, created_by) 
        values 
          (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
          'ERROR', 0, in_created_by);

        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;

  set l_insert_row_count = in_insert_row_count_mst;
  set l_json_str = trim(in_json_str_mst);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside master while loop';
    set l_insert_val_str_part = '';

    #insert into proc_error_logs (routine_name, label_name, sql_log)
    #values(l_routine_name, 'l_insert_row_count', l_insert_row_count);

    open cur_json_template_mst;

    cursor_loop: loop
      fetch cur_json_template_mst into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_json_substr', l_json_substr);
      
      
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
     

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_template_col_value', l_template_col_value);
                 
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_insert_val_str_part', l_insert_val_str_part);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    #insert into proc_error_logs (routine_name, label_name, sql_log)
    #values(l_routine_name, 'l_insert_val_str_full', l_insert_val_str_full);

    close cur_json_template_mst;

  end while;

  set l_insert_sql_str_mst = concat(l_insert_sql_str_mst, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'l_insert_sql_str_mst', l_insert_sql_str_mst);

  #######################################################

  set l_insert_row_count = 0;
  set l_json_str = '';
  set l_json_substr = '';
  set l_json_str_len = 0;
  set l_looping_done = false;
  set l_separator_idx = 1;
  set l_template_col_name = '';
  set l_template_col_value = '';
  set l_insert_val_str_part = '';
  set l_insert_val_str_full = '';

  set l_insert_row_count = in_insert_row_count_dtl;
  set l_json_str = trim(in_json_str_dtl);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside detail while loop';
    set l_insert_val_str_part = '';

    #insert into proc_error_logs (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);

    open cur_json_template_dtl;

    cursor_loop: loop
      fetch cur_json_template_dtl into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_template_col_name', l_template_col_name);

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      #insert into proc_error_logs (routine_name, label_name, sql_log)

      #values(l_routine_name, 'l_json_substr', l_json_substr);
      
     
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
     

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_template_col_value', l_template_col_value);
                 
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_insert_val_str_part', l_insert_val_str_part);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    #insert into proc_error_logs (routine_name, label_name, sql_log)
    #values(l_routine_name, 'l_insert_val_str_full', l_insert_val_str_full);

    close cur_json_template_dtl;

  end while;

  set l_insert_sql_str_dtl = concat(l_insert_sql_str_dtl, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'l_insert_sql_str_dtl', l_insert_sql_str_dtl);

  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode I : before insert';
      
          call sp_execute_immediate (l_insert_sql_str_mst);        
          call sp_execute_immediate (l_insert_sql_str_dtl);        

          set l_routine_block = 'Mode I : after insert';
        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode U : before soft delete';
      
        
                   
          update biomatric_attendance_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id 
            and is_deleted = 0 and biometric_att_date=in_biometric_att_date and 	employee_code=in_employee_code ;

          set l_routine_block = 'Mode U : before insert';
      
          call sp_execute_immediate (l_insert_sql_str_mst);        
          call sp_execute_immediate (l_insert_sql_str_dtl);  

          set l_routine_block = 'Mode U : after insert';
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  
end$$

DROP PROCEDURE IF EXISTS `sp_ins_book_chapter_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_book_chapter_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_book_chpt_map_id` MEDIUMINT(8), IN `in_book_id` MEDIUMINT(8), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_book_chapter_map_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'INSERT INTO book_chapter_map(ay_id, inst_id, book_chpt_map_id, curriculum_type, book_id, chapter_type, chapter_num, chapter_name, chapter_desc, chapter_abbr, is_system_def, is_active, created_by, updated_by ) VALUES';
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'book_chapter_map' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);
      if (l_template_col_name = 'book_chpt_map_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('BOOK_CHAPTER_MAP');
              end;
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('BOOK_CHAPTER_MAP');
               -- set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              end;
          end case;
        end;     
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Close Cursor', l_insert_val_str_full);
    close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'Before Close Cursor', l_insert_sql_str);
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
           update book_chapter_map set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and book_id = in_book_id
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_book_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_book_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_book_id` MEDIUMINT(8), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_standard_id` CHAR(2), IN `in_book_type` VARCHAR(25), IN `in_book_name` VARCHAR(25), IN `in_book_display_name` VARCHAR(25), IN `in_book_desc` VARCHAR(25), IN `in_book_abbr` VARCHAR(10), IN `in_publisher_name` VARCHAR(50), IN `in_is_system_def` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_ins_book_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_book_id mediumint(8);
  declare l_book_chpt_map_id mediumint(8);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                    err_desc, err_type, err_severity, created_by) 
             values (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                    'ERROR', 0, in_created_by);
        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
           set l_book_id = fn_sequence_generator('BOOK_MASTER');
           if(in_is_system_def = '1')then
                  INSERT INTO book_chapter_map(ay_id, inst_id, book_chpt_map_id, curriculum_type, book_id, chapter_type,
                    chapter_num, chapter_name, chapter_desc, chapter_abbr, is_system_def, is_active, created_by, updated_by)
                  select in_ay_id, in_inst_id, book_chpt_map_id, curriculum_type, book_id, chapter_type,
                    chapter_num, chapter_name, chapter_desc, chapter_abbr, is_system_def, is_active, created_by, updated_by
                  from book_chapter_map where book_id = in_book_id and ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 AND curriculum_type=in_curriculum_type;
              insert into book_master(ay_id, inst_id, book_id, curriculum_type,grading_system, standard_id,book_type,book_name, 
                          book_display_name,book_desc,book_abbr,publisher_name,is_system_def,is_active,created_by, updated_by) 
                   values (in_ay_id, in_inst_id,l_book_id, in_curriculum_type,in_grading_system, in_standard_id,in_book_type,
                          in_book_name, in_book_display_name,in_book_desc,in_book_abbr,in_publisher_name,in_is_system_def,in_is_active,
                          in_created_by, in_created_by);
           else
              insert into book_master(ay_id, inst_id, book_id, curriculum_type,grading_system, standard_id,book_type,book_name, 
                          book_display_name,book_desc,book_abbr,publisher_name,is_system_def,is_active,created_by, updated_by) 
                   values (in_ay_id, in_inst_id,l_book_id, in_curriculum_type,in_grading_system, in_standard_id,in_book_type,
                          in_book_name, in_book_display_name,in_book_desc,in_book_abbr,in_publisher_name,in_is_system_def,in_is_active,
                          in_created_by, in_created_by);
            end IF;
       end; 
       when 'U' then          
          begin
             set l_routine_block = 'update';   
                	update book_master set valid_to = NOW(), updated_by = in_created_by, 
                         updated_on = NOW(), is_deleted = 1
                   where book_id=in_book_id  and is_deleted = 0 and ay_id = in_ay_id 
                     and inst_id = in_inst_id and curriculum_type=in_curriculum_type;
            insert into book_master(ay_id, inst_id, book_id, curriculum_type,grading_system, standard_id,book_type,book_name, 
                          book_display_name,book_desc,book_abbr,publisher_name,is_system_def,is_active,created_by, updated_by) 
                   values (in_ay_id, in_inst_id,in_book_id, in_curriculum_type,in_grading_system, in_standard_id,in_book_type,
                          in_book_name, in_book_display_name,in_book_desc,in_book_abbr,in_publisher_name,in_is_system_def,in_is_active,
                          in_created_by, in_created_by);
      end;    
    end case;
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_campaign_history`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_campaign_history`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_campaign_name` VARCHAR(20), IN `in_campaign_description` VARCHAR(5000), IN `in_date` DATE, IN `in_user_group_id` MEDIUMINT(8), IN `in_message_body` VARCHAR(1000), IN `in_transaction_id` VARCHAR(200), IN `in_total_sent_count` MEDIUMINT(8), IN `in_sms_credits` MEDIUMINT(8), IN `in_success_count` MEDIUMINT(8), IN `in_failed_count` MEDIUMINT(8), IN `in_status` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_campaign_history';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_campaign_history_id mediumint(8);  	

  declare exit handler for sqlexception
	 begin
      rollback;
      
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        ('', in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
           -- set l_campaign_history_id = fn_sequence_generator('CAMPAIGN_HISTORY');
            INSERT INTO campaign_history(inst_id, campaign_name, campaign_description, date, user_group_id, message_body,
              transaction_id, total_sent_count, sms_credits,success_count, failed_count, status, created_by, updated_by, is_active)
            values(in_inst_id,in_campaign_name,in_campaign_description,in_date,in_user_group_id,in_message_body,
              in_transaction_id,in_total_sent_count,in_sms_credits,in_success_count,in_failed_count,in_status,in_created_by,
              in_created_by,in_is_active);
            

--               SELECT count(inst_id) INTO l_inst_count from sms_credit_status
--                where inst_id=in_inst_id and is_deleted=0 and is_active=1;
--              
--              IF(l_inst_count=0) THEN
-- 
--                   set l_sms_credits= 0 - in_sms_credits;
-- 
--                   insert into  sms_credit_status(
--                               inst_id,sms_credit_balance,rate,is_active,created_by,updated_by)
--                   values(in_inst_id,l_sms_credits,'',in_is_active,`in_updated_by`,`in_updated_by`);
--               
--              ELSE
--                 
--                select (sms_credit_balance) INTO l_sms_balance
--                  from sms_credit_status
--                  where inst_id=in_inst_id and is_active=1 and is_deleted=0 ;
-- 
--                 set l_sms_credits= l_sms_balance - in_sms_credits;
-- 
--                update  sms_credit_status set valid_to = NOW(), updated_by = `in_updated_by`, 
--                     updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_sms_credits
--                     where is_deleted = 0 and inst_id = in_inst_id;

          end;    

          when 'D' then
              begin
               set l_routine_block = 'delete';
              
               update  user_management set valid_to = NOW(), updated_by = in_created_by, 
                  updated_on = NOW(), is_deleted = 1 
                where user_group_id=in_user_group_id and is_deleted = 0  
                 and inst_id = in_inst_id; 
    
              end;    
      
      end case;
    
    commit;
     set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_channel_partner_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_channel_partner_details`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_channel_partner_id` MEDIUMINT(8), IN `in_payroll_type` VARCHAR(15), IN `in_joining_date` DATE, IN `in_resignation_date` DATE, IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(25), IN `in_middle_name` VARCHAR(25), IN `in_last_name` VARCHAR(25), IN `in_gender` CHAR(1), IN `in_edu_qual_degree1` VARCHAR(25), IN `in_edu_qual_stream1` VARCHAR(25), IN `in_edu_qual_degree2` VARCHAR(25), IN `in_edu_qual_stream2` VARCHAR(25), IN `in_previous_designation` VARCHAR(25), IN `in_work_exp_desc` VARCHAR(150), IN `in_work_exp_years` TINYINT(2), IN `in_work_exp_months` TINYINT(2), IN `in_emp_desc` VARCHAR(150), IN `in_birth_date` DATE, IN `in_birth_place` VARCHAR(20), IN `in_blood_group` VARCHAR(5), IN `in_nationality` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_category` VARCHAR(20), IN `in_subcategory` VARCHAR(20), IN `in_address_line_1` VARCHAR(50), IN `in_address_line_2` VARCHAR(50), IN `in_locality` INT(4), IN `in_city` INT(4), IN `in_district` INT(4), IN `in_state` INT(4), IN `in_country` INT(4), IN `in_pincode` MEDIUMINT(7), IN `in_fixed_phone_1` VARCHAR(20), IN `in_mobile_phone_1` VARCHAR(20), IN `in_fixed_phone_2` VARCHAR(20), IN `in_mobile_phone_2` VARCHAR(20), IN `in_email_main` VARCHAR(50), IN `in_email_alt` VARCHAR(50), IN `in_fax_number` VARCHAR(20), IN `in_profile_logo_path` VARCHAR(100), IN `in_status` VARCHAR(20), IN `in_status_desc` VARCHAR(100), IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_channel_partner_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin                                                          
	 declare l_routine_name varchar(50) default 'sp_ins_channel_partner_details';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
    declare l_channel_partner_id mediumint(8);
  declare exit handler for sqlexception
	  begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log( inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        ( in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
          set l_routine_block = 'insert';
		      set l_channel_partner_id = fn_sequence_generator('CHANNEL_PARTNER_DETAILS');
           insert into  channel_partner_details (inst_id,channel_partner_id,payroll_type,joining_date,resignation_date, 
    				salutation,  first_name,  middle_name,  last_name,  gender,  edu_qual_degree1,edu_qual_stream1,edu_qual_degree2,
            edu_qual_stream2,previous_designation, work_exp_desc,  work_exp_years,  work_exp_months, emp_desc,  
            birth_date, birth_place, blood_group,  nationality,  religion,  category,  subcategory,  
            address_line_1, address_line_2, locality,  city,  district, state,  country,  
            pincode,  fixed_phone_1,  mobile_phone_1,  fixed_phone_2,  mobile_phone_2,  email_main,  email_alt,  
            fax_number,profile_logo_path,status, status_desc, created_by,is_active)  	 						
           values(in_inst_id,l_channel_partner_id , in_payroll_type, in_joining_date,  in_resignation_date, 
    				in_salutation,  in_first_name,  in_middle_name,  in_last_name,  in_gender,   
            in_edu_qual_degree1,in_edu_qual_stream1,in_edu_qual_degree2,in_edu_qual_stream2,
            in_previous_designation,  in_work_exp_desc,  in_work_exp_years, 
            in_work_exp_months, in_emp_desc,  in_birth_date, in_birth_place,
            in_blood_group,  in_nationality,
            in_religion,  in_category,  in_subcategory,  in_address_line_1,
            in_address_line_2, in_locality,  in_city, in_district,  in_state,  in_country,  in_pincode, 
            in_fixed_phone_1,  in_mobile_phone_1,  in_fixed_phone_2,  in_mobile_phone_2,  in_email_main,  in_email_alt, 
            in_fax_number, in_profile_logo_path, in_status,  in_status_desc, 
            in_created_by,in_is_active);
          end;    
  	    when 'R' then
	      	set l_routine_block = 'update_resource_profile';
          begin
          	set l_channel_partner_id =in_channel_partner_id;
          update  channel_partner_details set inst_id=in_inst_id,channel_partner_id=l_channel_partner_id,payroll_type=in_payroll_type,
            joining_date=in_joining_date,resignation_date=in_resignation_date,salutation=in_salutation,first_name=in_first_name,middle_name=in_middle_name,last_name=in_last_name,gender=in_gender,
            birth_date=in_birth_date,birth_place=in_birth_place,blood_group=in_blood_group,nationality=in_nationality,religion=in_religion,category=in_category,subcategory=in_subcategory,
            status=in_status,status_desc=in_status_desc,mobile_phone_1=in_mobile_phone_1,email_main=in_email_main,created_by=in_created_by,is_active=in_is_active,updated_by=in_created_by 
          where channel_partner_id= in_channel_partner_id  and is_deleted = '0' and inst_id = in_inst_id;       
          end;  
  	   when 'W' then
        	set l_routine_block = 'update_resource_work_profile';
        	begin
            set l_channel_partner_id =in_channel_partner_id;
            update  channel_partner_details set channel_partner_id=in_channel_partner_id,payroll_type=in_payroll_type,
                    joining_date=in_joining_date,resignation_date=in_resignation_date,edu_qual_degree1=in_edu_qual_degree1,edu_qual_stream1=in_edu_qual_stream1,
                    edu_qual_degree2=in_edu_qual_degree2,edu_qual_stream2=in_edu_qual_stream2,previous_designation=in_previous_designation,
                    work_exp_desc=in_work_exp_desc,work_exp_years=in_work_exp_years,work_exp_months=in_work_exp_months,
                     work_exp_desc=in_work_exp_desc,updated_by=in_created_by 
            where channel_partner_id = in_channel_partner_id   and is_deleted = '0' and inst_id = in_inst_id;                
        	end;  
   	   when 'A' then
        	set l_routine_block = 'update_resource_address_profile';
        	begin
          update  channel_partner_details set 
            address_line_1=in_address_line_1,address_line_2=in_address_line_2,locality=in_locality,city=in_city,district=in_district,
            state=in_state,country=in_country, pincode=in_pincode,fixed_phone_1=in_fixed_phone_1,mobile_phone_1=in_mobile_phone_1,
            fixed_phone_2=in_fixed_phone_2,mobile_phone_2=in_mobile_phone_2,
            email_main=in_email_main,email_alt=in_email_alt,fax_number=in_fax_number,updated_by=in_created_by 
          where channel_partner_id = in_channel_partner_id   and is_deleted = '0' and inst_id = in_inst_id;                
        	end;         
    	when 'P' then
        	set l_routine_block = 'update_resource_profile_picture';
        	begin
          update  channel_partner_details set 
            profile_logo_path=in_profile_logo_path,updated_by=in_created_by 
          where channel_partner_id = in_channel_partner_id   and is_deleted = '0' and inst_id = in_inst_id;                
        	end;  
      end case;
    commit;
    set out_channel_partner_id = l_channel_partner_id;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_classSubTeacher_setup_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_classSubTeacher_setup_details`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_div_Count` TINYINT(3), IN `in_jsonClassStdDetails` TEXT, IN `in_sub_Count` TINYINT(3), IN `in_jsonSubTeacherDetails` TEXT, IN `in_status` VARCHAR(30), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_classSubTeacher_setup_details';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default ''; 
  declare l_attendance_mst_id mediumint(8);   
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_inst_count smallint(5);
  declare l_inst_count1 smallint(5);
  declare l_inst_count2 smallint(5);
  
  declare l_single_quot_const varchar(5) default '\'';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
 declare l_insert_sql_str_mst text default 'INSERT INTO  setup_class_master (inst_id, standard_id, division_id, class_id, emp_id, class_name, created_by) VALUES'; 
  declare l_insert_sql_str_dtl text default 'INSERT INTO setup_subject_teacher_map (inst_id, standard_id, subject_id, emp_id, created_by,
                                            division_id,class_id ) VALUES'; 
 
  declare l_insert_val_str_part text;
  declare l_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'setup_class_master' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'setup_subject_teacher_map' 
  order by col_pos;
  
  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

        insert into db_error_log( inst_id, routine_name, routine_block, err_code, 
          err_desc, err_type, err_severity, created_by) 
        values 
          (in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
          'ERROR', 0, in_created_by);

        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;

  set l_insert_row_count = in_div_Count;
  set l_json_str = trim(in_jsonClassStdDetails);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside master while loop';
    set l_insert_val_str_part = '';


    open cur_json_template_mst;

    cursor_loop: loop
      fetch cur_json_template_mst into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      case l_template_col_name 
        when 'attendance_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = fn_sequence_generator('STUDENT_ATTENDANCE_MASTER');
                  set l_attendance_mst_id = l_template_col_value;
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end case;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);

            
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);


      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    close cur_json_template_mst;

  end while;

  set l_insert_sql_str_mst = concat(l_insert_sql_str_mst, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  set l_insert_row_count = 0;
  set l_json_str = '';
  set l_json_substr = '';
  set l_json_str_len = 0;
  set l_looping_done = false;
  set l_separator_idx = 1;
  set l_template_col_name = '';
  set l_template_col_value = '';
  set l_insert_val_str_part = '';
  set l_insert_val_str_full = '';

  set l_insert_row_count = in_sub_Count;
  set l_json_str = trim(in_jsonSubTeacherDetails);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside detail while loop';
    set l_insert_val_str_part = '';

    open cur_json_template_dtl;

    cursor_loop: loop
      fetch cur_json_template_dtl into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      case l_template_col_name        
        when 'attendance_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = l_attendance_mst_id;
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     

        when 'attendance_dtl_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
--                   set l_template_col_value = fn_sequence_generator('STUDENT_ATTENDANCE_DETAIL');
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     

      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end case;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
 
                 
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    close cur_json_template_dtl;

  end while;

  set l_insert_sql_str_dtl = concat(l_insert_sql_str_dtl, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));


  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
        
          select count(inst_id) INTO l_inst_count from setup_class_master where inst_id=in_inst_id;
          IF(l_inst_count!=0)THEN
              delete from setup_class_master where inst_id=in_inst_id;
          END IF;
          call sp_execute_immediate (l_insert_sql_str_mst); 
          
          select count(inst_id) INTO l_inst_count1 from setup_subject_teacher_map where inst_id=in_inst_id;
          IF(l_inst_count1!=0)THEN
              delete from setup_subject_teacher_map where inst_id=in_inst_id;
          END IF;
          call sp_execute_immediate (l_insert_sql_str_dtl);   
            
         select count(inst_id) INTO l_inst_count2 from setup_tress_master where inst_id=in_inst_id and step_id=2;
        IF(l_inst_count2!=0)THEN
              delete from setup_tress_master where inst_id=in_inst_id and step_id=2;
         END IF;
          INSERT INTO setup_tress_master( inst_id, step_id, status,created_by) 
              VALUES ( in_inst_id,2, in_status,in_created_by);   
        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode U : before soft delete';
      
          update student_attendance_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0;
                   
          update student_attendance_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0;

          set l_routine_block = 'Mode U : before insert';
      
          call sp_execute_immediate (l_insert_sql_str_mst);        
          call sp_execute_immediate (l_insert_sql_str_dtl);  

          set l_routine_block = 'Mode U : after insert';
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
 
end$$

DROP PROCEDURE IF EXISTS `sp_ins_class_homework_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_class_homework_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stud_hw_mst_id` MEDIUMINT(8), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_stud_hw_mst_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_class_homework_details_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_stud_hw_mst_id mediumint(8);
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO class_homework_details(ay_id, 
                                                                            inst_id, 
																		     stud_hw_mst_id,
                                                                             hw_group_type, 
                                        			                         sub_std_map_id,
                                        								     hw_desc,
                                                                            created_by,
																		     	updated_by
                                                                              ) VALUES';

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'class_homework_details' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;

      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;

  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);

  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';

    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);

      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);

--       if (l_template_col_name = 'stud_hw_dtl_id') THEN
--         begin
--           case in_dml_mode 
--             when 'I' then
--               begin
--                
--               end;
--     
--             when 'U' then
--               begin
--                  set l_template_col_value = fn_sequence_generator('STUDENT_HOMEWORK_DETAILS');
--                -- set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
--               end;
--           end case;
--         end;     
        
--       else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
--       end if;

      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);

      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);

    end loop;

    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;

    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');

    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Close Cursor', l_insert_val_str_full);

    close cur_json_template;

  end while;

  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));

  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'Before Close Cursor', l_insert_sql_str);
  
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
      
              call sp_execute_immediate (l_insert_sql_str); 

        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

           update class_homework_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and stud_hw_mst_id = in_stud_hw_mst_id
            and is_deleted = 0;
                   
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_stud_hw_mst_id = in_stud_hw_mst_id;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_class_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_class_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_class_id` CHAR(8), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_emp_id` MEDIUMINT(8), IN `in_class_name` VARCHAR(30), IN `in_class_abbr` VARCHAR(15), IN `in_class_desc` VARCHAR(50), IN `in_shift_type` VARCHAR(15), IN `in_attendance_type` VARCHAR(15), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_ins_class_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
             set l_routine_block = 'insert';
            insert into class_master (ay_id, inst_id,class_id,standard_id, division_id,curriculum_type,
              grading_system,gradeset_mst_id,	emp_id,class_name,class_abbr,class_desc,attendance_type,shift_type,is_active,created_by, updated_by) 							
            values(in_ay_id, in_inst_id, in_class_id, in_standard_id, in_division_id,in_curriculum_type,
              in_grading_system,in_gradeset_mst_id, in_emp_id,in_class_name,in_class_abbr ,in_class_desc,in_attendance_type,in_shift_type,in_is_active,in_created_by, in_created_by);
          end;    
  	   when 'U' then
          set l_routine_block = 'update';
          begin
          	update class_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where class_id = in_class_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into class_master (ay_id, inst_id,class_id,standard_id, division_id,curriculum_type,
              grading_system,gradeset_mst_id,	emp_id,class_name,class_abbr,class_desc,attendance_type,shift_type,is_active,created_by, updated_by) 							
            values(in_ay_id, in_inst_id, in_class_id, in_standard_id, in_division_id,in_curriculum_type,
              in_grading_system,in_gradeset_mst_id, in_emp_id,in_class_name,in_class_abbr ,in_class_desc,in_attendance_type,in_shift_type,in_is_active,in_created_by, in_created_by);
          end;    
          
           when 'D' then
        set l_routine_block = 'delete';
        begin
        	update class_master set valid_to = NOW(), updated_by = in_created_by, 
            updated_on = NOW(), is_deleted = 1 
          where class_id = in_class_id and is_deleted = 0 and ay_id = in_ay_id 
          	and inst_id = in_inst_id and curriculum_type=in_curriculum_type;
       end;  
       
      end case;
    commit;
     set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_class_subject_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_class_subject_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_curriculum_type` VARCHAR(10), IN `in_class_id` VARCHAR(25), IN `in_subject_id` VARCHAR(25), IN `in_max_weekly_classes` TINYINT(3), IN `in_credit_hours` DECIMAL(10,2), IN `in_is_mandatory` CHAR(1), IN `in_is_exam_based` CHAR(1), IN `in_is_consecutive_preferred` CHAR(1), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_class_subject_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into class_subject_map (ay_id, inst_id,curriculum_type,class_id,subject_id, 
               	max_weekly_classes,credit_hours,is_mandatory,is_exam_based,is_consecutive_preferred,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_curriculum_type, in_class_id, in_subject_id, 
              in_max_weekly_classes,in_credit_hours,in_is_mandatory ,in_is_exam_based,in_is_consecutive_preferred,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update class_subject_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where class_id = in_class_id and subject_id=in_subject_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          insert into class_subject_map (ay_id, inst_id,curriculum_type,class_id,subject_id, 
               	max_weekly_classes,credit_hours,is_mandatory,is_exam_based,is_consecutive_preferred,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_curriculum_type, in_class_id, in_subject_id, 
              in_max_weekly_classes,in_credit_hours,in_is_mandatory ,in_is_exam_based,in_is_consecutive_preferred,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_class_timetable_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_class_timetable_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_class_id` VARCHAR(25), IN `in_timetable_id` VARCHAR(25), IN `in_timeslot_mst_id` INT(11), IN `in_shift_type` VARCHAR(15), IN `in_timetable_title` VARCHAR(25), IN `in_timetable_desc` VARCHAR(25), IN `in_is_active` VARCHAR(25), IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
    declare l_routine_name varchar(50) default 'sp_ins_class_timetable_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare l_timetable_id mediumint(8);
 declare exit handler for sqlexception
      begin
     rollback;
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
   start transaction;
     case in_dml_mode
       when 'I' then
         begin
         set l_routine_block = 'insert';
         set l_timetable_id = fn_sequence_generator('TIMETABLE_MASTER');
           insert into  timetable_master(ay_id, inst_id,class_id,timetable_id, timeslot_mst_id,shift_type,timetable_title,
                         timetable_desc,is_active,created_by, updated_by)
           values(in_ay_id, in_inst_id,in_class_id,l_timetable_id,in_timeslot_mst_id,in_shift_type,in_timetable_title,
                    in_timetable_desc,in_is_active,
                 in_created_by, in_created_by);
         end;    
         when 'U' then
       set l_routine_block = 'update';
         begin
             update timetable_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where ay_id = in_ay_id and inst_id = in_inst_id and class_id=in_class_id and  is_deleted = 0;
          insert into timetable_master (ay_id, inst_id, class_id,timetable_id, timeslot_mst_id,shift_type,timetable_title,
                                         timetable_desc,is_active,created_by, updated_by)                              
           values(in_ay_id, in_inst_id,in_class_id,in_timetable_id,in_timeslot_mst_id,in_shift_type,in_timetable_title,
                  in_timetable_desc,in_is_active,in_created_by,in_created_by);
         end;    
     end case;
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_collection_master_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_collection_master_details_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_demand_grp_id` INT(8), IN `in_fin_acct_id` INT(8), IN `in_party_id` INT(8), IN `in_party_type` CHAR(3), IN `in_party_name` VARCHAR(100), IN `in_pmt_desc` VARCHAR(100), IN `in_pmt_rcpt_num_gen_mode` VARCHAR(10), IN `in_pmt_rcpt_num` VARCHAR(50), IN `in_pmt_rcpt_entity` VARCHAR(50), IN `in_pmt_date` DATE, IN `in_pmt_amt` DECIMAL(12,2), IN `in_tax_amt` DECIMAL(12,2), IN `in_total_pmt_amt` DECIMAL(12,2), IN `in_pmt_mode` VARCHAR(15), IN `in_pmt_mode_desc` VARCHAR(50), IN `in_pmt_instru_num` VARCHAR(20), IN `in_pmt_instru_bank` VARCHAR(100), IN `in_pmt_instru_branch` VARCHAR(100), IN `in_pmt_instru_val_date` DATE, IN `in_pmt_instru_holder_name` VARCHAR(100), IN `in_pmt_instru_chg_amt` DECIMAL(12,2), IN `in_is_suspense_txn` TINYINT(1), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(50), IN `in_qp_mst_id` INT(8), IN `in_collection_json_row_count` TINYINT(3), IN `in_collection_json_str` TEXT, IN `in_demand_collection_json_row_count` TINYINT(3), IN `in_demand_collection_json_str` TEXT, IN `in_demand_master_update_json_row_count` TINYINT(3), IN `in_demand_master_update_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_collection_mst_id` VARCHAR(50), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
	declare l_routine_name varchar(50) default 'sp_ins_collection_master_details_json';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_collection_mst_id mediumint(8);    	
	declare l_json_str text;
	declare l_json_str_len int;
	declare l_json_substr text;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count tinyint(3);
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';		
	/* Local & DB PMT RCPT NUMBER for Custom Number Generator */
	declare l_pmt_rcpt_num  VARCHAR(50);
	declare t_pmt_rcpt_num  VARCHAR(50);
	/* *************************************************
		DECLARE PARAMS FOR DEMAND-COLLECTION MIX JSON 
	 ****************************************************/  
	declare l_dcm_collection_dtl_id mediumint(8); 
	declare l_dcm_demand_grp_id mediumint(8); 
	declare l_dcm_demand_mst_id mediumint(8);    
	declare l_dcm_demand_type VARCHAR(15);
	declare l_dcm_demand_num VARCHAR(15);
	declare l_dcm_txn_id VARCHAR(15);
	declare l_dcm_txn_desc VARCHAR(50); 	
	declare l_dcm_amt_due DECIMAL(12,2);   
	declare l_dcm_tax_due DECIMAL(12,2);   
	declare l_dcm_amt_clear DECIMAL(12,2);   
	declare l_dcm_tax_clear DECIMAL(12,2);   
	declare l_dcm_amt_unclear DECIMAL(12,2);   
	declare l_dcm_tax_unclear DECIMAL(12,2);   
	declare l_dcm_total_amt_due VARCHAR(50); 
	declare l_dcm_status VARCHAR(50);  
	declare l_dcm_collection_type VARCHAR(50); 
	declare l_dcm_pmt_amt DECIMAL(12,2);   
	declare l_dcm_tax_amt DECIMAL(12,2);   
	declare l_dcm_total_pmt_amt DECIMAL(12,2);   
	declare l_demand_ay_id CHAR(7) ; 
	/* END - DECLARE PARAMS FOR DEMAND-COLLECTION MIX JSON*/
	/* *************************************************
		DECLARE PARAMS FOR DEMAND-MASTER UPDATE JSON 
	 ****************************************************/ 
 	declare l_dmu_demand_grp_id mediumint(8); 
	declare l_dmu_demand_mst_id mediumint(8);     
	declare l_dmu_amt_clear DECIMAL(12,2);     
	declare l_dmu_tax_clear DECIMAL(12,2);     
	declare l_dmu_amt_unclear DECIMAL(12,2);     
	declare l_dmu_tax_unclear DECIMAL(12,2);     
	declare l_dmu_status VARCHAR(15);     
	/* END - DECLARE PARAMS FOR DEMAND-MASTER UPDATE JSON */
	declare l_insert_sql_collection_details_str text default 'insert into collection_details ( 
			ay_id,
			inst_id,
			collection_dtl_id,
			collection_mst_id,
			demand_mst_id,
			demand_grp_id,
			collection_type,
			pmt_desc,
			pmt_amt,
			tax_amt,
			total_pmt_amt,
			created_by 
	 ) VALUES';  
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare cur_json_template_collection_details cursor for 
		select col_name from json_template_master where tbl_name = 'collection_details' order by col_pos;
	declare cur_json_template_demand_collection cursor for 
		select col_name from json_template_master where tbl_name = 'demand_collection_details' order by col_pos;
	declare cur_json_template_demand_master_update cursor for 
		select col_name from json_template_master where tbl_name = 'demand_master_update' order by col_pos;
	declare continue handler for not found set l_looping_done = true;
	declare exit handler for sqlexception
		begin     
			rollback;
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			set l_routine_block = 'insert' ;
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 'ERROR', 0, in_created_by);
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
	begin
		rollback; 
		get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
		set l_routine_block = 'insert' ;
		insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
		values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
		set out_err_code = l_err_code; 
		set out_err_desc = l_err_desc;
	end; 
	 start transaction; 
		 begin    
			IF ( in_pmt_rcpt_num_gen_mode='Y') THEN 
				call sp_custom_seq_generator(in_inst_id,in_pmt_rcpt_entity,in_ay_id,in_created_by,l_pmt_rcpt_num) ;
				IF length(trim(l_pmt_rcpt_num)) = 0 THEN
				   SIGNAL SQLSTATE '10004' 
				  SET MESSAGE_TEXT = 'An error occurred while generating Payment Receipt Number';
				 END IF; 
				SELECT pmt_rcpt_num INTO t_pmt_rcpt_num FROM collection_master where pmt_rcpt_num=l_pmt_rcpt_num and inst_id=in_inst_id and fin_acct_id=in_fin_acct_id and is_active=1 and is_deleted=0;
					IF (t_pmt_rcpt_num=l_pmt_rcpt_num) THEN
						SIGNAL SQLSTATE '10005' 
					  SET MESSAGE_TEXT = 'Payment Receipt Number is already present'; 
				END IF;
			ELSE
				set l_pmt_rcpt_num = in_pmt_rcpt_num ;
			END IF; 
		end;	
			/* (A) COLLECTION_MASTER (INSERT) */
            set l_routine_block = 'insert'; 
            set l_collection_mst_id = fn_sequence_generator('COLLECTION_MASTER');
            /* Set OUTPUT PARAM collection_mst_id  */
            set out_collection_mst_id = l_collection_mst_id;
            insert into collection_master(ay_id, inst_id,fin_acct_id,collection_mst_id,demand_grp_id,
				party_id,party_type,party_name,
				pmt_desc,pmt_rcpt_num,pmt_date,pmt_amt,tax_amt,total_pmt_amt,
				pmt_mode,pmt_mode_desc,pmt_instru_num,pmt_instru_bank,pmt_instru_branch,
				pmt_instru_val_date,pmt_instru_holder_name,pmt_instru_chg_amt,
				is_suspense_txn,status,status_desc,valid_from,valid_to,created_by,created_on,updated_by,updated_on)
            values (in_ay_id, in_inst_id, in_fin_acct_id, l_collection_mst_id, in_demand_grp_id,
				in_party_id, in_party_type,in_party_name, 
				in_pmt_desc,l_pmt_rcpt_num,in_pmt_date,in_pmt_amt,in_tax_amt,in_total_pmt_amt,
				in_pmt_mode,in_pmt_mode_desc,in_pmt_instru_num,in_pmt_instru_bank,in_pmt_instru_branch,
				in_pmt_instru_val_date,in_pmt_instru_holder_name,in_pmt_instru_chg_amt,
				in_is_suspense_txn,in_status,in_status_desc,NOW(),NOW(),in_created_by,NOW(),in_created_by,NOW());
		/* (B) COLLECTION_DETAILS (INSERT-JSON) */	 
		set l_insert_row_count = in_collection_json_row_count;
		set l_json_str = trim(in_collection_json_str);
		set l_json_str_len = length(l_json_str);
		set l_looping_done = false; 
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = '';
			open cur_json_template_collection_details;	 
				cursor_loop: loop
					fetch cur_json_template_collection_details into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					if (l_template_col_name = 'collection_dtl_id') THEN
						begin  
							set l_template_col_value = fn_sequence_generator('COLLECTION_DETAILS'); 
						end;     
					elseif (l_template_col_name = 'collection_mst_id') THEN 
						set l_template_col_value = l_collection_mst_id ;   
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if; 
					set l_template_col_value = concat(l_single_quot_const, l_template_col_value, l_single_quot_const); 
					set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, l_template_col_value); 
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop;
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
				if length(trim(l_insert_val_str_full)) > 0 then        
					set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, l_insert_val_str_part, l_val_str_end, ',');
				else
					set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, l_val_str_end, ',');
				end if; 
				set l_insert_val_str_part = '';
				set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
			close cur_json_template_collection_details; 
		end while;  
		/* Final INSERT string for collection_details table */
		set l_insert_sql_collection_details_str = concat(l_insert_sql_collection_details_str, substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));	
		/*  Execute Insert statement */	
		call sp_execute_immediate (l_insert_sql_collection_details_str); 
		/* (C) DEMAND_MASTER (UPDATE-JSON) */	 
		set l_insert_row_count = in_demand_master_update_json_row_count ;
		set l_json_str = trim(in_demand_master_update_json_str);
		set l_json_str_len = length(l_json_str);
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = '';
			open cur_json_template_demand_master_update;	 
				cursor_loop: loop
					fetch cur_json_template_demand_master_update into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					/* Collect json values into local parameters */
					if (l_template_col_name = 'demand_mst_id') THEN  
						set l_dmu_demand_mst_id = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'demand_grp_id') THEN 
						set l_dmu_demand_grp_id = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_clear') THEN 
						set l_dmu_amt_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_clear') THEN 
						set l_dmu_tax_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_unclear') THEN 
						set l_dmu_amt_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_unclear') THEN 
						set l_dmu_tax_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'status') THEN 
						set l_dmu_status = substring(l_json_substr, 1, l_separator_idx - 1);     
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if;  
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
				/* *********************************************************** */
				/* *********************************************************** */
				/* ********************* NEED CODE INSERT AND UPDATE  ******** */
				/* *********************************************************** */
				/* *********************************************************** */  
				/* insert into proc_error_logs values('demand update',l_dmu_demand_mst_id,l_dmu_demand_grp_id); */
				/* Create Update query for Demand Master */ 
				UPDATE demand_master 
						SET 
							amt_clear = l_dmu_amt_clear, 
							tax_clear = l_dmu_tax_clear,
							amt_unclear = l_dmu_amt_unclear,
							tax_unclear = l_dmu_tax_unclear,
							status = l_dmu_status ,
							updated_by = in_created_by,
							updated_on = NOW()
						WHERE 
							inst_id = in_inst_id and
							demand_grp_id = l_dmu_demand_grp_id and 	
							demand_mst_id = l_dmu_demand_mst_id and
							is_active='1' and
							is_deleted='0'   ;
				/* Update QuickPay Master and Quick Pay Details and set is_active = 0 */			
				/*UPDATE pmt_quick_pay_master QPM INNER JOIN pmt_quick_pay_details QPD 
				ON (QPM.qp_mst_id= QPD.qp_mst_id)
				SET QPD.is_active = 0, 
					QPD.updated_by = in_created_by,
					QPD.updated_on = NOW(),
					QPM.status = l_dmu_status ,
					QPM.is_active = 0,
					QPM.updated_by = in_created_by,
					QPM.updated_on = NOW() 			
				WHERE QPD.demand_mst_id = l_dmu_demand_mst_id 
				AND QPD.demand_grp_id = l_dmu_demand_grp_id 
				AND QPD.inst_id = in_inst_id ;
				*/
				UPDATE pmt_quick_pay_master QPM INNER JOIN pmt_quick_pay_details QPD 
				ON (QPM.qp_mst_id= QPD.qp_mst_id)
				SET  
					QPD.updated_by = in_created_by,
					QPD.updated_on = NOW(),
					QPM.status = '2' , 
					QPM.updated_by = in_created_by,
					QPM.updated_on = NOW() 			
				WHERE QPM.qp_mst_id =  in_qp_mst_id 
				AND QPD.inst_id = in_inst_id ;
				
			close cur_json_template_demand_master_update; 
		end while;   
		/* (D) DEMAND & COLLECTION MIX (INSERT-JSON) */		
		set l_insert_row_count = in_demand_collection_json_row_count ;
		set l_json_str = trim(in_demand_collection_json_str);
		set l_json_str_len = length(l_json_str);
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = '';
			open cur_json_template_demand_collection;	 
				cursor_loop: loop
					fetch cur_json_template_demand_collection into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);  
					/* Collect json values into local parameters */
					if (l_template_col_name = 'demand_grp_id') THEN  
						set l_dcm_demand_grp_id = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'demand_type') THEN 
						set l_dcm_demand_type = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'demand_num') THEN 
						set l_dcm_demand_num = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'txn_id') THEN 
						set l_dcm_txn_id = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'txn_desc') THEN 
						set l_dcm_txn_desc = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_due') THEN 
						set l_dcm_amt_due = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'tax_due') THEN 
						set l_dcm_tax_due = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_clear') THEN 
						set l_dcm_amt_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_clear') THEN 
						set l_dcm_tax_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_unclear') THEN 
						set l_dcm_amt_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_unclear') THEN 
						set l_dcm_tax_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'total_amt_due') THEN 
						set l_dcm_total_amt_due = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'status') THEN 
						set l_dcm_status = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'collection_type') THEN 
						set l_dcm_collection_type = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'pmt_amt') THEN 
						set l_dcm_pmt_amt = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'tax_amt') THEN 
						set l_dcm_tax_amt = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'total_pmt_amt') THEN 
						set l_dcm_total_pmt_amt = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'demand_ay_id') THEN 
						set l_demand_ay_id = substring(l_json_substr, 1, l_separator_idx - 1);   
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if;   
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
				/* Create Insert query for Demand Master */
				set l_dcm_demand_mst_id = fn_sequence_generator('DEMAND_MASTER'); 
				INSERT into demand_master(ay_id,inst_id,fin_acct_id,
					demand_mst_id,demand_grp_id,demand_type,demand_num,
					txn_id,txn_desc,installment_num,
					party_type,party_id,party_name,
					gen_date,due_date,grace_period,final_date,
					amt_due,tax_due,amt_clear,tax_clear,amt_unclear,tax_unclear,total_amt_due,
					status,status_desc ,
					created_by,created_on,updated_by,updated_on)
				values (l_demand_ay_id, in_inst_id, in_fin_acct_id,
					l_dcm_demand_mst_id, l_dcm_demand_grp_id,l_dcm_demand_type,l_dcm_demand_num,
					l_dcm_txn_id, l_dcm_txn_desc,'1',
					in_party_type,in_party_id, in_party_name, 
					NOW(),NOW(),'0',NOW(),
					l_dcm_amt_due, l_dcm_tax_due,l_dcm_amt_clear,l_dcm_tax_clear,l_dcm_amt_unclear,l_dcm_tax_unclear,l_dcm_total_amt_due,
					l_dcm_status,'',
					in_created_by,NOW(),in_created_by,NOW());
				/* Create Insert query for Collection Details */	
				set l_dcm_collection_dtl_id = fn_sequence_generator('COLLECTION_DETAILS');
				INSERT into collection_details ( 
					ay_id, inst_id,
					collection_dtl_id, collection_mst_id,
					demand_mst_id, demand_grp_id, collection_type,
					pmt_desc, pmt_amt, tax_amt, total_pmt_amt, 
					created_by,created_on,updated_by,updated_on )
				VALUES (in_ay_id, in_inst_id, 
					l_dcm_collection_dtl_id,l_collection_mst_id,
					l_dcm_demand_mst_id,l_dcm_demand_grp_id,l_dcm_collection_type,
					in_pmt_desc,l_dcm_pmt_amt,l_dcm_tax_amt,l_dcm_total_pmt_amt,
					in_created_by,NOW(),in_created_by,NOW());
			close cur_json_template_demand_collection;
		end while;   
		/* (D) END */
       commit;  
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc; 

END$$

DROP PROCEDURE IF EXISTS `sp_ins_collection_master_details_json_test`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_collection_master_details_json_test`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_demand_grp_id` INT(8), IN `in_party_id` INT(8), IN `in_party_type` CHAR(3), IN `in_party_name` VARCHAR(100), IN `in_pmt_desc` VARCHAR(100), IN `in_pmt_rcpt_num_gen_mode` VARCHAR(10), IN `in_pmt_rcpt_num` VARCHAR(50), IN `in_pmt_date` DATE, IN `in_pmt_amt` DECIMAL(12,2), IN `in_tax_amt` DECIMAL(12,2), IN `in_total_pmt_amt` DECIMAL(12,2), IN `in_pmt_mode` VARCHAR(15), IN `in_pmt_mode_desc` VARCHAR(50), IN `in_pmt_instru_num` BIGINT(10), IN `in_pmt_instru_bank` VARCHAR(100), IN `in_pmt_instru_branch` VARCHAR(100), IN `in_pmt_instru_val_date` DATE, IN `in_pmt_instru_holder_name` VARCHAR(100), IN `in_pmt_instru_chg_amt` DECIMAL(12,2), IN `in_is_suspense_txn` TINYINT(1), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(50), IN `in_collection_json_row_count` TINYINT(3), IN `in_collection_json_str` TEXT, IN `in_demand_collection_json_row_count` TINYINT(3), IN `in_demand_collection_json_str` TEXT, IN `in_demand_master_update_json_row_count` TINYINT(3), IN `in_demand_master_update_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_collection_mst_id` VARCHAR(50), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
	declare l_routine_name varchar(50) default 'sp_ins_collection_master_details_json_test';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_collection_mst_id mediumint(8);    	
	declare l_json_str text;
	declare l_json_str_len int;
	declare l_json_substr text;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count tinyint(3);
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';		
	/* Local & DB PMT RCPT NUMBER for Custom Number Generator */
	declare l_pmt_rcpt_num  VARCHAR(50);
	declare t_pmt_rcpt_num  VARCHAR(50);
	/* *************************************************
		DECLARE PARAMS FOR DEMAND-COLLECTION MIX JSON 
	 ****************************************************/  
	declare l_dcm_collection_dtl_id mediumint(8); 
	declare l_dcm_demand_grp_id mediumint(8); 
	declare l_dcm_demand_mst_id mediumint(8);    
	declare l_dcm_demand_type VARCHAR(15);
	declare l_dcm_demand_num VARCHAR(15);
	declare l_dcm_txn_id VARCHAR(15);
	declare l_dcm_txn_desc VARCHAR(50); 	
	declare l_dcm_amt_due DECIMAL(12,2);   
	declare l_dcm_tax_due DECIMAL(12,2);   
	declare l_dcm_amt_clear DECIMAL(12,2);   
	declare l_dcm_tax_clear DECIMAL(12,2);   
	declare l_dcm_amt_unclear DECIMAL(12,2);   
	declare l_dcm_tax_unclear DECIMAL(12,2);   
	declare l_dcm_total_amt_due VARCHAR(50); 
	declare l_dcm_status VARCHAR(50);  
	declare l_dcm_collection_type VARCHAR(50); 
	declare l_dcm_pmt_amt DECIMAL(12,2);   
	declare l_dcm_tax_amt DECIMAL(12,2);   
	declare l_dcm_total_pmt_amt DECIMAL(12,2);   
	/* END - DECLARE PARAMS FOR DEMAND-COLLECTION MIX JSON*/
	/* *************************************************
		DECLARE PARAMS FOR DEMAND-MASTER UPDATE JSON 
	 ****************************************************/ 
 	declare l_dmu_demand_grp_id mediumint(8); 
	declare l_dmu_demand_mst_id mediumint(8);     
	declare l_dmu_amt_clear DECIMAL(12,2);     
	declare l_dmu_tax_clear DECIMAL(12,2);     
	declare l_dmu_amt_unclear DECIMAL(12,2);     
	declare l_dmu_tax_unclear DECIMAL(12,2);     
	declare l_dmu_status VARCHAR(15);     
	/* END - DECLARE PARAMS FOR DEMAND-MASTER UPDATE JSON */
	declare l_insert_sql_collection_details_str text default 'insert into collection_details ( 
			ay_id,
			inst_id,
			collection_dtl_id,
			collection_mst_id,
			demand_mst_id,
			demand_grp_id,
			collection_type,
			pmt_desc,
			pmt_amt,
			tax_amt,
			total_pmt_amt,
			created_by 
	 ) VALUES';  
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare cur_json_template_collection_details cursor for 
		select col_name from json_template_master where tbl_name = 'collection_details' order by col_pos;
	declare cur_json_template_demand_collection cursor for 
		select col_name from json_template_master where tbl_name = 'demand_collection_details' order by col_pos;
	declare cur_json_template_demand_master_update cursor for 
		select col_name from json_template_master where tbl_name = 'demand_master_update' order by col_pos;
	declare continue handler for not found set l_looping_done = true;
	declare exit handler for sqlexception
		begin     
			rollback;
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			set l_routine_block = 'insert' ;
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 'ERROR', 0, in_created_by);
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
	begin
		rollback; 
		get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
		set l_routine_block = 'insert' ;
		insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
		values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
		set out_err_code = l_err_code; 
		set out_err_desc = l_err_desc;
	end; 
	 start transaction; 
		 begin    
			IF ( in_pmt_rcpt_num_gen_mode='Y') THEN 
				call sp_custom_seq_generator(in_inst_id,'PMT_RCPT_NUM',in_ay_id,in_created_by,l_pmt_rcpt_num) ;
				IF length(trim(l_pmt_rcpt_num)) = 0 THEN
				   SIGNAL SQLSTATE '10004' 
				  SET MESSAGE_TEXT = 'An error occurred while generating Payment Receipt Number';
				 END IF; 
				SELECT pmt_rcpt_num INTO t_pmt_rcpt_num FROM collection_master where pmt_rcpt_num=l_pmt_rcpt_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
					IF (t_pmt_rcpt_num=l_pmt_rcpt_num) THEN
						SIGNAL SQLSTATE '10005' 
					  SET MESSAGE_TEXT = 'Payment Receipt Number is already present'; 
				END IF;
			ELSE
				set l_pmt_rcpt_num = in_pmt_rcpt_num ;
				insert into proc_error_logs values('demand update','PMT','1');
			END IF; 
		end;	
			/* (A) COLLECTION_MASTER (INSERT) */
            set l_routine_block = 'insert'; 
            set l_collection_mst_id = fn_sequence_generator('COLLECTION_MASTER');
            /* Set OUTPUT PARAM collection_mst_id  */
            set out_collection_mst_id = l_collection_mst_id;
			insert into proc_error_logs values('collection_master','insert-start',NOW());		
            insert into collection_master(ay_id, inst_id,collection_mst_id,demand_grp_id,
				party_id,party_type,party_name,
				pmt_desc,pmt_rcpt_num,pmt_date,pmt_amt,tax_amt,total_pmt_amt,
				pmt_mode,pmt_mode_desc,pmt_instru_num,pmt_instru_bank,pmt_instru_branch,
				pmt_instru_val_date,pmt_instru_holder_name,pmt_instru_chg_amt,
				is_suspense_txn,status,status_desc,valid_from,valid_to,created_by,created_on,updated_by,updated_on)
            values (in_ay_id, in_inst_id, l_collection_mst_id, in_demand_grp_id,
				in_party_id, in_party_type,in_party_name, 
				in_pmt_desc,l_pmt_rcpt_num,in_pmt_date,in_pmt_amt,in_tax_amt,in_total_pmt_amt,
				in_pmt_mode,in_pmt_mode_desc,in_pmt_instru_num,in_pmt_instru_bank,in_pmt_instru_branch,
				in_pmt_instru_val_date,in_pmt_instru_holder_name,in_pmt_instru_chg_amt,
				in_is_suspense_txn,in_status,in_status_desc,NOW(),NOW(),in_created_by,NOW(),in_created_by,NOW());
			insert into proc_error_logs values('collection_master','insert-end',NOW());		
				
		/* (B) COLLECTION_DETAILS (INSERT-JSON) */	 
		set l_insert_row_count = in_collection_json_row_count;
		set l_json_str = trim(in_collection_json_str);
		set l_json_str_len = length(l_json_str);
		set l_looping_done = false; 
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = '';
			open cur_json_template_collection_details;	 
				cursor_loop: loop
					fetch cur_json_template_collection_details into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					if (l_template_col_name = 'collection_dtl_id') THEN
						begin  
							set l_template_col_value = fn_sequence_generator('COLLECTION_DETAILS'); 
						end;     
					elseif (l_template_col_name = 'collection_mst_id') THEN 
						set l_template_col_value = l_collection_mst_id ;   
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if; 
					set l_template_col_value = concat(l_single_quot_const, l_template_col_value, l_single_quot_const); 
					set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, l_template_col_value); 
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop;
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
				if length(trim(l_insert_val_str_full)) > 0 then        
					set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, l_insert_val_str_part, l_val_str_end, ',');
				else
					set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, l_val_str_end, ',');
				end if; 
				set l_insert_val_str_part = '';
				set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
			close cur_json_template_collection_details; 
		end while;  
		/* Final INSERT string for collection_details table */
		set l_insert_sql_collection_details_str = concat(l_insert_sql_collection_details_str, substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));	
		/*  Execute Insert statement */	
		insert into proc_error_logs values('collection_details','insert-start',NOW());		
		call sp_execute_immediate (l_insert_sql_collection_details_str); 
		insert into proc_error_logs values('collection_details','insert-end',NOW());		
		/* (C) DEMAND_MASTER (UPDATE-JSON) */	 
		set l_insert_row_count = in_demand_master_update_json_row_count ;
		set l_json_str = trim(in_demand_master_update_json_str);
		set l_json_str_len = length(l_json_str);
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = '';
			open cur_json_template_demand_master_update;	 
				cursor_loop: loop
					fetch cur_json_template_demand_master_update into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					/* Collect json values into local parameters */
					if (l_template_col_name = 'demand_mst_id') THEN  
						set l_dmu_demand_mst_id = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'demand_grp_id') THEN 
						set l_dmu_demand_grp_id = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_clear') THEN 
						set l_dmu_amt_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_clear') THEN 
						set l_dmu_tax_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_unclear') THEN 
						set l_dmu_amt_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_unclear') THEN 
						set l_dmu_tax_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'status') THEN 
						set l_dmu_status = substring(l_json_substr, 1, l_separator_idx - 1);     
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if;  
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
				/* *********************************************************** */
				/* *********************************************************** */
				/* ********************* NEED CODE INSERT AND UPDATE  ******** */
				/* *********************************************************** */
				/* *********************************************************** */  
				 
				/* Create Update query for Demand Master */ 
				insert into proc_error_logs values('demand_master','UPDATE','1');	
				insert into proc_error_logs values('demand_master','UPDATE-start',NOW());						
				UPDATE demand_master 
						SET 
							amt_clear = l_dmu_amt_clear, 
							tax_clear = l_dmu_tax_clear,
							amt_unclear = l_dmu_amt_unclear,
							tax_unclear = l_dmu_tax_unclear,
							status = l_dmu_status ,
							updated_by = in_created_by,
							updated_on = NOW()
						WHERE 
							inst_id = in_inst_id and
							demand_grp_id = l_dmu_demand_grp_id and 	
							demand_mst_id = l_dmu_demand_mst_id and
							is_active='1' and
							is_deleted='0'   ;
							insert into proc_error_logs values('demand_master','UPDATE','2');	
				/* Update QuickPay Master and Quick Pay Details and set is_active = 0 */	
				insert into proc_error_logs values('demand_master','UPDATE-end',NOW());	
				
				insert into proc_error_logs values('pmt_quick_pay_master','UPDATE-start',NOW());	
				UPDATE pmt_quick_pay_master QPM INNER JOIN pmt_quick_pay_details QPD 
				ON (QPM.qp_mst_id= QPD.qp_mst_id)
				SET QPD.is_active = 0, 
					QPD.updated_by = in_created_by,
					QPD.updated_on = NOW(),
          QPM.status = l_dmu_status ,
					QPM.is_active = 0,
					QPM.updated_by = in_created_by,
					QPM.updated_on = NOW() 			
				WHERE QPD.demand_mst_id = l_dmu_demand_mst_id 
				AND QPD.demand_grp_id = l_dmu_demand_grp_id 
				AND QPD.inst_id = in_inst_id ;
				
				insert into proc_error_logs values('pmt_quick_pay_master','UPDATE-end',NOW());	
				
			close cur_json_template_demand_master_update; 
		end while;   
		
		insert into proc_error_logs values('cur_json_template_demand_master_update','ENd',NOW());	
		
		
		/* (D) DEMAND & COLLECTION MIX (INSERT-JSON) */		
		set l_insert_row_count = in_demand_collection_json_row_count ;
		set l_json_str = trim(in_demand_collection_json_str);
		set l_json_str_len = length(l_json_str);
		while (l_insert_row_count > 0) do
		
		insert into proc_error_logs values('demand_collection_json','START',NOW());	
		
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = '';
			open cur_json_template_demand_collection;	 
				cursor_loop: loop
					fetch cur_json_template_demand_collection into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);  
					/* Collect json values into local parameters */
					if (l_template_col_name = 'demand_grp_id') THEN  
						set l_dcm_demand_grp_id = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'demand_type') THEN 
						set l_dcm_demand_type = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'demand_num') THEN 
						set l_dcm_demand_num = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'txn_id') THEN 
						set l_dcm_txn_id = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'txn_desc') THEN 
						set l_dcm_txn_desc = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_due') THEN 
						set l_dcm_amt_due = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'tax_due') THEN 
						set l_dcm_tax_due = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_clear') THEN 
						set l_dcm_amt_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_clear') THEN 
						set l_dcm_tax_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_unclear') THEN 
						set l_dcm_amt_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_unclear') THEN 
						set l_dcm_tax_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'total_amt_due') THEN 
						set l_dcm_total_amt_due = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'status') THEN 
						set l_dcm_status = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'collection_type') THEN 
						set l_dcm_collection_type = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'pmt_amt') THEN 
						set l_dcm_pmt_amt = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'tax_amt') THEN 
						set l_dcm_tax_amt = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'total_pmt_amt') THEN 
						set l_dcm_total_pmt_amt = substring(l_json_substr, 1, l_separator_idx - 1);   
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if;   
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
				/* Create Insert query for Demand Master */
				set l_dcm_demand_mst_id = fn_sequence_generator('DEMAND_MASTER'); 
				INSERT into demand_master(ay_id,inst_id,
					demand_mst_id,demand_grp_id,demand_type,demand_num,
					txn_id,txn_desc,installment_num,
					party_type,party_id,party_name,
					gen_date,due_date,grace_period,final_date,
					amt_due,tax_due,amt_clear,tax_clear,amt_unclear,tax_unclear,total_amt_due,
					status,status_desc ,
					created_by,created_on,updated_by,updated_on)
				values (in_ay_id, in_inst_id, 
					l_dcm_demand_mst_id, l_dcm_demand_grp_id,l_dcm_demand_type,l_dcm_demand_num,
					l_dcm_txn_id, l_dcm_txn_desc,'1',
					in_party_type,in_party_id, in_party_name, 
					NOW(),NOW(),'0',NOW(),
					l_dcm_amt_due, l_dcm_tax_due,l_dcm_amt_clear,l_dcm_tax_clear,l_dcm_amt_unclear,l_dcm_tax_unclear,l_dcm_total_amt_due,
					l_dcm_status,'',
					in_created_by,NOW(),in_created_by,NOW());
				/* Create Insert query for Collection Details */	
				set l_dcm_collection_dtl_id = fn_sequence_generator('COLLECTION_DETAILS');
				INSERT into collection_details ( 
					ay_id, inst_id,
					collection_dtl_id, collection_mst_id,
					demand_mst_id, demand_grp_id, collection_type,
					pmt_desc, pmt_amt, tax_amt, total_pmt_amt, 
					created_by,created_on,updated_by,updated_on )
				VALUES (in_ay_id, in_inst_id, 
					l_dcm_collection_dtl_id,l_collection_mst_id,
					l_dcm_demand_mst_id,l_dcm_demand_grp_id,l_dcm_collection_type,
					in_pmt_desc,l_dcm_pmt_amt,l_dcm_tax_amt,l_dcm_total_pmt_amt,
					in_created_by,NOW(),in_created_by,NOW());
					
					insert into proc_error_logs values('demand_collection_json','END',NOW());	
			close cur_json_template_demand_collection;
		end while;   
		/* (D) END */
		
		 insert into proc_error_logs values('PROC','BEFORE COMMIT',NOW());
       commit;  
	   insert into proc_error_logs values('PROC','AFTER COMMIT',NOW());
	   insert into proc_error_logs values('PROC','END',NOW());
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc; 
END$$

DROP PROCEDURE IF EXISTS `sp_ins_collection_master_uncleared_payments_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_collection_master_uncleared_payments_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_collection_master_json_row_count` TINYINT(3), IN `in_collection_master_json_str` TEXT, IN `in_demand_master_update_json_row_count` TINYINT(3), IN `in_demand_master_update_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
	declare l_routine_name varchar(100) default 'sp_ins_collection_master_uncleared_payments_json';
	declare l_routine_block varchar(50);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_collection_mst_id mediumint(8);    	
	declare l_json_str text;
	declare l_json_str_len int;
	declare l_json_substr text;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count tinyint(3);
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';	 
	declare l_cmu_collection_mst_id mediumint(8); 
	declare l_cmu_status VARCHAR(15);         
	declare l_dmu_demand_grp_id mediumint(8); 
		declare l_dmu_demand_mst_id mediumint(8);     
		declare l_dmu_amt_clear DECIMAL(12,2);     
		declare l_dmu_tax_clear DECIMAL(12,2);     
		declare l_dmu_amt_unclear DECIMAL(12,2);     
		declare l_dmu_tax_unclear DECIMAL(12,2);     
		declare l_dmu_status VARCHAR(15);       
		
		   
	declare cur_json_template_collection_master_update cursor for 
		select col_name from json_template_master where tbl_name = 'collection_master_update' order by col_pos;
		
	declare cur_json_template_demand_master_update cursor for 
		select col_name from json_template_master where tbl_name = 'demand_master_update' order by col_pos;
	declare continue handler for not found set l_looping_done = true;
	declare exit handler for sqlexception
		begin     
			rollback;
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			set l_routine_block = 'insert' ;
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 'ERROR', 0, in_created_by);
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end; 
	start transaction;  
		/* COLLECTION_MASTER (UPDATE-JSON) */
		begin 
			set l_insert_row_count = in_collection_master_json_row_count ;
			set l_json_str = trim(in_collection_master_json_str);
			set l_json_str_len = length(l_json_str); 
			while (l_insert_row_count > 0) do
				set l_routine_block = 'inside while loop';  
				open cur_json_template_collection_master_update;	 
					cursor_loop: loop
						fetch cur_json_template_collection_master_update into l_template_col_name;
						if l_looping_done then
						  leave cursor_loop;
						end if;
						set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
						set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
						set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
						/* Collect json values into local parameters */
						if (l_template_col_name = 'collection_mst_id') THEN  
							set l_cmu_collection_mst_id = substring(l_json_substr, 1, l_separator_idx - 1);  
						elseif (l_template_col_name = 'status') THEN 
							set l_cmu_status = substring(l_json_substr, 1, l_separator_idx - 1);    
						else
							set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
						end if;  
						set l_json_str = l_json_substr;
						set l_json_str_len = length(l_json_str); 
					end loop; 
					set l_insert_row_count = l_insert_row_count - 1;
					set l_looping_done = false; 
					/* Create Update query for Collection Master */ 
					UPDATE collection_master 
						SET 
							status = l_cmu_status,  
							updated_by = in_created_by,
							updated_on = NOW()
						WHERE 
							inst_id = in_inst_id and
							collection_mst_id = l_cmu_collection_mst_id and 	 
							is_active='1' and
							is_deleted='0'   ; 
							
							insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, '1212121', '1212', '1', l_cmu_collection_mst_id , 'ERROR', 0, in_created_by);
							insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, '1212121', '1212', '1', l_cmu_status , 'ERROR', 0, in_created_by);
			
				close cur_json_template_collection_master_update; 
				
				
			end while;    
		end;
		/* (B) DEMAND_MASTER (UPDATE-JSON) */	 
		begin 
		set l_insert_row_count = in_demand_master_update_json_row_count ;
		set l_json_str = trim(in_demand_master_update_json_str);
		set l_json_str_len = length(l_json_str); 
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop';  
			open cur_json_template_demand_master_update;	 
				cursor_loop: loop
					fetch cur_json_template_demand_master_update into l_template_col_name;
					if l_looping_done then
					  leave cursor_loop;
					end if;
					set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
					/* Collect json values into local parameters */
					if (l_template_col_name = 'demand_mst_id') THEN  
						set l_dmu_demand_mst_id = substring(l_json_substr, 1, l_separator_idx - 1);  
					elseif (l_template_col_name = 'demand_grp_id') THEN 
						set l_dmu_demand_grp_id = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_clear') THEN 
						set l_dmu_amt_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_clear') THEN 
						set l_dmu_tax_clear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'amt_unclear') THEN 
						set l_dmu_amt_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'tax_unclear') THEN 
						set l_dmu_tax_unclear = substring(l_json_substr, 1, l_separator_idx - 1);   
					elseif (l_template_col_name = 'status') THEN 
						set l_dmu_status = substring(l_json_substr, 1, l_separator_idx - 1);     
					else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
					end if;  
					set l_json_str = l_json_substr;
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false; 
				/* Create Update query for Demand Master */ 
				UPDATE demand_master 
						SET 
							amt_clear = l_dmu_amt_clear, 
							tax_clear = l_dmu_tax_clear,
							amt_unclear = l_dmu_amt_unclear,
							tax_unclear = l_dmu_tax_unclear,
							status = l_dmu_status ,
							updated_by = in_created_by,
							updated_on = NOW()
						WHERE 
							inst_id = in_inst_id and
							demand_grp_id = l_dmu_demand_grp_id and 	
							demand_mst_id = l_dmu_demand_mst_id and
							is_active='1' and
							is_deleted='0'   ;
			close cur_json_template_demand_master_update; 
		end while;    
		end;
		/* END */ 
   commit;  
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_contracts_and_renewals`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_contracts_and_renewals`(IN `in_dml_mode` CHAR(1), 
  IN `in_ay_id` CHAR(7), 
  IN `in_inst_id` MEDIUMINT(8), 
  IN `in_con_renewal_id` MEDIUMINT(8), 
  IN `in_vendor_id` MEDIUMINT(8), 
  IN `in_file_upload_id` MEDIUMINT(8), 
  IN `in_title` VARCHAR(50),
  IN `in_amount` INT(10),
  IN `in_frequency` VARCHAR(25),
  IN `in_no_of_occurrences` SMALLINT(5),
  IN `in_send_notification` TINYINT(1),    
  IN `in_start_date` DATE,
  IN `in_created_by` VARCHAR(20), 
  OUT `out_err_code` CHAR(5), 
  OUT `out_err_desc` TEXT,
  OUT `l_cont_renewal_id` MEDIUMINT(8))
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_ins_contracts_and_renewals';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_con_renewal_id mediumint(8);
  declare exit handler for sqlexception
	  begin
      rollback;
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
       insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                   err_desc, err_type, err_severity, created_by) 
        values 
             (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
           set l_con_renewal_id = fn_sequence_generator('CONTRACT_AND_RENEWAL');
            insert into contract_and_renewal(ay_id, inst_id,con_renewal_id,vendor_id,
              file_upload_id,title,amount,frequency,no_of_occurrences,send_notification,
              start_date,created_by,updated_by) 
            values(in_ay_id, in_inst_id,l_con_renewal_id,in_vendor_id,in_file_upload_id,in_title,
             in_amount,in_frequency,in_no_of_occurrences,in_send_notification,
              in_start_date,in_created_by, in_created_by);
          end;    
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
            set l_cont_renewal_id = in_con_renewal_id;
          	update  contract_and_renewal set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where con_renewal_id=in_con_renewal_id 
              and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
             insert into contract_and_renewal(ay_id, inst_id,con_renewal_id,vendor_id,
                file_upload_id,title,amount,frequency,no_of_occurrences,send_notification,
                start_date,created_by,updated_by) 
              values(in_ay_id, in_inst_id,in_con_renewal_id,in_vendor_id,in_file_upload_id,in_title,
               in_amount,in_frequency,in_no_of_occurrences,in_send_notification,
                in_start_date,in_created_by, in_created_by);
          end;    
      end case;
    commit;
     set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
      set l_cont_renewal_id = l_con_renewal_id; 
end$$

DROP PROCEDURE IF EXISTS `sp_ins_data_clonning`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_data_clonning`(IN `in_dml_mode` CHAR(1), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
declare l_routine_name varchar(50) default 'sp_ins_data_clonning';
declare l_err_code char(5) default '00000';
declare l_err_desc text default '';        
declare l_routine_block varchar(15);
declare l_looping_done int default false;
declare l_inst_id smallint(5) default 0; 
declare l_delete_flag tinyint(1) default 0;      

declare l_user_id mediumint(8);
declare l_old_user_id mediumint(8);
declare l_looping_libraryModule_user_done int default false;

declare cur_institution_mst cursor for 
select inst_id,is_deleted
 from institution_master where inst_id NOT IN (-1,0) and is_active=1 and is_deleted=0 group by inst_id;

 declare continue handler for not found set l_looping_done = true;
declare exit handler for sqlexception
    begin
    rollback;
    
    get diagnostics condition 1
      l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

    insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
      err_desc, err_type, err_severity, created_by) 
    values 
      ("", l_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
      'ERROR', 0, '');

    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

       end;
open cur_institution_mst;

  cursor_loop: loop
     fetch cur_institution_mst into l_inst_id, l_delete_flag;
         if l_looping_done then
             leave cursor_loop;
         end if;
              
      
  start transaction;
  
    case in_dml_mode 
      when 'I' then
        begin
          set l_routine_block = 'insert';

        


   
--    select user_id into l_user_id from user_master  where  inst_id=l_inst_id and role_id=11  
--     or inst_id=l_inst_id and role_id=10 and is_active=1 and is_deleted=0;
--    

--             select user_id into l_old_user_id 
--               FROM  module_user_master where inst_id=l_inst_id and is_active=1
--                and is_deleted=0 and user_id=l_user_id;
--               if(l_old_user_id ='')then
--             insert into module_user_master (ay_id, inst_id,user_id, module_acct_id, 
--               module_name,is_create_allowed,is_read_allowed,is_update_allowed,
--               is_delete_allowed,
--               created_by,updated_by,is_active) 	 						
--             values('2018-19', l_inst_id, l_user_id, '1', 'library', 
--              '1','1','1','1', 'system', 'system',1);  
--               end if;
      
          
--               INSERT INTO appl_data_master(inst_id, data_type, data_key, data_value,
--                data_desc, data_abbr, data_pos, is_system_def, is_editable, is_validations, 
--                is_notification, is_active, is_deleted) 
--                VALUES (l_inst_id, 'GLOBAL_VARIABLES', 'MIGRATION_DONE_FOR_YEAR', '',
--                'MIGRATION_DONE_FOR_YEAR', '', '21', 0, 1, 0, 
--                0,  1, 0);

          
--               #notification_config data 
--               INSERT INTO notification_config(ay_id, inst_id, notif_template_id, notif_name, notif_desc,
--                 txn_id, txn_category, txn_sub_category, is_sms, sms_template_id, is_mail, mail_template_id,
--                 is_app, app_template_id, is_web, web_template_id, priority, handler_method, is_auto_mode,
--                 created_by, updated_by)
--                   select '', l_inst_id, notif_template_id, notif_name, notif_desc,
--                 txn_id, txn_category, txn_sub_category, is_sms, sms_template_id, is_mail, mail_template_id,
--                 is_app, app_template_id, is_web, web_template_id, priority, handler_method, is_auto_mode,
--                     created_by, created_by
--                   from notification_config where ay_id = '*******' and inst_id = 0 
--                        and is_deleted = 0 and is_active=1 and notif_template_id IN(148);
-- 
--               --               #notif_app_template_master data 
--                INSERT INTO notif_app_template_master(app_template_id, ay_id, inst_id, push_message, push_title, push_subtitle, push_action,
--                 push_vibrate, push_sound, push_large_icon, push_small_icon, push_registration_id, push_params, push_opt1, 
--                 push_opt2, recipient_type, created_by, updated_by)
--                   select app_template_id, '', l_inst_id,push_message, push_title, push_subtitle,push_action,
--                 push_vibrate, push_sound, push_large_icon, push_small_icon, push_registration_id, push_params, push_opt1, 
--                 push_opt2, recipient_type, created_by, created_by
--                   from notif_app_template_master where ay_id = '*******' and inst_id = 0 
--                        and is_deleted = 0 and is_active=1 and app_template_id IN(48);

              #notif_web_template_master data 
--               INSERT INTO notif_web_template_master(web_template_id, ay_id,  inst_id, web_from, web_subject, web_params, web_description, 
--                 web_icon, web_action_link, web_opt1, web_opt2, recipient_type, created_by, updated_by)
--                   select web_template_id, '', l_inst_id,web_from, web_subject, web_params, web_description, web_icon,
--                 web_action_link, web_opt1, web_opt2, recipient_type, created_by, created_by
--                   from notif_web_template_master where ay_id = '*******' and inst_id = 0 
--                        and is_deleted = 0 and is_active=1 and web_template_id IN(48);

              #notif_email_template_master data 
--               INSERT INTO notif_email_template_master(mail_template_id, ay_id, inst_id, email_subject, email_from, email_cc_address,
--                 email_bcc_address, email_replyto, email_body, email_params, email_attach_path1, email_attach_path2, email_opt1, email_opt2,
--                 recipient_type, created_by, updated_by)
--                   select mail_template_id, '', l_inst_id,email_subject, email_from, email_cc_address, email_bcc_address,
--                 email_replyto, email_body, email_params, email_attach_path1, email_attach_path2, email_opt1, email_opt2,
--                 recipient_type, created_by, created_by
--                   from notif_email_template_master where ay_id = '*******' and inst_id = 0 
--                        and is_deleted = 0 and is_active=1 and mail_template_id IN(48);

              #11 notif_sms_template_master data 
--               INSERT INTO notif_sms_template_master(sms_template_id, ay_id, inst_id, sms_from_mobile_no, sms_body, sms_params, sms_opt1, sms_opt2,
--                 recipient_type, created_by, updated_by)
--                   select sms_template_id, '', l_inst_id,sms_from_mobile_no, sms_body, sms_params, sms_opt1, sms_opt2,
--                 recipient_type, created_by, created_by
--                   from notif_sms_template_master where ay_id = '*******' and inst_id = 0 
--                        and is_deleted = 0 and is_active=1 and sms_template_id IN(48);

--                 INSERT INTO setup_tress_master( inst_id, step_id,status,created_by, created_on)
--                   select  l_inst_id, step_id, status, created_by, created_on from setup_tress_master where  inst_id = 0 ;

--                 if(l_inst_id > 1081)then
--                 INSERT INTO sub_module_notif_config(inst_id, module_name, module_display_name, 
--                   role_id, role_users, send, created_by, updated_by)
--                   select l_inst_id,module_name, module_display_name, 
--                   role_id, role_users, send, created_by, created_by
--                   from sub_module_notif_config where inst_id = 0 
--                        and is_deleted = 0 and is_active=1 ;
--                 end if;

--   INSERT INTO fin_accounts(inst_id, fin_acct_id,sequence_entity_id,
--                       sequence_entity_mode,acct_name,acct_display_name,
--                       acct_short_name,is_default,created_by, created_on)
--                   select  l_inst_id, fin_acct_id, sequence_entity_id,
--                       sequence_entity_mode,acct_name,acct_display_name,
--                       acct_short_name,is_default, created_by, created_on
--                   from fin_accounts where  inst_id = 0 ;



--                 INSERT INTO role_master (ay_id, inst_id, role_id, role_type, parent_id, role_level,
--                   role_name, role_display_name, role_desc, role_abbr, is_default, inst_alerts_allowed, 
--                   valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted)
--                   select  '', l_inst_id, role_id, role_type, parent_id, role_level,
--                   role_name, role_display_name, role_desc, role_abbr, is_default, inst_alerts_allowed, 
--                   valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted
--                 from role_master where inst_id = 0 and ay_id='*******'
--                  and is_deleted = 0 and is_active=1 and role_id IN(33,34,35,36,37,38,39,40);

                      
--         if(l_inst_id < 1123)then
--           INSERT INTO role_master (ay_id, inst_id, role_id, role_type, parent_id, role_level,
--                   role_name, role_display_name, role_desc, role_abbr, is_default, inst_alerts_allowed, 
--                   valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted)
--                   select  '', l_inst_id, role_id, role_type, parent_id, role_level,
--                   role_name, role_display_name, role_desc, role_abbr, is_default, inst_alerts_allowed, 
--                   valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted
--                 from role_master where inst_id = 0 and ay_id='*******'
--                  and is_deleted = 0 and is_active=1 and role_id IN(32);
--           end if;

--                 INSERT INTO role_master (ay_id, inst_id, role_id, role_type, parent_id, role_level,
--                   role_name, role_display_name, role_desc, role_abbr, is_default, inst_alerts_allowed, 
--                   valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted)
--                   select  '', l_inst_id, role_id, role_type, parent_id, role_level,
--                   role_name, role_display_name, role_desc, role_abbr, is_default, inst_alerts_allowed, 
--                   valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted
--                 from role_master where inst_id = 0 and ay_id='*******'
--                  and is_deleted = 0 and is_active=1 and role_id IN(33,34,35,36,37,38,39,40);

               --                INSERT INTO user_groups_master (id, inst_id, grp_name, grp_type, grp_display_name, grp_icon, grp_class, grp_order, group_module, valid_from, valid_to, created_by, created_on, updated_by, updated_on, is_active, is_deleted) VALUES
--                 ('', l_inst_id, 'STU', 'HOSTEL', 'Hostel', '', '', 16, '', 'now()', 'now()', 'SYSTEM', '2016-06-23 00:32:36', 'SYSTEM', 'now()', 1, 0),
--                 ('', l_inst_id, 'STU', 'NON_HOSTEL', 'Non Hostel', '', '', 17, '', 'now()', 'now()', 'SYSTEM', '2016-06-23 00:32:36', 'SYSTEM', 'now()', 1, 0),
--                 ('', l_inst_id, 'STU', 'TRANSPORT', 'Transport', '', '', 18, '', 'now()', 'now()', 'SYSTEM', '2016-06-23 00:32:36', 'SYSTEM', 'now()', 1, 0),
--                 ('', l_inst_id, 'TRANSPORT', 'ROUTE', 'Route Name', '', '', 37, '', 'now()', '2037-12-31 15:59:59', '0', 'now()', '0', 'now()', 1, 0);

--  INSERT INTO appl_data_master(inst_id, data_type, data_key, data_value,
--                data_desc, data_abbr, data_pos, is_system_def, is_editable, is_validations, 
--                is_notification, is_active, is_deleted) 
--                VALUES (l_inst_id, 'GLOBAL_VARIABLES', 'school_code', '',
--                'school_code', '', '23', 0, 1, 0, 
--                0,  1, 0);
               
		-- 	 INSERT INTO appl_data_master(inst_id, data_type, data_key, data_value,
--                data_desc, data_abbr, data_pos, is_system_def, is_editable, is_validations, 
--                is_notification, is_active, is_deleted) 
--             VALUES (l_inst_id, 'SUB_MODULE_NOTIFICATION_CONFIG', 'CLASS_ABSENT_PERCENTAGE', '1',
--                'CLASS_ABSENT_PERCENTAGE', 'CLASS_ABSENT_PERCENTAGE', '7', 1, 1, 0, 
--                0,  1, 0);
-- 			   
--             INSERT INTO appl_data_master(inst_id, data_type, data_key, data_value,
--                data_desc, data_abbr, data_pos, is_system_def, is_editable, is_validations, 
--                is_notification, is_active, is_deleted) 
--                VALUES (l_inst_id, 'SUB_MODULE_NOTIFICATION_CONFIG', 'CUSTOM_NOTIFICATION', '1',
--                'CUSTOM_NOTIFICATION', 'CUSTOM_NOTIFICATION', '8', 1, 1, 0, 
--                0,  1, 0);

--  INSERT INTO sub_module_notif_config(inst_id, module_name, module_display_name, 
--                role_id, role_users, send,is_active, is_deleted) 
--                VALUES (l_inst_id, 'CLASS_ABSENT_PERCENTAGE', 'Class absenty percentage',
--                 11, '', 0,1, 0);
-- 
--              INSERT INTO sub_module_notif_config(inst_id, module_name, module_display_name, 
--                role_id, role_users, send,is_active, is_deleted) 
--              VALUES (l_inst_id, 'CUSTOM_NOTIFICATION', 'Custom Notification',
--                 11, '', 0,1, 0);

           INSERT INTO event_calendar_category(inst_id, event_cat, cat_name, cat_icon, cat_class, cat_order)
                  select l_inst_id, event_cat, cat_name, cat_icon, cat_class, cat_order
                  from event_calendar_category where inst_id = 0 
                       and is_deleted = 0 and is_active=1 and event_cat IN('VIRTUAL_CLASSROOM');

          INSERT INTO event_calendar_subcategory(inst_id, event_cat, event_sub_cat, subcat_name, subcat_icon,
            subcat_class, subcat_order)
                  select l_inst_id, event_cat, event_sub_cat, subcat_name, subcat_icon, subcat_class, subcat_order
                  from event_calendar_subcategory where inst_id = 0 
                       and is_deleted = 0 and is_active=1 and event_cat IN('VIRTUAL_CLASSROOM');

        end;    
    end case;
    end loop;
  commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_demand_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_demand_master_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_fee_struct_mst_id` INT(8), IN `in_demand_num` VARCHAR(50), IN `in_demand_num_gen_mode` CHAR(1), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_fee_status` VARCHAR(20), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_demand_master_json';
  declare l_routine_block varchar(50);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'insert into demand_master (
ay_id,
inst_id,
demand_mst_id,
demand_grp_id,
demand_type,
demand_num,
txn_id,
txn_desc,
installment_num,
party_type,
party_id,
party_name,
gen_date,
due_date,
grace_period,
final_date,
amt_due,
tax_due,
total_amt_due,
status,  
created_by ,  
fin_acct_id 
  ) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare l_demand_num varchar(50);
	declare t_demand_num varchar(50);	
	declare cur_json_template cursor for select col_name from json_template_master where tbl_name = 'demand_master' order by col_pos;
	declare continue handler for not found set l_looping_done = true;
	declare exit handler for sqlexception
	begin     
		rollback;
			set l_routine_block = 'define sql ex'; 
		  get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text;
		insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
			err_desc, err_type, err_severity, created_by) 
		  values 
			(in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
			'ERROR', 0, in_created_by); 
		  set out_err_code = l_err_code;
		  set out_err_desc = l_err_desc;
	end;
	start transaction; 
		set l_looping_done = false; 
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = ''; 
			open cur_json_template;
			cursor_loop: loop
				fetch cur_json_template into l_template_col_name; 
				if l_looping_done then
				  leave cursor_loop;
				end if;
				set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
				set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
				set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
				if (l_template_col_name  =  'demand_mst_id') THEN  
					begin  
						set l_template_col_value = fn_sequence_generator('DEMAND_MASTER');
					end;   
				elseif (l_template_col_name =  'demand_grp_id') THEN  
						set l_template_col_value = fn_sequence_generator('DEMAND_GROUP');  
				elseif (l_template_col_name =  'demand_num' AND in_demand_num_gen_mode='Y'   ) THEN    
					set l_demand_num = '';
					begin     
						call sp_custom_seq_generator(in_inst_id,'FEE_DEMAND_NUM',in_ay_id,in_created_by,l_demand_num) ;
						IF length(trim(l_demand_num)) = 0 THEN
						   SIGNAL SQLSTATE '10004' 
						  SET MESSAGE_TEXT = 'An error occurred while generating Demand Number';
						 END IF; 
						SELECT demand_num INTO t_demand_num FROM demand_master where demand_num=l_demand_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
							IF (t_demand_num=l_demand_num) THEN
								SIGNAL SQLSTATE '10005' 
							  SET MESSAGE_TEXT = 'Demand Number is already present'; 
						END IF;
					end;	
					set l_template_col_value = l_demand_num;   
					set l_looping_done = false; 
				elseif (l_template_col_name =  'demand_num' AND in_demand_num_gen_mode='N'   ) THEN   
						set l_template_col_value = in_demand_num;   
				else
					set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
				end if;  
				set l_template_col_value = concat(l_single_quot_const, l_template_col_value, l_single_quot_const); 
				set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, l_template_col_value); 
				set l_json_str = l_json_substr;
				set l_json_str_len = length(l_json_str);  
			end loop;
			set l_insert_row_count = l_insert_row_count - 1;
			set l_looping_done = false;
			if length(trim(l_insert_val_str_full)) > 0 then        
			  set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, l_insert_val_str_part, l_val_str_end, ',');
			else
			  set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, l_val_str_end, ',');
			end if;
			set l_insert_val_str_part = '';
			set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
			close cur_json_template;
		end while;
		set l_insert_sql_str = concat(l_insert_sql_str, substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1)); 
		set l_routine_block = 'before soft delete';
		/* Update Demand Master */
		update demand_master set valid_to = now(), updated_by = in_created_by, updated_on = now() 
			where ay_id = in_ay_id 	
			  and inst_id = in_inst_id 
			  and txn_id = in_fee_struct_mst_id ;
		/* Update  fee_structure_master */	
		update fee_structure_master set status = in_fee_status
			where inst_id = in_inst_id 
			  and fee_struct_mst_id = in_fee_struct_mst_id and is_active='1' and is_deleted='0'; 
		set l_routine_block = 'before execute immediate'; 
		call sp_execute_immediate (l_insert_sql_str);   
	commit;
	set out_err_code = l_err_code;
	set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_demand_quickpay_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_demand_quickpay_details_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_fee_mst_id` INT(8), IN `in_demand_num_gen_mode` CHAR(1), IN `in_demand_json_row_count` INT(8), IN `in_demand_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
	declare l_routine_name varchar(50) default 'sp_ins_demand_quickpay_details_json';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_collection_mst_id mediumint(8);    	
	declare l_json_str text;
	declare l_json_str_len int;
	declare l_json_substr text;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count INT(8);
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';		
	/* *************************************************
		DECLARE PARAMS FOR DEMAND-QUICKPAY MIX JSON 
	 ****************************************************/  
	declare l_dq_ay_id CHAR(7); 
	declare l_dq_inst_id SMALLINT(5); 
  declare l_dq_fin_acct_id SMALLINT(5); 
	declare l_dq_created_by VARCHAR(20);  
	declare l_dq_demand_mst_id 		INT(8);
	declare l_dq_demand_grp_id 		INT(8);
	declare l_dq_demand_type 		VARCHAR(100) ;
	declare l_dq_demand_num    		VARCHAR(100) ;
	declare l_dq_txn_id          	VARCHAR(100) ; 
	declare l_dq_txn_desc      		VARCHAR(100) ; 
	declare l_dq_installment_num 	VARCHAR(100) ;
	declare l_dq_party_type 		VARCHAR(100) ;
	declare l_dq_party_id         	VARCHAR(100)  ;     
	declare l_dq_party_name   		VARCHAR(100) ;
	declare l_dq_gen_date     		VARCHAR(100) ;
	declare l_dq_due_date 			VARCHAR(100) ;    
	declare l_dq_grace_period   	VARCHAR(100) ;   
	declare l_dq_final_date        	VARCHAR(100) ;    
	declare l_dq_amt_due        	VARCHAR(100) ;      
	declare l_dq_tax_due           	VARCHAR(100) ;
	declare l_dq_total_amt_due   	VARCHAR(100) ;
	declare l_dq_qp_code 			VARCHAR(100) ;
	declare l_dq_status         	VARCHAR(100) ;
	declare l_dq_qp_mst_id 			INT(8); 
	declare l_dq_qp_dtls_id 		INT(8); 
    declare l_dq_opt_txn_id 		INT(8);
	declare t_demand_num varchar(50);	
	/* END - DECLARE PARAMS FOR DEMAND-QUICKPAY MIX JSON*/ 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare cur_json_template cursor for select col_name from json_template_master where tbl_name = 'demand_quickpay_mix' order by col_pos; 
	declare continue handler for not found set l_looping_done = true;
	declare exit handler for sqlexception
		begin     
			rollback;
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			set l_routine_block = 'insert' ;
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 'ERROR', 0, in_created_by);
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
	begin
		rollback; 
		get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
		set l_routine_block = 'insert' ;
		insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
		values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
		set out_err_code = l_err_code; 
		set out_err_desc = l_err_desc;
	end; 
	start transaction; 
		set l_looping_done = false; 
		set l_insert_row_count = in_demand_json_row_count;
		set l_json_str = trim(in_demand_json_str);
		set l_json_str_len = length(l_json_str);
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = ''; 
-- 			insert into proc_error_logs (routine_name,	label_name,sql_log) values('l_insert_row_count',l_insert_row_count,"OK");
			open cur_json_template;
-- 			insert into proc_error_logs (routine_name,	label_name,sql_log) values('l_insert_row_count',l_insert_row_count,"Opening cur_json_template ");
			cursor_loop: loop
				fetch cur_json_template into l_template_col_name; 
-- 				insert into proc_error_logs (routine_name,	label_name,sql_log) values('l_looping_done','-',l_looping_done);
				if l_looping_done then
				  leave cursor_loop;
				end if; 
