begin
   declare l_routine_name varchar(50) default 'sp_ins_institution_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_inst_id mediumint(8);
  declare l_date_format varchar(10);
  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;
      set out_inst_id   =  0;   
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            set l_routine_block = 'insert';
          	set l_inst_id =fn_sequence_generator('INSTITUTION_MASTER');
set l_date_format='d-m-Y';
            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,
                lib_book_num_gen_mode,lib_book_num_gen_id,
                web_theme_id, app_theme_id, inst_house_flag, records_per_page,sms_sender_id, created_by, updated_by, is_active) 
                select in_current_year, l_inst_id, inst_type, in_edu_board, fy_start_date, fy_end_date, ay_start_date, 
                ay_end_date, in_current_year, in_next_ay, attendance_type, first_day_of_week, weekly_holiday, l_date_format, currency_code, 
                class_display_format, instruction_mode, in_grading_system, terms_per_year, 'Y', enrollment_num_gen_id, 
                'Y', stud_num_gen_id, 'Y', emp_num_gen_id, 'Y', admission_num_gen_id, 
                'Y',demand_num_gen_id, 'Y', pmt_rcpt_num_gen_id,'Y',lib_book_num_gen_id,
                web_theme_id, app_theme_id, inst_house_flag, '10',sms_sender_id, 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 institution_master (inst_id, org_id, inst_name, inst_display_name, 
              inst_abbr, inst_desc, inst_logo_path, address_line_1, address_line_2, 
              locality, city, district,state, country, pincode,registration_num, udise_code,affiliation_number, 
              foundation_date, onboarding_date, website_address, email_main, email_alt, 
              facebook_address, twitter_address, linkedin_address, instagram_address, 
              contact_salutation_1, first_name_1, last_name_1, contact_role_1, 
              contact_salutation_2, first_name_2, last_name_2, contact_role_2, 
              contact_salutation_3, first_name_3, last_name_3, contact_role_3, 
              tel_country_code_1, tel_area_code_1, tel_number_1, tel_type_1, 
              tel_country_code_2, tel_area_code_2, tel_number_2, tel_type_2, 
              tel_country_code_3, tel_area_code_3, tel_number_3, tel_type_3,referral_id,website_reference, created_by,
              updated_by,is_active)  	 						
            values (l_inst_id, '', in_inst_name, in_inst_display_name, in_inst_abbr, 
              in_inst_desc, in_inst_logo_path, in_address_line_1, in_address_line_2, 
              in_locality, in_city, in_district,in_state, in_country, in_pincode,in_registration_num, 
              in_udise_code,in_affiliation_number, in_foundation_date, in_onboarding_date, in_website_address, 
              in_email_main, in_email_alt, in_facebook_address, in_twitter_address, 
              in_linkedin_address, in_instagram_address, in_contact_salutation_1, 
              in_first_name_1, in_last_name_1, in_contact_role_1, in_contact_salutation_2, 
              in_first_name_2, in_last_name_2, in_contact_role_2, in_contact_salutation_3, 
              in_first_name_3, in_last_name_3, in_contact_role_3, in_tel_country_code_1, 
              in_tel_area_code_1, in_tel_number_1, in_tel_type_1, in_tel_country_code_2, 
              in_tel_area_code_2, in_tel_number_2, in_tel_type_2, in_tel_country_code_3, 
              in_tel_area_code_3, in_tel_number_3, in_tel_type_3,in_referral_id,in_website_reference, in_created_by, 
              in_created_by,'0');
          end;    
  	    when 'U' then
         set l_routine_block = 'update'; 
          begin
          	update institution_master 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;
            insert institution_master (inst_id, org_id, inst_name, inst_display_name, 
              inst_abbr, inst_desc, inst_logo_path, address_line_1, address_line_2, 
              locality, city, district,state, country, pincode, registration_num, udise_code,affiliation_number,
              foundation_date, onboarding_date, website_address, email_main, email_alt, 
              facebook_address, twitter_address, linkedin_address, instagram_address, 
              contact_salutation_1, first_name_1, last_name_1, contact_role_1, 
              contact_salutation_2, first_name_2, last_name_2, contact_role_2, 
              contact_salutation_3, first_name_3, last_name_3, contact_role_3, 
              tel_country_code_1, tel_area_code_1, tel_number_1, tel_type_1, 
              tel_country_code_2, tel_area_code_2, tel_number_2, tel_type_2, 
              tel_country_code_3, tel_area_code_3, tel_number_3, tel_type_3,referral_id,website_reference, created_by, 
              updated_by)  	 						
            values (in_inst_id, in_org_id, in_inst_name, in_inst_display_name, in_inst_abbr, 
              in_inst_desc, in_inst_logo_path, in_address_line_1, in_address_line_2, 
              in_locality, in_city,in_district, in_state, in_country, in_pincode, in_registration_num, 
              in_udise_code,in_affiliation_number,in_foundation_date, in_onboarding_date, in_website_address, 
              in_email_main, in_email_alt, in_facebook_address, in_twitter_address, 
              in_linkedin_address, in_instagram_address, in_contact_salutation_1, 
              in_first_name_1, in_last_name_1, in_contact_role_1, in_contact_salutation_2, 
              in_first_name_2, in_last_name_2, in_contact_role_2, in_contact_salutation_3, 
              in_first_name_3, in_last_name_3, in_contact_role_3, in_tel_country_code_1, 
              in_tel_area_code_1, in_tel_number_1, in_tel_type_1, in_tel_country_code_2, 
              in_tel_area_code_2, in_tel_number_2, in_tel_type_2, in_tel_country_code_3, 
              in_tel_area_code_3, in_tel_number_3, in_tel_type_3,in_referral_id,in_website_reference, in_created_by, 
              in_created_by);
          end;    
      end case;
    commit;
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
      set out_inst_id=  l_inst_id;   
end$$

