  				      SET MESSAGE_TEXT = 'Enrollment Number is already present';
  				   ELSE   
  						set l_enrollment_num =in_enrollment_num;
  					END IF;	
  				END IF;


      set l_admission_num =in_admission_num;
			
			IF ( in_admission_num_gen_mode='Y' AND (length(trim(in_enrollment_num)) = 0 OR length(trim(in_enrollment_num)) is null)) THEN 
				call sp_custom_seq_generator(in_inst_id,'STUD_ADMISSION_NUM',in_ay_id,in_created_by,l_admission_num) ;
				IF length(trim(l_admission_num)) = 0 THEN
				   SIGNAL SQLSTATE '10006' 
				  SET MESSAGE_TEXT = 'An error occurred while generating Student Admission Num';
				END IF;
			END IF;		
			
			IF ( in_admission_num_gen_mode='N' AND length(trim(in_admission_num)) > 0 AND  in_stud_status>=90 ) THEN 
				SELECT admission_num INTO t_admission_num  FROM student_master where student_id=in_student_id  and inst_id=in_inst_id and is_active=1 and is_deleted=0;
				IF (length(trim(t_admission_num)) = 0  ) THEN
								select admission_num INTO t_admission_num FROM student_master where admission_num=in_admission_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
								IF (t_admission_num=in_admission_num) THEN
									SIGNAL SQLSTATE '10007'
									SET MESSAGE_TEXT = 'Admission Number is already present';
								END IF;
				END IF;
			ELSEIF ( in_admission_num_gen_mode='N' AND  in_stud_status>=90  AND length(trim(in_admission_num)) = 0 ) THEN 
				SIGNAL SQLSTATE '10008'
				SET MESSAGE_TEXT = 'Please Enter Admission Number';
			END IF;			


      	set l_stud_num= in_student_num;

			IF ( in_stud_num_gen_mode='Y' AND (length(trim(in_enrollment_num)) = 0 OR length(trim(in_enrollment_num)) is null)
        AND  in_stud_status>=100 ) THEN 
-- 				SELECT stud_status INTO t_stud_status  FROM student_master where student_id=in_student_id  and inst_id=in_inst_id and is_active=1 and is_deleted=0;
-- 				IF (t_stud_status<90  ) THEN
-- 					 SIGNAL SQLSTATE '10018' 
-- 				    SET MESSAGE_TEXT = '<br>Before moving Student to "On Roll" Status,<br> Please update status as "Admission Granted".<br>';
-- 				ELSE
					call sp_custom_seq_generator(in_inst_id,'STUD_GUID',in_ay_id,in_created_by,l_stud_num) ;
					IF length(trim(l_stud_num)) = 0 THEN
					   SIGNAL SQLSTATE '10009' 
					    SET MESSAGE_TEXT = 'An error occurred while generating Student Num';
					END IF;