DROP PROCEDURE IF EXISTS `sp_ins_institution_sequence_params`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_institution_sequence_params`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_inst_abbr` VARCHAR(10), IN `in_inst_br_abbr` VARCHAR(15), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_ins_institution_sequence_params';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                    err_desc, err_type, err_severity, created_by) 
             values (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                    'ERROR', 0, in_created_by);
        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
       end; 
       when 'U' then          
          begin
             set l_routine_block = 'update';   
                	update institution_sequence_params set valid_to = NOW(), created_by = in_created_by, 
                         is_deleted = 1
                   where is_deleted = 0  and inst_id = in_inst_id ;
            insert into institution_sequence_params(ay_id, inst_id,inst_abbr,inst_br_abbr, is_active,created_by) 
                   values ('', in_inst_id,in_inst_abbr,in_inst_br_abbr, 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_interview_schedule_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_interview_schedule_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_interview_schedule_id` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT, OUT `out_interview_schedule_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_interview_schedule_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_interviewScheduleId mediumint(8);
  declare l_insert_sql_str text default 'INSERT INTO stud_interview_schedule_details (ay_id, 
    inst_id, student_id, interview_date, from_slot, to_slot, is_confirmed, stud_status, is_active,
    created_by, updated_by, interview_schedule_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 = 'stud_interview_schedule_detail' 
  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';
          set l_routine_block = 'before execute immediate';
      	update stud_interview_schedule_details set valid_to = NOW(), 
               updated_by = in_created_by,updated_on = NOW(), is_deleted = 1 
        where is_deleted = 0 
          and ay_id = in_ay_id 
        	and inst_id = in_inst_id
          and interview_schedule_id = in_interview_schedule_id;
          call sp_execute_immediate (l_insert_sql_str);  
         UPDATE student_master sm
           JOIN stud_interview_schedule_details sisd ON sm.student_id = sisd.student_id 
            SET sm.valid_to = now(), sm.updated_by = in_created_by, 
                sm.updated_on = now(), sm.stud_status = 40,
                sisd.is_confirmed=10
          WHERE sm.inst_id = sisd.inst_id AND sm.ay_id=sisd.ay_id
            AND sm.is_deleted=sisd.is_deleted
            AND sm.inst_id = in_inst_id
            AND sm.ay_id = in_ay_id 
            AND sisd.is_confirmed=1
            AND sm.is_deleted = 0;
        commit;
      end;
      when 'N' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
            set l_interviewScheduleId = fn_sequence_generator('INTERVIEW_SCHEDULE');
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_interview_schedule_id = l_interviewScheduleId;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_inventory_item_category`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_inventory_item_category`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_item_category_id` MEDIUMINT(8), IN `in_inventory_dept_id` MEDIUMINT(8), IN `in_category_name` VARCHAR(50), IN `in_category_type` VARCHAR(40), IN `in_is_active` SMALLINT(5), 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_inventory_item_category';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_looping_done int default false;
 declare l_item_category_id mediumint(8);
 declare l_item_code_num varchar(20);


 declare continue handler for not found set l_looping_done = true;
 declare exit handler for sqlexception
      begin

     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

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

          
             INSERT INTO inventory_item_category(ay_id,inst_id,item_category_id,inventory_dept_id,
              category_name,category_type,created_by,updated_by,
              is_active) 
              VALUES(in_ay_id, in_inst_id,l_item_category_id,in_inventory_dept_id,in_category_name,
               in_category_type, in_created_by, in_created_by,in_is_active);
         end; 
         when 'U' then
      set l_routine_block = 'update';      
          begin
          	update  inventory_item_category set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where item_category_id=in_item_category_id  
              and is_deleted = 0 
            	and inst_id = in_inst_id;

            INSERT INTO inventory_item_category(ay_id,inst_id,item_category_id,inventory_dept_id,
              category_name,category_type,created_by,updated_by,
              is_active) 
              VALUES(in_ay_id, in_inst_id,in_item_category_id,in_inventory_dept_id,in_category_name,
               in_category_type, in_created_by, in_created_by,in_is_active);
            
          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_inventory_item_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_inventory_item_master`(IN `in_dml_mode` CHAR(1), 
  IN `in_ay_id` CHAR(7), 
  IN `in_inst_id` SMALLINT(5), 
  IN `in_item_id` MEDIUMINT(8),
  IN `in_item_category_id` MEDIUMINT(8), 
  IN `in_item_code` VARCHAR(20), 
  IN `in_item_name` VARCHAR(100),
  IN `in_item_display_name` VARCHAR(50),
  IN `in_unit` VARCHAR(20),
  IN `in_item_status_value` TINYINT(1),
  IN `in_is_active` SMALLINT(5),
  IN `in_created_by` VARCHAR(20),
  IN `in_inventory_dept_id` MEDIUMINT(8),
  IN `in_item_rate` BIGINT(30), 
  IN `in_cgst` decimal(7,2),
  IN `in_sgst` decimal(7,2),
  IN `in_igst` decimal(7,2),
  IN `in_total_item_rate` decimal(7,2), 
  IN `in_quantity` BIGINT(30),
  IN `in_item_label`CHAR(1),
  IN `in_sequence_entity_id` VARCHAR(30),
  IN `in_is_expense` CHAR(1),
  IN `in_cgst_amount` decimal(7,2), 
  IN `in_sgst_amount` decimal(7,2), 
  IN `in_igst_amount` decimal(7,2), 
  OUT `out_err_code` CHAR(7),
  OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_inventory_item_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_looping_done int default false;
 declare l_item_id mediumint(8);
 declare item_id_count mediumint(8);
 declare l_item_code_num varchar(20);


 declare continue handler for not found set l_looping_done = true;
 declare exit handler for sqlexception
      begin

     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
            set l_item_id = fn_sequence_generator('INVENTORY_ITEM_MASTER');
            set l_routine_block = 'insert';
      
           set l_item_code_num =in_item_code;

          IF ( in_item_label='Y' AND length(trim(in_item_code)) = '' ) THEN 
					    call sp_custom_seq_generator(in_inst_id,in_sequence_entity_id,in_ay_id,in_created_by,l_item_code_num) ;
             IF length(trim(l_item_code_num)) = 0 THEN
					     SIGNAL SQLSTATE '10012' 
					   SET MESSAGE_TEXT = 'An error occurred while generating inventory item label';
             END IF;
	        END IF;
         
         INSERT INTO inventory_item_master(ay_id,inst_id,item_id,item_category_id,item_code,inventory_dept_id,
          item_name,item_display_name,unit,item_status,item_rate,cgst,sgst,igst,total_item_rate,is_expense,initial_stock,created_by,updated_by,
          is_active,cgst_amount,sgst_amount,igst_amount) 
          VALUES(in_ay_id, in_inst_id, l_item_id,in_item_category_id,l_item_code_num,in_inventory_dept_id,
           in_item_name,in_item_display_name,in_unit,in_item_status_value,in_item_rate,in_cgst,in_sgst,in_igst,in_total_item_rate,in_is_expense,
          in_quantity, in_created_by, in_created_by,in_is_active,in_cgst_amount,in_sgst_amount,in_igst_amount);
          
          if(in_quantity!='')then
 --                added item stock if has initial quantity  
          INSERT INTO  inventory_stock_balance(ay_id, inst_id, inventory_dept_id,
            order_master_id,item_id,quantity,created_by,updated_by,is_active) 
            VALUES(in_ay_id, in_inst_id, in_inventory_dept_id,'0',l_item_id,
             in_quantity,in_created_by, in_created_by,in_is_active);
         end if;
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
        begin
          	update inventory_item_master set valid_to = NOW(), updated_by = in_created_by, updated_on = NOW(),
                is_deleted =1 
            where item_id=in_item_id  and is_deleted = 0 
                 and inst_id = in_inst_id ;

           INSERT INTO inventory_item_master(ay_id,inst_id,item_id,item_category_id,item_code,inventory_dept_id,
              item_name,item_display_name,unit,item_status,item_rate,cgst,sgst,igst,total_item_rate,is_expense,initial_stock,
              created_by,updated_by,is_active,cgst_amount,sgst_amount,igst_amount) 
           VALUES(in_ay_id, in_inst_id, in_item_id,in_item_category_id,in_item_code,in_inventory_dept_id,
               in_item_name,in_item_display_name,in_unit,in_item_status_value,in_item_rate,in_cgst,in_sgst,in_igst,in_total_item_rate,in_is_expense,in_quantity,
               in_created_by,in_created_by,in_is_active,in_cgst_amount,in_sgst_amount,in_igst_amount); 

--           if item entry is not present in stock balance table then insert item entry 
--              else update quantity balance for that item
--           select count(item_id) into item_id_count from inventory_stock_balance
--             where inst_id=in_inst_id and is_active=1 and is_deleted=0 
--             and item_id=in_item_id and inventory_dept_id=in_inventory_dept_id;
--         
--           if(in_quantity!='' and in_is_active=1)then
--             if(item_id_count!=0)then
--               update inventory_stock_balance set valid_to = NOW(), updated_by = in_created_by, updated_on = NOW(),
--                     quantity =in_quantity 
--               where item_id=in_item_id  and is_deleted = 0 
--                     and inst_id = in_inst_id and inventory_dept_id=in_inventory_dept_id;
--               else
-- --                added item stock if has initial quantity  
--                INSERT INTO  inventory_stock_balance(ay_id, inst_id, inventory_dept_id,
--                           order_master_id,item_id,quantity,created_by,updated_by,is_active) 
--                VALUES(in_ay_id, in_inst_id, in_inventory_dept_id,'0',in_item_id,
--                            in_quantity,in_created_by, in_created_by,in_is_active);
--            end if; 
--          end if; 
        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  
end$$

DROP PROCEDURE IF EXISTS `sp_ins_issue_itemDetails_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_issue_itemDetails_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_issue_mst_id` MEDIUMINT(8), IN `in_issue_dtl_id` MEDIUMINT(8), IN `in_inventory_dept_id` MEDIUMINT(8), IN `in_party_type` VARCHAR(20), IN `in_party_id` MEDIUMINT(8), IN `in_total_amount` BIGINT(50), IN `in_issue_date` DATE, IN `in_is_active` TINYINT(1), IN `in_insert_row_count` MEDIUMINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_issue_itemDetails_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_issue_mst_id int;

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

  declare l_insert_sql_str text default 'INSERT INTO inventory_issue_details(ay_id, inst_id, 
    issue_mst_id,issue_dtl_id, item_id,quantity,item_rate,unit,amount,is_active,created_by,
    updated_by,cgst,sgst,igst,total_item_rate) 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_issue_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_issue_mst_id = fn_sequence_generator('INVENTORY_ISSUE_MASTER');
      end;

    when 'U' then
      begin
        set l_issue_mst_id = in_issue_mst_id;
      
      end;
  end case;

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

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

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

      if (l_template_col_name = 'issue_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('INVENTORY_ISSUE_DETAILS');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('INVENTORY_ISSUE_DETAILS');
              
              end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'issue_mst_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = in_issue_mst_id;
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

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

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

    end loop;

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

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

    close cur_json_template;

  end while;

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

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

--           INSERT INTO inventory_issue_master(ay_id,inst_id,issue_mst_id,inventory_dept_id,
--           party_type,party_id, total_amount,issue_date,created_by, updated_by, is_active) 
--           VALUES (in_ay_id, in_inst_id, l_issue_mst_id,in_inventory_dept_id,in_party_type, 
--           in_party_id,in_total_amount,in_issue_date,
--           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 order_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and order_master_id = in_order_master_id
            and is_deleted = 0 and inventory_dept_id=in_inventory_dept_id;

          INSERT INTO order_master(ay_id, inst_id, order_master_id,inventory_dept_id,order_name, 
           order_desc,total_amount,order_date,order_status,fulfil_status,created_by, updated_by, is_active) 
          VALUES (in_ay_id, in_inst_id, in_order_master_id,in_inventory_dept_id,in_order_name, 
           in_order_desc,in_total_amount,in_order_date,in_order_status,in_fulfil_status,
           in_created_by, in_created_by, in_is_active);
                    
          set l_routine_block = 'before execute immediate';
      
           update 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);        
        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_kitchen_item_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_kitchen_item_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_item_id` MEDIUMINT(8), IN `in_item_name` VARCHAR(50), IN `in_item_display_name` VARCHAR(50), IN `in_unit` VARCHAR(20), IN `in_is_active` SMALLINT(5), 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_kitchen_item_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_looping_done int default false;
 declare l_item_id mediumint(8);


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

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

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
            set l_item_id = fn_sequence_generator('KITCHEN_ITEM_MASTER');
            set l_routine_block = 'insert';
      
           INSERT INTO kitchen_item_master(ay_id, inst_id, item_id,
            item_name,item_display_name, unit,created_by, updated_by, is_active) VALUES
                (in_ay_id, in_inst_id, l_item_id,
             in_item_name,in_item_display_name, in_unit,in_created_by, in_created_by, in_is_active);
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
           
        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_leave_balance_emp_store`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_leave_balance_emp_store`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_emp_id` MEDIUMINT(8), IN `in_package_id` MEDIUMINT(8), 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_leave_balance_emp_store';
  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_emp_id_data mediumint(8);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO leave_real_time_emp_balance(ay_id,inst_id, 
                                        emp_id,package_id,leave_type,credit,leave_balance,total_leave,used_leave,
                                        cary_forward_leave,is_active,created_by,updated_by,min_used_leave,
                                       total_max_cf_leave,credit_frequency) 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 = 'leave_real_time_emp_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;
        set l_routine_block = 'before diagnostics';

      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 leave_real_time_emp_balance 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 emp_id=in_emp_id
                     and is_deleted = 0 and is_active=1;

              call sp_execute_immediate (l_insert_sql_str);             
        commit;
      end;

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

		  	update  leave_package_emp_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where emp_id=in_emp_id
              and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;

           insert into  leave_package_emp_map(
             ay_id,inst_id,emp_id,package_id,is_active,created_by, 
              updated_by) 
            values(
             in_ay_id,in_inst_id, 
              in_emp_id,in_package_id,
             in_is_active,in_created_by,in_created_by);
			 
      
          update emp_leave_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 emp_leave_package_master(ay_id, inst_id, package_id, 

              package_name, package_display_name,start_date,end_date, package_desc, package_abbr,is_custom, created_by, updated_by, is_active) 

              VALUES (in_ay_id, in_inst_id, l_package_id, 

              in_package_name, in_package_display_name,in_start_date,in_end_date, in_package_desc, in_package_abbr,in_is_custom,

              in_created_by, in_created_by, in_is_active);

                   

          set l_routine_block = 'before execute immediate';

      

           update emp_leave_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 emp_leave_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 emp_leave_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_manage_students_roll_numbers`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_manage_students_roll_numbers`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_class_id` VARCHAR(10), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_manage_students_roll_numbers';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';
  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 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_student_id mediumint(8);
  declare l_class_roll_num smallint(5) default 0; 
  declare l_insert_sql_str MEDIUMTEXT default 'INSERT INTO temp_manage_students_roll_numbers(ay_id, inst_id,
    class_id, student_id, class_roll_num,  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 = 'temp_manage_students_roll_numbers' 
  order by col_pos;
  declare cur_temp_manage_students_roll_numbers cursor for
  select student_id, class_roll_num from temp_manage_students_roll_numbers 
  where ay_id = in_ay_id and inst_id=in_inst_id
    and class_id=in_class_id
  order by 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_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 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
              TRUNCATE table temp_manage_students_roll_numbers;
              call sp_execute_immediate (l_insert_sql_str); 
              open cur_temp_manage_students_roll_numbers;
              cursor_loop: loop
                fetch cur_temp_manage_students_roll_numbers into l_student_id, l_class_roll_num;
                if l_looping_done then
                leave cursor_loop;
                end if;
                update  student_master set class_roll_num=l_class_roll_num, updated_by=in_created_by
                  where inst_id = in_inst_id and student_id = l_student_id and is_deleted = 0;
                end loop;
        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_meal_calendar_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_meal_calendar_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_meal_dtl_id` MEDIUMINT(8), IN `in_meal_mst_id` MEDIUMINT(8), IN `in_standard_id` CHAR(2), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_meal_calendar_details_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  meal_calendar_details(ay_id, 
                                                                                inst_id, 
                                                                                                                meal_dtl_id,
                                                                                meal_mst_id, 
                                                                                    standard_id,
                                                                                            meal_cal_type, 
                                                                                                               meal_date,
                                                                                        meal_day,
                                                                                        meal_type,
                                                                                      meal_label,
                                                                                      meal_value,
                                                                              status,
                                                                                          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 cursor for 
  select col_name from json_template_master 
  where tbl_name = 'meal_calendar_details' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
      begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);
      if (l_template_col_name = 'meal_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('MEAL_CALENDAR_DETAIL');
              end;
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('MEAL_CALENDAR_DETAIL');
               -- 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  meal_calendar_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 meal_mst_id = in_meal_mst_id and standard_id = in_standard_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_meal_calendar_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_meal_calendar_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_standard_id` CHAR(2), IN `in_meal_mst_id` MEDIUMINT(8), IN `in_meal_calendar_valid_from` DATE, IN `in_meal_calendar_valid_to` DATE, IN `in_title` VARCHAR(100), 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_meal_calendar_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare l_meal_mst_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_meal_mst_id = fn_sequence_generator('MEAL_CALENDER_MASTER');
insert into  meal_calendar_master(ay_id,
                                 inst_id,
                                standard_id,
                            meal_mst_id,
                            meal_calendar_valid_from,
                            meal_calendar_valid_to,
                                title,
                            is_active,
                            created_by, updated_by)                              
          values(in_ay_id,
                       in_inst_id,
                       in_standard_id,
                       l_meal_mst_id,
                       in_meal_calendar_valid_from,
                      in_meal_calendar_valid_to,
                       in_title,
                       in_is_active,
                       in_created_by,
                       in_created_by);
         end;    
         when 'U' then
     set l_routine_block = 'update';      
         begin
             update meal_calendar_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where  meal_mst_id = in_meal_mst_id and  is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;
            insert into  meal_calendar_master(ay_id,
                                 inst_id,
                                standard_id,
                            meal_mst_id,
                            meal_calendar_valid_from,
                            meal_calendar_valid_to,
                                title,
                            is_active,
                            created_by, updated_by)                              
          values(in_ay_id,
                       in_inst_id,
                       in_standard_id,
                       in_meal_mst_id,
                       in_meal_calendar_valid_from,
                      in_meal_calendar_valid_to,
                       in_title,
                       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_news_posts`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_news_posts`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_org_id` SMALLINT(5), IN `in_inst_id` SMALLINT(5), IN `in_post_id` MEDIUMINT(8), IN `in_post_category` SMALLINT(5), IN `in_post_title` VARCHAR(100), IN `in_post_slug` VARCHAR(100), IN `in_post_content` TEXT, IN `in_post_date` DATE, IN `in_post_image` VARCHAR(100), IN `in_original_image_name` VARCHAR(100), IN `in_comments_enabled` TINYINT(2), IN `in_scope` VARCHAR(20), 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_post_id` MEDIUMINT(8))
    NO SQL
begin
     declare l_routine_name varchar(50) default 'sp_ins_news_posts';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
       
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc,
       'ERROR', 0, in_created_by);
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin
          set l_routine_block = 'insert';
          set in_post_id = fn_sequence_generator('NEWS_POST');
          set out_post_id = in_post_id ;
  insert into  news_posts(ay_id,
                            org_id,
                          inst_id,
                             post_id,
                                 post_category,
                                post_title,
                                 post_slug,
                                post_content,
                                post_date,
                             post_image,
                             original_image_name,
                                comments_enabled,
                               scope,
                              status,
                              created_by,
                            is_active,updated_by
                            )                              
          values(in_ay_id,in_org_id,in_inst_id,in_post_id,
                            in_post_category,
                            in_post_title,
                            in_post_slug,
                            in_post_content,
             in_post_date,
               in_post_image,
             in_original_image_name,
                            in_comments_enabled,
                            in_scope,
                           in_status,
                           in_created_by,
                            in_is_active,in_created_by);
           
         end;    
 
         when 'U' then
     set l_routine_block = 'update';      
         begin
             update news_posts set  updated_by = in_created_by,updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where  post_id = in_post_id and  is_deleted = 0  
               and inst_id = in_inst_id;
         
            insert into news_posts(ay_id,org_id,
                                 inst_id,
                               post_id,
                            post_category,
                            post_title,
                            post_slug,
                            post_content,
                            post_date,
                           post_image,
                          original_image_name,
                            comments_enabled,
                            scope,
                           status,
                            created_by,
                            is_active,updated_by
                            )                              
          values(in_ay_id,in_org_id,
             in_inst_id,
              in_post_id,
                            in_post_category,
                            in_post_title,
                            in_post_slug,
                            in_post_content,
                            in_post_date,
                            in_post_image,
                           in_original_image_name,
                            in_comments_enabled,
                            in_scope,
                           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 = out_post_id;
    set  out_post_id=in_post_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_notification_config_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notification_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_sms_override` TINYINT(1), IN `in_force_stop_notifications` 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_notification_config_json';
  declare l_routine_block varchar(50);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

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

  declare l_insert_sql_str text default 'INSERT INTO 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, 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 = 'notification_config' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

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

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

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

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

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

    
    

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

      
      

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

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

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

    end loop;

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

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

    
    

    close cur_json_template;

  end while;

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

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

              update institution_config set sms_override=in_sms_override, updated_by = in_created_by, 
               updated_on = now(), is_deleted = 1 
               where inst_id = in_inst_id and is_deleted = 0;

        commit;
      end;

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

         
          update notification_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);  

          update institution_config set sms_override=in_sms_override,
            force_stop_notifications=in_force_stop_notifications , updated_by = in_created_by, 
             updated_on = now()
             where inst_id = in_inst_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_notification_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notification_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notification_id` MEDIUMINT(8), IN `in_notif_template_id` MEDIUMINT(8), IN `in_notif_datetime` TIMESTAMP, IN `in_send_group_json` TEXT, IN `in_is_sms` TINYINT(1), IN `in_sms_from_mobile_no` VARCHAR(15), IN `in_sms_body` VARCHAR(1000), IN `in_sms_params` VARCHAR(500), IN `in_sms_opt1` VARCHAR(50), IN `in_sms_opt2` VARCHAR(50), IN `in_is_mail` TINYINT(1), IN `in_email_subject` VARCHAR(200), IN `in_email_from` VARCHAR(50), IN `in_email_cc_address` VARCHAR(200), IN `in_email_bcc_address` VARCHAR(200), IN `in_email_replyto` VARCHAR(50), IN `in_email_body` VARCHAR(5000), IN `in_email_params` VARCHAR(500), IN `in_email_attach_path1` VARCHAR(100), IN `in_email_attach_path2` VARCHAR(100), IN `in_email_opt1` VARCHAR(50), IN `in_email_opt2` VARCHAR(50), IN `in_is_app` TINYINT(1), IN `in_push_message` VARCHAR(1000), IN `in_push_title` VARCHAR(100), IN `in_push_subtitle` VARCHAR(100), IN `in_push_action` VARCHAR(100), IN `in_push_vibrate` TINYINT(1), IN `in_push_sound` TINYINT(1), IN `in_push_large_icon` VARCHAR(50), IN `in_push_small_icon` VARCHAR(50), IN `in_push_registration_id` VARCHAR(100), IN `in_push_params` VARCHAR(500), IN `in_push_opt1` VARCHAR(50), IN `in_push_opt2` VARCHAR(50), IN `in_is_web` TINYINT(1), IN `in_web_subject` VARCHAR(200), IN `in_web_params` VARCHAR(500), IN `in_web_from` VARCHAR(50), IN `in_web_description` VARCHAR(2000), IN `in_web_icon` VARCHAR(50), IN `in_web_action_link` VARCHAR(100), IN `in_web_opt1` VARCHAR(50), IN `in_web_opt2` VARCHAR(50), IN `in_actual_datetime` TIMESTAMP, IN `in_priority` TINYINT(1), IN `in_status` VARCHAR(15), IN `in_sms_compulsion` TINYINT(1), IN `in_updated_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_notif_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_ins_notification_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(50);
  declare l_notification_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_updated_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_notification_master';
            set l_notification_id =fn_sequence_generator('NOTIFICATION_MASTER');
            insert into  notification_master(ay_id,inst_id,notification_id ,notif_template_id ,notif_datetime ,
              send_group_json,is_sms,sms_from_mobile_no,sms_body,sms_params,sms_opt1,sms_opt2,is_mail,
              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,is_app,
              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,is_web,web_subject,
              web_params,web_from,web_description,web_icon,web_action_link,web_opt1,web_opt2,
              actual_datetime,priority ,status ,sms_compulsion, created_by ,updated_by,is_active ) 
            values(in_ay_id,in_inst_id,l_notification_id ,in_notif_template_id ,in_notif_datetime ,
              in_send_group_json,in_is_sms,in_sms_from_mobile_no,in_sms_body,in_sms_params,
              in_sms_opt1,in_sms_opt2,in_is_mail,in_email_subject,in_email_from,in_email_cc_address,
              in_email_bcc_address,in_email_replyto,in_email_body,in_email_params,in_email_attach_path1,
              in_email_attach_path2,in_email_opt1,in_email_opt2,in_is_app,in_push_message,in_push_title,
              in_push_subtitle,in_push_action,in_push_vibrate,in_push_sound,in_push_large_icon,
              in_push_small_icon,in_push_registration_id,in_push_params,in_push_opt1,in_push_opt2,
              in_is_web,in_web_subject,in_web_params,in_web_from,in_web_description,in_web_icon,
              in_web_action_link,in_web_opt1,in_web_opt2,in_actual_datetime,in_priority ,in_status ,
              in_sms_compulsion, in_updated_by,in_updated_by ,in_is_active);
          end;    
        when 'U' then
       set l_routine_block = 'update_notification_master';  
          begin
     end;    
      end case;
    commit;
     set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
    set out_notif_id= l_notification_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_notif_app_log`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_app_log`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notification_id` MEDIUMINT(8), IN `in_user_type` CHAR(3), IN `in_user_id` VARCHAR(50), IN `in_push_title` VARCHAR(100), IN `in_push_subtitle` VARCHAR(100), IN `in_push_action` VARCHAR(100), IN `in_push_vibrate` TINYINT(1), IN `in_push_sound` TINYINT(1), IN `in_push_message` VARCHAR(1000), IN `in_push_large_icon` VARCHAR(50), IN `in_push_small_icon` VARCHAR(50), IN `in_push_registration_id` VARCHAR(100), IN `in_push_opt1` VARCHAR(50), IN `in_push_opt2` VARCHAR(50), IN `in_recipient_type` VARCHAR(25), IN `in_priority` TINYINT(1), IN `in_expiries_on` TIMESTAMP, IN `in_sent_on` TIMESTAMP, IN `in_max_retry_count` TINYINT(2), IN `in_retry_count` TINYINT(2), IN `in_retry_interval` SMALLINT(5), IN `in_retried_on` TIMESTAMP, IN `in_status` VARCHAR(15), IN `in_response_message` VARCHAR(10000), IN `in_updated_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_notif_app_log';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(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(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_updated_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_notif_app_log';
		   insert into  notif_app_log(ay_id,inst_id,notification_id,user_type,user_id, push_title,push_subtitle,push_action,push_vibrate,push_sound,push_message,push_large_icon,push_small_icon,
push_registration_id,push_opt1,push_opt2,priority,expiries_on,sent_on,max_retry_count,retry_count,retry_interval,retried_on,status,response_message,created_by ,updated_by,is_active ) 
            values(in_ay_id,in_inst_id,in_notification_id,in_user_type,in_user_id,in_push_title,in_push_subtitle,in_push_action,in_push_vibrate,in_push_sound,in_push_message,in_push_large_icon,in_push_small_icon,
in_push_registration_id,in_push_opt1,in_push_opt2,in_priority,in_expiries_on,in_sent_on,in_max_retry_count,in_retry_count,in_retry_interval,in_retried_on,in_status,in_response_message,in_updated_by,in_updated_by ,in_is_active);
          end;    
        when 'U' then
       set l_routine_block = 'update_notif_app_log';  
          begin
     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_notif_email_log`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_email_log`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notification_id` MEDIUMINT(8), IN `in_user_type` CHAR(3), IN `in_user_id` MEDIUMINT(8), IN `in_email_subject` VARCHAR(100), IN `in_email_from` VARCHAR(50), IN `in_email_to` VARCHAR(50), IN `in_email_cc_address` VARCHAR(200), IN `in_email_bcc_address` VARCHAR(200), IN `in_email_replyto` VARCHAR(50), IN `in_email_body` VARCHAR(5000), IN `in_email_attach_path1` VARCHAR(100), IN `in_email_attach_path2` VARCHAR(100), IN `in_email_opt1` VARCHAR(50), IN `in_email_opt2` VARCHAR(50), IN `in_recipient_type` VARCHAR(25), IN `in_priority` TINYINT(1), IN `in_expiries_on` TIMESTAMP, IN `in_sent_on` TIMESTAMP, IN `in_max_retry_count` TINYINT(2), IN `in_retry_count` TINYINT(2), IN `in_retry_interval` SMALLINT(5), IN `in_retried_on` TIMESTAMP, IN `in_status` VARCHAR(15), IN `in_updated_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_notif_email_log';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(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(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_updated_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_notif_email_log';
		   insert into  notif_email_log(ay_id,inst_id,notification_id,user_type,user_id, email_subject,email_from,email_to,email_cc_address,email_bcc_address,email_replyto,email_body,email_attach_path1,
email_attach_path2,email_opt1,email_opt2,recipient_type,priority,expiries_on,sent_on,max_retry_count,retry_count,retry_interval,retried_on,status,created_by ,updated_by,is_active ) 
            values(in_ay_id,in_inst_id,in_notification_id,in_user_type,in_user_id,in_email_subject,in_email_from,in_email_to,in_email_cc_address,in_email_bcc_address,in_email_replyto,in_email_body,in_email_attach_path1,
in_email_attach_path2,in_email_opt1,in_email_opt2,in_recipient_type,in_priority,in_expiries_on,in_sent_on,in_max_retry_count,in_retry_count,in_retry_interval,in_retried_on,in_status,in_updated_by,in_updated_by ,in_is_active);
          end;    
        when 'U' then
       set l_routine_block = 'update_notif_email_log';  
          begin
     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_notif_sms_log`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_sms_log`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notification_id` MEDIUMINT(8), IN `in_user_type` CHAR(3), IN `in_user_id` MEDIUMINT(8), IN `in_sms_from_mobile_no` VARCHAR(15), IN `in_sms_to_mobile_no` VARCHAR(15), IN `in_sms_body` VARCHAR(1000), IN `in_sms_opt1` VARCHAR(50), IN `in_sms_opt2` VARCHAR(50), IN `in_recipient_type` VARCHAR(25), IN `in_priority` TINYINT(1), IN `in_expiries_on` TIMESTAMP, IN `in_sent_on` TIMESTAMP, IN `in_max_retry_count` TINYINT(2), IN `in_retry_count` TINYINT(2), IN `in_retry_interval` SMALLINT(5), IN `in_retried_on` TIMESTAMP, IN `in_status` VARCHAR(15), IN `in_response` VARCHAR(10000), IN `in_sms_credits` SMALLINT(5), IN `in_updated_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_notif_sms_log';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(50);
  declare l_inst_count bigint(50);
  declare l_sms_credit_balance bigint(50);
  declare l_sms_balance bigint(50);
  declare l_sms_credits 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(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_updated_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_notif_sms_log';
		   
		   insert into  notif_sms_log(ay_id,inst_id,notification_id,user_type,user_id,sms_from_mobile_no,
        sms_to_mobile_no,sms_body,sms_opt1,sms_opt2,recipient_type,priority,expiries_on,sent_on,
        max_retry_count,retry_count,retry_interval,retried_on,status,response,sms_credits,created_by ,
        updated_by,is_active ) 
            values(in_ay_id,in_inst_id,in_notification_id,in_user_type,in_user_id,in_sms_from_mobile_no,
        in_sms_to_mobile_no,in_sms_body,in_sms_opt1,in_sms_opt2,in_recipient_type,in_priority,
        in_expiries_on,in_sent_on,in_max_retry_count,in_retry_count,in_retry_interval,in_retried_on,
        in_status,in_response,in_sms_credits,in_updated_by,in_updated_by ,in_is_active);


            SELECT count(inst_id) INTO l_inst_count from sms_credit_status
               where inst_id=in_inst_id and is_deleted=0 and is_active=1;
             
             IF(l_inst_count=0) THEN

                  set l_sms_credits= 0 - in_sms_credits;

                  insert into  sms_credit_status(
                              inst_id,sms_credit_balance,rate,is_active,created_by,updated_by)
                  values(in_inst_id,l_sms_credits,'',in_is_active,`in_updated_by`,`in_updated_by`);
              
             ELSE
                
               select (sms_credit_balance) INTO l_sms_balance
                 from sms_credit_status
                 where inst_id=in_inst_id and is_active=1 and is_deleted=0 ;

                set l_sms_credits= l_sms_balance - in_sms_credits;

               update  sms_credit_status set valid_to = NOW(), updated_by = `in_updated_by`, 
                    updated_on = NOW(), is_deleted = 0,sms_credit_balance= l_sms_credits
                    where is_deleted = 0 and inst_id = in_inst_id;

                
              END IF;
                      end;    
  
        when 'U' then
       set l_routine_block = 'update_notif_sms_log';  
          begin
           
            
     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_notif_temp_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_temp_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notif_template_id` MEDIUMINT(8), IN `in_notif_name` VARCHAR(50), IN `in_notif_desc` VARCHAR(100), IN `in_txn_category` VARCHAR(50), IN `in_txn_sub_category` VARCHAR(50), IN `in_is_web` TINYINT(1), IN `in_is_mail` TINYINT(1), IN `in_is_app` TINYINT(1), IN `in_is_sms` TINYINT(1), IN `in_handler_method` VARCHAR(50), IN `in_web_template_id` MEDIUMINT(8), IN `in_web_subject` VARCHAR(100), IN `in_web_params` VARCHAR(500), IN `in_web_description` VARCHAR(2000), IN `in_web_icon` VARCHAR(50), IN `in_web_action_link` VARCHAR(100), IN `in_mail_template_id` MEDIUMINT(8), IN `in_email_subject` VARCHAR(100), IN `in_email_from` VARCHAR(50), IN `in_email_body` VARCHAR(5000), IN `in_email_params` VARCHAR(500), IN `in_app_template_id` MEDIUMINT(8), IN `in_push_message` VARCHAR(1000), IN `in_push_title` VARCHAR(100), IN `in_push_params` VARCHAR(500), IN `in_sms_template_id` MEDIUMINT(8), IN `in_sms_from_mobile_no` VARCHAR(15), IN `in_sms_body` VARCHAR(1000), IN `in_sms_params` VARCHAR(500), 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_notifTemplate_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_web_template_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_block, l_err_code, l_err_desc, 
                'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
           /*set l_web_template_id = fn_sequence_generator('NOTIF_WEB_TEMPLATE_MASTER'); */


            /*insertion for Notification Config*/
            insert into notification_config(
              ay_id,inst_id,notif_template_id,notif_name,
              notif_desc,txn_category,txn_sub_category,is_web,web_template_id,
              is_mail,mail_template_id,is_app,app_template_id, 
              is_sms,sms_template_id,handler_method,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_notif_template_id,in_notif_name,
              in_notif_desc,in_txn_category,in_txn_sub_category,
              in_is_web,in_web_template_id,in_is_mail,in_mail_template_id,
              in_is_app,in_app_template_id,in_is_sms,in_sms_template_id,
              in_handler_method,in_is_active,in_created_by);

            /*insertion for Web template*/
            insert into notif_web_template_master(
              ay_id,inst_id,web_template_id,web_subject,
              web_params,web_description,web_icon,
              web_action_link,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_web_template_id,in_web_subject,
              in_web_params,in_web_description,
              in_web_icon,in_web_action_link, in_is_active,in_created_by);
            
            /*insertion for Email template*/
            insert into notif_email_template_master(
              ay_id,inst_id,mail_template_id,email_subject,
              email_from,email_body,email_params,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_mail_template_id,in_email_subject,
              in_email_from,in_email_body,
              in_email_params,in_is_active,in_created_by);

            /*insertion for App template*/
            insert into notif_app_template_master(
              ay_id,inst_id,app_template_id,push_message,
              push_title,push_params,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_app_template_id,in_push_message,
              in_push_title,in_push_params,in_is_active,in_created_by);

            /*insertion for SMS template*/
            insert into  notif_sms_template_master(
              ay_id,inst_id,sms_template_id,sms_from_mobile_no,
              sms_body,sms_params,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_sms_template_id,in_sms_from_mobile_no,
              in_sms_body,in_sms_params,in_is_active,in_created_by);


            if(in_inst_id=0)then
                CALL sp_ins_notif_temp_master_all_inst('I', in_inst_id, in_created_by, l_err_code, l_err_desc); 
              end if;

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

            /*Code to update Notification Configuration*/
            update  notification_config set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(),is_deleted=1
            where notif_template_id=in_notif_template_id  
             and is_deleted = 0 and ay_id = in_ay_id
            	and inst_id = in_inst_id;

           insert into  notification_config(
              ay_id,inst_id, notif_template_id, notif_name,
              notif_desc,txn_category,txn_sub_category,
              is_web,web_template_id,is_mail,mail_template_id,is_app,app_template_id,
            is_sms,sms_template_id,handler_method,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_notif_template_id,in_notif_name,
              in_notif_desc,in_txn_category,in_txn_sub_category,
              in_is_web,in_web_template_id,in_is_mail,in_mail_template_id,in_is_app,
            in_app_template_id,in_is_sms,in_sms_template_id,in_handler_method,in_is_active,in_created_by);


            /*Code to update web Notificaiton Template*/
          	update  notif_web_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(),is_deleted=1
            where web_template_id=in_web_template_id  
             and is_deleted = 0 and is_active = in_is_active
            	and inst_id = in_inst_id and ay_id = in_ay_id;

           insert into notif_web_template_master(
              ay_id,inst_id, web_template_id, web_subject,
              web_params,web_description,web_icon,
              web_action_link,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_web_template_id,in_web_subject,
              in_web_params,in_web_description,in_web_icon,
              in_web_action_link,in_is_active,in_created_by);
            
          /*Code to update Email Notificaiton Template*/
          	update  notif_email_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(),is_deleted=1
            where mail_template_id=in_mail_template_id  
             and is_deleted = 0 and is_active = in_is_active
            	and inst_id = in_inst_id and ay_id = in_ay_id;

           insert into notif_email_template_master(
              ay_id,inst_id, mail_template_id, email_subject,
              email_from,email_body,email_params,
              is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_mail_template_id,in_email_subject,
              in_email_from,in_email_body,in_email_params,
              in_is_active,in_created_by);
            
          /*Code to update App Notificaiton Template*/
          	update  notif_app_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(),is_deleted=1
            where app_template_id=in_app_template_id  
             and is_deleted = 0 and is_active = in_is_active
            	and inst_id = in_inst_id and ay_id = in_ay_id;

           insert into  notif_app_template_master(
              ay_id,inst_id, app_template_id,push_message,
              push_title,push_params,
              is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_app_template_id,in_push_message,
              in_push_title,in_push_params,
              in_is_active,in_created_by);

          /*Code to update SMS Notificaiton Template*/
          	update  notif_sms_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(),is_deleted=1
            where sms_template_id=in_sms_template_id  
             and is_deleted = 0 and is_active = in_is_active
            	and inst_id = in_inst_id and ay_id = in_ay_id;

           insert into  notif_sms_template_master(
              ay_id,inst_id, sms_template_id,sms_from_mobile_no,
              sms_body,sms_params,is_active,created_by) 
            values(
              in_ay_id,in_inst_id,in_app_template_id,in_sms_from_mobile_no,
              in_sms_body,in_sms_params,in_is_active,in_created_by);

          if(in_inst_id=0)then
                CALL sp_ins_notif_temp_master_all_inst('I', in_inst_id, in_created_by, l_err_code, l_err_desc); 
              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_notif_temp_master_all_inst`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_temp_master_all_inst`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
BEGIN
declare l_routine_name varchar(50) default 'sp_ins_notif_temp_master_all_inst';
declare l_err_code char(5) default '00000';
declare l_err_desc text default '';        
declare l_routine_block varchar(15);
declare l_looping_done int default false;
declare l_inst_id smallint(5) default 0; 
declare l_delete_flag tinyint(1) default 0;      

declare cur_notif_temp_mst cursor for 
  select inst_id,is_deleted
  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, 'SQL Exception Handler', l_err_code, l_err_desc, 
      'ERROR', 0, in_created_by);

    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

       end;
open cur_notif_temp_mst;

  cursor_loop_new:loop
     fetch cur_notif_temp_mst into l_inst_id, l_delete_flag;
         if l_looping_done then
             leave cursor_loop_new;
         end if;
      
  start transaction;
  
    case in_dml_mode 
      when 'I' then
        begin
          set l_routine_block = 'insert';
            if(in_inst_id=0)then
              
              INSERT INTO notification_config(ay_id,inst_id, notif_template_id, notif_name,
              notif_desc,txn_category,txn_sub_category,
              is_web,web_template_id,is_mail,mail_template_id,is_app,app_template_id,
              is_sms,sms_template_id,handler_method,is_active,created_by)
                    select '', l_inst_id, notif_template_id, notif_name,
              notif_desc,txn_category,txn_sub_category,
              is_web,web_template_id,is_mail,mail_template_id,is_app,app_template_id,
              is_sms,sms_template_id,handler_method,is_active,created_by
                    from notification_config where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;
						 
				      INSERT INTO notif_web_template_master(ay_id,inst_id, web_template_id, web_subject,
              web_params,web_description,web_icon,web_action_link,is_active,created_by)
                    select '', l_inst_id, web_template_id, web_subject,
              web_params,web_description,web_icon,web_action_link,is_active,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(ay_id,inst_id,mail_template_id,email_subject,
              email_from,email_body,email_params,is_active,created_by)
                    select '',l_inst_id, mail_template_id,email_subject,
              email_from,email_body,email_params,is_active,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_app_template_master(ay_id,inst_id,app_template_id,push_message,
              push_title,push_params,is_active,created_by)
                    select '',l_inst_id,app_template_id,push_message,
              push_title,push_params,is_active,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_sms_template_master(ay_id,inst_id,sms_template_id,sms_from_mobile_no,
              sms_body,sms_params,is_active,created_by)
                    select '',l_inst_id, sms_template_id,sms_from_mobile_no,
              sms_body,sms_params,is_active,created_by
                    from notif_sms_template_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;


            end if;
        end;    

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

          if(in_inst_id=0)then

              /* Update Notification Configuration */
              update notification_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;

           
               INSERT INTO notification_config(ay_id,inst_id, notif_template_id, notif_name,
              notif_desc,txn_category,txn_sub_category,
              is_web,web_template_id,is_mail,mail_template_id,is_app,app_template_id,
            is_sms,sms_template_id,handler_method,is_active,created_by)
                    select '', l_inst_id,notif_template_id, notif_name,
              notif_desc,txn_category,txn_sub_category,is_web,web_template_id,is_mail,
                      mail_template_id,is_app,app_template_id,
            is_sms,sms_template_id,handler_method,is_active,created_by
                    from notification_config where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;

              /* Update Web Notification Template */
              update notif_web_template_master 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;

               INSERT INTO notif_web_template_master(ay_id,inst_id, web_template_id, web_subject,
              web_params,web_description,web_icon,web_action_link,is_active,created_by)
                    select '',l_inst_id, web_template_id, web_subject,
              web_params,web_description,web_icon,web_action_link,is_active,created_by
                    from notif_web_template_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;

              /* Update Email Notification Template */
              update notif_email_template_master 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;

               INSERT INTO notif_email_template_master(ay_id,inst_id, mail_template_id, email_subject,
              email_from,email_body,email_params,is_active,created_by)
                    select '',l_inst_id,mail_template_id, email_subject,email_from,
                      email_body,email_params,is_active,created_by
                    from notif_web_template_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;

            /* Update App Notification Template */
              update notif_app_template_master 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;

               INSERT INTO notif_app_template_master(ay_id,inst_id, app_template_id,push_message,
              push_title,push_params,is_active,created_by)
                    select '',l_inst_id,app_template_id,push_message,push_title,push_params,
              is_active,created_by
                    from notif_app_template_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;

              /* Update SMS Notification Template */
              update notif_sms_template_master 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;

               INSERT INTO notif_sms_template_master(ay_id,inst_id, sms_template_id,sms_from_mobile_no,
              sms_body,sms_params,is_active,created_by)
                    select '', l_inst_id, sms_template_id,sms_from_mobile_no,
              sms_body,sms_params,is_active,created_by
                    from notif_sms_template_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;

           end if;    
        end;    

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

DROP PROCEDURE IF EXISTS `sp_ins_notif_temp_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_temp_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_notif_temp_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 notif_web_template_master(web_template_id,inst_id,
    web_subject,web_params,web_description,web_icon,web_action_link, 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 cursor for 
  select col_name from json_template_master 
  where tbl_name = 'notif_web_template_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';

    #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 = 'asset_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
--                set l_template_col_value = fn_sequence_generator('QAMS_ASSET_MASTER');
              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 book_chapter_map set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where 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_notif_web_log`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_notif_web_log`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_notification_id` MEDIUMINT(8), IN `in_user_type` CHAR(3), IN `in_user_id` MEDIUMINT(8), IN `in_web_from` VARCHAR(50), IN `in_web_subject` VARCHAR(100), IN `in_web_description` VARCHAR(2000), IN `in_web_icon` VARCHAR(50), IN `in_web_action_link` VARCHAR(100), IN `in_web_opt1` VARCHAR(50), IN `in_web_opt2` VARCHAR(50), IN `in_recipient_type` VARCHAR(25), IN `in_priority` TINYINT(1), IN `in_expiries_on` TIMESTAMP, IN `in_sent_on` TIMESTAMP, IN `in_is_read` TINYINT(1), IN `in_is_star` TINYINT(1), IN `in_opt1` VARCHAR(50), IN `in_opt2` VARCHAR(50), IN `in_status` VARCHAR(15), IN `in_updated_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_notif_web_log';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_routine_block varchar(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(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_updated_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_notif_web_log';
		   insert into  notif_web_log(ay_id,inst_id,notification_id,user_type,user_id, web_from,web_subject,web_description,web_icon,web_action_link,web_opt1,web_opt2,recipient_type,priority,expiries_on,sent_on,is_read,is_star,opt1,opt2,status,created_by ,updated_by,is_active ) 
            values(in_ay_id,in_inst_id,in_notification_id,in_user_type,in_user_id,in_web_from,in_web_subject,in_web_description,in_web_icon,in_web_action_link,in_web_opt1,in_web_opt2,in_recipient_type,in_priority,in_expiries_on,in_sent_on,in_is_read,in_is_star,in_opt1,in_opt2,in_status,in_updated_by,in_updated_by ,in_is_active);
          end;    
        when 'U' then
       set l_routine_block = 'update_notif_web_log';  
          begin
     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_online_admission_parent_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_online_admission_parent_master`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_student_id` MEDIUMINT(8), IN `in_parent_id` MEDIUMINT(8), IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_relation_type` VARCHAR(25), IN `in_relation` VARCHAR(25), IN `in_blood_group` VARCHAR(15), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_caste` VARCHAR(25), IN `in_profile_logo_path` VARCHAR(100), IN `in_student_id_default` MEDIUMINT, IN `in_email_main` VARCHAR(50), IN `in_email_alt` VARCHAR(50), IN `in_fixed_phone_1` VARCHAR(20), IN `in_fixed_phone_2` VARCHAR(20), IN `in_mobile_phone_1` VARCHAR(20), IN `in_mobile_phone_2` VARCHAR(20), IN `in_occupation` VARCHAR(20), IN `in_income_bracket` VARCHAR(20), IN `in_edu_qual_degree` VARCHAR(25), IN `in_edu_qual_stream` VARCHAR(25), IN `in_aadhar_card_num` VARCHAR(12), IN `in_pan_card_num` VARCHAR(10), IN `in_passport_num` VARCHAR(10), IN `in_curr_addr_line_1` VARCHAR(25), IN `in_curr_addr_line_2` VARCHAR(25), IN `in_curr_locality` INT(4), IN `in_curr_city` INT(4), IN `in_curr_state` INT(4), IN `in_curr_country` INT(4), IN `in_curr_pincode` MEDIUMINT(8), IN `in_is_addr_replicated` TINYINT(1), IN `in_perm_addr_line_1` VARCHAR(25), IN `in_perm_addr_line_2` VARCHAR(25), IN `in_perm_locality` INT(4), IN `in_perm_city` INT(4), IN `in_perm_state` INT(4), IN `in_perm_country` INT(4), IN `in_perm_pincode` MEDIUMINT(8), IN `in_note` VARCHAR(100), IN `in_bulk_upload_status` TINYINT(3), IN `in_stud_bulk_file_upload_id` MEDIUMINT(8), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_parent_id` CHAR(5), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_ins_online_admission_parent_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '00000';    	
  declare l_routine_block varchar(15) default '00000';
  declare l_parent_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;
          begin
           set l_routine_block = 'insert';
			  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, 
                   	birth_date,gender,relation_type,relation,blood_group,birth_place,nationality,language,religion,caste,
                    profile_logo_path,student_id_default,email_main,email_alt,
                   fixed_phone_1,fixed_phone_2,mobile_phone_1, mobile_phone_2,occupation,income_bracket ,edu_qual_degree ,edu_qual_stream ,
                   aadhar_card_num, pan_card_num,  passport_num , curr_addr_line_1,curr_addr_line_2,
                   curr_locality,curr_city,curr_state,curr_country,curr_pincode,is_addr_replicated , perm_addr_line_1, perm_addr_line_2 , 
                   perm_locality , perm_city , perm_state, perm_country , perm_pincode, note,
                  bulk_upload_status, stud_bulk_file_upload_id, is_active,created_by, updated_by) 	 						
            values(in_ay_id,in_inst_id,l_parent_id,in_salutation,in_first_name ,in_middle_name,in_last_name,in_birth_date ,in_gender ,
                 in_relation_type ,in_relation ,in_blood_group ,in_birth_place,in_nationality , in_language ,
				         in_religion,in_caste ,in_profile_logo_path,in_student_id_default,in_email_main, in_email_alt ,in_fixed_phone_1, in_fixed_phone_2,
                 in_mobile_phone_1 ,in_mobile_phone_2,in_occupation ,in_income_bracket, in_edu_qual_degree , in_edu_qual_stream,
                 in_aadhar_card_num ,in_pan_card_num ,in_passport_num ,in_curr_addr_line_1,in_curr_addr_line_2 ,in_curr_locality ,
                 in_curr_city,in_curr_state ,in_curr_country,in_curr_pincode ,in_is_addr_replicated ,in_perm_addr_line_1,
                 in_perm_addr_line_2, in_perm_locality ,in_perm_city , in_perm_state , in_perm_country,
                  in_perm_pincode ,in_note, in_bulk_upload_status, in_stud_bulk_file_upload_id,
                 in_is_active, in_created_by, in_created_by);
          end;    
    commit;
	 set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
  Set out_parent_id=l_parent_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_online_student_admission_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_online_student_admission_master`(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_enrolled_for_std` CHAR(2), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_blood_group` VARCHAR(10), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_student_category` VARCHAR(20), IN `in_student_subcategory` VARCHAR(20), IN `in_consession_category` VARCHAR(20), IN `in_disability` VARCHAR(20), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_locality` VARCHAR(25), IN `in_city` VARCHAR(25), IN `in_district` VARCHAR(20), IN `in_state` VARCHAR(20), IN `in_country` VARCHAR(25), IN `in_pincode` MEDIUMINT(8), IN `in_mobile_phone_main` VARCHAR(15), IN `in_email_main` VARCHAR(50), IN `in_identification_mark_1` VARCHAR(50), IN `in_aadhar_card_num` VARCHAR(12), IN `in_passport_num` VARCHAR(15), IN `in_prev_school_name` VARCHAR(50), IN `in_prev_school_address` VARCHAR(50), IN `in_prev_school_board` VARCHAR(20), IN `in_admission_ref` VARCHAR(25), IN `in_enrollment_date` DATE, IN `in_stud_status` VARCHAR(25), IN `in_is_active` TINYINT(1), IN `in_is_new_admission` TINYINT(3), IN `in_distance_from_school` SMALLINT(25), IN `in_special_interest` VARCHAR(100), IN `in_profile_logo_path` VARCHAR(100), IN `in_is_sibling` TINYINT(3), IN `in_sibling_detail` VARCHAR(100), IN `in_father_salutation` VARCHAR(10), IN `in_father_first_name` VARCHAR(20), IN `in_father_middle_name` VARCHAR(20), IN `in_father_last_name` VARCHAR(20), IN `in_father_gender` ENUM('M','F','O'), IN `in_father_relation_type` VARCHAR(25), IN `in_father_relation` VARCHAR(25), IN `in_father_email_main` VARCHAR(50), IN `in_father_mobile_phone_1` VARCHAR(20), IN `in_father_birth_date` DATE, IN `in_father_birth_place` VARCHAR(20), IN `in_father_edu_qual_degree` VARCHAR(25), IN `in_father_edu_qual_stream` VARCHAR(25), IN `in_father_occupation` VARCHAR(20), IN `in_father_income_bracket` VARCHAR(20), IN `in_mother_salutation` VARCHAR(10), IN `in_mother_first_name` VARCHAR(20), IN `in_mother_middle_name` VARCHAR(20), IN `in_mother_last_name` VARCHAR(20), IN `in_mother_gender` ENUM('M','F','O'), IN `in_mother_relation_type` VARCHAR(25), IN `in_mother_relation` VARCHAR(25), IN `in_mother_email_main` VARCHAR(50), IN `in_mother_mobile_phone_1` VARCHAR(20), IN `in_mother_birth_date` DATE, IN `in_mother_birth_place` VARCHAR(20), IN `in_mother_edu_qual_degree` VARCHAR(25), IN `in_mother_edu_qual_stream` VARCHAR(25), IN `in_mother_occupation` VARCHAR(20), IN `in_mother_income_bracket` VARCHAR(20), IN `in_login_name` VARCHAR(60), IN `in_bcrpt_password` VARCHAR(60), IN `in_admission_mode` VARCHAR(60), IN `in_created_by` VARCHAR(20),
IN `in_boarding_type` VARCHAR(60), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_student_id` MEDIUMINT(8), OUT `out_enrollment_num` VARCHAR(50))
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_ins_online_student_admission_master';
  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 l_looping_done int default false;
  declare l_contact_id_1 INT;
  declare l_contact_id_2 INT;
  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;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
          set l_routine_block = 'insert';
           set l_student_id = fn_sequence_generator('STUDENT_MASTER');
					call sp_custom_seq_generator(in_inst_id,'STUD_ENROLLMENT_NUM',in_ay_id,in_created_by,l_enrollment_num) ;
					IF length(trim(l_enrollment_num)) = 0 THEN
					   SIGNAL SQLSTATE '10004' 
				      SET MESSAGE_TEXT = 'An error occurred while generating Student Enrollment Num';
			     END IF;
          insert into   student_master(ay_id, inst_id,student_id, admission_ref,
            enrollment_num, enrolled_for_std, first_name,middle_name,last_name,
            birth_date,gender,blood_group,birth_place,nationality,language,religion,
            student_category,student_subcategory,consession_category,disability,address_line_1,
            address_line_2,locality,city ,district,state,country,pincode,mobile_phone_main,
            email_main,identification_mark_1,aadhar_card_num,passport_num,prev_school_name,
            prev_school_address,prev_school_board,stud_status, enrollment_date,admission_mode,
            is_new_admission, is_active,created_by, updated_by, profile_logo_path,
            distance_from_school, special_interest,is_sibling,sibling_detail,boarding_type) 
  	 			values(in_ay_id, in_inst_id,l_student_id,
            in_admission_ref, l_enrollment_num, in_enrolled_for_std, in_first_name,
            in_middle_name, in_last_name, in_birth_date,in_gender,in_blood_group,in_birth_place,
            in_nationality,in_language,in_religion, in_student_category,in_student_subcategory,
            in_consession_category,in_disability,in_address_line_1,in_address_line_2,in_locality,
            in_city ,in_district,in_state,in_country,in_pincode,in_mobile_phone_main,in_email_main,
            in_identification_mark_1,in_aadhar_card_num,in_passport_num,in_prev_school_name,
            in_prev_school_address,in_prev_school_board,in_stud_status, in_enrollment_date,
            in_admission_mode, in_is_new_admission, in_is_active,
            in_created_by, in_created_by, in_profile_logo_path,
            in_distance_from_school, in_special_interest,in_is_sibling,in_sibling_detail, in_boarding_type);
          call sp_ins_online_admission_parent_master(
              in_ay_id, in_inst_id,
              l_student_id, '0',
              in_father_salutation, in_father_first_name, in_father_middle_name,
              in_father_last_name, in_father_birth_date, in_father_gender, 
              in_father_relation_type, in_father_relation, '',
              in_father_birth_place, '', '',
              '', '', '',
              '0', in_father_email_main, '',
              '', '',
              in_father_mobile_phone_1, '', 
              in_father_occupation, in_father_income_bracket, 
              in_father_edu_qual_degree, in_father_edu_qual_stream, 
              '', '', 
              '', '', 
              '', '0',
              '0', '0', '0',
              '0', '0', 
              '', '', 
              '0', '0', '0', 
              '0', '0', '', 
              '0', '0', 
              '1', in_created_by, 
              l_contact_id_1, l_err_code, l_err_desc) ;
         call sp_ins_online_admission_parent_master(
              in_ay_id, in_inst_id,
              l_student_id, '0',
              in_mother_salutation, in_mother_first_name, in_mother_middle_name,
              in_mother_last_name, in_mother_birth_date, in_mother_gender, 
              in_mother_relation_type, in_mother_relation, '',
              in_mother_birth_place, '', '',
              '', '', '',
              '0', in_mother_email_main, '',
              '', '',
              in_mother_mobile_phone_1, '', 
              in_mother_occupation, in_mother_income_bracket, 
              in_mother_edu_qual_degree, in_mother_edu_qual_stream, 
              '', '', 
              '', '', 
              '', '0',
              '0', '0', '0',
              '0', '0', 
              '', '', 
              '0', '0', '0', 
              '0', '0', '', 
              '0', '0', 
              '1', in_created_by, 
              l_contact_id_2, l_err_code, l_err_desc) ;
        update student_master set contact_id_1=l_contact_id_1 where student_id=l_student_id and is_deleted='0';
        update student_master set contact_id_2=l_contact_id_2 where student_id=l_student_id and is_deleted='0';
        CALL sp_ins_user_master('E','', in_inst_id, 'STU', l_student_id, '28', in_login_name, in_bcrpt_password,'',
        '','1','1','','','','','','','','','','','1','1','SYSTEM', l_err_code, l_err_desc);
        -- calculate Score
        call sp_calculate_student_score_in_bulk (in_ay_id, in_inst_id, l_student_id, in_created_by, 
          l_err_code, l_err_desc);
          end;
      end case;
    commit;
    set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
    set out_student_id = l_student_id;
      set out_enrollment_num = l_enrollment_num;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_online_student_admission_master_nouse`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_online_student_admission_master_nouse`(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_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_class_id` CHAR(8), IN `in_file_upload_id` MEDIUMINT(8), IN `in_student_num` VARCHAR(55), IN `in_admission_num` VARCHAR(55), IN `in_admission_ref` VARCHAR(25), IN `in_admission_ref_desc` VARCHAR(50), IN `in_enrollment_num` VARCHAR(25), IN `in_enrollment_date` DATE, IN `in_enrolled_for_std` CHAR(2), IN `in_class_roll_num` TINYINT(3), IN `in_house_id` SMALLINT(5), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_blood_group` VARCHAR(10), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_student_category` VARCHAR(20), IN `in_student_subcategory` VARCHAR(20), IN `in_consession_category` VARCHAR(20), IN `in_disability` VARCHAR(20), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_locality` VARCHAR(25), IN `in_city` VARCHAR(25), IN `in_district` VARCHAR(20), IN `in_state` VARCHAR(20), IN `in_country` VARCHAR(25), IN `in_pincode` MEDIUMINT(8), IN `in_mobile_phone_main` VARCHAR(15), IN `in_email_main` VARCHAR(50), IN `in_contact_id_1` MEDIUMINT(8), IN `in_contact_id_2` MEDIUMINT(8), IN `in_identification_mark_1` VARCHAR(50), IN `in_aadhar_card_num` VARCHAR(12), IN `in_passport_num` VARCHAR(15), IN `in_prev_school_name` VARCHAR(50), IN `in_prev_school_address` VARCHAR(50), IN `in_prev_school_board` VARCHAR(20), IN `in_stud_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), IN `in_note` VARCHAR(100), IN `in_bulk_upload_status` TINYINT(3), IN `in_stud_bulk_file_upload_id` MEDIUMINT(8), IN `in_is_new_admission` TINYINT(3), IN `in_father_salutation` VARCHAR(10), IN `in_father_first_name` VARCHAR(20), IN `in_father_middle_name` VARCHAR(20), IN `in_father_last_name` VARCHAR(20), IN `in_father_gender` ENUM('M','F','O'), IN `in_father_relation_type` VARCHAR(25), IN `in_father_relation` VARCHAR(25), IN `in_father_email_main` VARCHAR(50), IN `in_father_mobile_phone_1` VARCHAR(20), IN `in_father_birth_date` DATE, IN `in_father_birth_place` VARCHAR(20), IN `in_father_edu_qual_degree` VARCHAR(25), IN `in_father_edu_qual_stream` VARCHAR(25), IN `in_father_occupation` VARCHAR(20), IN `in_father_income_bracket` VARCHAR(20), IN `in_mother_salutation` VARCHAR(10), IN `in_mother_first_name` VARCHAR(20), IN `in_mother_middle_name` VARCHAR(20), IN `in_mother_last_name` VARCHAR(20), IN `in_mother_gender` ENUM('M','F','O'), IN `in_mother_relation_type` VARCHAR(25), IN `in_mother_relation` VARCHAR(25), IN `in_mother_email_main` VARCHAR(50), IN `in_mother_mobile_phone_1` VARCHAR(20), IN `in_mother_birth_date` DATE, IN `in_mother_birth_place` VARCHAR(20), IN `in_mother_edu_qual_degree` VARCHAR(25), IN `in_mother_edu_qual_stream` VARCHAR(25), IN `in_mother_occupation` VARCHAR(20), IN `in_mother_income_bracket` 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_student_id` MEDIUMINT(8), OUT `out_enrollment_num` VARCHAR(50))
    NO SQL
begin
	declare l_routine_name varchar(50) default 'sp_ins_online_student_admission_master';
  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 l_looping_done int default false;
  declare l_contact_id_1 INT;
  declare l_contact_id_2 INT;
  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;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
          set l_routine_block = 'insert';
           set l_student_id = fn_sequence_generator('STUDENT_MASTER');
					call sp_custom_seq_generator(in_inst_id,'STUD_ENROLLMENT_NUM',in_ay_id,in_created_by,l_enrollment_num) ;
					IF length(trim(l_enrollment_num)) = 0 THEN
					   SIGNAL SQLSTATE '10004' 
				      SET MESSAGE_TEXT = 'An error occurred while generating Student Enrollment Num';
			     END IF;
           INSERT INTO student_admission_master(ay_id, inst_id,
          student_id, standard_id, division_id, class_id, house_id, file_upload_id,
          student_num, admission_num, admission_ref, admission_ref_desc, enrollment_num,
          enrollment_date, enrolled_for_std, class_roll_num, first_name, middle_name,
          last_name, birth_date, gender, blood_group, birth_place, nationality,
          language, religion, student_category, student_subcategory, consession_category, 
          disability, address_line_1, address_line_2, locality, city, district, state,
          country, pincode, mobile_phone_main, email_main, contact_id_1, contact_id_2, 
          identification_mark_1, aadhar_card_num, passport_num, prev_school_name,
          prev_school_address, prev_school_board, stud_status, status_desc, note, 
          bulk_upload_status, stud_bulk_file_upload_id,is_new_admission,
          father_salutation, father_first_name,
          father_middle_name, father_last_name, father_birth_date, father_gender, 
          father_relation_type, father_relation, father_birth_place, father_email_main,
          father_mobile_phone_1, father_occupation, father_income_bracket,
          father_edu_qual_degree, father_edu_qual_stream, mother_salutation, 
          mother_first_name, mother_middle_name, mother_last_name, mother_birth_date,
          mother_gender, mother_relation_type, mother_relation, mother_birth_place, 
          mother_email_main, mother_mobile_phone_1, mother_occupation, mother_income_bracket,
          mother_edu_qual_degree, mother_edu_qual_stream, is_active, created_by, updated_by) 
          VALUES 
          (in_ay_id, in_inst_id,
    		  l_student_id, in_standard_id, in_division_id, in_class_id, in_house_id, in_file_upload_id,
          in_student_num, in_admission_num, in_admission_ref, in_admission_ref_desc, l_enrollment_num, 
    		  in_enrollment_date, in_enrolled_for_std, in_class_roll_num, in_first_name, in_middle_name,
    		  in_last_name, in_birth_date,in_gender,in_blood_group,in_birth_place, in_nationality,
    		  in_language, in_religion, in_student_category, in_student_subcategory, in_consession_category,
    		  in_disability, in_address_line_1 ,in_address_line_2, in_locality, in_city ,in_district,in_state,
    		  in_country,in_pincode,in_mobile_phone_main,in_email_main, in_contact_id_1, in_contact_id_2, 
          in_identification_mark_1, in_aadhar_card_num, in_passport_num, in_prev_school_name,
          in_prev_school_address, in_prev_school_board, in_stud_status, in_status_desc, in_note,
		      in_bulk_upload_status, in_stud_bulk_file_upload_id,in_is_new_admission,
          in_father_salutation, in_father_first_name,
          in_father_middle_name, in_father_last_name, in_father_birth_date, in_father_gender, 
          in_father_relation_type, in_father_relation, in_father_birth_place, in_father_email_main,
          in_father_mobile_phone_1, in_father_occupation, in_father_income_bracket,
          in_father_edu_qual_degree, in_father_edu_qual_stream, in_mother_salutation, 
          in_mother_first_name, in_mother_middle_name, in_mother_last_name, in_mother_birth_date,
          in_mother_gender, in_mother_relation_type, in_mother_relation, in_mother_birth_place, 
          in_mother_email_main, in_mother_mobile_phone_1, in_mother_occupation, in_mother_income_bracket,
          in_mother_edu_qual_degree, in_mother_edu_qual_stream,
		      in_is_active, in_created_by, in_created_by);
          CALL sp_ins_user_master('I','', in_inst_id, 'STU', '', '28', in_login_name, in_password,'',
            '','1','1','','','','','','','','','','','1','1','SYSTEM', l_err_code, l_err_desc);
          end;    
      end case;
    commit;
    set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
    set out_student_id = l_student_id;
      set out_enrollment_num = l_enrollment_num;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_optional_field_config_setting_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_optional_field_config_setting_json`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_field_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_optional_field_config_setting_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 optional_field_master(inst_id,field_set_id,country_id,
    state_id, board_id, table_name,field_id,field_label,field_name,data_type,default_value,
    array_value,field_seq,is_optional,category,is_active,created_by) VALUES'; 

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'optional_field_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 = 'field_id') THEN
--         begin
--           case in_dml_mode 
--             when 'I' then
--               begin
--                 set l_template_col_value = fn_sequence_generator('OPTIONAL_FIELD_MASTER');
--               end;
--     
--             when 'U' then
--               begin
--                  set l_template_col_value = fn_sequence_generator('OPTIONAL_FIELD_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 'E' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';

            update optional_field_master 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 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
            update optional_field_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
            where inst_id = in_inst_id and field_id = in_field_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_organization_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_organization_master`(IN `in_dml_mode` CHAR(1), IN `in_org_id` SMALLINT(5), IN `in_org_type` VARCHAR(20), IN `in_org_name` VARCHAR(50), IN `in_org_display_name` VARCHAR(50), IN `in_org_abbr` VARCHAR(10), IN `in_org_desc` VARCHAR(250), IN `in_org_logo_path` VARCHAR(50), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_locality` INT(4), IN `in_city` INT(4), IN `in_district` INT(4), IN `in_state` INT(4), IN `in_country` INT(4), IN `in_pincode` MEDIUMINT(7), IN `in_registration_num` VARCHAR(25), IN `in_foundation_date` DATE, IN `in_onboarding_date` DATE, IN `in_website_address` VARCHAR(100), IN `in_email_main` VARCHAR(100), IN `in_email_alt` VARCHAR(100), IN `in_facebook_address` VARCHAR(100), IN `in_twitter_address` VARCHAR(100), IN `in_linkedin_address` VARCHAR(100), IN `in_instagram_address` VARCHAR(100), IN `in_institutes` VARCHAR(100), IN `in_head_institute` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_org_id` SMALLINT(5), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_ins_organization_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_org_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 
        ('*****', '0', 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;
      set out_org_id   =  0;   
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            set l_routine_block = 'insert';
          	set l_org_id =fn_sequence_generator('ORGANIZATION_MASTER');
            INSERT INTO organization_master( org_id, org_type, org_name, 
               org_display_name, org_abbr, org_desc, org_logo_path, address_line_1,
               address_line_2, locality, city, state, district, country, pincode, 
               registration_num, foundation_date, onboarding_date, website_address, 
               email_main, email_alt, facebook_address, twitter_address, linkedin_address, 
               instagram_address, institutes, head_institute, created_by, updated_by, is_active) 
              VALUES (l_org_id, in_org_type, in_org_name, 
               in_org_display_name, in_org_abbr, in_org_desc, in_org_logo_path, in_address_line_1,
               in_address_line_2, in_locality, in_city, in_state, in_district, in_country, in_pincode, 
               in_registration_num, in_foundation_date, in_onboarding_date, in_website_address, 
               in_email_main, in_email_alt, in_facebook_address, in_twitter_address, in_linkedin_address, 
               in_instagram_address, in_institutes, in_head_institute, in_created_by, in_updated_by, in_is_active);
          end;    
  	    when 'U' then
         set l_routine_block = 'update'; 
          begin
          	update organization_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where org_id = in_org_id and is_deleted = 0;
           INSERT INTO organization_master( org_id, org_type, org_name, 
               org_display_name, org_abbr, org_desc, org_logo_path, address_line_1,
               address_line_2, locality, city, state, district, country, pincode, 
               registration_num, foundation_date, onboarding_date, website_address, 
               email_main, email_alt, facebook_address, twitter_address, linkedin_address, 
               instagram_address, institutes, head_institute, created_by, updated_by, is_active) 
              VALUES (in_org_id, in_org_type, in_org_name, 
               in_org_display_name, in_org_abbr, in_org_desc, in_org_logo_path, in_address_line_1,
               in_address_line_2, in_locality, in_city, in_state, in_district, in_country, in_pincode, 
               in_registration_num, in_foundation_date, in_onboarding_date, in_website_address, 
               in_email_main, in_email_alt, in_facebook_address, in_twitter_address, in_linkedin_address, 
               in_instagram_address, in_institutes, in_head_institute, in_created_by, in_updated_by, in_is_active);
          end;    
      end case;
    commit;
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
      set out_org_id=  l_org_id;   
end$$

DROP PROCEDURE IF EXISTS `sp_ins_parents_bulk_temp_users_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_parents_bulk_temp_users_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stud_bulk_file_upload_id` MEDIUMINT(8), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_parents_bulk_temp_users_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 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 text default 'INSERT INTO temp_user_parent_master(ay_id, inst_id, parent_id,
    login_name, password, mobile_phone_main, email_main, status, bulk_upload_status,
    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 = 'temp_user_parent_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);
      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 'S' then          
        begin
           set l_routine_block = 'update parent_master and temp_user_parent_master';   
                UPDATE parent_master SET is_active=1, bulk_upload_status=100 
                  WHERE is_active=-1 AND inst_id=in_inst_id  AND ay_id=in_ay_id AND is_deleted=0
                  AND stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;
                UPDATE temp_user_parent_master tupm,parent_master pm
                   SET tupm.is_active=1, tupm.stud_status=100, tupm.bulk_upload_status=100
                 WHERE tupm.inst_id=pm.inst_id
                  AND tupm.ay_id=pm.ay_id
                  AND tupm.is_deleted=pm.is_deleted
                  AND tupm.student_id=pm.student_id
                  AND tupm.is_active=-1 AND tupm.inst_id=in_inst_id
                  AND tupm.ay_id=in_ay_id
                  AND tupm.is_deleted=0
                  AND tupm.stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;
     end;     
      when 'T' then          
      begin
         set l_routine_block = 'update temp_user_student_master';   
            UPDATE temp_user_student_master SET is_active=1, stud_status=100 WHERE is_active=-1 AND inst_id=in_inst_id
              AND ay_id=in_ay_id
              AND is_deleted=0;
       end;     
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_parents_bulk_upload_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_parents_bulk_upload_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_parents_bulk_upload_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 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 text default 'INSERT INTO parent_master(ay_id, inst_id, parent_id, salutation,
    first_name, middle_name, last_name, gender, relation_type, relation, student_id_default, email_main, 
	mobile_phone_1, bulk_upload_status, stud_bulk_file_upload_id, is_active, created_by, updated_by,
	occupation,edu_qual_degree,edu_qual_stream,income_bracket) 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 = 'parent_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 = 'parent_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
					set l_template_col_value = fn_sequence_generator('PARENT_MASTER');
              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';
          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_parents_bulk_user_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_parents_bulk_user_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` INT, IN `in_json_str` MEDIUMTEXT, 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_parents_bulk_user_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 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_user_id mediumint(8);

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

  declare l_insert_sql_str MEDIUMTEXT default 'INSERT INTO user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,
    password,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_token_verified, is_active,created_by, updated_by, api_token) 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_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 = 'user_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
				        set l_template_col_value = fn_sequence_generator('USER_MASTER');
                set l_user_id=l_template_col_value;
                CALL `sp_ins_user_role_map`('U', in_inst_id, 'PAR', l_user_id, '21', in_created_by, l_err_code, l_err_desc);
			        	CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, 'PAR', l_user_id, in_created_by, l_err_code, l_err_desc);
          
              end;
    
            when 'U' then
              begin
                set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                set l_user_id=l_template_col_value;
                 CALL `sp_ins_user_role_map`('U', in_inst_id, 'PAR', l_user_id, '21', in_created_by, l_err_code, l_err_desc);
			        	CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, 'PAR', l_user_id, in_created_by, l_err_code, l_err_desc);
          
              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 'U' 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_parent_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_parent_master`(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_parent_num` CHAR(10), IN `in_parent_id` MEDIUMINT(8), IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_relation_type` VARCHAR(25), IN `in_relation` VARCHAR(25), IN `in_blood_group` VARCHAR(15), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_caste` VARCHAR(25), IN `in_profile_logo_path` VARCHAR(100), IN `in_student_id_default` MEDIUMINT, IN `in_email_main` VARCHAR(50), IN `in_email_alt` VARCHAR(50), IN `in_fixed_phone_1` VARCHAR(20), IN `in_fixed_phone_2` VARCHAR(20), IN `in_mobile_phone_1` VARCHAR(20), IN `in_mobile_phone_2` VARCHAR(20), IN `in_occupation` VARCHAR(20), IN `in_income_bracket` VARCHAR(20), IN `in_edu_qual_degree` VARCHAR(25), IN `in_edu_qual_stream` VARCHAR(25), IN `in_aadhar_card_num` VARCHAR(12), IN `in_pan_card_num` VARCHAR(10), IN `in_passport_num` VARCHAR(10), IN `in_curr_addr_line_1` VARCHAR(25), IN `in_curr_addr_line_2` VARCHAR(25), IN `in_curr_locality` INT(4), IN `in_curr_city` INT(4), IN `in_curr_state` INT(4), IN `in_curr_country` INT(4), IN `in_curr_pincode` MEDIUMINT(8), IN `in_is_addr_replicated` TINYINT(1), IN `in_perm_addr_line_1` VARCHAR(25), IN `in_perm_addr_line_2` VARCHAR(25), IN `in_perm_locality` INT(4), IN `in_perm_city` INT(4), IN `in_perm_state` INT(4), IN `in_perm_country` INT(4), IN `in_perm_pincode` MEDIUMINT(8), IN `in_note` VARCHAR(100), IN `in_bulk_upload_status` TINYINT(3), IN `in_stud_bulk_file_upload_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, OUT `out_parent_id` MEDIUMINT(8))
    NO SQL
begin
 
  declare l_routine_name varchar(50) default 'sp_ins_parent_master';

  declare l_err_code char(5) default '00000';

  declare l_err_desc text default '00000';    	

  declare l_routine_block varchar(15) default '00000';

  declare l_parent_id   mediumint(8);	
  declare out_l_parent_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_parent_id = fn_sequence_generator('PARENT_MASTER');
           set out_l_parent_id = l_parent_id;
          insert into  parent_master (ay_id,inst_id,parent_id, salutation,first_name,middle_name,last_name, 

                   	birth_date,gender,relation_type,relation,blood_group,birth_place,nationality,language,religion,caste,

                    profile_logo_path,student_id_default,email_main,email_alt,

                   fixed_phone_1,fixed_phone_2,mobile_phone_1, mobile_phone_2,occupation,income_bracket ,edu_qual_degree ,edu_qual_stream ,

                   aadhar_card_num, pan_card_num,  passport_num , curr_addr_line_1,curr_addr_line_2,

                   curr_locality,curr_city,curr_state,curr_country,curr_pincode,is_addr_replicated , perm_addr_line_1, perm_addr_line_2 , 

                   perm_locality , perm_city , perm_state, perm_country , perm_pincode, note,
            
                  bulk_upload_status, stud_bulk_file_upload_id, is_active,created_by, updated_by) 	 						

            values(in_ay_id,in_inst_id,l_parent_id,in_salutation,in_first_name ,in_middle_name,in_last_name,in_birth_date ,in_gender ,

                 in_relation_type ,in_relation ,in_blood_group ,in_birth_place,in_nationality , in_language ,

				         in_religion,in_caste ,in_profile_logo_path,in_student_id,in_email_main, in_email_alt ,in_fixed_phone_1, in_fixed_phone_2,

                 in_mobile_phone_1 ,in_mobile_phone_2,in_occupation ,in_income_bracket, in_edu_qual_degree , in_edu_qual_stream,

                 in_aadhar_card_num ,in_pan_card_num ,in_passport_num ,in_curr_addr_line_1,in_curr_addr_line_2 ,in_curr_locality ,

                 in_curr_city,in_curr_state ,in_curr_country,in_curr_pincode ,in_is_addr_replicated ,in_perm_addr_line_1,

                 in_perm_addr_line_2, in_perm_locality ,in_perm_city , in_perm_state , in_perm_country,

                  in_perm_pincode ,in_note, in_bulk_upload_status, in_stud_bulk_file_upload_id,
            
                 in_is_active, in_created_by, in_created_by);

						case in_parent_num 
							when 'P1' then
								begin
									update student_master set contact_id_1=l_parent_id where student_id=in_student_id and is_deleted='0';
								end;    
							when 'P2' then
								begin
									update student_master set contact_id_2=l_parent_id where student_id=in_student_id and is_deleted='0';
								end;    
						end case;

          end;   

  	    when 'U' then

         set l_routine_block = 'update'; 

          begin

            set out_l_parent_id = in_parent_id;

          	update parent_master set valid_to = NOW(), updated_by = in_created_by, 

              updated_on = NOW(), is_deleted = 1 

            where parent_id = in_parent_id and is_deleted = 0  

            	and inst_id = in_inst_id;

          
				insert into  parent_master (ay_id,inst_id,parent_id, salutation,first_name,middle_name,last_name, 

                   	birth_date,gender,relation_type,relation,blood_group,birth_place,nationality,language,religion,caste,

                    profile_logo_path,email_main,email_alt,

                   fixed_phone_1,fixed_phone_2,mobile_phone_1, mobile_phone_2,occupation,income_bracket ,edu_qual_degree ,edu_qual_stream ,

                   aadhar_card_num, pan_card_num,  passport_num , curr_addr_line_1,curr_addr_line_2,

                   curr_locality,curr_city,curr_state,curr_country,curr_pincode,is_addr_replicated , perm_addr_line_1, perm_addr_line_2 , 

                   perm_locality , perm_city , perm_state, perm_country , perm_pincode, note,
          
                   bulk_upload_status, stud_bulk_file_upload_id, is_active,created_by, updated_by) 	 						

            values(in_ay_id,in_inst_id,in_parent_id,in_salutation,in_first_name ,in_middle_name,in_last_name,in_birth_date ,in_gender ,

                 in_relation_type ,in_relation ,in_blood_group ,in_birth_place,in_nationality , in_language ,

				         in_religion,in_caste ,in_profile_logo_path,in_email_main, in_email_alt ,in_fixed_phone_1, in_fixed_phone_2,

                 in_mobile_phone_1 ,in_mobile_phone_2,in_occupation ,in_income_bracket, in_edu_qual_degree , in_edu_qual_stream,

                 in_aadhar_card_num ,in_pan_card_num ,in_passport_num ,in_curr_addr_line_1,in_curr_addr_line_2 ,in_curr_locality ,

                 in_curr_city,in_curr_state ,in_curr_country,in_curr_pincode ,in_is_addr_replicated ,in_perm_addr_line_1,

                 in_perm_addr_line_2, in_perm_locality ,in_perm_city , in_perm_state , in_perm_country,

                  in_perm_pincode ,in_note, in_bulk_upload_status, in_stud_bulk_file_upload_id, in_is_active, in_created_by, in_created_by);
          
          end;    
      end case;
    commit;
	 set out_err_code = l_err_code;
   set out_err_desc = l_err_desc;
   set out_parent_id = out_l_parent_id;
    
    

end$$

DROP PROCEDURE IF EXISTS `sp_ins_parent_profile_for_stud_bulk_edit`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_parent_profile_for_stud_bulk_edit`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_parent_id` MEDIUMINT(8), IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_relation_type` VARCHAR(25), IN `in_relation` VARCHAR(25), IN `in_blood_group` VARCHAR(15), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_caste` VARCHAR(25), IN `in_student_id_default` MEDIUMINT(8), IN `in_email_main` VARCHAR(50), IN `in_mobile_phone_1` VARCHAR(15), IN `in_occupation` VARCHAR(20), IN `in_income_bracket` VARCHAR(20), IN `in_edu_qual_degree` VARCHAR(25), IN `in_edu_qual_stream` VARCHAR(25), IN `in_aadhar_card_num` VARCHAR(12), IN `in_pan_card_num` VARCHAR(10), IN `in_passport_num` VARCHAR(10), IN `in_login_name` VARCHAR(50), IN `in_bcrpt_password` VARCHAR(100), IN `in_password` VARCHAR(60), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_parent_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_parent_profile_for_stud_bulk_edit';
  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_parent_id mediumint(8);
  declare l_enrollment_num varchar(50) default 0;
  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 l_first_name_f varchar(20);
  


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

      insert into db_error_log(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_parent_id = fn_sequence_generator('PARENT_MASTER');

      insert into parent_master(ay_id,inst_id,parent_id,salutation,first_name,middle_name,
        last_name,birth_date,gender,relation_type,relation,blood_group,birth_place,nationality,
        language,religion,caste,student_id_default,email_main,mobile_phone_1,occupation,
        income_bracket,edu_qual_degree,edu_qual_stream,aadhar_card_num,pan_card_num,passport_num,
              is_active,created_by, updated_by) 
    	 			values(in_ay_id,in_inst_id,l_parent_id,in_salutation,in_first_name,in_middle_name,in_last_name,
        in_birth_date,in_gender,in_relation_type,in_relation,in_blood_group,in_birth_place,in_nationality,
        in_language,in_religion,in_caste,in_student_id_default,in_email_main,in_mobile_phone_1,in_occupation,
        in_income_bracket,in_edu_qual_degree,in_edu_qual_stream,in_aadhar_card_num,in_pan_card_num,in_passport_num,
              in_is_active,in_created_by, in_created_by
              );

        CALL sp_ins_user_master('E','', in_inst_id, 'PAR', l_parent_id, '21', in_login_name, in_bcrpt_password,'',
        '','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,in_password,
              in_mobile_phone_1,in_email_main,'100',
              in_is_active,
              in_created_by, in_created_by
              );

        if(in_relation='FATHER')then
            update student_master set contact_id_1=l_parent_id where student_id=in_student_id_default  
            and inst_id=in_inst_id and is_active=1 AND is_deleted=0;
        elseif(in_relation='MOTHER')then
           update student_master set contact_id_2=l_parent_id where student_id=in_student_id_default  
                  and inst_id=in_inst_id and is_active=1 AND is_deleted=0;
        end if;

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

DROP PROCEDURE IF EXISTS `sp_ins_qams_asset_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_qams_asset_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_asset_id` MEDIUMINT(8), IN `in_asset_name` VARCHAR(50), IN `in_asset_type` VARCHAR(50), IN `in_asset_code` VARCHAR(100), IN `in_asset_desc` VARCHAR(500), 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_qams_asset_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_asset_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(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_asset_id;
		end;
        
    start transaction;
    
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
           set l_asset_id = fn_sequence_generator('QAMS_ASSET_MASTER');

            insert into  qams_asset_master(
              inst_id,asset_id,asset_name,
              asset_type,asset_code,
              asset_desc,is_active,created_by, 
              updated_by) 
            values(
              in_inst_id,l_asset_id,in_asset_name, 
              in_asset_type,in_asset_code,
              in_asset_desc,
               in_is_active,in_created_by, in_created_by);
            
          end;    
  
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update  qams_asset_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where asset_id=in_asset_id  
              and is_deleted = 0 
            	and inst_id = in_inst_id;

           insert into  qams_asset_master(
              inst_id,asset_id,asset_name,
              asset_type,asset_code,
             asset_desc,is_active,created_by, 
              updated_by) 
            values(
              in_inst_id,in_asset_id,in_asset_name,
              in_asset_type,in_asset_code,
              in_asset_desc,in_is_active,in_created_by, in_created_by);
            
          end;    
  

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

DROP PROCEDURE IF EXISTS `sp_ins_qams_asset_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_qams_asset_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_qams_asset_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 qams_asset_master(inst_id,asset_id, asset_type, asset_code,
    asset_name,asset_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 cursor for 
  select col_name from json_template_master 
  where tbl_name = 'qams_asset_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 = 'asset_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('QAMS_ASSET_MASTER');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('QAMS_ASSET_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 = in_ay_id and inst_id = in_inst_id and book_id = in_book_id
            and is_deleted = 0;
                   
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_quickpay_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_quickpay_details_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_qp_code` VARCHAR(50), IN `in_party_id` VARCHAR(20), IN `in_party_type` VARCHAR(20), IN `in_party_name` VARCHAR(100), IN `in_pmt_title` VARCHAR(100), IN `in_pmt_desc` VARCHAR(100), IN `in_pmt_due_date` VARCHAR(20), IN `in_pmt_date` VARCHAR(20), IN `in_pmt_amt` VARCHAR(20), IN `in_tax_amt` VARCHAR(20), IN `in_total_pmt_amt` VARCHAR(20), IN `in_status` VARCHAR(1), IN `in_qp_json_row_count` INT(8), IN `in_qp_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_quickpay_details_json';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';   
	declare l_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_dq_ay_id CHAR(7); 
	declare l_dq_inst_id SMALLINT(5); 
	declare l_dq_created_by VARCHAR(20);   
	declare l_dq_demand_mst_id 		VARCHAR(100) ;
	declare l_dq_demand_grp_id 		VARCHAR(100) ;
	declare l_dq_demand_type 		VARCHAR(100) ;
	declare l_dq_demand_num    		VARCHAR(100) ;
	declare l_dq_txn_id          	VARCHAR(100) ; 
	declare l_dq_txn_desc      		VARCHAR(100) ; 
	declare l_dq_installment_num 	VARCHAR(100) ;
	declare l_dq_party_type 		VARCHAR(100) ;
	declare l_dq_party_id         	VARCHAR(100)  ;     
	declare l_dq_party_name   		VARCHAR(100) ;
	declare l_dq_gen_date     		VARCHAR(100) ;
	declare l_dq_due_date 			VARCHAR(100) ;    
	declare l_dq_grace_period   	VARCHAR(100) ;   
	declare l_dq_final_date        	VARCHAR(100) ;    
	declare l_dq_amt_due        	VARCHAR(100) ;      
	declare l_dq_tax_due           	VARCHAR(100) ;
	declare l_dq_total_amt_due   	VARCHAR(100) ;
	declare l_dq_qp_code 			VARCHAR(100) ;
	declare l_dq_status         	VARCHAR(100) ;
	declare l_dq_qp_mst_id 			INT(8); 
	declare l_qp_mst_id 			INT(8); 
	declare l_dq_qp_dtls_id 		INT(8); 
	declare t_demand_num varchar(50);	
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare cur_json_template cursor for select col_name from json_template_master where tbl_name = 'demand_quickpay_mix' order by col_pos; 
	declare continue handler for not found set l_looping_done = true;
	declare exit handler for sqlexception
		begin     
			rollback;
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			set l_routine_block = 'insert' ;
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 'ERROR', 0, in_created_by);
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
	begin
		rollback; 
		get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
		set l_routine_block = 'insert' ;
		insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, err_desc, err_type, err_severity, created_by) 
		values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
		set out_err_code = l_err_code; 
		set out_err_desc = l_err_desc;
	end; 
	start transaction; 
		 	begin   
			set l_qp_mst_id = fn_sequence_generator('QUICKPAY_MASTER'); 
			end; 
		INSERT into pmt_quick_pay_master ( 
					ay_id,inst_id,
					qp_mst_id,qp_code,
					party_id,party_type,party_name,
					pmt_title,pmt_desc,pmt_due_date,pmt_date,pmt_amt,tax_amt,total_pmt_amt,
					status ,
					created_by,created_on,
					updated_by,updated_on,
					is_active,is_deleted)
				VALUES (in_ay_id, in_inst_id, 
					l_qp_mst_id,in_qp_code,
				    in_party_id,in_party_type,in_party_name,
					in_pmt_title, in_pmt_desc,in_pmt_date,in_pmt_date,in_pmt_amt,in_tax_amt,in_total_pmt_amt,
					in_status ,
					in_created_by,NOW(),
					in_created_by,NOW(),
					'1','0'
				);
		set l_looping_done = false; 
		set l_insert_row_count = in_qp_json_row_count;
		set l_json_str = trim(in_qp_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; 
				insert into proc_error_logs (routine_name,	label_name,sql_log) values('l_looping_done','-',l_looping_done);
				if l_looping_done then
				  leave cursor_loop;
				end if; 
				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('col_name',l_insert_row_count,l_json_str);
				insert into proc_error_logs (routine_name,	label_name,sql_log) values('col_name',l_template_col_name,l_json_substr); 
				if     (l_template_col_name = 'ay_id') 			THEN set l_dq_ay_id = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'inst_id') 		THEN set l_dq_inst_id = substring(l_json_substr, 1, l_separator_idx - 1);      
				elseif (l_template_col_name = 'demand_mst_id') 	THEN set l_dq_demand_mst_id = substring(l_json_substr, 1, l_separator_idx - 1);   
				elseif (l_template_col_name = 'demand_grp_id') 	THEN set l_dq_demand_grp_id = substring(l_json_substr, 1, l_separator_idx - 1);   
				elseif (l_template_col_name = 'demand_type') 	THEN set l_dq_demand_type = substring(l_json_substr, 1, l_separator_idx - 1);   
				elseif (l_template_col_name = 'demand_num') 	THEN set l_dq_demand_num = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'txn_id') 		THEN set l_dq_txn_id = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'txn_desc') 		THEN set l_dq_txn_desc = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'installment_num') THEN set l_dq_installment_num = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'party_type') 	THEN set l_dq_party_type = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'party_id') 		THEN set l_dq_party_id = substring(l_json_substr, 1, l_separator_idx - 1);   
				elseif (l_template_col_name = 'party_name') 	THEN set l_dq_party_name = substring(l_json_substr, 1, l_separator_idx - 1); 
				elseif (l_template_col_name = 'gen_date') 		THEN set l_dq_gen_date = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'due_date') 		THEN set l_dq_due_date = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'grace_period') 	THEN set l_dq_grace_period = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'final_date') 	THEN set l_dq_final_date = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'amt_due') 		THEN set l_dq_amt_due = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'tax_due') 		THEN set l_dq_tax_due = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'total_amt_due') 	THEN set l_dq_total_amt_due = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'status') 		THEN set l_dq_status = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'created_by') 	THEN set l_dq_created_by = substring(l_json_substr, 1, l_separator_idx - 1);
				elseif (l_template_col_name = 'qp_code') 		THEN set l_dq_qp_code = substring(l_json_substr, 1, l_separator_idx - 1);  				
				elseif (l_template_col_name = 'qp_mst_id') 		THEN set l_dq_qp_mst_id = substring(l_json_substr, 1, l_separator_idx - 1);   
				elseif (l_template_col_name = 'qp_dtls_id') 	THEN set l_dq_qp_dtls_id = substring(l_json_substr, 1, l_separator_idx - 1);   
				else
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);   
				end if;   
				set l_json_str = l_json_substr;
				set l_json_str_len = length(l_json_str);  
			end loop; 
			begin   
				set l_dq_qp_dtls_id = fn_sequence_generator('QUICKPAY_DETAILS'); 
			end;  	
				INSERT into pmt_quick_pay_details (  
						ay_id,inst_id,
						qp_dtl_id,qp_mst_id,demand_mst_id,demand_grp_id,
						collection_type,pmt_desc,pmt_amt,tax_amt,total_pmt_amt,  
						created_by,created_on,
						updated_by,updated_on,
						is_active,is_deleted)
				VALUES (l_dq_ay_id, l_dq_inst_id,  
						l_dq_qp_dtls_id,l_qp_mst_id,l_dq_demand_mst_id,l_dq_demand_grp_id,
						l_dq_demand_type,l_dq_txn_desc,l_dq_amt_due,l_dq_tax_due,l_dq_total_amt_due, 
						l_dq_created_by,NOW(),
						l_dq_created_by,NOW(),
						'1','0'
					); 
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
			close cur_json_template;
		end while;   	  
	commit;  
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

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

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

declare cur_role_txn_map cursor for 
  select inst_id,is_deleted
  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, 'SQL Exception Handler', l_err_code, l_err_desc, 
      'ERROR', 0, in_created_by);

    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

       end;
open cur_role_txn_map;

  cursor_loop_new:loop
     fetch cur_role_txn_map into l_inst_id, l_delete_flag;
         if l_looping_done then
             leave cursor_loop_new;
         end if;
      
  start transaction;
  
    case in_dml_mode 
      when 'I' then
        begin
          set l_routine_block = 'insert';
            if(in_inst_id=0)then
    
               INSERT INTO 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 '', l_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 AND role_id=in_role_id;

            end if;
        end;    

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

          if(in_inst_id=0)then

              update role_txn_map set valid_to = now(), updated_by = in_created_by, 
                updated_on = now(), is_deleted = 1 
               where inst_id = l_inst_id and role_id = in_role_id 
               and is_deleted = 0;

           
              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 '', l_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 AND role_id=in_role_id;

	if(in_role_id != 21 AND in_role_id != 22)THEN
              CALL sp_ins_role_txn_map_user_entitlements(in_ay_id, l_inst_id, in_role_id, in_created_by, l_err_code, l_err_desc);    
 	end if; 
           end if;    
        end;    

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

DROP PROCEDURE IF EXISTS `sp_ins_role_txn_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_role_txn_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_role_id` SMALLINT(5), IN `in_insert_row_count` SMALLINT(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_role_txn_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 SMALLINT(5);
  
  declare l_single_quot_const varchar(5) default '"';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default '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, 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 = 'role_txn_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';
      
              call sp_execute_immediate (l_insert_sql_str);
              if(in_inst_id=0)then
             
                CALL sp_ins_role_txn_map_all_inst('I', in_inst_id, in_role_id, in_created_by, l_err_code, l_err_desc);       
             
              end if; 

        commit;
      end;

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

        

         update role_txn_map set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where inst_id = in_inst_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);    
          
          if(in_role_id != 21 AND in_role_id != 22)THEN
          
             CALL sp_ins_role_txn_map_user_entitlements(in_ay_id, in_inst_id, in_role_id, in_created_by, l_err_code, l_err_desc);    
 		
          end if;
          
          if(in_inst_id=0)then
             
                CALL sp_ins_role_txn_map_all_inst('U',in_ay_id, in_inst_id, in_role_id, in_created_by, l_err_code, l_err_desc);       
             
            
           end if;
        commit;
      end;

    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_role_txn_map_user_entitlements`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_role_txn_map_user_entitlements`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_role_id` SMALLINT(5), 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_role_txn_map_user_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_user_type char(3); 
  declare l_user_id mediumint(8); 
  # Step 1 : Check User Role Map table for Users that have this Role mapped
  declare cur_user_role_map cursor for 
  select user_type, user_id 
  from user_role_map 
  where inst_id = in_inst_id and is_deleted = 0 and role_id=in_role_id and is_active = 1;
  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 (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;
    open cur_user_role_map;
    cursor_loop: loop
      fetch cur_user_role_map into l_user_type, l_user_id;
      if l_looping_done then
        leave cursor_loop;
      end if;
      begin
        start transaction;
        # Step 2 : Soft Delete all current User Entitlements for this Role 
        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 = 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.inst_id = in_inst_id and ue.is_deleted = 0 and ue.is_active = 1
          and ue.user_id = l_user_id and ue.user_type = l_user_type and rtm.role_id = in_role_id;
        # Step 3 : Insert new User Entitlements that are a common set vis-a-vis Role Txn Map table  
        insert into user_entitlements (ay_id, 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, l_user_type, l_user_id,in_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 = in_role_id;
        commit;
      end;
    end loop;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_school_document_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_school_document_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_document_upload_id` VARCHAR(25), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_school_document_details_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  school_document_details(ay_id, 
                                                                                inst_id, 
                                                                                doc_id,
                                                                                group_type,
                                                                                	emp_id, 
																					  class_id,
                                                                                    standard_id,
                                                                                    division_id, 
                                                                                    title,
                                                                                        comment,
                                                                                      document_upload_id,
                                                                                      status,
                                                                                    created_by,
                                                                                    updated_by,
                                                                              is_active,date) 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 = 'school_document_details' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
      begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
            set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
                  
         
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
     
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
            close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
      
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
      
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
           update  school_document_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 document_upload_id = in_document_upload_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_sequence_generator_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_sequence_generator_master`(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_sequence_generator_master';
  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 sequence_generator_master(ay_id, inst_id, seq_gen_mst_id, 
    entity_id, reset_freq, param_count, seperator_char, op_code, seq_pattern, seq_seed_num, seq_current_num, is_active,
           created_by, updated_by) VALUES';
	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 = 'sequence_generator_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);
        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';
             #donothing
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
           update sequence_generator_master 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;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_service_provider_appl_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_service_provider_appl_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_data_type` VARCHAR(100), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_service_provider_appl_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 service_provider_appl(ay_id, 
                                                                            inst_id, 
																		    data_type,
                                                                             	data_key, 
                                        			                               data_value,
                                        								                      data_desc,
                                                                             data_abbr,
                                        									                   data_pos, 
                                        								                   		is_system_def,
                                                                            	is_editable,
                                                                            is_validations,
                                                                            	is_notifaction,
                                        									                is_active,
                                                                            created_by
                                                                              ) VALUES';
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'service_provider_appl' 
  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 service_provider_appl 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 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_service_provider_institute_mapping`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_service_provider_institute_mapping`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_service_prov_inst_map_id` MEDIUMINT(8), IN `in_prov_id` MEDIUMINT(8), IN `in_category` TEXT, IN `in_sub_category` 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_service_provider_institute_mapping';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
   declare l_service_prov_inst_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_service_prov_inst_map_id = fn_sequence_generator('SERVICE_PROVIDER_MAP');
insert into  service_provider_institute_mapping(
					             ay_id,
							inst_id,
							service_prov_inst_map_id,
								prov_id,
							category,
							sub_category,	is_active,
								 created_by, updated_by) 	 						
           values(
  in_ay_id ,
   in_inst_id ,
  l_service_prov_inst_map_id, 
   in_prov_id, 
  in_category ,
  in_sub_category  ,
  in_is_active,in_created_by,in_created_by);
          end;    
    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update service_provider_institute_mapping set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where  		service_prov_inst_map_id = in_service_prov_inst_map_id and  is_deleted = 0 
            	and inst_id = inst_id;
          insert into  value_added_service_providers(
					            ay_id,
							inst_id,
							service_prov_inst_map_id,
								prov_id,
							category,
							sub_category,	is_active,
								 created_by, updated_by) 	 						
           values(
  in_ay_id ,
   in_inst_id ,
  in_service_prov_inst_map_id, 
   in_prov_id, 
  in_category ,
  in_sub_category  ,
  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_sms_template_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_sms_template_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_txn_id` VARCHAR(25), IN `in_recipient_type` VARCHAR(25), IN `in_sms_body` VARCHAR(164), IN `in_param_count` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_sms_template_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  sms_template_master (ay_id, inst_id,txn_id,recipient_type,sms_body, 
               	param_count,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_txn_id, in_recipient_type,in_sms_body, 
              in_param_count,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update sms_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where txn_id = in_txn_id and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          insert into  sms_template_master (ay_id, inst_id,txn_id,recipient_type,sms_body, 
               	param_count,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_txn_id, in_recipient_type,in_sms_body, 
              in_param_count,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_social_post`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_social_post`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_facebook_user_id` BIGINT(30), IN `in_facebook_page_id` BIGINT(30), IN `in_app_id` BIGINT(30), IN `in_fb_app_secret` VARCHAR(100), IN `in_user_access_token` VARCHAR(500), IN `in_long_lived_access_token` VARCHAR(500), IN `in_facebook_page_name` VARCHAR(20), 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_social_post';
     declare l_err_code char(5) default '00000';
     declare l_err_desc text default '';        
     declare l_routine_block varchar(15);
   declare l_channel_partner_id mediumint(8);
   declare l_inst_id SMALLINT(5);

 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 'F' then

              set l_routine_block = 'update_facebook_profile';
        
         begin
--           select inst_id INTO l_inst_id from social_post;    
--           if  (l_inst_id>0) then
--          
--           update  social_post set inst_id=in_inst_id,    facebook_user_id=in_facebook_user_id,    facebook_page_id=in_facebook_page_id,
--             app_id=in_app_id,fb_app_secret=in_fb_app_secret,
--             user_access_token=in_user_access_token,long_lived_access_token=in_long_lived_access_token,
--            facebook_page_name=in_facebook_page_name,created_by=in_created_by,
--             is_active=in_is_active,updated_by=in_created_by
--           where is_deleted = '0' and inst_id = in_inst_id;  
--                
--              else
--
--             insert into social_post(inst_id,facebook_user_id,facebook_page_id,app_id,fb_app_secret,
--                          user_access_token,long_lived_access_token,facebook_page_name,created_by,is_active)
--                   values (in_inst_id,in_facebook_user_id,in_facebook_page_id,in_app_id,in_fb_app_secret,
--                          in_user_access_token,in_long_lived_access_token,in_facebook_page_name,in_created_by,in_is_active);
--                
--             END IF;

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

           insert into social_post(inst_id,facebook_user_id,facebook_page_id,app_id,fb_app_secret,
                         user_access_token,long_lived_access_token,facebook_page_name,created_by,is_active)
                 values (in_inst_id,in_facebook_user_id,in_facebook_page_id,in_app_id,in_fb_app_secret,
                         in_user_access_token,in_long_lived_access_token,in_facebook_page_name,in_created_by,in_is_active);

         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_standard_admission_config_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_standard_admission_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), 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_standard_admission_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 standards_admission_config_master(ay_id,inst_id,standard_id,
   admission_start_date,admission_end_date,intake,min_age_criteria,max_age_criteria,std_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 = 'standards_admission_config_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 standards_admission_config_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_standard_division_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_standard_division_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_std_div_map_id` MEDIUMINT(8), IN `in_curriculum_type` VARCHAR(10), IN `in_standard_id` VARCHAR(25), IN `in_division_id` VARCHAR(25), IN `in_division_name` VARCHAR(25), IN `in_division_desc` VARCHAR(25), IN `in_division_abbr` VARCHAR(10), IN `in_shift_type` VARCHAR(10), IN `in_grading_system` VARCHAR(25), 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_standard_division_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_standard_division_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_standard_division_map_id = fn_sequence_generator('STANDARD_DIVISION_MAP');
             insert into  standard_division_map (ay_id, inst_id,std_div_map_id,standard_id,curriculum_type, division_id,division_name,division_desc,division_abbr,shift_type, grading_system,is_active,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,l_standard_division_map_id,in_standard_id,in_curriculum_type, in_division_id,in_division_name,in_division_desc,in_division_abbr,in_shift_type,in_grading_system,in_is_active,in_created_by, in_created_by);
          end;    
  	    when 'U' then
           set l_routine_block = 'update';
          begin
          	update standard_division_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where std_div_map_id = in_std_div_map_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into  standard_division_map (ay_id, inst_id,std_div_map_id,standard_id,curriculum_type, division_id,division_name,division_desc,division_abbr,shift_type, grading_system,is_active,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_std_div_map_id,in_standard_id,in_curriculum_type, in_division_id,in_division_name,in_division_desc,in_division_abbr,in_shift_type,in_grading_system,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_standard_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_standard_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_standard_id` CHAR(2), IN `in_standard_name` VARCHAR(25), IN `in_standard_desc` VARCHAR(25), IN `in_standard_abbr` VARCHAR(10), IN `in_standard_stream_name` VARCHAR(25), IN `in_standard_seq` SMALLINT(5), IN `in_standard_strength` SMALLINT(5), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
    declare l_routine_name varchar(50) default 'sp_ins_standard_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare exit handler for sqlexception
      begin
     rollback;
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
     insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,
       err_desc, err_type, err_severity, created_by)
     values
       (in_ay_id, in_inst_id, l_routine_name, 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  standard_master (ay_id, inst_id,curriculum_type,grading_system, gradeset_mst_id, standard_id,standard_name,standard_desc,standard_abbr,
                  standard_stream_name,standard_seq, standard_strength, is_active,created_by, updated_by)                              
           values(in_ay_id, in_inst_id,in_curriculum_type,in_grading_system,in_gradeset_mst_id, in_standard_id,in_standard_name,in_standard_desc,in_standard_abbr,
                  in_standard_stream_name,in_standard_seq,in_standard_strength,in_is_active,in_created_by, in_created_by);
         end;    
         when 'U' then
       set l_routine_block = 'update';
         begin
             update standard_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where standard_id = in_standard_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;
          insert into  standard_master (ay_id, inst_id,curriculum_type,grading_system, gradeset_mst_id, standard_id,standard_name,standard_desc,standard_abbr,
                  standard_stream_name,standard_seq,standard_strength,is_active,created_by, updated_by)                              
           values(in_ay_id,in_inst_id,in_curriculum_type,in_grading_system,in_gradeset_mst_id, in_standard_id,in_standard_name,in_standard_desc,in_standard_abbr,
                  in_standard_stream_name,in_standard_seq,in_standard_strength, 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_standard_timetable_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_standard_timetable_master_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_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_standard_timetable_master_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_timetable_id SMALLINT(5);
  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_master(ay_id,
																		inst_id, 
																		standard_id,
																		
																		division_id,
																		class_id, 
																		timetable_id,
																		timeslot_mst_id,
																		shift_type,
																		timetable_title,
																		timetable_desc,
																		
																		 created_by, 
																		 updated_by,
                                     timetable_valid_from,
                                     timetable_valid_to,timetable_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 = 'timetable_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 = 'timetable_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('TIMETABLE_MASTER');
				 set l_timetable_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 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';

         
       
                   
                   
          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_standard_wise_timetable_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_standard_wise_timetable_master_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_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_standard_wise_timetable_master_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_timetable_id SMALLINT(5);
  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_master(ay_id,
																		inst_id, 
																		standard_id,
																		
																		division_id,
																		class_id, 
																		timetable_id,
																		timeslot_mst_id,
																		shift_type,
																		timetable_title,
																		timetable_desc,
																		
																		 created_by, 
																		 updated_by,
                                     timetable_valid_from,
                                     timetable_valid_to,timetable_status,timetable_meta_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 = 'timetable_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 = 'timetable_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('TIMETABLE_MASTER');
				 set l_timetable_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 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';

         
       
                   
                   
          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_store_emp_setup_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_store_emp_setup_details`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(25), IN `in_last_name` VARCHAR(25), IN `in_mobile_phone_1` VARCHAR(25), IN `in_gender` VARCHAR(25), IN `in_subject_1` VARCHAR(50), IN `in_subject_2` VARCHAR(50), IN `in_subject_3` VARCHAR(50), IN `in_subject_4` VARCHAR(50), IN `in_subject_5` VARCHAR(50), IN `in_subject_6` VARCHAR(50), IN `in_subject_7` VARCHAR(50), IN `in_subject_8` VARCHAR(50), IN `in_subject_9` VARCHAR(50), IN `in_divisionA_1` CHAR(1), IN `in_divisionB_2` CHAR(1), IN `in_divisionC_3` CHAR(1), IN `in_standard` CHAR(2), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_insert_row_count` MEDIUMINT(3), IN `in_json_str` TEXT, IN `in_status` VARCHAR(30), IN `in_address_line_1` VARCHAR(50), IN `in_locality` INT(4), IN `in_city` INT(4), IN `in_district` INT(4), IN `in_state` INT(4), IN `in_country` INT(4), IN `in_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_store_emp_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_package_id int;
  declare l_custom_group_mst_id int;
  declare l_inst_count smallint(5);
  declare l_inst_count1 smallint(5);
  declare l_inst_count2 smallint(5);
  declare l_inst_count3 smallint(5);
  declare l_inst_count4 smallint(5);
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';

  declare l_insert_sql_str text default 'INSERT INTO setup_employee_master(inst_id, salutation,
    first_name, last_name,gender,mobile_phone_1, role, created_by) VALUES'; 

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

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


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

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

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

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

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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


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

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

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

    end loop;

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

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

    close cur_json_template;

  end while;

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

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

--          set Subject master
        select count(inst_id) INTO l_inst_count from setup_subject_master where inst_id=in_inst_id;
        IF(l_inst_count!=0)THEN
            delete from setup_subject_master where inst_id=in_inst_id;
        END IF;
        IF(in_subject_1!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
             values(in_inst_id,in_subject_1,in_created_by);
        END IF;
           IF(in_subject_2!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_2,in_created_by);
        END IF;
        IF(in_subject_3!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
             values(in_inst_id,in_subject_3,in_created_by);
        END IF;
        IF(in_subject_4!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_4,in_created_by);
        END IF;
        IF(in_subject_5!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_5,in_created_by);
        END IF;
        IF(in_subject_6!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_6,in_created_by);
        END IF;
        IF(in_subject_7!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_7,in_created_by);
        END IF;
        IF(in_subject_8!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_8,in_created_by);
        END IF;
        IF(in_subject_9!='') THEN
             insert into  setup_subject_master(inst_id,subject_name,created_by) 
                 values(in_inst_id,in_subject_9,in_created_by);
        END IF;
       
    
--        set Division master
       select count(inst_id) INTO l_inst_count1 from setup_division_master where inst_id=in_inst_id;
        IF(l_inst_count1!=0)THEN
            delete from setup_division_master where inst_id=in_inst_id;
        END IF;
        IF(in_divisionA_1!='') THEN
             insert into  setup_division_master(inst_id,division_id,created_by) 
                 values(in_inst_id,'A',in_created_by);
        END IF;
        IF(in_divisionB_2!='') THEN
             insert into  setup_division_master(inst_id,division_id,created_by) 
                 values(in_inst_id,'B',in_created_by);
        END IF;
        IF(in_divisionC_3!='') THEN
             insert into  setup_division_master(inst_id,division_id,created_by) 
                 values(in_inst_id,'C',in_created_by);
        END IF;

--         set Employee master
        select count(inst_id) INTO l_inst_count2 from setup_employee_master where inst_id=in_inst_id;
        IF(l_inst_count2!=0)THEN
            delete from setup_employee_master where inst_id=in_inst_id;
            
        END IF;
        delete from setup_employee_master where inst_id=0;
        insert into  setup_employee_master(inst_id,salutation,first_name,last_name,gender,mobile_phone_1,
                    role,created_by) 
        values(in_inst_id,in_salutation,in_first_name,in_last_name,in_gender,in_mobile_phone_1,
                   'ADMIN',in_created_by);
        call sp_execute_immediate (l_insert_sql_str); 
         
        
         select count(inst_id) INTO l_inst_count3 from setup_standard_master where inst_id=in_inst_id;
         IF(l_inst_count3!=0)THEN
              delete from setup_standard_master where inst_id=in_inst_id;
         END IF;
         INSERT INTO setup_standard_master( inst_id, standard_id,gradeset_mst_id,created_by) 
              VALUES ( in_inst_id, in_standard,in_gradeset_mst_id,in_created_by); 

       select count(inst_id) INTO l_inst_count4 from setup_tress_master where inst_id=in_inst_id and step_id=1;
        IF(l_inst_count4!=0)THEN
              delete from setup_tress_master where inst_id=in_inst_id and step_id=1;
         END IF;
       INSERT INTO setup_tress_master( inst_id, step_id, status,created_by) 
              VALUES ( in_inst_id, 1, in_status,in_created_by);   
        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_student_admission_history`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_admission_history`(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_student_admission_history';
  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 student_admission_history (ay_id, 
    inst_id, student_id, updated_date_time, stage_id, status_id, status_note, status_description, 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 = 'student_admission_history' 
  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));
        start transaction;  
          set l_routine_block = 'before execute immediate';
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_student_admission_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_admission_master`(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_student_num` VARCHAR(50), IN `in_standard_id` CHAR(2), IN `in_admission_num` VARCHAR(50), IN `in_admission_ref` VARCHAR(25), IN `in_enrollment_num` VARCHAR(50), IN `in_enquiry_date` DATE, IN `in_enrollment_date` DATE, IN `in_enrolled_for_std` CHAR(2), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_blood_group` VARCHAR(10), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_student_category` VARCHAR(20), IN `in_student_subcategory` VARCHAR(20), IN `in_consession_category` VARCHAR(20), IN `in_disability` VARCHAR(20), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_locality` VARCHAR(25), IN `in_city` VARCHAR(25), IN `in_district` VARCHAR(20), IN `in_state` VARCHAR(20), IN `in_country` VARCHAR(25), IN `in_pincode` MEDIUMINT(8), IN `in_mobile_phone_main` VARCHAR(15), IN `in_email_main` VARCHAR(50), IN `in_identification_mark_1` VARCHAR(50), IN `in_aadhar_card_num` VARCHAR(12), IN `in_passport_num` VARCHAR(15), IN `in_prev_school_name` VARCHAR(50), IN `in_prev_school_address` VARCHAR(50), IN `in_prev_school_board` VARCHAR(20), IN `in_stud_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), IN `in_enrollment_num_gen_mode` VARCHAR(10), IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_is_active` TINYINT(1), IN `in_is_new_admission` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_distance_from_school` SMALLINT(5), IN `in_special_interest` VARCHAR(20), IN `in_is_sibling` TINYINT(1), IN `in_sibling_detail` VARCHAR(20), IN `in_is_rte` TINYINT(1), IN `in_rte_category` VARCHAR(20), IN `in_boarding_type` VARCHAR(50), IN `in_course_group` VARCHAR(10), IN `in_gr_number` MEDIUMINT(8), IN `in_sts_number` VARCHAR(50), IN `in_admission_mode` VARCHAR(50), OUT `out_student_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_student_admission_master';
  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 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_student_id = fn_sequence_generator('STUDENT_MASTER');
           
				IF ( in_enrollment_num_gen_mode='Y' AND length(trim(in_enrollment_num)) = 0 AND  in_stud_status>0 ) THEN 
					call sp_custom_seq_generator(in_inst_id,'STUD_ENROLLMENT_NUM',in_ay_id,in_created_by,l_enrollment_num) ;
					IF length(trim(l_enrollment_num)) = 0 THEN
					   SIGNAL SQLSTATE '10004' 
				      SET MESSAGE_TEXT = 'An error occurred while generating Student Enrollment Num';
			     END IF;
				ELSE
					select enrollment_num INTO t_enrollment_num FROM student_master where enrollment_num=in_enrollment_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
					IF (t_enrollment_num=in_enrollment_num) THEN
						SIGNAL SQLSTATE '10005' 
				      SET MESSAGE_TEXT = 'Enrollment Number is already present';
				   ELSE   
						set l_enrollment_num =in_enrollment_num;
					END IF;	
				END IF;

        
            insert into student_master(ay_id, inst_id,student_id,standard_id,admission_num,
              admission_ref, enrollment_num,enquiry_date,enrollment_date,enrolled_for_std,first_name,
              middle_name,last_name, birth_date,gender,blood_group,birth_place,nationality,
              language,religion,student_category,student_subcategory,consession_category,
              disability,address_line_1, address_line_2,locality,city ,district,state,
              country,pincode,mobile_phone_main,email_main,identification_mark_1,
              aadhar_card_num,passport_num,prev_school_name,prev_school_address,
              prev_school_board,stud_status, status_desc, is_new_admission, is_active,
              created_by, updated_by, distance_from_school, special_interest, 
              is_sibling, sibling_detail, is_rte, rte_category,
              boarding_type,course_group, gr_number, sts_number,admission_mode) 
    	 			values(in_ay_id, in_inst_id,l_student_id,in_standard_id,in_admission_num,
              in_admission_ref, l_enrollment_num,in_enquiry_date,in_enrollment_date,in_enrolled_for_std,
              in_first_name,in_middle_name, in_last_name, in_birth_date,in_gender,
              in_blood_group,in_birth_place,in_nationality,in_language,in_religion,
              in_student_category,in_student_subcategory,in_consession_category,
              in_disability,in_address_line_1,in_address_line_2,in_locality,in_city ,
              in_district,in_state,in_country,in_pincode,in_mobile_phone_main,in_email_main,
              in_identification_mark_1,in_aadhar_card_num,in_passport_num,
              in_prev_school_name,in_prev_school_address,in_prev_school_board,
              in_stud_status,in_status_desc, in_is_new_admission, in_is_active,
              in_created_by, in_created_by,
              in_distance_from_school, in_special_interest, 
              in_is_sibling, in_sibling_detail, in_is_rte, in_rte_category,
              in_boarding_type,in_course_group, in_gr_number, in_sts_number,in_admission_mode);
            

          end;    
  
  	    when 'U' then
       set l_routine_block = 'update';   
         begin
			
			set l_admission_num =in_admission_num;
			
			IF ( in_admission_num_gen_mode='Y' AND length(trim(in_admission_num)) = 0 AND  in_stud_status>=90 ) 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_student_num)) = 0  OR  in_student_num<=0  ) AND  in_stud_status>=100 ) THEN 
					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;

         update student_master set ay_id=in_ay_id, 
        		standard_id=in_standard_id,
        		student_num=l_stud_num,
            admission_num=l_admission_num,
            admission_ref=in_admission_ref, 
            enrollment_num=in_enrollment_num,
			enquiry_date=in_enquiry_date,
            enrollment_date=in_enrollment_date,
            enrolled_for_std=in_enrolled_for_std,
            first_name=in_first_name,
            middle_name=in_middle_name,
            last_name=in_last_name,
            birth_date=in_birth_date,
            gender=in_gender,
            blood_group=in_blood_group,
            birth_place=in_birth_place,
            nationality=in_nationality,
            language=in_language,
            religion=in_religion,
            student_category=in_student_category,
            student_subcategory=in_student_subcategory,
            consession_category=in_consession_category,
            disability=in_disability,
            address_line_1=in_address_line_1,
            address_line_2=in_address_line_2,
            locality=in_locality,
            city=in_city,
            district=in_district,
            state=in_state,
            country=in_country,
            pincode=in_pincode,
            mobile_phone_main=in_mobile_phone_main,
            email_main=in_email_main,
            identification_mark_1=in_identification_mark_1,
            aadhar_card_num=in_aadhar_card_num,
            passport_num=in_passport_num,
            prev_school_name=in_prev_school_name,
            prev_school_address=in_prev_school_address,
            prev_school_board=in_prev_school_board,
            stud_status=in_stud_status,
            status_desc=in_status_desc,
            is_new_admission=in_is_new_admission,
            is_active=in_is_active,
            created_by=in_created_by, 
            updated_by=in_created_by,
            distance_from_school=in_distance_from_school,
            special_interest=in_special_interest,
            is_sibling=in_is_sibling,
            sibling_detail=in_sibling_detail,
            is_rte=in_is_rte,
            rte_category=in_rte_category,
            boarding_type=in_boarding_type,
            course_group=in_course_group,
            gr_number=in_gr_number,
            sts_number=in_sts_number,
			admission_mode=in_admission_mode
          	where inst_id =in_inst_id and student_id=in_student_id and is_active=1 and is_deleted=0;

        call sp_calculate_student_score_in_bulk (in_ay_id, in_inst_id, in_student_id, in_created_by, 
            l_err_code, l_err_desc);
       

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

DROP PROCEDURE IF EXISTS `sp_ins_student_admission_master_1`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_admission_master_1`(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_student_num` VARCHAR(50), IN `in_standard_id` CHAR(2), IN `in_admission_num` VARCHAR(50), IN `in_admission_ref` VARCHAR(25), IN `in_enrollment_num` VARCHAR(50), IN `in_enrollment_date` DATE, IN `in_enrolled_for_std` CHAR(2), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_blood_group` VARCHAR(10), IN `in_birth_place` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_student_category` VARCHAR(20), IN `in_student_subcategory` VARCHAR(20), IN `in_consession_category` VARCHAR(20), IN `in_disability` VARCHAR(20), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_locality` VARCHAR(25), IN `in_city` VARCHAR(25), IN `in_district` VARCHAR(20), IN `in_state` VARCHAR(20), IN `in_country` VARCHAR(25), IN `in_pincode` MEDIUMINT(8), IN `in_mobile_phone_main` VARCHAR(15), IN `in_email_main` VARCHAR(50), IN `in_identification_mark_1` VARCHAR(50), IN `in_aadhar_card_num` VARCHAR(12), IN `in_passport_num` VARCHAR(15), IN `in_prev_school_name` VARCHAR(50), IN `in_prev_school_address` VARCHAR(50), IN `in_prev_school_board` VARCHAR(20), IN `in_stud_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), IN `in_enrollment_num_gen_mode` VARCHAR(10), IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_is_active` TINYINT(1), IN `in_is_new_admission` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_distance_from_school` SMALLINT(5), IN `in_special_interest` VARCHAR(20), IN `in_is_sibling` TINYINT(1), IN `in_sibling_detail` VARCHAR(20), IN `in_is_rte` TINYINT(1), IN `in_rte_category` VARCHAR(20), IN `in_boarding_type` VARCHAR(50), IN `in_course_group` VARCHAR(10), IN `in_gr_number` MEDIUMINT(8), IN `in_sts_number` VARCHAR(50), OUT `out_student_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_student_admission_master';
  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 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_student_id = fn_sequence_generator('STUDENT_MASTER');
           
				IF ( in_enrollment_num_gen_mode='Y' AND length(trim(in_enrollment_num)) = 0 AND  in_stud_status>0 ) THEN 
					call sp_custom_seq_generator(in_inst_id,'STUD_ENROLLMENT_NUM',in_ay_id,in_created_by,l_enrollment_num) ;
					IF length(trim(l_enrollment_num)) = 0 THEN
					   SIGNAL SQLSTATE '10004' 
				      SET MESSAGE_TEXT = 'An error occurred while generating Student Enrollment Num';
			     END IF;
				ELSE
					select enrollment_num INTO t_enrollment_num FROM student_master where enrollment_num=in_enrollment_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
					IF (t_enrollment_num=in_enrollment_num) THEN
						SIGNAL SQLSTATE '10005' 
				      SET MESSAGE_TEXT = 'Enrollment Number is already present';
				   ELSE   
						set l_enrollment_num =in_enrollment_num;
					END IF;	
				END IF;
        
            insert into student_master(ay_id, inst_id,student_id,standard_id,admission_num,
              admission_ref, enrollment_num,enrollment_date,enrolled_for_std,first_name,
              middle_name,last_name, birth_date,gender,blood_group,birth_place,nationality,
              language,religion,student_category,student_subcategory,consession_category,
              disability,address_line_1, address_line_2,locality,city ,district,state,
              country,pincode,mobile_phone_main,email_main,identification_mark_1,
              aadhar_card_num,passport_num,prev_school_name,prev_school_address,
              prev_school_board,stud_status, status_desc, is_new_admission, is_active,
              created_by, updated_by, distance_from_school, special_interest, 
              is_sibling, sibling_detail, is_rte, rte_category,
              boarding_type,course_group, gr_number, sts_number) 
    	 			values(in_ay_id, in_inst_id,l_student_id,in_standard_id,in_admission_num,
              in_admission_ref, 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_blood_group,in_birth_place,in_nationality,in_language,in_religion,
              in_student_category,in_student_subcategory,in_consession_category,
              in_disability,in_address_line_1,in_address_line_2,in_locality,in_city ,
              in_district,in_state,in_country,in_pincode,in_mobile_phone_main,in_email_main,
              in_identification_mark_1,in_aadhar_card_num,in_passport_num,
              in_prev_school_name,in_prev_school_address,in_prev_school_board,
              in_stud_status,in_status_desc, in_is_new_admission, in_is_active,
              in_created_by, in_created_by,
              in_distance_from_school, in_special_interest, 
              in_is_sibling, in_sibling_detail, in_is_rte, in_rte_category,
              in_boarding_type,in_course_group, in_gr_number, in_sts_number);
            
          end;    
  
  	    when 'U' then
       set l_routine_block = 'update';   
         begin
			
			set l_admission_num =in_admission_num;
			
			IF ( in_admission_num_gen_mode='Y' AND length(trim(in_admission_num)) = 0 AND  in_stud_status>=90 ) 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_student_num)) = 0  OR  in_student_num<=0  ) AND  in_stud_status>=100 ) THEN 
					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;

         update student_master set ay_id=in_ay_id, 
        		standard_id=in_standard_id,
        		student_num=l_stud_num,
            admission_num=l_admission_num,
            admission_ref=in_admission_ref, 
            enrollment_num=in_enrollment_num,
            enrollment_date=in_enrollment_date,
            enrolled_for_std=in_enrolled_for_std,
            first_name=in_first_name,
            middle_name=in_middle_name,
            last_name=in_last_name,
            birth_date=in_birth_date,
            gender=in_gender,
            blood_group=in_blood_group,
            birth_place=in_birth_place,
            nationality=in_nationality,
            language=in_language,
            religion=in_religion,
            student_category=in_student_category,
            student_subcategory=in_student_subcategory,
            consession_category=in_consession_category,
            disability=in_disability,
            address_line_1=in_address_line_1,
            address_line_2=in_address_line_2,
            locality=in_locality,
            city=in_city,
            district=in_district,
            state=in_state,
            country=in_country,
            pincode=in_pincode,
            mobile_phone_main=in_mobile_phone_main,
            email_main=in_email_main,
            identification_mark_1=in_identification_mark_1,
            aadhar_card_num=in_aadhar_card_num,
            passport_num=in_passport_num,
            prev_school_name=in_prev_school_name,
            prev_school_address=in_prev_school_address,
            prev_school_board=in_prev_school_board,
            stud_status=in_stud_status,
            status_desc=in_status_desc,
            is_new_admission=in_is_new_admission,
            is_active=in_is_active,
            created_by=in_created_by, 
            updated_by=in_created_by,
            distance_from_school=in_distance_from_school,
            special_interest=in_special_interest,
            is_sibling=in_is_sibling,
            sibling_detail=in_sibling_detail,
            is_rte=in_is_rte,
            rte_category=in_rte_category,
            boarding_type=in_boarding_type,
            course_group=in_course_group,
            gr_number=in_gr_number,
            sts_number=in_sts_number
          	where inst_id =in_inst_id and student_id=in_student_id and is_active=1 and is_deleted=0;

        call sp_calculate_student_score_in_bulk (in_ay_id, in_inst_id, in_student_id, in_created_by, 
            l_err_code, l_err_desc);
       

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

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