-- 				END IF;
			END IF;

      insert into student_master(ay_id, inst_id,student_id,standard_id,division_id,class_id,admission_num,student_num,
              enrollment_num,enrollment_date,enrolled_for_std,first_name,
              middle_name,last_name, birth_date,gender,religion,student_category,student_subcategory,
              consession_category,birth_place,
              mobile_phone_main,email_main,country,locality,city,district,
              state,stud_status,is_active,is_new_admission,
              class_roll_num,house_id,blood_group,nationality,language,address_line_1,address_line_2,pincode,
              prev_school_name,prev_school_address,prev_school_board,disability,
              gr_number,sts_number,aadhar_card_num,is_rte,rte_category,
              created_by,updated_by) 
    	 			values(in_ay_id, in_inst_id,l_student_id,in_enrolled_for_std,in_division_id,in_class_id,l_admission_num,l_stud_num,
               l_enrollment_num,in_enrollment_date,in_enrolled_for_std,
              in_first_name,in_middle_name, in_last_name, in_birth_date,in_gender,
              in_religion,in_student_category,in_student_subcategory,
              in_consession_category,in_birth_place,
              in_mobile_phone_main,in_email_main,in_country,in_locality,in_city,in_district,
              in_state,in_stud_status,in_is_active,in_is_new_admission,
              in_class_roll_num,in_house_id,in_blood_group,in_nationality,in_language,in_address_line_1,in_address_line_2,in_pincode,
              in_prev_school_name,in_prev_school_address,in_prev_school_board,in_disability,
              in_gr_number,in_sts_number,in_aadhar_card_num, in_is_rte,in_rte_category,
              in_created_by, in_created_by
              );


     CALL sp_ins_user_master('E','', in_inst_id, 'STU', l_student_id, '22', in_login_name, in_bcrpt_password,'',
        '','1','1','','','','','','','','','','','1','1','SYSTEM', l_err_code, l_err_desc);

          insert into temp_user_student_master(ay_id,inst_id,student_id,login_name,password,mobile_phone_main,
                  email_main,stud_status,bulk_upload_status,
                  is_active,
                  created_by, updated_by) 
        	 			values(in_ay_id,in_inst_id,l_student_id,in_login_name,in_password,
                  in_mobile_phone_main,in_email_main,in_stud_status,100,
                  in_is_active,
                  in_created_by, in_created_by
                  );

      IF(in_first_name_f != 0 or in_first_name_f!=null or in_first_name_f!='') THEN
      set l_parent_id = fn_sequence_generator('PARENT_MASTER');

      insert into parent_master(ay_id, inst_id,parent_id,salutation,first_name,
              middle_name,last_name,mobile_phone_1,email_main,
              edu_qual_degree,edu_qual_stream,occupation,income_bracket,
              gender,relation_type,relation,
              is_active,created_by, updated_by,student_id_default) 
    	 			values(in_ay_id, in_inst_id,l_parent_id,'MR.',in_first_name_f,
              in_middle_name_f, in_last_name_f, in_mobile_phone_1,in_email_main_1,
              in_edu_qual_degree_f,in_edu_qual_stream_f,in_occupation_f,in_income_bracket_f,
              'M','PARENT','FATHER',
              in_is_active,in_created_by, in_created_by,l_student_id
              );

        CALL sp_ins_user_master('E','', in_inst_id, 'PAR', l_parent_id, '21', in_login_name_f, in_bcrpt_password_f,'',
        '','1','1','','','','','','','','','','','1','1','SYSTEM', l_err_code, l_err_desc);
         insert into temp_user_parent_master(ay_id, inst_id,parent_id,login_name,password,mobile_phone_main,email_main,status
              ,is_active,
              created_by, updated_by) 
    	 			values(in_ay_id, in_inst_id,l_parent_id,in_login_name_f,in_password_f,
              in_mobile_phone_1,in_email_main_1,in_stud_status,
              in_is_active,
              in_created_by, in_created_by
              );
        update student_master set contact_id_1=l_parent_id where student_id=l_student_id  
        and inst_id=in_inst_id and is_active=1 AND is_deleted=0;

      END IF;

       IF(in_first_name_m != 0 or in_first_name_m!=null or in_first_name_m!='') THEN
     set l_parent_id = fn_sequence_generator('PARENT_MASTER');
     insert into parent_master(ay_id, inst_id,parent_id,salutation,first_name,
              middle_name,last_name,mobile_phone_2,email_alt,
              edu_qual_degree,edu_qual_stream,occupation,income_bracket,
              gender,relation_type,relation,
              is_active,created_by, updated_by,student_id_default) 
    	 			values(in_ay_id, in_inst_id,l_parent_id,'MRS.',in_first_name_m,
              in_middle_name_m,in_last_name_m, in_mobile_phone_2,in_email_main_2,
              in_edu_qual_degree_m,in_edu_qual_stream_m,in_occupation_m,in_income_bracket_m,
              'F','PARENT','MOTHER',
              in_is_active,in_created_by, in_created_by,l_student_id
              );

   
       CALL sp_ins_user_master('E','', in_inst_id, 'PAR', l_parent_id, '21', in_login_name_m, in_bcrpt_password_m,'',
        '','1','1','','','','','','','','','','','1','1','SYSTEM', l_err_code, l_err_desc);

       insert into temp_user_parent_master(ay_id,inst_id,parent_id,login_name,password,mobile_phone_main,
              email_main,status,
              is_active,
              created_by, updated_by) 
    	 			values(in_ay_id,in_inst_id,l_parent_id,in_login_name_m,in_password_m,
              in_mobile_phone_2,in_email_main_2,in_stud_status,
              in_is_active,
              in_created_by, in_created_by
              );

      update student_master set contact_id_2=l_parent_id where student_id=l_student_id  
        and inst_id=in_inst_id and is_active=1 AND is_deleted=0;
      END IF;
          
          end;    
  
      end case;
    
    commit;
    set out_student_id =l_student_id;
    set out_err_code = l_err_code;
    set out_err_desc = in_student_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_student_setup_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_setup_details`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_class_id` CHAR(8), IN `in_standard_id` CHAR(2), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_status` VARCHAR(30), 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_student_setup_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_inst_count 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_inst_count1 smallint(5);
 declare l_inst_count3 smallint(5);
  declare l_insert_sql_str text default  'INSERT INTO setup_student_master(inst_id, student_id, class_id, 
                         first_name,last_name, birth_date, gender, mobile_phone_main, created_by,standard_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 = 'setup_student_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( 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_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 = 'student_id') THEN

        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('SETUP_STUD_MASTER');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('SETUP_STUD_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';
              select count(inst_id) INTO l_inst_count from setup_student_master 
                     where inst_id=in_inst_id and class_id=in_class_id;
              IF(l_inst_count!=0)THEN

           delete from setup_student_master where inst_id=in_inst_id  and class_id=in_class_id;
      
          END IF;
--         All Delete Student from already added student in student master
          delete from setup_student_master where inst_id=in_inst_id and standard_id!=in_standard_id;
     
          call sp_execute_immediate (l_insert_sql_str); 

       select count(inst_id) INTO l_inst_count1 from setup_tress_master where inst_id=in_inst_id and step_id=3;
        IF(l_inst_count1!=0)THEN
              delete from setup_tress_master where inst_id=in_inst_id and step_id=3;
         END IF;
               INSERT INTO setup_tress_master( inst_id, step_id, status,created_by) 
              VALUES ( in_inst_id,3, in_status,in_created_by);   
        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
              
        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_stud_admission_data_score_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_admission_data_score_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_category` VARCHAR(100), IN `in_data_type` VARCHAR(100), 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_stud_admission_data_score_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 stud_admissiom_score_master(ay_id,inst_id,
    category,data_type,data_key,data_value,score,data_desc,data_abbr, 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 = 'stud_admission_score_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); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
         update stud_admissiom_score_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 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_stud_admission_notif_templates_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_admission_notif_templates_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stud_template_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_stud_admission_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 stud_admission_notif_templates (ay_id, inst_id, stud_template_id,
    admission_status, 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 = 'stud_admission_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 stud_admission_notif_templates set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id
            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 stud_admission_notif_templates set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and stud_template_id=in_stud_template_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_stud_admission_rating_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_admission_rating_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_student_id` MEDIUMINT(8), IN `in_field_1` VARCHAR(100), IN `in_field_2` VARCHAR(100), IN `in_field_3` VARCHAR(100), IN `in_field_4` VARCHAR(100), IN `in_field_5` VARCHAR(100), IN `in_field_6` VARCHAR(100), IN `in_field_7` VARCHAR(100), IN `in_field_8` VARCHAR(100), IN `in_field_9` VARCHAR(100), IN `in_field_10` VARCHAR(100), IN `in_is_shortlisted` TINYINT(1), IN `in_note` VARCHAR(500), IN `in_udf_1` VARCHAR(100), IN `in_udf_2` VARCHAR(100), IN `in_udf_3` VARCHAR(100), IN `in_is_active` TINYINT(1), IN `in_stud_status` 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_stud_admission_rating_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
	declare l_total_rate int 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';
          set l_total_rate=in_field_1 + in_field_2 + in_field_3+ in_field_4+ in_field_5+ in_field_6
          + in_field_7+ in_field_8+ in_field_9+ in_field_10;
            INSERT INTO stud_admission_rating_master(ay_id, inst_id, student_id, field_1, field_2,
              field_3, field_4, field_5, field_6, field_7, field_8, field_9, field_10, is_shortlisted,
              note, udf_1, udf_2, udf_3, student_rate, is_active, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_student_id, in_field_1, in_field_2,
              in_field_3, in_field_4, in_field_5, in_field_6, in_field_7, in_field_8, in_field_9, 
              in_field_10, in_is_shortlisted, in_note, in_udf_1, in_udf_2, in_udf_3, l_total_rate,
              in_is_active, in_created_by, in_created_by);
          end;    
          	update student_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), stud_status = in_stud_status
            where student_id = in_student_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
  	    when 'U' then
        set l_routine_block = 'update';
          begin
          	update stud_admission_rating_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where student_id = in_student_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            set l_total_rate=in_field_1 + in_field_2 + in_field_3+ in_field_4+ in_field_5+ in_field_6
          + in_field_7+ in_field_8+ in_field_9+ in_field_10;
           INSERT INTO stud_admission_rating_master(ay_id, inst_id, student_id, field_1, field_2,
              field_3, field_4, field_5, field_6, field_7, field_8, field_9, field_10, is_shortlisted,
              note, udf_1, udf_2, udf_3, student_rate, is_active, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_student_id, in_field_1, in_field_2,
              in_field_3, in_field_4, in_field_5, in_field_6, in_field_7, in_field_8, in_field_9, 
              in_field_10, in_is_shortlisted, in_note, in_udf_1, in_udf_2, in_udf_3, l_total_rate,
              in_is_active, in_created_by, in_created_by);
          	update student_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), stud_status = in_stud_status
            where student_id = in_student_id and is_deleted = 0 and ay_id = in_ay_id 
            	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_stud_admission_stage_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_admission_stage_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stage_id` MEDIUMINT(8), IN `in_stage_name` VARCHAR(100), IN `in_stage_seq` VARCHAR(50), IN `in_stage_desc` VARCHAR(100), IN `in_stage_abbr` VARCHAR(15), IN `in_stage_color` VARCHAR(100), IN `in_is_active` TINYINT(1), 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_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 l_book_id mediumint(8);
 declare l_stage_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';
         select MAX(stage_id) INTO l_stage_id from admission_stage_master where inst_id=in_inst_id
        AND ay_id=in_ay_id;
          set l_stage_id = l_stage_id+1;
             insert into admission_stage_master(ay_id,inst_id,stage_id,stage_name,stage_seq,stage_desc,
                         stage_abbr,stage_color,is_active,created_by,updated_by)
                  values (in_ay_id,in_inst_id,l_stage_id,in_stage_name,in_stage_seq,in_stage_desc,
                         in_stage_abbr,in_stage_color,in_is_active,in_created_by,in_updated_by);
      end;
      when 'U' then          
         begin  
            set l_routine_block = 'update';  
                   update admission_stage_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 stage_id=in_stage_id and  is_deleted = 0;
            insert into admission_stage_master(ay_id, inst_id,stage_id,stage_name,stage_seq,stage_desc,
                         stage_abbr,stage_color,is_active,created_by,updated_by)
                  values (in_ay_id,in_inst_id,in_stage_id,in_stage_name,in_stage_seq,in_stage_desc,
                         in_stage_abbr,in_stage_color,in_is_active,in_created_by,in_updated_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_stud_admission_stage_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_admission_stage_master_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_stud_admission_stage_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 admission_stage_master(ay_id,inst_id,stage_id,
    stage_name,stage_seq,stage_desc,stage_abbr,stage_color,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_stage_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); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
         update admission_stage_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 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_stud_admission_status_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_admission_status_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stage_id` MEDIUMINT(8), IN `in_status_id` MEDIUMINT(8), IN `in_status_name` VARCHAR(50), IN `in_status_type` VARCHAR(100), IN `in_status_desc` VARCHAR(100), IN `in_status_abbr` VARCHAR(15), IN `in_status_pos` TINYINT(3), IN `in_is_active` TINYINT(1), 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_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 l_book_id mediumint(8);
  declare l_book_chpt_map_id mediumint(8);
  declare l_min_status_id 	mediumint(8);
  declare l_totalCount 	int;
  declare l_status_type text;
  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 MIN(status_id) INTO l_min_status_id from admission_stage_status_master 
            where stage_id=in_stage_id + 1;
          	IF (in_status_id > l_min_status_id) THEN
            --  set l_status_type = concat_ws('Invalid Status Id.Please enter status Id which is below this ID : ',l_min_status_id);
    				  set l_status_type = concat('Invalid Status Id.Please enter status Id which is below this ID : ',l_min_status_id);
              SIGNAL SQLSTATE '10001' 
                   SET MESSAGE_TEXT =l_status_type;
    			     END IF;
               	IF (in_status_type = 'PRIMARY') THEN
                  SELECT COUNT(1) AS totalCount INTO l_totalCount
                    FROM  admission_stage_status_master
                    where ay_id=in_ay_id
                    AND inst_id=in_inst_id
                    AND is_deleted=0 AND status_type=in_status_type and stage_id=in_stage_id;
                   IF (l_totalCount !=0) THEN
          					   SIGNAL SQLSTATE '10002' 
          				      SET MESSAGE_TEXT = 'Primary Status Type already exist in this Stage';
          			     END IF;
                 END IF;
              insert into admission_stage_status_master(ay_id, inst_id,stage_id,status_id,status_name, status_type,status_desc, 
                          status_abbr,status_pos,is_active,created_by,updated_by) 
                   values (in_ay_id,in_inst_id,in_stage_id,in_status_id,in_status_name,in_status_type,in_status_desc,
                          in_status_abbr, in_status_pos,in_is_active,in_created_by,in_updated_by);
           end; 
       when 'U' then          
          begin
             set l_routine_block = 'update';   
                	update admission_stage_status_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 status_id=in_status_id and is_deleted=0;
             insert into admission_stage_status_master(ay_id, inst_id,stage_id,status_id,status_name, status_type,status_desc, 
                          status_abbr,status_pos,is_active,created_by,updated_by) 
                   values (in_ay_id,in_inst_id,in_stage_id,in_status_id,in_status_name,in_status_type,in_status_desc,
                          in_status_abbr, in_status_pos,in_is_active,in_created_by,in_updated_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_stud_assignment_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_assignment_dtl_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_assignment_mst_id` MEDIUMINT(8), 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, OUT `out_assignment_mst_id` MEDIUMINT(8))
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_stud_assignment_dtl_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default ''; 
  declare l_assignment_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  student_assignment_details (ay_id, 
													inst_id,
													assignment_mst_id, 
													assignment_dtl_id,
													standard_id, 
													division_id, 
													group_type,
                           group_id,
															student_id,
																	assignment_done_date,
																	assignment_status,
																	status_desc,
																		created_by,
																		updated_by,
																		is_active
													) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO student_assignment_master (
																	ay_id,
																	inst_id,
																	assignment_mst_id,
																	standard_id,
																	division_id, 
																	group_type, 
																	group_id,
																	emp_id,
																	sub_std_map_id, 
																	book_chpt_map_id,
																	assignment_title, 
																	assignment_desc,
																	assignment_init_date, 
																	assignment_target_date,
																	is_mandatory, 
																	is_backdated,
																	assignment_file_1,
																	assignment_file_2,
																	assignment_file_3,
																	status,
																	status_desc,
																	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 = 'student_assignment_master' 
  order by col_pos;
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_assignment_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);
      case l_template_col_name 
        when 'assignment_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = fn_sequence_generator('STUDENT_ASSIGNMENT_MASTER');
                  set l_assignment_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);
      #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);
      case l_template_col_name        
        when 'assignment_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = l_assignment_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 'assignment_dtl_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = fn_sequence_generator('STUDENT_ASSIGNMENT_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);
      #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  student_assignment_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 assignment_mst_id = in_assignment_mst_id
            and is_deleted = 0;
          update student_assignment_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 assignment_mst_id = in_assignment_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;
  set out_assignment_mst_id = l_assignment_mst_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_attendance_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_attendance_dtl_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_insert_row_count_mst` TINYINT(3), IN `in_insert_row_count_dtl` MEDIUMINT(8), IN `in_json_str_mst` TEXT, IN `in_json_str_dtl` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_student_id` MEDIUMINT(8), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_attendance_mst_id` MEDIUMINT(8))
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_stud_attendance_dtl_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_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO  student_attendance_details (ay_id, inst_id, attendance_mst_id, attendance_dtl_id, student_id, attendance_status, attendance_comments, created_by, updated_by, is_active,stud_att_upload_type,bio_type_id) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO student_attendance_master (ay_id, inst_id, attendance_mst_id, group_type, group_id, standard_id, division_id, timetable_period_id, file_upload_id, attendance_type, attendance_date, class_count, present_count, absent_count, attendance_comments, status, status_desc, created_by, updated_by, is_active,attendance_upload_type,notification_status) VALUES'; 
  declare l_insert_val_str_part 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  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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_attendance_master' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'E' 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);

      #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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'E' 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;
				 when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'E' 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);

      #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 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;
	  
	      when 'B' 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  and attendance_status = 'A'  and stud_att_upload_type = 'MANUAL'  ;

          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;
	  
	   when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : before soft delete';

           DELETE FROM student_attendance_master 
           WHERE  inst_id = in_inst_id and ay_id = in_ay_id and  attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0;
                   
      
--         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;
                   
          

          set l_routine_block = 'Mode D : 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 D : after insert';
        commit;
      end;

      when 'E' 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 student_id = in_student_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;
  set out_attendance_mst_id = l_attendance_mst_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_attendance_upload_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_attendance_upload_dtl_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_file_upload_id` MEDIUMINT(8), IN `in_attendance_dtl_id` MEDIUMINT(8), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_stud_attendance_upload_dtl_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  MEDIUMTEXT;
  declare l_json_str_len int;
  declare l_json_substr  MEDIUMTEXT;
  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;
  
  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  student_attendance_details(ay_id, inst_id, attendance_mst_id, attendance_dtl_id, student_id, attendance_status, attendance_comments, created_by, updated_by, is_active,stud_att_upload_type,bio_type_id) VALUES';

	declare l_insert_val_str_part  MEDIUMTEXT;
	declare l_insert_val_str_full  MEDIUMTEXT;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'student_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);
 

      if (l_template_col_name = 'attendance_dtl_id') THEN
        begin
        
                set l_template_col_value = fn_sequence_generator('STUDENT_ATTENDANCE_DETAIL');
            
        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));

 
  
 
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
                 
				 
              call sp_execute_immediate (l_insert_sql_str); 
			  
			  update student_attendance_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), status='PUBLISHED'
            where file_upload_id = in_file_upload_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;

        commit;
      end;

   



  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_attendance_upload_mst_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_attendance_upload_mst_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `attendance_mst_id` MEDIUMINT(8), 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, OUT `out_attendance_mst_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_stud_attendance_upload_mst_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 text default 'INSERT INTO student_attendance_master(ay_id, inst_id, attendance_mst_id, group_type, group_id, standard_id, division_id, timetable_period_id, file_upload_id, attendance_type, attendance_date, class_count, present_count, absent_count, attendance_comments, status, status_desc, created_by, updated_by, is_active,	attendance_upload_type,notification_status	) 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 = 'student_attendance_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';

    #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 = '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 = fn_sequence_generator('STUDENT_ATTENDANCE_MASTER');
               -- 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 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;
                   
          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_attendance_mst_id = l_attendance_mst_id;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_biometric_attendance`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_biometric_attendance`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_student_id` MEDIUMINT(8), 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, OUT `out_attendance_mst_id` MEDIUMINT(8))
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_stud_biometric_attendance';
  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_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO  student_attendance_details (ay_id, inst_id, attendance_mst_id, attendance_dtl_id, student_id, attendance_status, attendance_comments, created_by, updated_by, is_active,stud_att_upload_type) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO student_attendance_master (ay_id, inst_id, attendance_mst_id, group_type, group_id, standard_id, division_id, timetable_period_id, file_upload_id, attendance_type, attendance_date, class_count, present_count, absent_count, attendance_comments, status, status_desc, created_by, updated_by, is_active,attendance_upload_type,	notification_status) VALUES'; 
  declare l_insert_val_str_part 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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_attendance_master' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'M' 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);

      #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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'M' 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;
				 when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'M' 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);

      #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 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;
	  
	      when 'B' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode U : before soft delete';
      
          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  and student_id = in_student_id  ;

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

          set l_routine_block = 'Mode U : after insert';
        commit;
      end;
       when 'M' 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;
                   

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

          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;
  set out_attendance_mst_id = l_attendance_mst_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_biometric_attendance_upload_dtl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_biometric_attendance_upload_dtl_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_attendance_upload_type` VARCHAR(25), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_stud_biometric_attendance_upload_dtl_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  MEDIUMTEXT;
  declare l_json_str_len int;
  declare l_json_substr  MEDIUMTEXT;
  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;
  
  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  student_attendance_details(ay_id, inst_id, attendance_mst_id, attendance_dtl_id, student_id, attendance_status, attendance_comments, created_by, updated_by, is_active,stud_att_upload_type,bio_type_id) VALUES';

	declare l_insert_val_str_part  MEDIUMTEXT;
	declare l_insert_val_str_full  MEDIUMTEXT;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'student_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);
 

      if (l_template_col_name = 'attendance_dtl_id') THEN
        begin
        
                set l_template_col_value = fn_sequence_generator('STUDENT_ATTENDANCE_DETAIL');
            
        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));

 
  
 
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
                 
				 
              call sp_execute_immediate (l_insert_sql_str); 
			  
			  update student_attendance_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), status='DRAFT'
            where attendance_mst_id = in_attendance_mst_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id and 	attendance_upload_type =in_attendance_upload_type;

        commit;
      end;

   



  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_period_wise_attendance_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_period_wise_attendance_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_insert_row_count_mst` TINYINT(3), IN `in_insert_row_count_dtl` MEDIUMINT(8), IN `in_json_str_mst` TEXT, IN `in_json_str_dtl` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_student_id` MEDIUMINT(8), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_attendance_mst_id` MEDIUMINT(8))
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_stud_period_wise_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_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO  student_attendance_details (ay_id, inst_id, attendance_mst_id, attendance_dtl_id, student_id, attendance_status, attendance_comments, created_by, updated_by, is_active,stud_att_upload_type,bio_type_id) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO student_attendance_master (ay_id, inst_id, attendance_mst_id, group_type, group_id, standard_id, division_id, timetable_period_id, file_upload_id, attendance_type, attendance_date, class_count, present_count, absent_count, attendance_comments, status, status_desc, created_by, updated_by, is_active,attendance_upload_type,notification_status,attendance_for,sub_str_map_id,time_from,time_to,period_number,opt_id) VALUES'; 
  declare l_insert_val_str_part 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  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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_periodwise_attendance' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'E' 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);

      #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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'E' 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;
				 when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'E' 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);

      #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 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;
	  
	      when 'B' 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  and attendance_status = 'A'  and stud_att_upload_type = 'MANUAL'  ;

          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;
	  
	   when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : before soft delete';

           DELETE FROM student_attendance_master 
           WHERE  inst_id = in_inst_id and ay_id = in_ay_id and  attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0;
                   
      
--         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;
                   
          

          set l_routine_block = 'Mode D : 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 D : after insert';
        commit;
      end;

      when 'E' 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 student_id = in_student_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;
  set out_attendance_mst_id = l_attendance_mst_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_stud_subject_package_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_stud_subject_package_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_student_id` MEDIUMINT(8), IN `in_package_id` MEDIUMINT(8), IN `in_insert_row_count` INT, 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_stud_subject_package_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_timeslot_mst_id int;

  declare l_insert_sql_str text default 'INSERT INTO stud_subject_package_map(ay_id, inst_id,
    student_id, package_id, subject_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 = 'stud_subject_package_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);
      
      
     
      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';
      
          update stud_subject_package_map set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and student_id=in_student_id
          and is_deleted = 0 and ay_id=in_ay_id ;

          call sp_execute_immediate (l_insert_sql_str); 

        commit;
      end;

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

         update stud_subject_package_map set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and student_id=in_student_id
          and is_deleted = 0 and ay_id=in_ay_id ;

          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_subject_book_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_book_map`(IN `in_dml_mode` CHAR(1), 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(10), IN `in_sub_std_map_id` CHAR(6), IN `in_book_id` VARCHAR(25), 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_subject_book_map';
  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 'I' then
          begin
           set l_routine_block = 'insert';
           set l_subject_book_map_id = fn_sequence_generator('SUBJECT_BOOK_MAP');
            insert into  subject_book_map(ay_id, inst_id,sub_book_map_id,curriculum_type, 
              sub_std_map_id, book_id,is_system_def,is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id, l_subject_book_map_id, in_curriculum_type,IN_sub_std_map_id, in_book_id,
              in_is_system_def,in_is_active,in_created_by, in_created_by);
          end;    
  	   when 'U' then
      set l_routine_block = 'update';      
          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 and curriculum_type=in_curriculum_type;
             insert into  subject_book_map(ay_id, inst_id,sub_book_map_id,curriculum_type, 
              sub_std_map_id, book_id,is_system_def,is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id, in_sub_book_map_id, in_curriculum_type,IN_sub_std_map_id, in_book_id,
              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_subject_book_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_book_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_book_map_id` MEDIUMINT(8), 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_subject_book_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 subject_book_map(ay_id, inst_id, sub_book_map_id, curriculum_type, sub_std_map_id, book_id, 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 = 'subject_book_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 = 'sub_book_map_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('SUBJECT_BOOK_MAP');
              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, '(,', '(');
    #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 subject_book_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 sub_book_map_id = in_sub_book_map_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_subject_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_subject_id` MEDIUMINT(8), IN `in_subject_name` VARCHAR(50), IN `in_subject_display_name` VARCHAR(50), IN `in_subject_desc` VARCHAR(100), IN `in_subject_abbr` CHAR(4), IN `in_subject_group_name` VARCHAR(25), IN `in_is_system_def` TINYINT(3), 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_subject_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_subject_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_subject_id = fn_sequence_generator('SUBJECT_MASTER');
            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,is_active,created_by, 
              updated_by) 
            values(
              in_ay_id, in_inst_id,in_curriculum_type, 
              in_grading_system,l_subject_id,in_subject_name,
              in_subject_display_name,in_subject_desc,in_subject_abbr,
              in_subject_group_name,in_is_system_def, in_is_active,in_created_by, in_created_by);
          end;    
  	    when 'U' then
      set l_routine_block = 'update';      
          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;
           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,is_active,created_by, 
              updated_by) 
            values(
              in_ay_id, in_inst_id,in_curriculum_type, 
              in_grading_system,in_subject_id,in_subject_name,
              in_subject_display_name,in_subject_desc,in_subject_abbr,
              in_subject_group_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_subject_package_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_package_json`(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_package_id` MEDIUMINT(8), IN `in_package_name` VARCHAR(50), IN `in_package_display_name` VARCHAR(50), IN `in_package_desc` VARCHAR(100), IN `in_package_abbr` VARCHAR(10), IN `in_is_active` TINYINT(1), IN `in_insert_row_count` MEDIUMINT(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_subject_package_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_package_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 subject_package_details(ay_id, inst_id, 
    package_dtl_id, package_id, subject_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 = 'subject_package_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_package_id = fn_sequence_generator('SUBJECT_PACKAGE_MASTER');
      end;

    when 'U' then
      begin
        set l_package_id = in_package_id;
      
      end;

     when 'D' then
    begin
      set l_package_id = in_package_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 = 'package_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('SUBJECT_PACKAGE_DETAILS');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('SUBJECT_PACKAGE_DETAILS');
              
              end;
            when 'D' then
            begin
               set l_template_col_value = fn_sequence_generator('SUBJECT_PACKAGE_DETAILS');
            
            end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'package_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_package_id;
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
             when 'D' 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 subject_package_master(ay_id, inst_id, standard_id, package_id, 
              package_name, package_display_name, package_desc, package_abbr, created_by, updated_by, is_active) 
              VALUES (in_ay_id, in_inst_id, in_standard_id, l_package_id, 
              in_package_name, in_package_display_name, in_package_desc, in_package_abbr,
              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 subject_package_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 package_id = in_package_id
            and is_deleted = 0;

           INSERT INTO subject_package_master(ay_id, inst_id, standard_id, package_id, 
              package_name, package_display_name, package_desc, package_abbr, created_by, updated_by, is_active) 
              VALUES (in_ay_id, in_inst_id, in_standard_id, l_package_id, 
              in_package_name, in_package_display_name, in_package_desc, in_package_abbr,
              in_created_by, in_created_by, in_is_active);
                   
          set l_routine_block = 'before execute immediate';
      
           update subject_package_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 package_id = in_package_id
            and is_deleted = 0;

          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;

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

          update subject_package_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 package_id = in_package_id
            and is_deleted = 0;

      
           update subject_package_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 package_id = in_package_id
            and is_deleted = 0;
     
        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_subject_standard_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_standard_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_std_map_id` CHAR(6), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_group_type` CHAR(3), IN `in_group_id` VARCHAR(10), IN `in_subject_id` MEDIUMINT(8), IN `in_subject_type_id` VARCHAR(25), IN `in_subject_category_id` VARCHAR(25), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_evaluation_type` VARCHAR(15), IN `in_subject_level` TINYINT(2), IN `in_max_weekly_classes` TINYINT(3), IN `in_credit_hours` DECIMAL(10,2), IN `in_is_mandatory` TINYINT(1), IN `in_exam_type` CHAR(1), IN `in_is_book_based` TINYINT(1), IN `in_is_consecutive_preferred` TINYINT(1), 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)
BEGIN

  declare l_routine_name varchar(50) default 'sp_ins_subject_standard_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_subject_standard_map_id mediumint(8);
  declare l_sub_struct_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_subject_standard_map_id = fn_sequence_generator('SUBJECT_STANDARD_MAP');

            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, is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id,l_subject_standard_map_id,in_curriculum_type, in_grading_system ,in_standard_id,
                in_division_id,in_group_type, in_group_id, in_subject_id ,in_subject_type_id,in_subject_category_id,
              in_gradeset_mst_id, in_evaluation_type,in_subject_level,
              in_max_weekly_classes, in_credit_hours,in_is_mandatory, in_exam_type,in_is_book_based, 
              in_is_consecutive_preferred, in_is_system_def,in_is_active,in_created_by, in_created_by);

              if(in_subject_level=0)then

          		 set l_sub_struct_map_id = fn_sequence_generator('SUBJECT_STRUCTURE_MAP');
          		 
          			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,
                        is_active,created_by, updated_by) 
                      values(in_ay_id, in_inst_id,l_sub_struct_map_id ,l_subject_standard_map_id, in_curriculum_type ,in_grading_system,
                        in_standard_id, in_division_id, in_group_type, in_group_id,in_subject_id, l_sub_struct_map_id,  in_subject_level,
                        0, in_is_system_def,'Y', 'Y', 'Y', in_is_active,
                        in_created_by, in_created_by);
          			  
                end if;
         
              end;    
  
  	   when 'U' then
      set l_routine_block = 'update';      
          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;
  
          
            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, is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_sub_std_map_id,in_curriculum_type, in_grading_system ,in_standard_id,
                in_division_id,in_group_type, in_group_id, in_subject_id ,in_subject_type_id,in_subject_category_id,
              in_gradeset_mst_id, in_evaluation_type,in_subject_level,
              in_max_weekly_classes, in_credit_hours,in_is_mandatory, in_exam_type,in_is_book_based, 
              in_is_consecutive_preferred, 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_subject_structure_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_structure_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_struct_map_id` MEDIUMINT(8), IN `in_sub_std_map_id` MEDIUMINT(8), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_group_type` CHAR(3), IN `in_group_id` VARCHAR(10), IN `in_subject_id` MEDIUMINT(8), IN `in_parent_id` CHAR(6), IN `in_subject_level` TINYINT(2), IN `in_subject_pos` TINYINT(2), IN `in_is_system_def` TINYINT(1), IN `in_time_table_enabled` ENUM('Y','N','X'), IN `in_exam_enabled` ENUM('Y','N','X'), IN `in_homework_enabled` ENUM('Y','N','X'), 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_subject_structure_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_sub_struct_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_sub_struct_map_id = fn_sequence_generator('SUBJECT_STRUCTURE_MAP');
            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,
              is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id,l_sub_struct_map_id ,in_sub_std_map_id, in_curriculum_type ,in_grading_system,
              in_standard_id, in_division_id, in_group_type, in_group_id,in_subject_id, in_parent_id,  in_subject_level,
              in_subject_pos, is_system_def, in_time_table_enabled, in_exam_enabled, in_homework_enabled, in_is_active,
              in_created_by, in_created_by);
         if(in_subject_level=0)then
              	update  subject_structure_map set parent_id=l_sub_struct_map_id
            where   sub_struct_map_id = l_sub_struct_map_id   and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            end if;
          end;    
  	   when 'U' then
      set l_routine_block = 'update';      
          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;
          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,
              is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_sub_struct_map_id ,in_sub_std_map_id, in_curriculum_type ,in_grading_system,
              in_standard_id, in_division_id, in_group_type, in_group_id,in_subject_id, in_parent_id,  in_subject_level,
              in_subject_pos, is_system_def, in_time_table_enabled, in_exam_enabled, in_homework_enabled, in_is_active,
              in_created_by, in_created_by);
              
               if(in_subject_level=0)then

              	update  subject_structure_map set parent_id=in_sub_struct_map_id
            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;

            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_subject_syllabus_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_subject_syllabus_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_std_map_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_subject_syllabus_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 subject_syllabus_map(ay_id, inst_id, sub_sylbs_map_id, sub_std_map_id,
    sub_book_map_id, book_chpt_map_id, term_num, unit_number, start_date,target_date, completion_date, percent_complete,
    percent_update_date,status,status_desc,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 = 'subject_syllabus_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 = 'sub_sylbs_map_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('SUBJECT_SYLLABUS_MAP');
              end;
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('SUBJECT_SYLLABUS_MAP');
              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 subject_syllabus_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 sub_std_map_id = in_sub_std_map_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_substitute_lectures`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_substitute_lectures`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), 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_substitute_lectures';
  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_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO teacher_lecture_details(ay_id,
																		inst_id, 
																		emp_id,
																		extra_lecture_count,
																		missed_lecture_count	,
																	created_by, 
																		 updated_by
																		 ) VALUES';   
  declare l_insert_sql_str_mst text default 'INSERT INTO  substitute_lecture_details(ay_id,
																		inst_id, 
																		emp_id,
																		timetable_period_id,
                                    timetable_id,
    	                              timeslot_id,
																	  created_by,
																		updated_by,
                                  substitute_date,previous_emp_id
																		
																		
																		 ) VALUES'; 
  declare l_insert_val_str_part 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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'substitute_lecture_details' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'teacher_lecture_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;

  end case;

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

DROP PROCEDURE IF EXISTS `sp_ins_sub_module_notification_config_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_sub_module_notification_config_json`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_module_list` 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_sub_module_notification_config_json';
  declare l_routine_block varchar(50) default '00000';
  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_inst_id smallint(5) default 0;

  declare l_insert_sql_str text default 'INSERT INTO sub_module_notif_config(inst_id, module_name,module_display_name, 
    role_id, role_users, send, created_by, updated_by) VALUES'; 

  
  declare l_module_list text;

	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 = 'sub_module_notif_config' 
  order by col_pos;

 


  -- Cursor to get list of all inst
  declare cur_institution_master cursor for 
  select inst_id
  from institution_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, 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 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

         
          update sub_module_notif_config set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id 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_module_list!='') then
-- 
--           set l_module_list=REPLACE(in_module_list, '#', ',');
-- 
--           -- open cursor
-- 
--           open cur_institution_master;
-- 
--           cursor_loop_new: loop
--            fetch cur_institution_master into l_inst_id;
--                if l_looping_done then
--                    leave cursor_loop_new;
--                end if;
-- 
--             update sub_module_notif_config set valid_to = now(), updated_by = in_created_by, 
--                         updated_on = now(), is_deleted = 1 
--                       where inst_id = l_inst_id and is_deleted = 0 and module_name IN (l_module_list);
-- 
--               INSERT INTO sub_module_notif_config(inst_id, module_name,module_display_name,
--                 role_id, role_users, send, created_by, is_active)
--                  select l_inst_id, module_name,module_display_name,role_id, role_users, send, created_by, is_active
--                  from sub_module_notif_config where inst_id = 0 and module_name IN (l_module_list)
--                  and is_deleted = 0 and is_active=1;
-- 
--              end loop;
--           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_sub_teacher_workload_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_sub_teacher_workload_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), 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_sub_teacher_workload_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default ''; 
  declare l_teacher_load_id mediumint(8);   
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO weekly_teacher_work_load(ay_id,
																		inst_id, 
																		emp_id,
																		class_id,
																		sub_struct_map_id,
																		weekly_teacher_load,
																		 created_by, 
																		 updated_by,
                                     shift_type,load_start_date,load_end_date,standard_id,workload_mst_id
																		
																		 ) VALUES';   
  declare l_insert_sql_str_mst text default 'INSERT INTO teacher_work_load(ay_id,
																		inst_id, 
																		emp_id,
																		weekly_teacher_load,
																		created_by,
																		updated_by,
    	                              load_start_date,
    	                              load_end_date,
																		shift_type,workload_mst_id
																		
																		 ) VALUES'; 
																		 
 
  declare l_insert_val_str_part 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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'teacher_work_load' 
  order by col_pos;
  
  
  
  
   declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'weekly_teacher_work_load' 
  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 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;
	  
	      when 'B' 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  and attendance_status = 'A'  and stud_att_upload_type = 'MANUAL'  ;

          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;
	  
	   when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : 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;
                   
          

          set l_routine_block = 'Mode D : 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 D : after insert';
        commit;
      end;

      when 'E' 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 student_id = in_student_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_teacher_workload_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_teacher_workload_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), 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_subject_teacher_workload_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default ''; 
  declare l_teacher_load_id mediumint(8);   
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO weekly_teacher_work_load(ay_id,
																		inst_id, 
																		emp_id,
																		class_id,
																		sub_struct_map_id,
																		weekly_teacher_load,
																		 created_by, 
																		 updated_by,
                                     shift_type,load_start_date,load_end_date,standard_id
																		
																		 ) VALUES';   
  declare l_insert_sql_str_mst text default 'INSERT INTO teacher_work_load(ay_id,
																		inst_id, 
																		emp_id,
																		weekly_teacher_load,
																		created_by,
																		updated_by,
    	                              load_start_date,
    	                              load_end_date,
																		shift_type
																		
																		 ) VALUES'; 
																		 
 
  declare l_insert_val_str_part 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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'teacher_work_load' 
  order by col_pos;
  
  
  
  
   declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'weekly_teacher_work_load' 
  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 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;
	  
	      when 'B' 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  and attendance_status = 'A'  and stud_att_upload_type = 'MANUAL'  ;

          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;
	  
	   when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : 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;
                   
          

          set l_routine_block = 'Mode D : 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 D : after insert';
        commit;
      end;

      when 'E' 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 student_id = in_student_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_timeslot_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_timeslot_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_timeslot_id` VARCHAR(25), IN `in_shift_type` VARCHAR(15), IN `in_class_group_type` VARCHAR(25), IN `in_timeslot_type` VARCHAR(10), IN `in_timeslot_from` TIME, IN `in_timeslot_to` TIME, IN `in_timeslot_valid_from` TIMESTAMP, IN `in_timeslot_valid_to` TIMESTAMP, IN `in_timeslot_status` VARCHAR(25), IN `in_initiator_comments` VARCHAR(50), IN `in_approved_by` TIMESTAMP, IN `in_approved_on` DATE, IN `in_approver_comments` VARCHAR(50), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_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;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  timeslot_master(ay_id, inst_id,timeslot_id,shift_type,class_group_type,timeslot_type,timeslot_from,timeslot_to,timeslot_valid_from,
                         timeslot_valid_to,timeslot_status,initiator_comments,approved_by,approved_on,approver_comments,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_timeslot_id,in_shift_type,in_class_group_type,in_timeslot_type,in_timeslot_from,in_timeslot_to,in_timeslot_valid_from,
                   in_timeslot_valid_to,in_timeslot_status,in_initiator_comments,in_approved_by,in_approved_on,in_approver_comments,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          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;
           insert into  timeslot_master(ay_id, inst_id,timeslot_id,shift_type,class_group_type,timeslot_type,timeslot_from,timeslot_to,timeslot_valid_from,
                         timeslot_valid_to,timeslot_status,initiator_comments,approved_by,approved_on,approver_comments,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_timeslot_id,in_shift_type,in_class_group_type,in_timeslot_type,in_timeslot_from,in_timeslot_to,in_timeslot_valid_from,
                   in_timeslot_valid_to,in_timeslot_status,in_initiator_comments,in_approved_by,in_approved_on,in_approver_comments,in_created_by, in_created_by);
     end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_timetable_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_timetable_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `class_id` VARCHAR(25), IN `in_timetable_id` VARCHAR(25), IN `in_shift_type` VARCHAR(15), IN `in_class_group_type` VARCHAR(25), IN `in_timetable_title` VARCHAR(25), IN `in_timetable_desc` VARCHAR(25), IN `in_timetable_valid_from` TIMESTAMP, IN `in_timetable_valid_to` TIMESTAMP, IN `in_timetable_status` VARCHAR(25), IN `in_initiator_comments` VARCHAR(50), IN `in_approved_by` VARCHAR(25), IN `in_approved_on` DATE, IN `in_approver_comments` VARCHAR(50), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_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;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  timetable_master(ay_id, inst_id,class_id,timetable_id, inst_id,shift_type,class_group_type,timetable_title, 
               	       timetable_desc,timetable_valid_from,timetable_valid_to,timetable_status,initiator_comments,approved_by,approved_on,
                       approver_comments,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_class_id,in_timetable_id, in_inst_id,in_shift_type,in_class_group_type,in_timetable_title, 
               	  in_timetable_desc,in_timetable_valid_from,in_timetable_valid_to,in_timetable_status,in_initiator_comments,in_approved_by,in_approved_on, 
                  in_approver_comments,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          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;
           insert into  timetable_master(ay_id, inst_id,class_id,timetable_id, inst_id,shift_type,class_group_type,timetable_title, 
               	       timetable_desc,timetable_valid_from,timetable_valid_to,timetable_status,initiator_comments,approved_by,approved_on,
                       approver_comments,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_class_id,in_timetable_id, in_inst_id,in_shift_type,in_class_group_type,in_timetable_title, 
               	  in_timetable_desc,in_timetable_valid_from,in_timetable_valid_to,in_timetable_status,in_initiator_comments,in_approved_by,in_approved_on, 
                  in_approver_comments,in_created_by, in_created_by);
     end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_timetable_period_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_timetable_period_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), 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_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_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;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  timetable_period_map(ay_id, inst_id,timetable_period_id, timetable_id,timeslot_id,weekday_id,subject_id, 
               	emp_id,created_by, updated_by) 
            values(in_ay_id,in_inst_id,in_timetable_period_id, in_timetable_id,in_timeslot_id,in_weekday_id,in_subject_id, 
               	in_emp_id,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          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  is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into  timetable_period_map(ay_id, inst_id,timetable_period_id, timetable_id,timeslot_id,weekday_id,subject_id, 
               	emp_id,created_by, updated_by) 
            values(in_ay_id,in_inst_id,in_timetable_period_id, in_timetable_id,in_timeslot_id,in_weekday_id,in_subject_id, 
               	in_emp_id,in_created_by, in_created_by);
     end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_timetable_teacher_workload_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_timetable_teacher_workload_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), 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_workload_mst_id` MEDIUMINT(8), 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_timetable_teacher_workload_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default ''; 
  declare l_teacher_load_id mediumint(8);   
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO weekly_teacher_work_load(ay_id,
																		inst_id, 
																		emp_id,
																		class_id,
																		sub_struct_map_id,
																		weekly_teacher_load,
																		 created_by, 
																		 updated_by,
                                     shift_type,load_start_date,load_end_date,standard_id
																		
																		 ) VALUES';   
  declare l_insert_sql_str_mst text default 'INSERT INTO teacher_work_load(ay_id,
																		inst_id, 
																		emp_id,
																		weekly_teacher_load,
																		created_by,
																		updated_by,
    	                              load_start_date,
    	                              load_end_date,
																		shift_type
																		
																		 ) VALUES'; 
																		 
 
  declare l_insert_val_str_part 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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'teacher_work_load' 
  order by col_pos;
  
  
  
  
   declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'weekly_teacher_work_load' 
  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';



            update  teacher_work_load set updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where workload_mst_id=in_workload_mst_id  
              and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;

             update  weekly_teacher_work_load set updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where workload_mst_id=in_workload_mst_id  
              and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;

      
          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 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;
	  
	      when 'B' 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  and attendance_status = 'A'  and stud_att_upload_type = 'MANUAL'  ;

          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;
	  
	   when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : 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;
                   
          

          set l_routine_block = 'Mode D : 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 D : after insert';
        commit;
      end;

      when 'E' 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 student_id = in_student_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_timetble_subject_load_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_timetble_subject_load_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_load_start_date` DATE, IN `in_sub_load_end_date` DATE, IN `in_standard_id` CHAR(2), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_workload_mst_id` MEDIUMINT(8), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_timetble_subject_load_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 weekly_subject_load(ay_id,
																		inst_id, 
																		standard_id,
    
																		sub_struct_map_id,
																		weekly_subject_load,
																		total_weekly_sub_load,
																		created_by, 
																		updated_by,
																		sub_load_start_date,
																		sub_load_end_date,class_id,shift_type) 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 = 'weekly_subject_load' 
  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';