DROP PROCEDURE IF EXISTS `sp_ins_student_assignment_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_assignment_details_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_assignment_dtl_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)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_student_assignment_details_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  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,remark,parent_remark,child_assignment_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_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;
  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 = '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 = fn_sequence_generator('STUDENT_ASSIGNMENT_DETAIL');
               -- 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_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 = '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_student_assignment_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_assignment_master`(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_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_group_type` CHAR(3), IN `in_group_id` VARCHAR(8), IN `in_emp_id` MEDIUMINT(8), IN `in_sub_std_map_id` MEDIUMINT(8), IN `in_book_chpt_map_id` MEDIUMINT(8), IN `in_assignment_title` VARCHAR(50), IN `in_assignment_desc` TEXT, IN `in_assignment_init_date` DATE, IN `in_assignment_target_date` DATE, IN `in_is_mandatory` TINYINT(1), IN `in_is_backdated` TINYINT(1), IN `in_assignment_file_1` VARCHAR(25), IN `in_assignment_file_2` VARCHAR(25), IN `in_assignment_file_3` VARCHAR(25), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), 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_assignment_mst_id` MEDIUMINT(8))
    NO SQL
begin
  	declare l_routine_name varchar(50) default 'sp_ins_student_assignment_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_assignment_mst_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_assignment_mst_id = fn_sequence_generator('STUDENT_ASSIGNMENT_MASTER');
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,
							is_active, 
							created_by, updated_by) 	 						
           values(in_ay_id,
					   in_inst_id,
					   l_assignment_mst_id,
					    in_standard_id,
					   in_division_id,
					   in_group_type,
					   in_group_id,
					   in_emp_id,
					   in_sub_std_map_id,
					   in_book_chpt_map_id,
					   in_assignment_title,
                       in_assignment_desc,
					   in_assignment_init_date,
					   in_assignment_target_date,
					   in_is_mandatory,
					   in_is_backdated,
					   in_assignment_file_1,
					   in_assignment_file_2,
					   in_assignment_file_3,
                     in_status,
					   in_status_desc,
					   in_is_active,
					   in_created_by, 
					   in_created_by);
          end;    
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update student_assignment_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where  assignment_mst_id = in_assignment_mst_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
             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,
			 is_active, 
			 created_by, updated_by) 	 						
           values(in_ay_id,
					   in_inst_id,
					   in_assignment_mst_id,
					    in_standard_id,
					   in_division_id,
					   in_group_type,
					   in_group_id,
					   in_emp_id,
					   in_sub_std_map_id,
					   in_book_chpt_map_id,
					   in_assignment_title,
             in_assignment_desc,
					   in_assignment_init_date,
					   in_assignment_target_date,
					   in_is_mandatory,
					   in_is_backdated,
					   in_assignment_file_1,
					   in_assignment_file_2,
					   in_assignment_file_3,
             in_status,
					   in_status_desc,
					   in_is_active,
					   in_created_by, 
					   in_created_by);
     end;    
      end case;
    commit;
     set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
         set out_assignment_mst_id = l_assignment_mst_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_student_attendance_master_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_attendance_master_details`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_group_type` CHAR(3), IN `in_group_id` VARCHAR(8), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_timetable_period_id` VARCHAR(25), IN `in_file_upload_id` MEDIUMINT(8), IN `in_attendance_type` VARCHAR(15), IN `in_attendance_date` DATE, IN `in_class_count` TINYINT(3), IN `in_present_count` TINYINT(3), IN `in_absent_count` TINYINT(3), IN `in_attendance_comments` VARCHAR(100), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), 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_student_attendance_master_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
        begin
          	update student_attendance_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), status=in_status
            where  attendance_mst_id = in_attendance_mst_id and  is_deleted = 0 and is_active = 1 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
     end;    
    commit;
     set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_student_bulk_temp_users_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_bulk_temp_users_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stud_bulk_file_upload_id` MEDIUMINT(8), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_bulk_temp_users_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 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 text default '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';

	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 = 'temp_user_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(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 'S' then          
        begin
           set l_routine_block = 'update student_master and temp_user_student_master';   

                UPDATE student_master SET is_active=1, stud_status=100, bulk_upload_status=100 
                  WHERE is_active=-1 AND inst_id=in_inst_id  AND ay_id=in_ay_id AND is_deleted=0
                  AND stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;
              
          
                UPDATE temp_user_student_master tusm,student_master sm
                   SET tusm.is_active=1, tusm.stud_status=100, tusm.bulk_upload_status=100
                 WHERE tusm.inst_id=sm.inst_id
                  AND tusm.ay_id=sm.ay_id
                  AND tusm.is_deleted=sm.is_deleted
                  AND tusm.student_id=sm.student_id
                  AND tusm.is_active=-1 AND tusm.inst_id=in_inst_id
                  AND tusm.ay_id=in_ay_id
                  AND tusm.is_deleted=0
                  AND sm.stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;

                 UPDATE parent_master SET is_active=1, bulk_upload_status=100 
                  WHERE is_active=-1 AND inst_id=in_inst_id  
                  AND is_deleted=0
                  AND stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;
              
          
                UPDATE temp_user_parent_master tupm,parent_master pm
                   SET tupm.is_active=1, tupm.status=100, tupm.bulk_upload_status=100
                 WHERE tupm.inst_id=pm.inst_id
                  AND tupm.is_deleted=pm.is_deleted
                  AND tupm.parent_id=pm.parent_id
                  AND tupm.is_active=-1 AND tupm.inst_id=in_inst_id
                  AND tupm.is_deleted=0
                  AND pm.stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;

     end;     

      when 'T' then          
      begin
         set l_routine_block = 'update temp_user_student_master';   
  
            UPDATE temp_user_student_master SET is_active=1, stud_status=100 WHERE is_active=-1 AND inst_id=in_inst_id
              AND ay_id=in_ay_id
              AND is_deleted=0;
      
       end;     
    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_student_bulk_upload_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_bulk_upload_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_enrollment_num_gen_mode` VARCHAR(10), IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_stud_status` VARCHAR(25), IN `in_stud_bulk_file_upload_id` MEDIUMINT(8), IN `in_insert_row_count` INT, IN `in_json_str` MEDIUMTEXT, 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_bulk_upload_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';
  
  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 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 student_master(ay_id, inst_id, student_id, class_id,
    admission_num, enrollment_num, student_num, class_roll_num, first_name, middle_name, last_name, birth_date, gender,
    religion, student_category, consession_category, address_line_1, locality, city, state, district, country, 
    mobile_phone_main, email_main, aadhar_card_num, stud_status, is_active, created_by, updated_by, standard_id,
    division_id, bulk_upload_status, stud_bulk_file_upload_id, contact_id_1, contact_id_2,
    sts_number,gr_number,boarding_type,distance_from_school,rte_category,
    nationality,blood_group,birth_place,language,disability,passport_num,
    prev_school_name,prev_school_address,prev_school_board,emer_contact_name_1,
    emer_contact_1_relation,emer_contact_num_1,emer_contact_name_2,emer_contact_2_relation,
    emer_contact_num_2,dr_name,dr_hospital_name,dr_contact_mobile,
    health_issue_desc,sibling_detail,is_rte,is_stud_health_issue,is_sibling,
    student_subcategory,address_line_2,house_id,admission_ref,admission_ref_desc,enrollment_date,
    enrolled_for_std,is_new_admission,course_group) 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_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);

      
      

      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('STUDENT_MASTER');
              end;
    
            when 'U' then
              begin
                set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;     
        
      elseif(l_template_col_name = 'enrollment_num') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                if (in_enrollment_num_gen_mode='Y' AND in_stud_status>0 ) THEN
       
        					call sp_custom_seq_generator(in_inst_id,'STUD_ENROLLMENT_NUM',in_ay_id,in_created_by,l_enrollment_num) ;
        					
              	 IF length(trim(l_enrollment_num)) = 0 THEN
    					      SIGNAL SQLSTATE '10004' 
      				      SET MESSAGE_TEXT = 'An error occurred while generating Student Enrollment Num';
      			     END IF;

                  
                  set l_template_col_value = l_enrollment_num;   

                  else 

                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
        					  
    			      end if;
              end;
    
            when 'U' then
              begin
                set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'admission_num') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                IF ( in_admission_num_gen_mode='Y' AND in_stud_status>0 ) 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;
                  
                  set l_template_col_value = l_admission_num;

                  else 

                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
        					  
        				END IF;	
              end;
    
            when 'U' then
              begin
                set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
          end case;
        end;   
      
      elseif (l_template_col_name = 'student_num') THEN
      begin
        case in_dml_mode 
          when 'I' then
            begin
              IF ( in_stud_num_gen_mode='Y' AND in_stud_status>0 ) THEN 

      					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;

      					set l_template_col_value = l_stud_num;
      
                else 

                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
        					  
      				END IF;	
            end;
  
          when 'U' then
            begin
              set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
            
            end;
        end case;
      end;    
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

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

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


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

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

    
    

    close cur_json_template;

  end while;

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

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

        commit;
      end;

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

      DELETE  From student_master  WHERE is_active=-1 AND inst_id=in_inst_id  AND ay_id=in_ay_id 
                AND is_deleted=0 and bulk_upload_status=1
                  AND stud_bulk_file_upload_id=in_stud_bulk_file_upload_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_student_bulk_user_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_bulk_user_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` INT, IN `in_json_str` MEDIUMTEXT, 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_bulk_user_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 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_user_id mediumint(8);

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

  declare l_insert_sql_str MEDIUMTEXT default 'INSERT INTO user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,
    password,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_token_verified, is_active,created_by, updated_by, api_token) 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_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 = 'user_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
				        set l_template_col_value = fn_sequence_generator('USER_MASTER');
                set l_user_id=l_template_col_value;
                CALL `sp_ins_user_role_map`('U', in_inst_id, 'STU', l_user_id, '22', in_created_by, l_err_code, l_err_desc);
			        	CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, 'STU', l_user_id, in_created_by, l_err_code, l_err_desc);
          
              end;
    
            when 'U' then
              begin
                set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                set l_user_id=l_template_col_value;
                 CALL `sp_ins_user_role_map`('U', in_inst_id, 'STU', l_user_id, '22', in_created_by, l_err_code, l_err_desc);
			        	CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, 'STU', l_user_id, in_created_by, l_err_code, l_err_desc);
          
              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 'U' 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_student_elective_subject_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_elective_subject_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_class_id` VARCHAR(25), IN `in_student_id` VARCHAR(25), IN `in_subject_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_student_elective_subject_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  student_elective_subject_map (ay_id, inst_id,class_id, student_id,subject_id,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_class_id, in_student_id,in_subject_id,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update student_elective_subject_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  subject_id=in_subject_id and student_id=in_student_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  student_elective_subject_map (ay_id, inst_id,class_id, student_id,subject_id,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_class_id, in_student_id,in_subject_id,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_student_health_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_health_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_class_id` MEDIUMINT(8), IN `in_student_id` CHAR(8), IN `in_height` DECIMAL(7,2), IN `in_weight` DECIMAL(7,2), IN `in_chest` DECIMAL(7,2), IN `in_birth_mark` VARCHAR(50), IN `in_blood_group` VARCHAR(50), IN `in_eyesight_right` DECIMAL(7,2), IN `in_eyesight_left` DECIMAL(7,2), IN `in_added_by` 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_student_health_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  	
  declare exit handler for sqlexception
	 begin
      rollback;
      
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
        
    start transaction;
    
      case in_dml_mode 
        when 'I' then
          begin

             update  student_health_details 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_routine_block = 'insert';
           
            insert into  student_health_details(
			      ay_id, inst_id,
              class_id, 
              student_id, 
              height,
              weight, 
              chest,
              birth_mark,
              blood_group,
              eyesight_right,
              eyesight_left,
              added_by,
              created_by, 
              updated_by,is_active) 
            values( in_ay_id,
					 in_inst_id,
					 in_class_id, 
					 in_student_id,
					 in_height,
					 in_weight,
           in_chest,
					 in_birth_mark,
           in_blood_group,
           in_eyesight_right,
           in_eyesight_left,
           in_added_by,
					 in_created_by, 
					 in_created_by,
           in_is_active);

         
          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_student_homework_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_homework_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stud_hw_mst_id` MEDIUMINT(8), IN `in_stud_hw_dtl_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)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_student_homework_details_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_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_homework_details(ay_id, 
                                                                            inst_id, 
																		                                         stud_hw_mst_id,
                                                                             stud_hw_dtl_id, 
                                        			                               group_type,
                                        								                      group_id,
                                                                             standard_id,
                                        									                   division_id, 
                                        								                   	student_id,
                                                                            percent_complete,
                                                                            percent_update_date,
                                                                            hw_completion_date,
                                        									                  status,
                                                                            status_desc,
                                                                            created_by,
																		                                       	updated_by,
                                                                              is_active,remark,parent_remark,child_homework_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_homework_details' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);
      if (l_template_col_name = 'stud_hw_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('STUDENT_HOMEWORK_DETAILS');
              end;
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('STUDENT_HOMEWORK_DETAILS');
               -- set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              end;
          end case;
        end;     
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Close Cursor', l_insert_val_str_full);
    close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'Before Close Cursor', l_insert_sql_str);
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
           update student_homework_details set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and stud_hw_mst_id = in_stud_hw_mst_id
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_student_homework_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_homework_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_stud_hw_mst_id` MEDIUMINT(8), IN `in_hw_group_type` VARCHAR(25), IN `in_emp_id` MEDIUMINT(8), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_group_type` CHAR(3), IN `in_group_id` VARCHAR(8), IN `in_sub_std_map_id` MEDIUMINT(8), IN `in_book_chpt_map_id` MEDIUMINT(8), IN `in_hw_assign_date` DATE, IN `in_hw_target_date` DATE, IN `in_hw_type` VARCHAR(10), IN `in_hw_desc` TEXT, IN `in_is_mandatory` TINYINT(1), IN `in_is_backdated` TINYINT(1), IN `in_homework_file_1` VARCHAR(25), IN `in_homework_file_2` VARCHAR(25), IN `in_homework_file_3` VARCHAR(25), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), 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_stud_hw_mst_id` MEDIUMINT(8))
    NO SQL
begin
  	declare l_routine_name varchar(50) default 'sp_ins_student_homework_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_stud_hw_mst_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_stud_hw_mst_id = fn_sequence_generator('Student_HOMEWORK_MASTER');
           insert into  student_homework_master(ay_id, inst_id,stud_hw_mst_id,hw_group_type,emp_id,standard_id,division_id,group_type, group_id,sub_std_map_id,
			book_chpt_map_id,hw_assign_date,hw_target_date,hw_type,hw_desc,is_mandatory,is_backdated,homework_file_1, homework_file_2,
			 homework_file_3,status, status_desc,is_active, created_by, updated_by) 	 						
                       values(in_ay_id, in_inst_id,l_stud_hw_mst_id,in_hw_group_type,in_emp_id,in_standard_id,in_division_id,
					   in_group_type,in_group_id,in_sub_std_map_id,in_book_chpt_map_id,in_hw_assign_date,in_hw_target_date,in_hw_type,
					   in_hw_desc,
					   in_is_mandatory,in_is_backdated,in_homework_file_1,in_homework_file_2,in_homework_file_3,
              in_status,in_status_desc,in_is_active,in_created_by, in_created_by);
          end;    
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update student_homework_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where  stud_hw_mst_id = in_stud_hw_mst_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into  student_homework_master(ay_id, inst_id,stud_hw_mst_id,hw_group_type,emp_id,standard_id,division_id,group_type, group_id,sub_std_map_id,
			book_chpt_map_id,hw_assign_date,hw_target_date,hw_type,hw_desc,is_mandatory,is_backdated,homework_file_1, homework_file_2,
			 homework_file_3,status, status_desc,is_active, created_by, updated_by) 	 						
                       values(in_ay_id, in_inst_id,in_stud_hw_mst_id,in_hw_group_type,in_emp_id,in_standard_id,in_division_id,
					   in_group_type,in_group_id,in_sub_std_map_id,in_book_chpt_map_id,in_hw_assign_date,in_hw_target_date,in_hw_type,
					   in_hw_desc,
					   in_is_mandatory,in_is_backdated,in_homework_file_1,in_homework_file_2,in_homework_file_3,
              in_status,in_status_desc,in_is_active,in_created_by, in_created_by);
     end;    
      end case;
    commit;
     set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
         set out_stud_hw_mst_id = l_stud_hw_mst_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_student_leave_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_leave_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_student_id` VARCHAR(25), IN `in_leave_type` VARCHAR(25), IN `in_leave_start_date` DATE, IN `in_leave_end_date` DATE, IN `in_is_back_dated` CHAR(1), IN `in_leave_duration` INT(3), IN `in_leave_applied_on` DATE, IN `in_leave_status` VARCHAR(25), IN `in_initiated_by` VARCHAR(25), IN `in_initiator_comments` VARCHAR(50), IN `in_approved_on` DATE, IN `in_approved_by` VARCHAR(25), IN `in_approval_type` VARCHAR(15), 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_student_leave_details';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  student_leave_details(ay_id, inst_id,student_id, leave_type,leave_start_date,leave_end_date,is_back_dated, 
               	leave_duration,leave_applied_on,leave_status,initiated_by,initiator_comments,approved_on,approved_by, approval_type,approver_comments,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_student_id, in_leave_type,in_leave_start_date,in_leave_end_date,in_is_back_dated, 
               	in_leave_duration,in_leave_applied_on,in_leave_status,in_initiated_by,in_initiator_comments,in_approved_on,in_approved_by, in_approval_type,in_approver_comments,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update student_leave_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  student_id=in_student_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
             insert into  student_leave_details(ay_id, inst_id,student_id, leave_type,leave_start_date,leave_end_date,is_back_dated, 
               	leave_duration,leave_applied_on,leave_status,initiated_by,initiator_comments,approved_on,approved_by, approval_type,approver_comments,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_student_id, in_leave_type,in_leave_start_date,in_leave_end_date,in_is_back_dated, 
               	in_leave_duration,in_leave_applied_on,in_leave_status,in_initiated_by,in_initiator_comments,in_approved_on,in_approved_by, in_approval_type,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_student_leave_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_leave_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_leave_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, OUT `out_leave_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_student_leave_details_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_leave_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_leave_details(ay_id,
																		inst_id, 
																		leave_id,
																		standard_id,
																		division_id,
																		class_id, 
																		student_id,
																		leave_type,
																		leave_start_date,
																		leave_end_date,
																		is_back_dated,
																		leave_duration,
																		leave_applied_on,
																		status,
																		status_desc,
																		initiated_by,
																		initiator_comments,
																		approved_on,
																		approved_by,
																		approval_type,
																		approver_comments,
																		 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 cursor for 
  select col_name from json_template_master 
  where tbl_name = 'student_leave_details' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);
      if (l_template_col_name = 'leave_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('STUDENT_LEAVE_DETAILS');
				 set l_leave_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 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_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);        
          set l_leave_id = in_leave_id;
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_leave_id= l_leave_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_student_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_master`(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_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_class_id` CHAR(8), IN `in_file_upload_id` MEDIUMINT(8), IN `in_student_num` VARCHAR(55), IN `in_admission_num` VARCHAR(55), IN `in_admission_ref` VARCHAR(25), IN `in_admission_ref_desc` VARCHAR(50), IN `in_enrollment_num` VARCHAR(25), IN `in_enrollment_date` DATE, IN `in_enrolled_for_std` CHAR(2), IN `in_class_roll_num` TINYINT(3), IN `in_house_id` SMALLINT(5), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_blood_group` VARCHAR(10), IN `in_birth_place` VARCHAR(200), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_student_category` VARCHAR(20), IN `in_student_subcategory` VARCHAR(200), IN `in_consession_category` VARCHAR(20), IN `in_disability` VARCHAR(20), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_locality` INT(4), IN `in_city` INT(4), IN `in_district` INT(4), IN `in_state` INT(4), IN `in_country` INT(4), IN `in_pincode` MEDIUMINT(8), IN `in_mobile_phone_main` VARCHAR(15), IN `in_email_main` VARCHAR(50), IN `in_profile_logo_path` VARCHAR(100), IN `in_photo_content_type` VARCHAR(20), IN `in_photo_file_data` BINARY(255), IN `in_photo_file_path` VARCHAR(25), IN `in_photo_file_size` MEDIUMINT(8), IN `in_contact_id_1` MEDIUMINT(8), IN `in_contact_id_2` MEDIUMINT(8), IN `in_identification_mark_1` VARCHAR(50), IN `in_identification_mark_2` VARCHAR(50), IN `in_aadhar_card_num` VARCHAR(12), IN `in_passport_num` VARCHAR(15), IN `in_prev_school_name` VARCHAR(50), IN `in_prev_school_address` VARCHAR(50), IN `in_prev_school_board` VARCHAR(20), IN `in_stud_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_distance_from_school` SMALLINT(5), IN `in_special_interest` VARCHAR(100), IN `in_is_sibling` TINYINT(3), IN `in_sibling_detail` VARCHAR(100), IN `in_is_rte` TINYINT(1), IN `in_rte_category` VARCHAR(100), IN `in_boarding_type` VARCHAR(50), IN `in_course_group` VARCHAR(10), IN `in_gr_number` VARCHAR(50), IN `in_sts_number` VARCHAR(50), IN `in_is_new_admission` TINYINT(3), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_student_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(50);
  declare l_student_id mediumint(8);
  declare 	l_standard_id char(2);
  declare 	l_division_id char(1);
  declare l_student_num varchar(50);
  declare t_student_num varchar(50);
  declare l_class_roll_num tinyint(3);
  
  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;
        
    start transaction;
    
      case in_dml_mode 
        
  
  	    when 'U' then
       set l_routine_block = 'update_student_master_1';   
          begin
          
          
          IF ( in_stud_status=100 ) THEN 
	          update  user_master set is_active=1 where user_type='STU' and user_id = in_student_id   and is_deleted = '0' and inst_id = in_inst_id;    
              update  student_master set is_active=1 where student_id = in_student_id   and is_deleted = '0' and inst_id = in_inst_id;       
        END IF;	
        
           set	 l_standard_id='';
           set	 l_division_id='';
			 			  
          IF (length(trim(in_class_id)) > 0  ) THEN 
	   	    select standard_id,division_id INTO l_standard_id , l_division_id FROM class_master where ay_id=in_ay_id and inst_id=in_inst_id and class_id=in_class_id and is_active=1 and is_deleted=0;
          END IF;

       	set l_routine_block = 'update_student_master_2';            
			set l_student_num=in_student_num;       
			IF ( in_stud_num_gen_mode='N' AND length(trim(in_student_num)) > 0 AND  in_stud_status>=100 ) THEN 
				SELECT student_num INTO t_student_num  FROM student_master where student_id=in_student_id  and inst_id=in_inst_id and is_active=1 and is_deleted=0 LIMIT 1;
				IF (length(trim(t_student_num)) = 0  ) THEN

				set l_routine_block = 'update_student_master_3';      
								select student_num INTO t_student_num FROM student_master where student_num=in_student_num and inst_id=in_inst_id and is_active=1 and is_deleted=0 LIMIT 1;
								IF (t_student_num=in_student_num) THEN
									SIGNAL SQLSTATE '10010'
									SET MESSAGE_TEXT = 'Student Number is already present';
								END IF;
				END IF;
			ELSEIF ( in_stud_num_gen_mode='N' AND  in_stud_status>=100  AND length(trim(in_student_num)) = 0 ) THEN 
				SIGNAL SQLSTATE '10011'
				SET MESSAGE_TEXT = 'Please Enter Student Number';
			END IF;	
			             
			IF(in_class_id!='')	 THEN     
				set l_routine_block = 'update_student_master_4';   
				SELECT COUNT(*) INTO l_class_roll_num  FROM student_master 
          where student_id!=in_student_id  and class_id=in_class_id 
          and class_roll_num=in_class_roll_num and class_roll_num!='0' and inst_id=in_inst_id  AND ay_id=in_ay_id and stud_status=100
          and is_active=1 and is_deleted=0;

				IF ( l_class_roll_num>0 ) THEN 
					SIGNAL SQLSTATE '10012'
					SET MESSAGE_TEXT = 'Duplicate Roll Number. Please select unique Roll number';
				END IF;
			END IF;				

			update student_master set 	
					inst_id=in_inst_id,
					student_id =in_student_id ,
					standard_id =l_standard_id ,
					division_id =l_division_id ,
					class_id =in_class_id ,
					student_num =l_student_num ,
					admission_ref =in_admission_ref ,
					enrollment_date =in_enrollment_date ,
					enrolled_for_std =in_enrolled_for_std ,
					class_roll_num =in_class_roll_num ,
					house_id=in_house_id,
					first_name =in_first_name ,
					middle_name =in_middle_name,
					last_name =in_last_name ,
					birth_date =in_birth_date ,
					gender =in_gender ,
					blood_group =in_blood_group ,
					birth_place =in_birth_place ,
					nationality =in_nationality ,
					language =in_language ,
					religion =in_religion ,
					student_category =in_student_category ,
					student_subcategory =in_student_subcategory ,
					consession_category =in_consession_category ,
					disability =in_disability ,
					address_line_1 =in_address_line_1 ,
					address_line_2 =in_address_line_2 ,
					locality =in_locality ,
					city =in_city ,
					district =in_district ,
					state =in_state ,
					country =in_country ,
					pincode =in_pincode ,
					mobile_phone_main=in_mobile_phone_main,
					email_main=in_email_main,
					identification_mark_1 =in_identification_mark_1 ,
					aadhar_card_num =in_aadhar_card_num ,
					passport_num =in_passport_num ,
					prev_school_name =in_prev_school_name ,
					prev_school_address =in_prev_school_address ,
					prev_school_board =in_prev_school_board ,
					stud_status =in_stud_status ,
					status_desc =in_status_desc ,
					is_active =in_is_active ,
					created_by =in_created_by ,
					updated_by=in_created_by,
					distance_from_school=in_distance_from_school,
					special_interest=in_special_interest,
					is_sibling=in_is_sibling,
					sibling_detail=in_sibling_detail,
					is_rte=in_is_rte,
					rte_category=in_rte_category,
					boarding_type=in_boarding_type,
					course_group=in_course_group,
					gr_number=in_gr_number,
					sts_number=in_sts_number,
                    is_new_admission=in_is_new_admission,
					updated_on=now()
			where inst_id =in_inst_id and ay_id=in_ay_id and student_id=in_student_id and is_active=1 and is_deleted=0;             

 		IF ( in_stud_status>100 ) THEN 
	          update  user_master set is_active=0,updated_on=now() where user_type='STU' and user_id = in_student_id   and is_deleted = '0' and inst_id = in_inst_id;    
              update  student_master set is_active=0,updated_on=now() where student_id = in_student_id   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_student_previous_institutions`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_previous_institutions`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_student_id` VARCHAR(25), IN `in_standard_id` VARCHAR(25), IN `in_inst_name` VARCHAR(25), IN `in_inst_desc` VARCHAR(50), IN `in_inst_joining_date` DATE, IN `in_inst_leaving_date` DATE, IN `in_inst_shift_reason` VARCHAR(100), IN `in_address_line_1` VARCHAR(25), IN `in_address_line_2` VARCHAR(25), IN `in_locality` VARCHAR(25), IN `in_city` VARCHAR(25), IN `in_state` VARCHAR(20), IN `in_country` VARCHAR(25), IN `in_pincode` MEDIUMINT(7), IN `in_is_shift_midterm` CHAR(1), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_student_previous_institutions';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  student_previous_institutions(ay_id, inst_id,student_id, standard_id,inst_name,inst_desc,inst_joining_date, 
               	inst_leaving_date,inst_shift_reason,address_line_1,address_line_2,locality,city,state,country,pincode,
                 is_shift_midterm,created_by, updated_by) 
            values(in_ay_id, in_inst_id,in_student_id, in_standard_id,in_inst_name,in_inst_desc,in_inst_joining_date, 
               	in_inst_leaving_date,in_inst_shift_reason,in_address_line_1,in_address_line_2,in_locality,in_city,in_state,in_country,in_pincode,
                 in_is_shift_midterm,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update  student_previous_institutions set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where  student_id=in_student_id and standard_id=in_standard_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
           insert into  student_previous_institutions(ay_id, inst_id,student_id, standard_id,inst_name,inst_desc,inst_joining_date, 
               	inst_leaving_date,inst_shift_reason,address_line_1,address_line_2,locality,city,state,country,pincode,
                 is_shift_midterm,created_by, updated_by) 
           values(in_ay_id, in_inst_id,in_student_id, in_standard_id,in_inst_name,in_inst_desc,in_inst_joining_date, 
               	in_inst_leaving_date,in_inst_shift_reason,in_address_line_1,in_address_line_2,in_locality,in_city,in_state,in_country,in_pincode,
                 in_is_shift_midterm,in_created_by, in_created_by);
     end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_student_profile_update_api`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_profile_update_api`(IN `in_action` VARCHAR(50), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_student_id` MEDIUMINT(8), IN `in_mobile_phone_main` VARCHAR(10), IN `in_email_main` VARCHAR(50), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_pincode` MEDIUMINT(8), IN `in_blood_group` VARCHAR(10), IN `in_language` VARCHAR(20), IN `in_nationality` VARCHAR(20), IN `in_aadhar_card_num` VARCHAR(20), IN `in_father_first_name` VARCHAR(20), IN `in_father_middle_name` VARCHAR(20), IN `in_father_last_name` VARCHAR(20), IN `in_father_mobile_phone_1` VARCHAR(20), IN `in_father_email_main` VARCHAR(50), IN `in_father_birth_date` DATE, IN `in_father_birth_place` VARCHAR(20), IN `in_father_edu_qual_degree` VARCHAR(25), IN `in_father_occupation` VARCHAR(20), IN `in_father_income_bracket` VARCHAR(20), IN `in_father_religion` VARCHAR(20), IN `in_father_relation_type` VARCHAR(20), IN `in_father_relation` VARCHAR(20), IN `in_father_aadhar_card_num` VARCHAR(12), IN `in_father_pan_card_num` VARCHAR(10), IN `in_mother_first_name` VARCHAR(20), IN `in_mother_middle_name` VARCHAR(20), IN `in_mother_last_name` VARCHAR(20), IN `in_mother_mobile_phone_1` VARCHAR(20), IN `in_mother_email_main` VARCHAR(50), IN `in_mother_birth_date` DATE, IN `in_mother_birth_place` VARCHAR(20), IN `in_mother_edu_qual_degree` VARCHAR(25), IN `in_mother_occupation` VARCHAR(20), IN `in_mother_income_bracket` VARCHAR(20), IN `in_mother_religion` VARCHAR(20), IN `in_mother_relation_type` VARCHAR(20), IN `in_mother_relation` VARCHAR(20), IN `in_mother_aadhar_card_num` VARCHAR(12), IN `in_mother_pan_card_num` VARCHAR(10), IN `in_emer_contact_name_1` VARCHAR(50), IN `in_emer_contact_1_relation` VARCHAR(25), IN `in_emer_contact_num_1` VARCHAR(20), IN `in_emer_contact_name_2` VARCHAR(50), IN `in_emer_contact_2_relation` VARCHAR(25), IN `in_emer_contact_num_2` VARCHAR(20), IN `in_dr_name` VARCHAR(50), IN `in_dr_hospital_name` VARCHAR(50), IN `in_dr_contact_off` VARCHAR(20), IN `in_dr_contact_mobile` VARCHAR(20), IN `in_is_stud_health_issue` TINYINT(1), IN `in_health_issue_desc` VARCHAR(200), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_student_profile_update_api';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(1000) default 'sp_ins_student_profile_update_api';
  declare l_contact_id_1 mediumint(8);
  declare l_contact_id_2 mediumint(8);
  declare l_parent_id mediumint(8);
  declare l_division_id char(1);
  declare l_student_num varchar(50);
  declare t_student_num varchar(50);
  declare l_class_roll_num tinyint(3);
  
  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_student_id);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_action 
        
  
	    when 'student_info' then
       set l_routine_block = 'update_student_master';   
          begin
          

    			update student_master set 	
    					inst_id=in_inst_id,
    					blood_group =in_blood_group ,
    					nationality =in_nationality ,
    					language =in_language ,
    					address_line_1 =in_address_line_1 ,
    					address_line_2 =in_address_line_2 ,
    					pincode =in_pincode ,
    					-- mobile_phone_main=in_mobile_phone_main,
           		email_main=in_email_main,
    					aadhar_card_num =in_aadhar_card_num ,
    					created_by =in_student_id ,
    					updated_by=in_student_id
    			where inst_id =in_inst_id and ay_id=in_ay_id and student_id=in_student_id and is_active=1 and is_deleted=0;             
           
      end;    

      when 'father_info' then
       set l_routine_block = 'update_parent_master';   
          begin
          
          
	   	    select contact_id_1 INTO l_contact_id_1 FROM student_master
            where ay_id=in_ay_id and inst_id=in_inst_id and student_id=in_student_id and is_active=1 and is_deleted=0;
      	        
        

     if(l_contact_id_1 IS NULL OR l_contact_id_1='' OR l_contact_id_1=null OR l_contact_id_1='0')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, birth_date,gender,relation_type,
        relation,birth_place,religion,email_main,mobile_phone_1,occupation,
        income_bracket ,edu_qual_degree ,aadhar_card_num, pan_card_num, is_active,
        created_by, updated_by) 
       values(
        in_ay_id,in_inst_id,l_parent_id,'MR.',UPPER(in_father_first_name) ,
        UPPER(in_father_middle_name),UPPER(in_father_last_name),in_father_birth_date ,'M' ,in_father_relation_type ,
        in_father_relation ,in_father_birth_place,in_father_religion,in_father_email_main,in_father_mobile_phone_1 ,in_father_occupation ,
        in_father_income_bracket, in_father_edu_qual_degree ,in_father_aadhar_card_num ,in_father_pan_card_num ,1,
        in_student_id,in_student_id);

    	update student_master set contact_id_1=l_parent_id where student_id=in_student_id and is_deleted='0';

      else

      set l_parent_id=l_contact_id_1;
        update parent_master set 
          first_name=UPPER(in_father_first_name),
          middle_name=UPPER(in_father_middle_name),
          last_name=UPPER(in_father_last_name),
          mobile_phone_1=in_father_mobile_phone_1,
          email_main=in_father_email_main,
          birth_date=in_father_birth_date,
          birth_place=in_father_birth_place,
          edu_qual_degree=in_father_edu_qual_degree,
          occupation=in_father_occupation,
          income_bracket=in_father_income_bracket,
          religion=in_father_religion,
          relation_type=in_father_relation_type,
          relation=in_father_relation,
          aadhar_card_num=in_father_aadhar_card_num,
          pan_card_num=in_father_pan_card_num
          where parent_id=l_contact_id_1 and is_active=1 and is_deleted=0;  

        end if;
     end;

     when 'mother_info' then
       set l_routine_block = 'update_parent_master';   
          begin
          
	   	   select contact_id_2 INTO l_contact_id_2 FROM student_master
            where ay_id=in_ay_id and inst_id=in_inst_id and student_id=in_student_id and is_active=1 and is_deleted=0;
      	        
     if(l_contact_id_2 IS NULL OR l_contact_id_2='' OR l_contact_id_2=null OR l_contact_id_2='0')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, birth_date,gender,relation_type,
        relation,birth_place,religion,email_main,mobile_phone_1,occupation,
        income_bracket ,edu_qual_degree ,aadhar_card_num, pan_card_num, is_active,
        created_by, updated_by) 
       values(
        in_ay_id,in_inst_id,l_parent_id,'MRS.',UPPER(in_mother_first_name) ,
        UPPER(in_mother_middle_name),UPPER(in_mother_last_name),in_mother_birth_date ,'F' ,in_mother_relation_type ,
        in_mother_relation ,in_mother_birth_place,in_mother_religion,in_mother_email_main,in_mother_mobile_phone_1 ,in_mother_occupation ,
        in_mother_income_bracket, in_mother_edu_qual_degree ,in_mother_aadhar_card_num ,in_mother_pan_card_num ,1,
        in_student_id,in_student_id);

    	update student_master set contact_id_2=l_parent_id where student_id=in_student_id and is_deleted='0';

      else

      set l_parent_id=l_contact_id_2;
        update parent_master set 
          first_name=UPPER(in_mother_first_name),
          middle_name=UPPER(in_mother_middle_name),
          last_name=UPPER(in_mother_last_name),
          mobile_phone_1=in_mother_mobile_phone_1,
          email_main=in_mother_email_main,
          birth_date=in_mother_birth_date,
          birth_place=in_mother_birth_place,
          edu_qual_degree=in_mother_edu_qual_degree,
          occupation=in_mother_occupation,
          income_bracket=in_mother_income_bracket,
          religion=in_mother_religion,
          relation_type=in_mother_relation_type,
          relation=in_mother_relation,
          aadhar_card_num=in_mother_aadhar_card_num,
          pan_card_num=in_mother_pan_card_num
          where parent_id=l_contact_id_2 and is_active=1 and is_deleted=0;  

        end if;
     end;

     when 'emergency_info' then
       set l_routine_block = 'update_student_master';   
          begin

    			update student_master set 
    				  emer_contact_name_1=in_emer_contact_name_1,
              emer_contact_1_relation=in_emer_contact_1_relation,
              emer_contact_num_1=in_emer_contact_num_1,
              emer_contact_name_2=in_emer_contact_name_2,
              emer_contact_2_relation=in_emer_contact_2_relation,
              emer_contact_num_2=in_emer_contact_num_2,
    					created_by =in_student_id ,
    					updated_by=in_student_id
    			where inst_id =in_inst_id and ay_id=in_ay_id and student_id=in_student_id and is_active=1 and is_deleted=0;             
        
     end;



        when 'doctor_info' then
       set l_routine_block = 'update_student_master';   
          begin
       
    			update student_master set 	
              dr_name=in_dr_name,
              dr_hospital_name=in_dr_hospital_name,
              dr_contact_off=in_dr_contact_off,
              dr_contact_mobile=in_dr_contact_mobile,
              is_stud_health_issue=in_is_stud_health_issue,
              health_issue_desc=in_health_issue_desc,
    					created_by =in_student_id ,
    					updated_by=in_student_id
    			where inst_id =in_inst_id and ay_id=in_ay_id and student_id=in_student_id and is_active=1 and is_deleted=0;             
             
     end;

        when 'document_info' then
       set l_routine_block = 'update_file_upload';   
          begin
          
          
     
            
     end;
      end case;
    
    commit;
    set out_err_code = l_err_code;
      set out_err_desc = l_parent_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_student_quick_admission`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_student_quick_admission`(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_student_num` VARCHAR(50), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_class_id` VARCHAR(30), IN `in_admission_num` VARCHAR(50), IN `in_enrollment_num` VARCHAR(50), IN `in_enrollment_date` DATE, IN `in_enrolled_for_std` CHAR(2), IN `in_first_name` VARCHAR(20), IN `in_middle_name` VARCHAR(20), IN `in_last_name` VARCHAR(20), IN `in_birth_date` DATE, IN `in_gender` ENUM('M','F','O'), IN `in_religion` VARCHAR(20), IN `in_student_category` VARCHAR(20), IN `in_student_subcategory` VARCHAR(20), IN `in_consession_category` VARCHAR(20), IN `in_birth_place` VARCHAR(20), IN `in_mobile_phone_main` VARCHAR(15), IN `in_email_main` VARCHAR(50), IN `in_country` INT(4), IN `in_locality` INT(4), IN `in_city` INT(4), IN `in_district` INT(4), IN `in_state` INT(4), IN `in_class_roll_num` SMALLINT(5), IN `in_house_id` SMALLINT(5), IN `in_blood_group` VARCHAR(10), IN `in_nationality` VARCHAR(20), IN `in_language` VARCHAR(20), IN `in_address_line_1` VARCHAR(100), IN `in_address_line_2` VARCHAR(100), IN `in_pincode` MEDIUMINT(8), IN `in_prev_school_name` VARCHAR(50), IN `in_prev_school_address` VARCHAR(50), IN `in_prev_school_board` VARCHAR(20), IN `in_disability` VARCHAR(20), IN `in_gr_number` VARCHAR(50), IN `in_sts_number` VARCHAR(50), IN `in_aadhar_card_num` VARCHAR(12), IN `in_first_name_f` VARCHAR(20), IN `in_middle_name_f` VARCHAR(20), IN `in_last_name_f` VARCHAR(20), IN `in_mobile_phone_1` VARCHAR(15), IN `in_email_main_1` VARCHAR(50), IN `in_edu_qual_degree_f` VARCHAR(25), IN `in_edu_qual_stream_f` VARCHAR(25), IN `in_occupation_f` VARCHAR(20), IN `in_income_bracket_f` VARCHAR(20), IN `in_first_name_m` VARCHAR(20), IN `in_middle_name_m` VARCHAR(20), IN `in_last_name_m` VARCHAR(20), IN `in_mobile_phone_2` VARCHAR(15), IN `in_email_main_2` VARCHAR(50), IN `in_edu_qual_degree_m` VARCHAR(25), IN `in_edu_qual_stream_m` VARCHAR(25), IN `in_occupation_m` VARCHAR(20), IN `in_income_bracket_m` VARCHAR(20), IN `in_stud_status` VARCHAR(25), IN `in_enrollment_num_gen_mode` VARCHAR(10), IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_login_name` VARCHAR(50), IN `in_bcrpt_password` VARCHAR(60), IN `in_password` VARCHAR(60), IN `in_login_name_f` VARCHAR(50), IN `in_bcrpt_password_f` VARCHAR(60), IN `in_password_f` VARCHAR(60), IN `in_login_name_m` VARCHAR(50), IN `in_bcrpt_password_m` VARCHAR(60), IN `in_password_m` VARCHAR(60), IN `in_is_new_admission` TINYINT(1), IN `in_is_rte` TINYINT(1), IN `in_rte_category` VARCHAR(100), OUT `out_student_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_student_quick_admission';
  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_parent_id mediumint(8);
  declare l_enrollment_num varchar(50) default 0;
  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 l_first_name_f varchar(20);
  


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

      insert into db_error_log(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_student_id = fn_sequence_generator('STUDENT_MASTER');
          
           
           	IF ( in_enrollment_num_gen_mode='Y' AND (length(trim(in_enrollment_num)) = 0 OR length(trim(in_enrollment_num)) is null)
              AND  in_stud_status>0 ) THEN 
					call sp_custom_seq_generator(in_inst_id,'STUD_ENROLLMENT_NUM',in_ay_id,in_created_by,l_enrollment_num) ;
					IF length(trim(l_enrollment_num)) = 0 THEN
					   SIGNAL SQLSTATE '10004' 
				      SET MESSAGE_TEXT = 'An error occurred while generating Student Enrollment Num';
			     END IF;
  				ELSE
  					select enrollment_num INTO t_enrollment_num FROM student_master where enrollment_num=in_enrollment_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
  					IF (t_enrollment_num=in_enrollment_num) THEN
  						SIGNAL SQLSTATE '10005' 