update weekly_subject_load set is_deleted =1, updated_by = in_created_by, 
                    updated_on = now()
              where ay_id = in_ay_id and inst_id = in_inst_id and workload_mst_id = in_workload_mst_id
               ;

              call sp_execute_immediate (l_insert_sql_str); 
              update timetable_master set valid_to = now(), updated_by = in_created_by, 
                    updated_on = now(), 	status = '11'
              where ay_id = in_ay_id and inst_id = in_inst_id and timetable_valid_from = in_sub_load_start_date
                    and timetable_valid_to=in_sub_load_end_date and is_deleted = 0 and standard_id=in_standard_id;


              
                  
        commit;
      end;

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

         
         update student_leave_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 leave_id = in_leave_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_time_table_mgmt_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_time_table_mgmt_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_timetable_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)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_time_table_mgmt_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 timetable_period_map (ay_id, inst_id, timetable_period_id, 
    timetable_id, timeslot_id, weekday_id, sub_std_map_id, emp_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 = 'timetable_period_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 = 'timetable_period_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('TIMETABLE_PERIOD_MAP');
              end;
            when 'U' then
              begin
                set l_template_col_value = fn_sequence_generator('TIMETABLE_PERIOD_MAP');
              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 timetable_period_map set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and timetable_id=in_timetable_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_time_table_slots_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_time_table_slots_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_timeslot_mst_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)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_time_table_slots_details_json';
  declare l_routine_block varchar(15) default '';
  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_timeslot_mst_id int;

  declare l_insert_sql_str text default 'INSERT INTO timeslot_details (ay_id, inst_id, timeslot_mst_id,
    template_name, weekday, period_no, type, units, duration, time_from, time_to, 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 = 'timeslot_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);

  set l_timeslot_mst_id = fn_sequence_generator('TIMESLOT_DETAILS');

  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 = 'timeslot_mst_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_timeslot_mst_id;
              end;
               when 'U' then
              begin
                set l_template_col_value = in_timeslot_mst_id;
              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 timeslot_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and timeslot_mst_id=in_timeslot_mst_id 
          and is_deleted = 0 and ay_id=in_ay_id ;
                                      
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;

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

         update timeslot_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and timeslot_mst_id=in_timeslot_mst_id 
          and is_deleted = 0 and ay_id=in_ay_id ;
                     
        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_trans_gps_device_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_trans_gps_device_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_device_id` MEDIUMINT(8), IN `in_device_name` VARCHAR(20), IN `in_model_number` BIGINT(20), IN `in_description` VARCHAR(100), IN `in_imei_number` VARCHAR(50), IN `in_sim_number` VARCHAR(15), IN `in_product_dimension` VARCHAR(50), IN `in_batteries_included` 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)
BEGIN
	declare l_routine_name varchar(50) default '`sp_ins_trans_gps_device_master`';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_device_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_device_id = fn_sequence_generator('TRANS_GPS_DEVICE_MASTER');

            insert into  trans_gps_device_master(inst_id, device_id, device_name, model_number, description, 
              imei_number, sim_number, product_dimension, batteries_included,
              is_active,created_by, updated_by) 
            values(in_inst_id, l_device_id, in_device_name, in_model_number, in_description, in_imei_number, 
              in_sim_number, in_product_dimension, in_batteries_included,
              in_is_active,in_created_by, in_created_by);
            
         
          end;    
  
  	   when 'U' then
      set l_routine_block = 'update';      
          begin
          	update  trans_gps_device_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where device_id = in_device_id   and is_deleted = 0 
            	and inst_id = in_inst_id;
  
            
          insert into  trans_gps_device_master(inst_id, device_id, device_name, model_number, description, 
              imei_number, sim_number, product_dimension, batteries_included,
              is_active,created_by, updated_by) 
            values(in_inst_id, in_device_id, in_device_name, in_model_number, in_description, in_imei_number, 
              in_sim_number, in_product_dimension, in_batteries_included,
              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_trans_route_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_trans_route_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_route_id` MEDIUMINT(8), IN `in_route_name` VARCHAR(100), IN `in_route_code` VARCHAR(25), IN `in_description` VARCHAR(100), IN `in_start_point` VARCHAR(20), IN `in_end_point` VARCHAR(20), IN `in_vehicle_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_trans_route_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_route_id varchar(15);
  declare l_routine_block 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_route_id = fn_sequence_generator('TRANS_ROUTE_MASTER');

            insert into  trans_route_master(
              inst_id,route_id,route_name,
              route_code,description,start_point,
             end_point ,vehicle_id,is_active,created_by 
              ) 
            values(
              in_inst_id,l_route_id,in_route_name, 
              in_route_code,in_description,in_start_point,
              in_end_point,in_vehicle_id,
               in_is_active,in_created_by);
            
          end;    
  
  	    when 'U' then
      set l_routine_block = 'update';      
          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;

           insert into  trans_route_master(
             inst_id, route_id, route_name,
              route_code, description, start_point,
             end_point ,vehicle_id,is_active,created_by 
              ) 
            values(
              in_inst_id,in_route_id,in_route_name,
              in_route_code,in_description,in_start_point,
              in_end_point,in_vehicle_id,in_is_active,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_trans_route_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_trans_route_master_json`(IN `in_dml_mode` CHAR(1), 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)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_trans_route_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 trans_route_master(inst_id,route_id,
    route_name, route_code, description,start_point,end_point,vehicle_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 = 'trans_route_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_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 = 'route_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('TRANS_ROUTE_MASTER');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('TRANS_ROUTE_MASTER');
               -- 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 = '' 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_trans_stop_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_trans_stop_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stop_id` MEDIUMINT(8), IN `in_stop_name` VARCHAR(150), IN `in_stop_address` VARCHAR(100), IN `in_description` VARCHAR(100), IN `in_longitude` MEDIUMINT(8), IN `in_latitude` MEDIUMINT(8), IN `in_pickup_charges` DOUBLE(10,2), IN `in_pickup_charges_tax` DOUBLE(10,2), IN `in_drop_charges` DOUBLE(10,2), IN `in_drop_charges_tax` DOUBLE(10,2), IN `in_both_way_charges` DOUBLE(10,2), IN `in_both_way_charges_tax` DOUBLE(10,2), IN `in_total_fee_amt` DOUBLE(10,2), IN `in_distance_from_school` DOUBLE(10,2), IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_stop_id` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_trans_stop_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_stop_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_stop_id  = fn_sequence_generator('TRANS_STOP_MASTER');

          set out_stop_id=l_stop_id;

           insert into  trans_stop_master(
             inst_id, stop_id, stop_name, stop_address, description, longitude, latitude,distance_from_school, created_by,updated_by)  
            values(
                 in_inst_id, l_stop_id, in_stop_name, in_stop_address, in_description, in_longitude, in_latitude, in_distance_from_school,
              in_created_by,in_created_by);

            INSERT INTO trans_fee_struct_master(ay_id, inst_id, stop_id, pickup_charges, pickup_charges_tax, 
              drop_charges, drop_charges_tax, both_way_charges, both_way_charges_tax, total_fee_amt,
              created_by, updated_by, is_active)
            VALUES (in_ay_id, in_inst_id, l_stop_id, in_pickup_charges, in_pickup_charges_tax, 
              in_drop_charges, in_drop_charges_tax, in_both_way_charges, in_both_way_charges_tax, in_total_fee_amt, 
              in_created_by, in_created_by, in_is_active);
            
          end;    
  
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update  trans_stop_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where stop_id=in_stop_id  
              and is_deleted = 0 
            	and inst_id = in_inst_id;

          set out_stop_id=in_stop_id;

           insert into  trans_stop_master(
             inst_id, stop_id, stop_name, stop_address, description, longitude, latitude, distance_from_school,
              created_by,updated_by)  
            values(
                 in_inst_id, in_stop_id, in_stop_name, in_stop_address, in_description, in_longitude, in_latitude, 
              in_distance_from_school,in_created_by,in_created_by);

          update  trans_fee_struct_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where stop_id=in_stop_id  
              and is_deleted = 0 
            	and inst_id = in_inst_id and ay_id=in_ay_id;

          INSERT INTO trans_fee_struct_master(ay_id, inst_id, stop_id, pickup_charges, pickup_charges_tax, 
              drop_charges, drop_charges_tax, both_way_charges, both_way_charges_tax, total_fee_amt, 
              created_by, updated_by, is_active)
            VALUES (in_ay_id, in_inst_id, in_stop_id, in_pickup_charges, in_pickup_charges_tax, 
              in_drop_charges, in_drop_charges_tax, in_both_way_charges, in_both_way_charges_tax, in_total_fee_amt, 
              in_created_by, in_created_by, in_is_active
              );
            


          end;    
      

    when 'D' then
      set l_routine_block = 'delete';      
          begin
          	update  trans_stop_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where stop_id=in_stop_id  
              and is_deleted = 0 
            	and inst_id = in_inst_id;

          set out_stop_id=in_stop_id;


          update  trans_fee_struct_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where stop_id=in_stop_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_trans_vehicle_driver_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_trans_vehicle_driver_map`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_vehicle_driver_map_id` MEDIUMINT(8), IN `in_vehicle_id` MEDIUMINT(8), IN `in_driver_emp_id` MEDIUMINT(8), IN `in_attendant_emp_id` MEDIUMINT(8), IN `in_is_temporary` TINYINT(1), IN `in_temporary_from_date` DATE, IN `in_temporary_to_date` DATE, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_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 l_vehicle_driver_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_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_vehicle_driver_map_id	 = fn_sequence_generator('TRANS_VEHICLE_DRIVER_MAP');

            insert into  trans_vehicle_driver_map(
						 inst_id,vehicle_driver_map_id,vehicle_id,driver_emp_id,attendant_emp_id,is_temporary,
						 temporary_from_date,temporary_to_date,
             created_by, updated_by)  
					  values(
						 in_inst_id,l_vehicle_driver_map_id,in_vehicle_id,in_driver_emp_id,in_attendant_emp_id,in_is_temporary,
						 in_temporary_from_date,in_temporary_to_date,
             in_created_by, in_created_by);
            
          end;    
  
  	    when 'U' then
      set l_routine_block = 'update';      
          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;

          insert into  trans_vehicle_driver_map(
						 inst_id,vehicle_driver_map_id,vehicle_id,driver_emp_id,attendant_emp_id,is_temporary,
						 temporary_from_date,temporary_to_date,
             created_by, updated_by)  
					  values(
						 in_inst_id,in_vehicle_driver_map_id,in_vehicle_id,in_driver_emp_id,in_attendant_emp_id,in_is_temporary,
						 in_temporary_from_date,in_temporary_to_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;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_trans_vehicle_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_trans_vehicle_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_vehicle_id` MEDIUMINT(8), IN `in_vehicle_name` VARCHAR(25), IN `in_vehicle_code` VARCHAR(25), IN `in_type` VARCHAR(20), IN `in_description` VARCHAR(100), IN `in_seat_capacity` VARCHAR(15), IN `in_is_standing_allowed` VARCHAR(15), IN `in_standing_capacity` VARCHAR(15), IN `in_total_capacity` VARCHAR(15), IN `in_ownership` VARCHAR(15), IN `in_vendor_emp_id` MEDIUMINT(8), IN `in_registration_number` VARCHAR(25), IN `in_registration_date` DATE, IN `in_registration_expiry_date` DATE, IN `in_year_of_manufacture` CHAR(7), IN `in_has_accident_history` TINYINT(1), IN `in_insurance_details` VARCHAR(100), IN `in_insurance_expiry_date` DATE, IN `in_puc_expiry_date` DATE, IN `in_fuel_type` VARCHAR(20),IN `in_is_gps_enabled` TINYINT(1),  IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default '`sp_ins_trans_vehicle_master`';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_vehicle_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_vehicle_id  = fn_sequence_generator('TRANS_VEHICLE_MASTER');

            insert into  trans_vehicle_master(
             inst_id,vehicle_id,vehicle_name,vehicle_code,type,description,seat_capacity,is_standing_allowed,
						 standing_capacity,total_capacity,ownership,vendor_emp_id,registration_number,registration_date,
              registration_expiry_date,year_of_manufacture,has_accident_history,insurance_details,
              insurance_expiry_date,puc_expiry_date,fuel_type,created_by,updated_by)  
            values(
                 in_inst_id,l_vehicle_id,in_vehicle_name,in_vehicle_code,in_type,in_description,in_seat_capacity,
              in_is_standing_allowed,in_standing_capacity,in_total_capacity,in_ownership,in_vendor_emp_id,
              in_registration_number,in_registration_date,in_registration_expiry_date,
              in_year_of_manufacture,in_has_accident_history,in_insurance_details,
              in_insurance_expiry_date,in_puc_expiry_date,in_fuel_type,in_created_by,in_created_by);
            
          end;    
  
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update  trans_vehicle_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where vehicle_id=in_vehicle_id  
              and is_deleted = 0 
            	and inst_id = in_inst_id;


            insert into  trans_vehicle_master(
             inst_id,vehicle_id,vehicle_name,vehicle_code,type,description,seat_capacity,is_standing_allowed,
						 standing_capacity,total_capacity,ownership,vendor_emp_id,registration_number,registration_date,
              registration_expiry_date,year_of_manufacture,has_accident_history,insurance_details,
              insurance_expiry_date,puc_expiry_date,fuel_type,is_gps_enabled,created_by,updated_by)  
            values(
                 in_inst_id,in_vehicle_id,in_vehicle_name,in_vehicle_code,in_type,in_description,in_seat_capacity,
              in_is_standing_allowed,in_standing_capacity,in_total_capacity,in_ownership,in_vendor_emp_id,
              in_registration_number,in_registration_date,in_registration_expiry_date,
              in_year_of_manufacture,in_has_accident_history,in_insurance_details,
              in_insurance_expiry_date,in_puc_expiry_date,in_fuel_type,in_is_gps_enabled,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_txn_alert_config_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_txn_alert_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_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_txn_alert_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 txn_alert_config(ay_id, inst_id, txn_id, is_app_enabled, app_reminder_count, 
    is_email_enabled, email_reminder_count, is_portal_enabled,portal_reminder_count, is_sms_enabled, sms_reminder_count, 
    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 = 'txn_alert_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';
    #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 txn_alert_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 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_update_emp_RFID_code`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_update_emp_RFID_code`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_device_reg_id` VARCHAR(20), IN `in_user_id` MEDIUMINT(8), IN `in_user_type` VARCHAR(20), IN `in_RFID_code` VARCHAR(200), 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_update_emp_RFID_code';
  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_balance bigint(50);
  declare l_sms_balance bigint(50);
  declare l_inst_count 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 l_routine_block = 'insert';

            insert into sms_credit_history(inst_id,sms_credit_no,rate,amount,bank_account_no,
                        bank_name,credit_date,is_active,created_by,updated_by) 
            values(
                        in_inst_id,in_sms_credit_no,in_rate,in_amount,in_bank_account_no,in_bank_name,
                        in_credit_date,in_is_active,in_created_by,in_created_by);
            
          end;    
  
  	    when 'U' then
        set l_routine_block = 'update';      
          begin
            
                 update  user_device_map set valid_to = NOW(), updated_by = in_created_by, 
                        updated_on = NOW(), is_deleted = 1  AND inst_id=in_inst_id
                 where  is_deleted = 0 and inst_id = in_inst_id AND user_id=in_user_id;

                 insert into user_device_map(ay_id,inst_id,device_reg_id,user_id,user_type,
                        RFID_code,is_active,created_by,updated_by) 
                 values(
                        in_ay_id,in_inst_id,in_device_reg_id,in_user_id,in_user_type,in_RFID_code,
                        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_update_order_fulfil_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_update_order_fulfil_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_name` VARCHAR(100), IN `in_order_desc` VARCHAR(20), IN `in_order_status` VARCHAR(20), IN `in_fulfil_status` VARCHAR(20), IN `in_order_date` DATE, IN `in_total_amount` BIGINT(50), 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_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_update_order_fulfil_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_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, order_name, 
              order_desc, order_date,order_status,fulfil_status,created_by, updated_by, is_active) 
              VALUES (in_ay_id, in_inst_id, l_order_master_id, in_order_name, 
              in_order_desc, in_order_date,in_order_status,in_fulfil_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 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;

          INSERT INTO inventory_order_master(ay_id, inst_id, order_master_id,inventory_dept_id,
              order_name,order_desc, order_date,total_amount,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_order_date, in_total_amount,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_update_sms_credit_rate`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_update_sms_credit_rate`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_rate` BIGINT(30), 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_update_sms_credit_rate';
  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_balance bigint(50);
  declare l_sms_balance bigint(50);
  declare l_inst_count 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 l_routine_block = 'insert';

            insert into sms_credit_history(inst_id,sms_credit_no,rate,amount,bank_account_no,
                        bank_name,credit_date,is_active,created_by,updated_by) 
            values(
                        in_inst_id,in_sms_credit_no,in_rate,in_amount,in_bank_account_no,in_bank_name,
                        in_credit_date,in_is_active,in_created_by,in_created_by);
            
          end;    
  
  	    when 'U' then
        set l_routine_block = 'update';      
          begin
            
             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
                  insert into  sms_credit_status(
                              inst_id,rate,is_active,created_by,updated_by) 
                  values(in_inst_id,in_rate,in_is_active,in_created_by,in_created_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 ;

                 update  sms_credit_status 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;

                 insert into  sms_credit_status(inst_id,rate,sms_credit_balance,is_active,created_by,updated_by) 
                 values(in_inst_id,in_rate,l_sms_balance,in_is_active,in_created_by,in_created_by);
              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_update_stud_RFID_code`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_update_stud_RFID_code`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_device_reg_id` VARCHAR(20), IN `in_user_id` MEDIUMINT(8), IN `in_user_type` VARCHAR(20), IN `in_RFID_code` VARCHAR(200), 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_update_stud_RFID_code';
  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_balance bigint(50);
  declare l_sms_balance bigint(50);
  declare l_inst_count 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 l_routine_block = 'insert';

            insert into sms_credit_history(inst_id,sms_credit_no,rate,amount,bank_account_no,
                        bank_name,credit_date,is_active,created_by,updated_by) 
            values(
                        in_inst_id,in_sms_credit_no,in_rate,in_amount,in_bank_account_no,in_bank_name,
                        in_credit_date,in_is_active,in_created_by,in_created_by);
            
          end;    
  
  	    when 'U' then
        set l_routine_block = 'update';      
          begin
            
                 update  user_device_map set valid_to = NOW(), updated_by = in_created_by, 
                        updated_on = NOW(), is_deleted = 1  AND inst_id=in_inst_id
                 where  is_deleted = 0 and inst_id = in_inst_id AND user_id=in_user_id;

                 insert into user_device_map(ay_id,inst_id,device_reg_id,user_id,user_type,
                        RFID_code,is_active,created_by,updated_by) 
                 values(
                        in_ay_id,in_inst_id,in_device_reg_id,in_user_id,in_user_type,in_RFID_code,
                        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_user_entitlements_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_user_entitlements_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_user_type` CHAR(3), IN `in_user_id` MEDIUMINT(8), IN `in_role_id` MEDIUMINT(5),IN `in_insert_row_count` MEDIUMINT(5), 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_user_entitlements_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 MEDIUMINT(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 text default 'INSERT INTO user_entitlements(ay_id, inst_id, user_id, txn_id, 
    is_create_allowed, is_read_allowed,is_update_allowed, is_delete_allowed, create_auth_type, 
    update_auth_type , delete_auth_type, is_active, created_by, updated_by ,user_type, role_id, is_user_specific) 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_entitlements' 
  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 user_entitlements set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_id and user_type=in_user_type  and user_id = in_user_id  AND role_id=in_role_id
            and is_deleted = 0 and is_active=1;
          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_user_management_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_user_management_json`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` MEDIUMINT(8), IN `in_insert_row_count` INT, 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_user_management_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';
  
  declare l_user_id mediumint(8);

  declare l_json_str MEDIUMTEXT;
  declare l_json_str_len int;
  declare l_json_substr MEDIUMTEXT;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len INT 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;
  
  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 MEDIUMTEXT default 'INSERT INTO user_management(inst_id, user_id, user_group_id,user_group_name,
    mobile_phone, salutation, first_name, middle_name, last_name, column_1, column_2, column_3, column_4,
    column_5, column_6, column_7, column_8, column_9, column_10, is_active,created_by, updated_by) VALUES'; 

	declare l_insert_val_str_part MEDIUMTEXT;
	declare l_insert_val_str_full MEDIUMTEXT;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'user_management' 
  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 
        ('2016-17', 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_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
				        set l_template_col_value = fn_sequence_generator('USER_MANAGEMENT');
              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;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_user_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_user_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_user_type` VARCHAR(15), IN `in_user_id` MEDIUMINT(8), IN `in_role_id` VARCHAR(100), IN `in_login_name` VARCHAR(50), IN `in_password` VARCHAR(60), IN `in_api_token` VARCHAR(100), IN `in_remember_token` VARCHAR(100), IN `in_is_web_enabled` TINYINT(1), IN `in_is_app_enabled` TINYINT(1), IN `in_reset_pwd_hint` VARCHAR(50), IN `in_reset_pwd_ans` VARCHAR(20), IN `in_pwd_valid_from` TIMESTAMP, IN `in_pwd_valid_to` TIMESTAMP, IN `in_last_successful_login` TIMESTAMP, IN `in_last_failed_login` TIMESTAMP, IN `in_failed_login_attempts` TINYINT(1), IN `in_force_change_pwd_flag` TINYINT(1), IN `in_is_locked` TINYINT(1), IN `in_lock_reason` VARCHAR(50), IN `in_is_active` TINYINT(1), IN `in_is_token_verified` 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_user_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(15);
  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(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_user_master';
            set l_user_id =fn_sequence_generator('USER_MASTER');
            insert into   user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,password,api_token,remember_token, 
                      is_web_enabled,is_app_enabled,reset_pwd_hint,reset_pwd_ans,pwd_valid_from,
                      pwd_valid_to,last_successful_login, last_failed_login,failed_login_attempts,force_change_pwd_flag,
                 is_locked,lock_reason,is_active,is_token_verified,created_by, updated_by) 
            values(in_ay_id,in_inst_id,l_user_id, in_user_type, in_role_id,in_login_name,in_password,in_api_token,in_remember_token, 
                    in_is_web_enabled,in_is_app_enabled,in_reset_pwd_hint,in_reset_pwd_ans,in_pwd_valid_from,
                    in_pwd_valid_to,in_last_successful_login, in_last_failed_login,in_failed_login_attempts,in_force_change_pwd_flag,
                    in_is_locked,in_lock_reason,in_is_active,in_is_token_verified,in_created_by, in_created_by);
				CALL `sp_ins_user_role_map`('U', in_inst_id, in_user_type, l_user_id, in_role_id, in_created_by, l_err_code, l_err_desc);
                
                if(in_role_id != 21 AND in_role_id != 22)then
				    CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, in_user_type, l_user_id, in_created_by, l_err_code, l_err_desc);
                end if;
                
                 IF ( in_user_type ='STU') THEN 
            update  student_master set is_active=in_is_active where student_id = l_user_id   and is_deleted = '0' and inst_id = in_inst_id;                   
       ELSEIF ( in_user_type ='EMP') THEN             
            update  employee_master set is_active=in_is_active where emp_id = l_user_id   and is_deleted = '0' and inst_id = in_inst_id;                
       ELSEIF ( in_user_type ='PAR') THEN 
            update  parent_master set is_active=in_is_active where parent_id = l_user_id   and is_deleted = '0' and inst_id = in_inst_id;                  
       END IF;
       
          end;    
        when 'U' then
       set l_routine_block = 'update_user_master';  
          begin
            update    user_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where   user_id=in_user_id and role_id=in_role_id and is_deleted = 0 and ay_id = in_ay_id 
                and inst_id = in_inst_id;
         	insert into   user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,password,api_token,remember_token, 
                      is_web_enabled,is_app_enabled,reset_pwd_hint,reset_pwd_ans,pwd_valid_from,
                      pwd_valid_to,last_successful_login, last_failed_login,failed_login_attempts,force_change_pwd_flag,
                 is_locked,lock_reason,is_active,is_token_verified,created_by, updated_by) 
            values(in_ay_id,in_inst_id,in_user_id, in_user_type, in_role_id,in_login_name,in_password,in_api_token,in_remember_token, 
                    in_is_web_enabled,in_is_app_enabled,in_reset_pwd_hint,in_reset_pwd_ans,in_pwd_valid_from,
                    in_pwd_valid_to,in_last_successful_login, in_last_failed_login,in_failed_login_attempts,in_force_change_pwd_flag,
                    in_is_locked,in_lock_reason,in_is_active,in_is_token_verified,in_created_by, in_created_by);
            CALL `sp_ins_user_role_map`('U', in_inst_id, in_user_type, in_user_id, in_role_id, in_created_by, l_err_code, l_err_desc);
            
           if(in_role_id != 21 AND in_role_id != 22)then
                CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, in_user_type, in_user_id, in_created_by, l_err_code, l_err_desc);
          end if;
            
             IF ( in_user_type ='STU') THEN 
            update  student_master set is_active=in_is_active where student_id = in_user_id   and is_deleted = '0' and inst_id = in_inst_id;                   
       ELSEIF ( in_user_type ='EMP') THEN             
            update  employee_master set is_active=in_is_active where emp_id = in_user_id   and is_deleted = '0' and inst_id = in_inst_id;                
       ELSEIF ( in_user_type ='PAR') THEN 
            update  parent_master set is_active=in_is_active where parent_id = in_user_id   and is_deleted = '0' and inst_id = in_inst_id;                  
       END IF;
     end;    
       when 'E' then
        set l_routine_block = 'update_user_master_employee_student_parent';  
          begin
             set     l_user_id=0;
        select user_id INTO l_user_id FROM user_master where user_type=in_user_type and user_id=in_user_id and inst_id=in_inst_id and is_deleted = '0' ;
          IF l_user_id=0 THEN 
             insert into   user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,password,api_token,remember_token, is_web_enabled,is_app_enabled,reset_pwd_hint,reset_pwd_ans,pwd_valid_from,pwd_valid_to,last_successful_login, last_failed_login,failed_login_attempts,force_change_pwd_flag,is_locked,lock_reason,is_active,is_token_verified,created_by, updated_by)  
				 values(in_ay_id,in_inst_id,in_user_id, in_user_type, in_role_id,in_login_name,in_password,in_api_token,in_remember_token, in_is_web_enabled,in_is_app_enabled,in_reset_pwd_hint,in_reset_pwd_ans,in_pwd_valid_from,in_pwd_valid_to,in_last_successful_login, in_last_failed_login,in_failed_login_attempts,in_force_change_pwd_flag,in_is_locked,in_lock_reason,in_is_active,in_is_token_verified,in_created_by, in_created_by);
          ELSE
	            update user_master set role_id=in_role_id,is_web_enabled=in_is_web_enabled,is_app_enabled=in_is_app_enabled,is_active=in_is_active  where  user_id=in_user_id and user_type=in_user_type and is_deleted = '0' and inst_id = in_inst_id;
          END IF;
			 CALL `sp_ins_user_role_map`('U', in_inst_id, in_user_type, in_user_id, in_role_id, in_created_by, l_err_code, l_err_desc);			 
             
            if(in_role_id != 21 AND in_role_id != 22)then
			    CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, in_user_type, in_user_id, in_created_by, l_err_code, l_err_desc);
                end if;
           
            
             IF ( in_user_type ='STU') THEN 
            update  student_master set is_active=in_is_active where student_id = in_user_id   and is_deleted = '0' and inst_id = in_inst_id;                   
       ELSEIF ( in_user_type ='EMP') THEN             
            update  employee_master set is_active=in_is_active where emp_id = in_user_id   and is_deleted = '0' and inst_id = in_inst_id;                
       ELSEIF ( in_user_type ='PAR') THEN 
            update  parent_master set is_active=in_is_active where parent_id = in_user_id   and is_deleted = '0' and inst_id = in_inst_id;                  
       END IF;
     end;   
     
     --     Case S used for Global School Enrollment
           when 'S' then
        set l_routine_block = 'update_user_master_employee_student_parent';  
          begin
             set     l_user_id=0;
        select user_id INTO l_user_id FROM user_master where user_type=in_user_type and user_id=in_user_id and inst_id=in_inst_id and is_deleted = '0' ;
          IF l_user_id=0 THEN 
             insert into   user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,password,api_token,remember_token, is_web_enabled,is_app_enabled,reset_pwd_hint,reset_pwd_ans,pwd_valid_from,pwd_valid_to,last_successful_login, last_failed_login,failed_login_attempts,force_change_pwd_flag,is_locked,lock_reason,is_active,is_token_verified,created_by, updated_by)  
				 values(in_ay_id,in_inst_id,in_user_id, in_user_type, in_role_id,in_login_name,in_password,in_api_token,in_remember_token, in_is_web_enabled,in_is_app_enabled,in_reset_pwd_hint,in_reset_pwd_ans,in_pwd_valid_from,in_pwd_valid_to,in_last_successful_login, in_last_failed_login,in_failed_login_attempts,in_force_change_pwd_flag,in_is_locked,in_lock_reason,in_is_active,in_is_token_verified,in_created_by, in_created_by);
          ELSE
	            update user_master set login_name=in_login_name , password=in_password
                where  user_id=in_user_id and user_type=in_user_type and is_deleted = '0' and inst_id = in_inst_id;
          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_user_role_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_user_role_map`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_user_type` VARCHAR(15), IN `in_user_id` MEDIUMINT(8), IN `in_role_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_ins_user_role_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(15);
  declare l_user_id mediumint(8);
  DECLARE a INT Default 0 ;
  DECLARE str 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_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
          begin
           set l_routine_block = 'insert_user_role_map';
           update    user_role_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where   user_id=in_user_id and user_type=in_user_type and is_deleted = 0  and inst_id = in_inst_id;
			  simple_loop: LOOP
			         SET a=a+1;
			         SET str=SPLIT_STR(in_role_ids,',',a);
			         IF str='' THEN
			            LEAVE simple_loop;
			         END IF;
			         insert into user_role_map (inst_id,user_type,user_id,role_id) values (in_inst_id,in_user_type,in_user_id,str);
			   END LOOP simple_loop;
          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_user_role_map_entitlements`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_user_role_map_entitlements`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_user_type` CHAR(3), IN `in_user_id` MEDIUMINT(8), 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_user_role_map_entitlements';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_looping_done int default false;
  declare l_role_id mediumint(8) default 0; 
  declare l_delete_flag tinyint(1) default 0; 
  declare l_entitlement_count smallint(5) default 0;
  # Step 1 : Check User Role Map table for roles that have this user mapped
  declare cur_user_role_map cursor for 
  select role_id, is_deleted 
  from user_role_map  
  where inst_id = in_inst_id and user_type = in_user_type and user_id = in_user_id 
    and is_active = 1 order by is_deleted DESC;
  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 = 'In Error Handler';
        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;
    open cur_user_role_map;
    cursor_loop: loop
      fetch cur_user_role_map into l_role_id, l_delete_flag;
      if l_looping_done then
        leave cursor_loop;
      end if;
      case in_dml_mode 
        when 'I' then
          begin
            start transaction;
            # Step 2 : Insert new User Entitlements that are a common set vis-a-vis Role Txn Map table  
            if (l_delete_flag = 0) then
              insert into user_entitlements (inst_id, user_type, user_id, txn_id, is_create_allowed, 
                is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, 
                delete_auth_type, created_by, updated_by) 
              select in_inst_id, in_user_type, in_user_id, txn_id, is_create_allowed, is_read_allowed, 
                is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, delete_auth_type, 
                in_created_by, in_created_by
              from role_txn_map
              where inst_id = in_inst_id and role_id = l_role_id and is_deleted = 0 
                and is_active = 1;
            end if;              
            commit;
        end;
      when 'U' then
        begin
          start transaction;
            begin      
              if (l_delete_flag = 0) then
              
--                 select count(ue.txn_id) into l_entitlement_count
--                 from user_entitlements ue, user_role_map urm, role_txn_map rtm
--                 where ue.inst_id = urm.inst_id and ue.inst_id = rtm.inst_id
--                   and ue.is_deleted = urm.is_deleted and ue.is_deleted = rtm.is_deleted
--                   and ue.is_active = urm.is_active and ue.is_active = rtm.is_active
--                   and ue.user_id = urm.user_id and ue.user_type = urm.user_type
--                   and urm.role_id = rtm.role_id and ue.txn_id = rtm.txn_id
--                   and ue.inst_id = in_inst_id 
--                   and ue.is_deleted = 0 and ue.is_active = 1
--                   and ue.user_id = in_user_id and ue.user_type = in_user_type 
--                   and rtm.role_id = l_role_id;
                  
                 select count(ue.txn_id) into l_entitlement_count
                from user_entitlements ue
                where ue.inst_id = in_inst_id 
                  and ue.is_deleted = 0 and ue.is_active = 1
                  and ue.user_id = in_user_id and ue.user_type = in_user_type 
                  and ue.role_id = l_role_id;

                              
                if (l_entitlement_count = 0) then
                  insert into user_entitlements (inst_id, user_type, user_id,role_id, txn_id, is_create_allowed, 
                      is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, 
                      delete_auth_type, created_by, updated_by) 
                    select in_inst_id, in_user_type, in_user_id,l_role_id, txn_id, is_create_allowed, is_read_allowed, 
                      is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, delete_auth_type, 
                      in_created_by, in_created_by
                    from role_txn_map
                    where inst_id = in_inst_id and is_deleted = 0 and is_active = 1
                      and role_id = l_role_id;
                       
                end if;
              elseif (l_delete_flag = 1) then
                update user_entitlements ue, user_role_map urm, role_txn_map rtm 
                set ue.updated_by = in_created_by, ue.updated_on = now(), ue.is_deleted = 1
                where ue.inst_id = urm.inst_id and ue.inst_id = rtm.inst_id
                and ue.is_deleted = rtm.is_deleted
                and ue.is_active = urm.is_active and ue.is_active = rtm.is_active
                and ue.user_id = urm.user_id and ue.user_type = urm.user_type
                and urm.role_id = rtm.role_id and ue.txn_id = rtm.txn_id
                and ue.inst_id = in_inst_id and ue.is_deleted = 0 and ue.is_active = 1
                and ue.user_id = in_user_id and ue.user_type = in_user_type and rtm.role_id = l_role_id;
              end if;
            end;
          commit;
        end;
    end case;
  end loop;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_value_added_service_providers`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_value_added_service_providers`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` SMALLINT(5), IN `in_INST_ID` SMALLINT(5), IN `in_FLD_VAS_PROV_ID` TEXT, IN `in_CATEGORY` TEXT, IN `in_SUB_CATEGORY` TEXT, IN `in_FLD_VAS_OWNER_NAME` TEXT, IN `in_FLD_VAS_CONTACT_NAME` TEXT, IN `in_FLD_VAS_TITLE` TEXT, IN `in_FLD_VAS_DESIGNATION` TEXT, IN `in_FLD_VAS_REG_NUM` TEXT, IN `in_FLD_VAS_QUAL` TEXT, IN `in_FLD_VAS_DESC` TEXT, IN `in_FLD_VAS_SPECIALIST` TEXT, IN `in_FLD_VAS_PHOTO_URL` TEXT, IN `in_FLD_VAS_THUMBNAIL_URL` TEXT, IN `in_FLD_VAS_YEAR_STARTED` TEXT, IN `in_FLD_VAS_ADDRESS` TEXT, IN `in_FLD_VAS_PINCODE` TEXT, IN `in_FLD_VAS_AREA` TEXT, IN `in_FLD_VAS_TIMINGS_1` TEXT, IN `in_FLD_VAS_TIMINGS_2` TEXT, IN `in_FLD_VAS_TIMINGS_3` TEXT, IN `in_FLD_VAS_CLOSED_ON` TEXT, IN `in_FLD_VAS_PHONE_1` TEXT, IN `in_FLD_VAS_PHONE_2` TEXT, IN `in_FLD_VAS_MOBILE_1` TEXT, IN `in_FLD_VAS_MOBILE_2` TEXT, IN `in_FLD_VAS_FAX_1` TEXT, IN `in_FLD_VAS_FAX_2` TEXT, IN `in_FLD_VAS_EMAIL_1` TEXT, IN `in_FLD_VAS_EMAIL_2` TEXT, IN `in_FLD_VAS_WEBSITE_1` TEXT, IN `in_FLD_VAS_WEBSITE_2` TEXT, IN `in_FLD_VAS_PREMIUM_MEMBER` TEXT, IN `in_FLD_VAS_AFFILIATED_TO` TEXT, IN `in_FLD_VAS_APPOINTMENT_REQD` TEXT, IN `in_FLD_VAS_RATE_1` TEXT, IN `in_FLD_VAS_RATE_2` TEXT, IN `in_FLD_VAS_RATE_3` TEXT, IN `in_FLD_VAS_RATING` TEXT, IN `in_FLD_VAS_REVIEW` TEXT, IN `in_FLD_VAS_CAPACITY` TEXT, IN `in_FLD_VAS_TERMS_CONDITIONS` TEXT, IN `in_status` TEXT, 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_value_added_service_providers';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_ID int(11);
   declare l_PROV_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_PROV_ID = fn_sequence_generator('SERVICE_PROVIDER');
insert into  value_added_service_providers(
					             INST_ID,
							FLD_VAS_PROV_ID,
							CATEGORY,
							SUB_CATEGORY,
							FLD_VAS_OWNER_NAME,
							FLD_VAS_CONTACT_NAME,
								FLD_VAS_TITLE,
								FLD_VAS_DESIGNATION,
							FLD_VAS_REG_NUM,
							FLD_VAS_QUAL,
							FLD_VAS_DESC,
							 FLD_VAS_SPECIALIST,
							FLD_VAS_PHOTO_URL,
							FLD_VAS_THUMBNAIL_URL,
							FLD_VAS_YEAR_STARTED,
							FLD_VAS_ADDRESS, 
							FLD_VAS_PINCODE,
						FLD_VAS_AREA,
						FLD_VAS_TIMINGS_1,
								FLD_VAS_TIMINGS_2,FLD_VAS_TIMINGS_3,FLD_VAS_CLOSED_ON,FLD_VAS_PHONE_1,
FLD_VAS_PHONE_2,FLD_VAS_MOBILE_1,FLD_VAS_MOBILE_2,FLD_VAS_FAX_1,FLD_VAS_FAX_2,
  FLD_VAS_EMAIL_1,FLD_VAS_EMAIL_2,FLD_VAS_WEBSITE_1,FLD_VAS_WEBSITE_2,
  FLD_VAS_PREMIUM_MEMBER,FLD_VAS_AFFILIATED_TO,FLD_VAS_APPOINTMENT_REQD,
FLD_VAS_RATE_1,FLD_VAS_RATE_2,FLD_VAS_RATE_3,FLD_VAS_RATING,FLD_VAS_REVIEW,FLD_VAS_CAPACITY,FLD_VAS_TERMS_CONDITIONS,status, created_by, updated_by) 	 						
           values(
  in_INST_ID ,
   l_PROV_ID, 
   in_CATEGORY, 
  in_SUB_CATEGORY ,
  in_FLD_VAS_OWNER_NAME  ,
  in_FLD_VAS_CONTACT_NAME  ,
  in_FLD_VAS_TITLE ,
  in_FLD_VAS_DESIGNATION  ,
 in_FLD_VAS_REG_NUM  ,
  in_FLD_VAS_QUAL  ,
 in_FLD_VAS_DESC ,
 in_FLD_VAS_SPECIALIST, 
  in_FLD_VAS_PHOTO_URL , 
  in_FLD_VAS_THUMBNAIL_URL ,
  in_FLD_VAS_YEAR_STARTED ,
  in_FLD_VAS_ADDRESS  ,
  in_FLD_VAS_PINCODE  ,
 in_FLD_VAS_AREA , 
  in_FLD_VAS_TIMINGS_1  , 
 in_FLD_VAS_TIMINGS_2  , 
  in_FLD_VAS_TIMINGS_3  , 
 in_FLD_VAS_CLOSED_ON , 
 in_FLD_VAS_PHONE_1  , 
 in_FLD_VAS_PHONE_2 ,
 in_FLD_VAS_MOBILE_1  , 
  in_FLD_VAS_MOBILE_2 ,
 in_FLD_VAS_FAX_1  , 
  in_FLD_VAS_FAX_2  ,
 in_FLD_VAS_EMAIL_1 , 
  in_FLD_VAS_EMAIL_2  ,
 in_FLD_VAS_WEBSITE_1  , 
  in_FLD_VAS_WEBSITE_2  ,
 in_FLD_VAS_PREMIUM_MEMBER ,
 in_FLD_VAS_AFFILIATED_TO  ,
 in_FLD_VAS_APPOINTMENT_REQD  ,
 in_FLD_VAS_RATE_1  ,
 in_FLD_VAS_RATE_2  ,
 in_FLD_VAS_RATE_3  ,
 in_FLD_VAS_RATING ,
 in_FLD_VAS_REVIEW ,
 in_FLD_VAS_CAPACITY  ,
 in_FLD_VAS_TERMS_CONDITIONS,in_status,in_is_active,in_created_by);
          end;    
    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update value_added_service_providers set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where  	FLD_VAS_PROV_ID = in_FLD_VAS_PROV_ID and  is_deleted = 0 
            	and INST_ID = in_INST_ID;
          insert into  value_added_service_providers(
					            INST_ID,
							FLD_VAS_PROV_ID,
						CATEGORY,
							SUB_CATEGORY,
							FLD_VAS_OWNER_NAME,
							FLD_VAS_CONTACT_NAME,
								FLD_VAS_TITLE,
								FLD_VAS_DESIGNATION,
							FLD_VAS_REG_NUM,
							FLD_VAS_QUAL,
							FLD_VAS_DESC,
							 FLD_VAS_SPECIALIST,
							FLD_VAS_PHOTO_URL,
							FLD_VAS_THUMBNAIL_URL,
							FLD_VAS_YEAR_STARTED,
							FLD_VAS_ADDRESS, 
							FLD_VAS_PINCODE,
						FLD_VAS_AREA,
						FLD_VAS_TIMINGS_1,
								FLD_VAS_TIMINGS_2,FLD_VAS_TIMINGS_3,FLD_VAS_CLOSED_ON,FLD_VAS_PHONE_1,
FLD_VAS_PHONE_2,FLD_VAS_MOBILE_1,FLD_VAS_MOBILE_2,FLD_VAS_FAX_1,FLD_VAS_FAX_2,
  FLD_VAS_EMAIL_1,FLD_VAS_EMAIL_2,FLD_VAS_WEBSITE_1,FLD_VAS_WEBSITE_2,
  FLD_VAS_PREMIUM_MEMBER,FLD_VAS_AFFILIATED_TO,FLD_VAS_APPOINTMENT_REQD,
FLD_VAS_RATE_1,FLD_VAS_RATE_2,FLD_VAS_RATE_3,FLD_VAS_RATING,FLD_VAS_REVIEW,FLD_VAS_CAPACITY,FLD_VAS_TERMS_CONDITIONS,status, created_by, updated_by) 	 						
           values(
  in_INST_ID ,
  in_FLD_VAS_PROV_ID,
   in_CATEGORY, 
  in_SUB_CATEGORY ,
  in_FLD_VAS_OWNER_NAME  ,
  in_FLD_VAS_CONTACT_NAME  ,
  in_FLD_VAS_TITLE ,
  in_FLD_VAS_DESIGNATION  ,
 in_FLD_VAS_REG_NUM  ,
  in_FLD_VAS_QUAL  ,
 in_FLD_VAS_DESC ,
 in_FLD_VAS_SPECIALIST, 
  in_FLD_VAS_PHOTO_URL , 
  in_FLD_VAS_THUMBNAIL_URL ,
  in_FLD_VAS_YEAR_STARTED ,
  in_FLD_VAS_ADDRESS  ,
  in_FLD_VAS_PINCODE  ,
 in_FLD_VAS_AREA , 
  in_FLD_VAS_TIMINGS_1  , 
 in_FLD_VAS_TIMINGS_2  , 
  in_FLD_VAS_TIMINGS_3  , 
 in_FLD_VAS_CLOSED_ON , 
 in_FLD_VAS_PHONE_1  , 
 in_FLD_VAS_PHONE_2 ,
 in_FLD_VAS_MOBILE_1  , 
  in_FLD_VAS_MOBILE_2 ,
 in_FLD_VAS_FAX_1  , 
  in_FLD_VAS_FAX_2  ,
 in_FLD_VAS_EMAIL_1 , 
  in_FLD_VAS_EMAIL_2  ,
 in_FLD_VAS_WEBSITE_1  , 
  in_FLD_VAS_WEBSITE_2  ,
 in_FLD_VAS_PREMIUM_MEMBER ,
 in_FLD_VAS_AFFILIATED_TO  ,
 in_FLD_VAS_APPOINTMENT_REQD  ,
 in_FLD_VAS_RATE_1  ,
 in_FLD_VAS_RATE_2  ,
 in_FLD_VAS_RATE_3  ,
 in_FLD_VAS_RATING ,
 in_FLD_VAS_REVIEW ,
 in_FLD_VAS_CAPACITY  ,
 in_FLD_VAS_TERMS_CONDITIONS,in_status,in_is_active,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_video_posts`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_video_posts`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_video_id` MEDIUMINT(8), IN `in_video_title` VARCHAR(100), IN `in_post_slug` VARCHAR(100), IN `in_video_content` TEXT, IN `in_post_date` DATE, IN `in_post_video` VARCHAR(100), IN `in_comments_enabled` TINYINT(2), IN `in_scope` VARCHAR(10), IN `in_is_social_media` CHAR(1), 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, OUT `out_video_id` MEDIUMINT(8))
    NO SQL
begin

declare l_routine_name varchar(50) default 'sp_ins_video_posts';
declare l_err_code char(5) default '00000';
declare l_err_desc text default '';        
declare l_routine_block varchar(15);
declare l_video_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_video_id = fn_sequence_generator('VIDEO_POST');
          set out_video_id = l_video_id ;
       
          insert into video_posts (ay_id,inst_id, video_id,  video_title, post_slug, video_content,
                               post_date, post_video,comments_enabled, scope,
                               is_social_media, status, created_by, is_active,updated_by)                              
          values(in_ay_id,in_inst_id,l_video_id,  in_video_title, in_post_slug,in_video_content,
                 in_post_date, in_post_video,in_comments_enabled,
                 in_scope,in_is_social_media, in_status, in_created_by,in_is_active,in_created_by);
         
        end;    

         when 'U' then

       set l_routine_block = 'update';
       set out_video_id = in_video_id ;
        begin
            update video_posts set valid_to = NOW(), updated_by = in_created_by,
            updated_on = NOW(), is_deleted = 1
          where video_id = in_video_id and is_deleted = 0 and ay_id = in_ay_id
              and inst_id = in_inst_id;
       
         insert into video_posts (ay_id,inst_id,video_id,video_title,post_slug,video_content,
                               post_date,post_video,comments_enabled,scope,
                               is_social_media,status,created_by,is_active,updated_by)                              
          values(in_ay_id,in_inst_id,in_video_id,in_video_title, in_post_slug,in_video_content,
                 in_post_date, in_post_video,in_comments_enabled,
                 in_scope,is_social_media, in_status, in_created_by,in_is_active,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_weekly_subject_load_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_weekly_subject_load_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_load_start_date` DATE, IN `in_sub_load_end_date` DATE, IN `in_standard_id` CHAR(2), 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_weekly_subject_load_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 weekly_subject_load(ay_id,
																		inst_id, 
																		standard_id,
    
																		sub_struct_map_id,
																		weekly_subject_load,
																		total_weekly_sub_load,
																		created_by, 
																		updated_by,
																		sub_load_start_date,
																		sub_load_end_date,class_id,shift_type,workload_mst_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 = 'weekly_subject_load' 
  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); 
              update timetable_master set valid_to = now(), updated_by = in_created_by, 
                    updated_on = now(), 	status = '11'
              where ay_id = in_ay_id and inst_id = in_inst_id and timetable_valid_from = in_sub_load_start_date
                    and timetable_valid_to=in_sub_load_end_date and is_deleted = 0 and standard_id=in_standard_id;
                  
        commit;
      end;

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

         
         update student_leave_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 leave_id = in_leave_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_weekly_sub_load_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_weekly_sub_load_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sub_load_start_date` DATE, IN `in_sub_load_end_date` DATE, IN `in_standard_id` CHAR(2), 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_weekly_sub_load_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 weekly_subject_load(ay_id,
																		inst_id, 
																		standard_id,
    
																		sub_struct_map_id,
																		weekly_subject_load,
																		total_weekly_sub_load,
																		created_by, 
																		updated_by,
																		sub_load_start_date,
																		sub_load_end_date,class_id,shift_type) 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 = 'weekly_subject_load' 
  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); 
              update timetable_master set valid_to = now(), updated_by = in_created_by, 
                    updated_on = now(), 	status = '11'
              where ay_id = in_ay_id and inst_id = in_inst_id and timetable_valid_from = in_sub_load_start_date
                    and timetable_valid_to=in_sub_load_end_date and is_deleted = 0 and standard_id=in_standard_id;
                  
        commit;
      end;

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

         
         update student_leave_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 leave_id = in_leave_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_is_day_zero_setup_defined`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_is_day_zero_setup_defined`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), OUT `out_count_status` MEDIUMINT(5), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_is_day_zero_setup_defined';
  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 l_institution_config MEDIUMINT(5) default 0;
  declare l_appl_txn_master MEDIUMINT(5) default 0;
  declare l_appl_data_master MEDIUMINT(5) default 0;
  declare l_role_master MEDIUMINT(5) default 0;
  declare l_role_txn_map MEDIUMINT(5) default 0;
  declare l_user_entitlements MEDIUMINT(5) default 0;
  declare l_notification_config MEDIUMINT(5) default 0;
  declare l_gradeset_master MEDIUMINT(5) default 0;
  declare l_gradeset_details MEDIUMINT(5) default 0;
  declare l_account_head_master MEDIUMINT(5) default 0;
  declare l_notif_app_template_master MEDIUMINT(5) default 0;
  declare l_notif_sms_template_master MEDIUMINT(5) default 0;
  declare l_notif_email_template_master MEDIUMINT(5) default 0;
  declare l_notif_web_template_master MEDIUMINT(5) default 0;
  declare l_event_calendar_category MEDIUMINT(5) default 0;
  declare l_event_calendar_subcategory MEDIUMINT(5) default 0;
  declare l_user_groups_master MEDIUMINT(5) default 0;
  declare l_document_master MEDIUMINT(5) default 0;
  declare l_tCount MEDIUMINT(5) 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 'S' then          
          begin
             set l_routine_block = 'Setup'; 
                select is_active into l_is_active from institution_master where inst_id = in_inst_id and is_deleted = 0 ;  
            if (l_is_active = 1) then
               #1 institution_config data
              select COUNT(1) into l_institution_config from institution_config where inst_id = in_inst_id and is_deleted = 0 ;
              # appl_txn_master data
              select COUNT(1) into l_appl_txn_master from appl_txn_master where inst_id = in_inst_id and is_deleted = 0 ;  
              # appl_data_master data 
              select COUNT(1) into l_appl_data_master from appl_data_master where inst_id = in_inst_id and is_deleted = 0 ;  
              # role_master data 
              select COUNT(1) into l_role_master from role_master where inst_id = in_inst_id and is_deleted = 0 ;  
              # role_txn_map data of super admin role
              select COUNT(1) into l_role_txn_map from role_txn_map where inst_id = in_inst_id and is_deleted = 0 ;  
              # user_entitlements data of user type SU and user id = in_user_id
              select COUNT(1) into l_user_entitlements from user_entitlements where inst_id = in_inst_id and is_deleted = 0 ;  
              # notification_config data 
              select COUNT(1) into l_notification_config from notification_config where inst_id = in_inst_id and is_deleted = 0 ; 
              # notif_app_template_master data 
              select COUNT(1) into l_notif_app_template_master from notif_app_template_master where inst_id = in_inst_id and is_deleted = 0 ;
              # notif_sms_template_master data 
              select COUNT(1) into l_notif_sms_template_master from notif_sms_template_master where inst_id = in_inst_id and is_deleted = 0 ;
              # notif_email_template_master data 
              select COUNT(1) into l_notif_email_template_master from notif_email_template_master where inst_id = in_inst_id and is_deleted = 0 ;
              # notif_web_template_master data 
              select COUNT(1) into l_notif_web_template_master from notif_web_template_master where inst_id = in_inst_id and is_deleted = 0 ;
              # gradeset_master data 
              select COUNT(1) into l_gradeset_master from gradeset_master where inst_id = in_inst_id and is_deleted = 0 ;  
              # gradeset_details data 
              select COUNT(1) into l_gradeset_details from gradeset_details where inst_id = in_inst_id and is_deleted = 0 ;  
              #account_head_master data
              select COUNT(1) into l_account_head_master from account_head_master where inst_id = in_inst_id and is_deleted = 0 ;  
              #event_calendar_category data
              select COUNT(1) into l_event_calendar_category from event_calendar_category where inst_id = in_inst_id and is_deleted = 0 ; 
              #event_calendar_subcategory data
              select COUNT(1) into l_event_calendar_subcategory from event_calendar_subcategory where inst_id = in_inst_id and is_deleted = 0 ; 
              #user_groups_master data
              select COUNT(1) into l_user_groups_master from user_groups_master where inst_id = in_inst_id and is_deleted = 0 ; 
              #document_master data
              select COUNT(1) into l_document_master from document_master where inst_id = in_inst_id and is_deleted = 0 ; 
              if (l_institution_config=0 and l_appl_txn_master = 0 and l_appl_data_master=0 and l_role_master=0 
                and l_role_txn_map=0 and l_user_entitlements=0 and l_notification_config=0 and l_gradeset_master=0 
                and l_gradeset_details=0 and l_account_head_master=0 and l_notif_app_template_master=0 and l_notif_sms_template_master=0 
                and l_notif_email_template_master=0 and l_notif_web_template_master=0 and l_event_calendar_category=0 
                and l_event_calendar_subcategory=0 and l_user_groups_master=0 and l_document_master=0) then
                  Set l_tCount=0;
              else
                  Set l_tCount=1;
              end if;
            end if;
      end;    
    end case; 
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
     set out_count_status = l_tCount;
end$$

DROP PROCEDURE IF EXISTS `sp_push_biometric_attendance`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_push_biometric_attendance`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_insert_row_count_mst` TINYINT(3), IN `in_insert_row_count_dtl` MEDIUMINT(8), IN `in_json_str_mst` TEXT, IN `in_json_str_dtl` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_student_id` MEDIUMINT(8), IN `in_present_count` MEDIUMINT(8), IN `in_attendance_date` DATE, IN `in_absent_count` MEDIUMINT(8), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_attendance_mst_id` MEDIUMINT(8))
    SQL SECURITY INVOKER
BEGIN
  declare l_routine_name varchar(50) default 'sp_push_biometric_attendance';
  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_val_str_end char(1) default ')';

  declare l_insert_sql_str_dtl text default 'INSERT INTO  student_attendance_details (ay_id, inst_id, attendance_mst_id, attendance_dtl_id, student_id, attendance_status, attendance_comments, created_by, updated_by, is_active,stud_att_upload_type,bio_type_id) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO student_attendance_master (ay_id, inst_id, attendance_mst_id, group_type, group_id, standard_id, division_id, timetable_period_id, file_upload_id, attendance_type, attendance_date, class_count, present_count, absent_count, attendance_comments, status, status_desc, created_by, updated_by, is_active,attendance_upload_type,notification_status) VALUES'; 
  declare l_insert_val_str_part 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  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_insert_val_str_full text;

  declare cur_json_template_mst cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_attendance_master' 
  order by col_pos;
  
  declare cur_json_template_dtl cursor for  
  select col_name from json_template_master 
  where tbl_name = 'student_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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'E' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'F' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'G' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'H' 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);

      #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);
      
      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;
				when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'E' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'F' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'G' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                	when 'H' 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;
				 when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'E' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'F' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'G' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'H' 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);

      #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 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;
	  
	      when 'B' 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  and attendance_status = 'A'  and stud_att_upload_type = 'MANUAL'  ;

          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;
	  
	   when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : before soft delete';

           DELETE FROM student_attendance_master 
           WHERE  inst_id = in_inst_id and ay_id = in_ay_id and  attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0;
                   

                   
          

          set l_routine_block = 'Mode D : 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 D : after insert';
        commit;
      end;

      when 'E' 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(), present_count = in_present_count
          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_dtl);  

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

  when 'F' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode F : 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_date = in_attendance_date
            and is_deleted = 0 and attendance_upload_type='BIOMETRIC' and status='DRAFT';
                   
        
          set l_routine_block = 'Mode F : 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 F : after insert';
        commit;
      end;
 when 'G' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode F : before soft delete';
      
          update student_attendance_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), absent_count = in_absent_count
          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 F : before insert';
      
       
          call sp_execute_immediate (l_insert_sql_str_dtl);  

          set l_routine_block = 'Mode F : after insert';
        commit;
      end;
when 'H' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode F : before soft delete';
      
          update student_attendance_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), absent_count = in_absent_count,status='PUBLISHED',notification_status='ALL'
          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 F : before insert';
      
       
          call sp_execute_immediate (l_insert_sql_str_dtl);  

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


    end case;

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

DROP PROCEDURE IF EXISTS `sp_setup_new_institute`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_setup_new_institute`(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_user_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_setup_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_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 'S' then          
          begin
             set l_routine_block = 'Setup'; 
              select is_active into l_is_active
                  from institution_master
                  where inst_id = in_inst_id 
                  and is_deleted = 0 ;  
            if (l_is_active = 1) then
                               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,
                web_theme_id, app_theme_id, inst_house_flag, records_per_page, created_by, updated_by, is_active) 
                select '', in_inst_id, inst_type, edu_board, fy_start_date, fy_end_date, ay_start_date, 
                ay_end_date, in_current_ay, in_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,
                web_theme_id, app_theme_id, inst_house_flag, records_per_page, in_created_by,in_created_by,is_active
                  from institution_config where ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;
                             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,
			         created_by,updated_by,is_active)
               select '', in_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,
	             in_created_by,in_created_by,is_active
               from appl_txn_master where ay_id = '*******' and inst_id = 0
               and is_deleted = 0 and is_active=1;
                            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, created_by, updated_by)
                  select '', in_inst_id, data_type ,data_key, data_value,
               data_desc, data_abbr, data_pos, is_system_def, is_editable, 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;
                            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, created_by, updated_by)
                  select in_current_ay, in_inst_id, role_id ,role_type, parent_id, role_level,
               role_name, role_display_name, role_desc, role_abbr, is_default, in_created_by, in_created_by
                  from role_master where ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;
                             INSERT INTO role_txn_map(ay_id, inst_id, role_id, txn_id, is_txn_allowed, is_create_allowed,
                is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, 
                delete_auth_type, created_by, updated_by)
                  select '', in_inst_id, role_id, txn_id, is_txn_allowed, is_create_allowed,
                is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, 
                delete_auth_type, in_created_by, in_created_by
                  from role_txn_map where ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;
                             INSERT INTO user_entitlements(ay_id, inst_id, user_type, user_id, txn_id, is_create_allowed,
                is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type,
                delete_auth_type, created_by, updated_by)
                  select '', in_inst_id, user_type, in_user_id, txn_id, is_create_allowed,
                is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type,
                delete_auth_type, in_created_by, in_created_by
                  from user_entitlements where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;
                            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 '', in_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,
                    in_created_by, in_created_by
                  from notification_config where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;
                             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, '', in_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, in_created_by, in_created_by
                  from notif_app_template_master where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;
                            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, '', in_inst_id,web_from, web_subject, web_params, web_description, web_icon,
                web_action_link, web_opt1, web_opt2, recipient_type, in_created_by, in_created_by
                  from notif_web_template_master where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;
                            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, '', in_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, in_created_by, in_created_by
                  from notif_email_template_master where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;
                            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, '', in_inst_id,sms_from_mobile_no, sms_body, sms_params, sms_opt1, sms_opt2,
                recipient_type, in_created_by, in_created_by
                  from notif_sms_template_master where ay_id = '*******' and inst_id = 0 
                       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_current_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 = '*******' and inst_id = 0
                      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_current_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 = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;
                            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, created_by, updated_by)
                  select in_current_ay, in_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, in_created_by,
                    in_created_by
                  from account_head_master where ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;
                              INSERT INTO event_calendar_category(inst_id, event_cat, cat_name, cat_icon, cat_class, cat_order,
                  created_by, updated_by)
                  select in_inst_id,event_cat, cat_name, cat_icon, cat_class, cat_order, in_created_by, in_created_by
                  from event_calendar_category where inst_id = 0
                       and is_deleted = 0 and is_active=1;
                              INSERT INTO event_calendar_subcategory(inst_id, event_cat, event_sub_cat, subcat_name, subcat_icon, subcat_class,
                  subcat_order, created_by, updated_by)
                  select in_inst_id, event_cat, event_sub_cat, subcat_name, subcat_icon, subcat_class,
                  subcat_order, in_created_by, in_created_by
                  from event_calendar_subcategory where inst_id = 0
                       and is_deleted = 0 and is_active=1;
                              INSERT INTO user_groups_master(inst_id, grp_name, grp_type, grp_display_name, grp_icon, grp_class, grp_order,
                  created_by, updated_by)
                  select in_inst_id, grp_name, grp_type, grp_display_name, grp_icon, grp_class, grp_order, in_created_by,
                    in_created_by
                  from user_groups_master where inst_id = 0
                       and is_deleted = 0 and is_active=1;
			                   INSERT INTO document_master(ay_id, inst_id, entity_type, entity_id, file_upload_id, module_name, doc_category,
                  doc_subcategory, doc_name, is_mandatory, doc_upload_status, doc_submit_status, status_desc, is_verified,
                  created_by, updated_by)
                  select '', in_inst_id, entity_type, entity_id, file_upload_id, module_name, doc_category,
                  doc_subcategory, doc_name, is_mandatory, doc_upload_status, doc_submit_status, status_desc, is_verified,
                  in_created_by, in_created_by
                  from document_master where inst_id = 0
                       and is_deleted = 0 and is_active=1;
                              INSERT INTO appl_data_notif_templates (ay_id, inst_id, data_type, data_key, subject,
                  message_body, created_by, updated_by, is_active) 
                select '', in_inst_id, data_type, data_key, subject,
                  message_body, in_created_by, in_created_by, is_active
                      from appl_data_notif_templates where ay_id = '*******' and inst_id = 0
                           and is_deleted = 0 and is_active=1;
           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_student_admission_onrolling_in_bulk`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_student_admission_onrolling_in_bulk`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_student_ids` TEXT, IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_stud_status` 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_student_admission_onrolling_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_id mediumint(8);
  declare l_enrollment_num varchar(50);
  declare t_enrollment_num varchar(50);
  declare l_admission_num varchar(50);
  declare t_admission_num varchar(50);
  declare l_stud_num varchar(50);
  declare t_stud_num varchar(50);
  declare t_stud_status varchar(25);
  DECLARE a INT Default 0 ;
  DECLARE in_student_id VARCHAR(255);
  DECLARE l_standard_id CHAR(2);
  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);
