				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);
-- 					insert into proc_error_logs (routine_name,	label_name,sql_log) values('party_name',l_insert_row_count,l_dq_party_name);
				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);  
        elseif (l_template_col_name = 'fin_acct_id') 		THEN set l_dq_fin_acct_id = substring(l_json_substr, 1, l_separator_idx - 1);  
				elseif (l_template_col_name = 'opt_txn_id') 		THEN set l_dq_opt_txn_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_demand_mst_id = fn_sequence_generator('DEMAND_MASTER'); 
				set l_dq_demand_grp_id = fn_sequence_generator('DEMAND_GROUP'); 
				set l_dq_qp_mst_id = fn_sequence_generator('QUICKPAY_MASTER'); 
				set l_dq_qp_dtls_id = fn_sequence_generator('QUICKPAY_DETAILS'); 
				IF ( in_demand_num_gen_mode='Y') THEN    
					set l_dq_demand_num = '';
					begin     
						call sp_custom_seq_generator(in_inst_id,'FEE_DEMAND_NUM',in_ay_id,in_created_by,l_dq_demand_num) ;
						IF length(trim(l_dq_demand_num)) = 0 THEN
							SIGNAL SQLSTATE '10004' 
							SET MESSAGE_TEXT = 'An error occurred while generating Demand Number';
						END IF; 
						SELECT demand_num INTO t_demand_num FROM demand_master where demand_num=l_dq_demand_num and inst_id=in_inst_id and is_active=1 and is_deleted=0;
						IF (t_demand_num=l_dq_demand_num) THEN
							SIGNAL SQLSTATE '10005' 
						  SET MESSAGE_TEXT = 'Demand Number is already present'; 
						END IF; 
					end;	 
				END IF; 
			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_dq_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'
					);
				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 (l_dq_ay_id, l_dq_inst_id, 
					l_dq_qp_mst_id,l_dq_qp_code,
				    l_dq_party_id,l_dq_party_type,l_dq_party_name,
					l_dq_txn_desc,l_dq_txn_desc,l_dq_due_date,l_dq_due_date,l_dq_amt_due,l_dq_tax_due,l_dq_total_amt_due,
					l_dq_status ,
					l_dq_created_by,NOW(),
					l_dq_created_by,NOW(),
					'1','0'
				);
				INSERT into demand_master(ay_id,inst_id,fin_acct_id,
					demand_mst_id,demand_grp_id,demand_type,demand_num,
					txn_id,opt_txn_id,txn_desc,installment_num,
					party_type,party_id,party_name,
					gen_date,due_date,grace_period,final_date,
					amt_due,tax_due,amt_clear,tax_clear,amt_unclear,tax_unclear,total_amt_due,
					status,status_desc ,
					created_by,created_on,updated_by,updated_on)
				values (l_dq_ay_id, l_dq_inst_id, l_dq_fin_acct_id ,
					l_dq_demand_mst_id, l_dq_demand_grp_id,l_dq_demand_type,l_dq_demand_num,
					l_dq_txn_id, l_dq_opt_txn_id,l_dq_txn_desc,l_dq_installment_num,
					l_dq_party_type,l_dq_party_id, l_dq_party_name, 
					NOW(),l_dq_due_date,'0',NOW(),
					l_dq_amt_due, l_dq_tax_due,0,0,0,0,l_dq_total_amt_due,
					l_dq_status,'',
					l_dq_created_by,NOW(),l_dq_created_by,NOW()
				);
				set l_insert_row_count = l_insert_row_count - 1;
				set l_looping_done = false;
			close cur_json_template;
-- 			insert into proc_error_logs (routine_name,	label_name,sql_log) values('l_insert_row_count',l_insert_row_count,"AT END ");
		end while;   	 
		/* Update Demand Master */
		update demand_master set valid_to = now(), updated_by = in_created_by, updated_on = now() 
			where ay_id = in_ay_id 	
			  and inst_id = in_inst_id 
			  and txn_id = in_fee_mst_id ;
		/* Update  fee_structure_master */	
		update fee_structure_master set status = '30' 
			where inst_id = in_inst_id 
			  and fee_struct_mst_id = in_fee_mst_id and is_active='1' and is_deleted='0'; 
	commit;  
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_department_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_department_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_dept_id` VARCHAR(20), IN `in_parent_id` VARCHAR(20), IN `in_dept_name` VARCHAR(20), IN `in_dept_desc` VARCHAR(50), IN `in_	dept_abbr` VARCHAR(20), IN `in_dept_level` TINYINT(2), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_department_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 department_master (ay_id, inst_id,dept_id,parent_id,dept_name, 
               	dept_desc,dept_abbr,dept_level,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_dept_id, in_parent_id, in_dept_name, 
              in_dept_desc,in_dept_abbr,in_dept_level ,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update department_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where dept_id = in_dept_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 department_master (ay_id, inst_id,dept_id,parent_id,dept_name, 
               	dept_desc,dept_abbr,dept_level,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_dept_id, in_parent_id, in_dept_name, 
              in_dept_desc,in_dept_abbr,in_dept_level ,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_department_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_department_master_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_dept_id` MEDIUMINT(8), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_department_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 department_master(ay_id, inst_id, dept_id,
    parent_id, dept_name, dept_display_name, dept_desc, dept_abbr, dept_level,
    is_active, created_by, updated_by,dept_type ) VALUES';
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'department_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 = 'dept_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('DEPARTMENT_MASTER');
              end;
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('DEPARTMENT_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 department_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and dept_id = in_dept_id
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

DROP PROCEDURE IF EXISTS `sp_ins_device_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_device_map_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_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_device_map_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';       
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'INSERT INTO  institute_device_map(ay_id, 
                                                                                inst_id, 
                                                                                device_id,
                                                                                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 = 'institute_device_map' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
      begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #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  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_division_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_division_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), 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_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_division_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	  begin
      rollback;
       get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 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 division_master (ay_id, inst_id,division_id,division_name,division_desc, 
               division_abbr,is_active, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_division_id, in_division_name, in_division_desc, 
              in_division_abbr,in_is_active, in_created_by, in_created_by);
          end;    
  	    when 'U' then
         set l_routine_block = 'update'; 
          begin
          	update division_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where division_id = in_division_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
           insert into division_master (ay_id, inst_id,division_id,division_name,division_desc, 
               division_abbr, is_active, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_division_id, in_division_name, in_division_desc, 
              in_division_abbr,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_email_template_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_email_template_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_txn_id` MEDIUMINT(5), IN `in_recipient_type` VARCHAR(25), IN `in_email_title` VARCHAR(50), IN `in_email_body` VARCHAR(5000), IN `in_param_count` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
declare l_routine_name varchar(50) default 'sp_ins_email_template_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
 declare exit handler for sqlexception
	 begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
           set l_routine_block = 'insert';
            insert into email_template_master(
              ay_id,
              inst_id,
              txn_id ,
              recipient_type,
              email_title,
              email_body,
              param_count,
              is_active,
              created_by, 
              updated_by) 	 						
            values(
              in_ay_id,
              in_inst_id,
              in_txn_id,  
              in_recipient_type,
              in_email_title,
              in_email_body,
              in_param_count,
              in_is_active,
              in_created_by,
              in_created_by);
          end;    
  	    when 'U' then
          set l_routine_block = 'update';
          begin
          	update email_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1
            where txn_id = in_txn_id and is_deleted =0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into email_template_master(
              ay_id,
              inst_id,
              txn_id ,
              recipient_type,
              email_title,
              email_body,
              param_count,
              is_active,
              created_by, 
              updated_by) 	 						
            values(
              in_ay_id,
              in_inst_id,
              in_txn_id,  
              in_recipient_type,
              in_email_title,
              in_email_body,
              in_param_count,
              in_is_active,
              in_created_by,
              in_created_by);
          end;    
      end case;
    commit;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_employee_attendance_master_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_employee_attendance_master_details`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_attendance_mst_id` MEDIUMINT(8), IN `in_file_upload_id` VARCHAR(25), IN `in_attendance_type` VARCHAR(10), IN `in_attendance_date` DATE, IN `in_emp_count` TINYINT(3), IN `in_present_count` TINYINT(3), IN `in_halfday_count` TINYINT(3), IN `in_absent_count` TINYINT(3), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(100), IN `in_attendance_comments` VARCHAR(50), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_employee_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 emp_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_employee_bulk_upload`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_employee_bulk_upload`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_emp_num_gen_mode` VARCHAR(10), IN `in_emp_id` MEDIUMINT(8), IN `in_emp_num` VARCHAR(50), IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(25), IN `in_middle_name` VARCHAR(25), IN `in_last_name` VARCHAR(25), IN `in_birth_date` DATE, IN `in_gender` CHAR(1), IN `in_mobile_phone_1` VARCHAR(20), IN `in_email_main` VARCHAR(50), IN `in_role` MEDIUMINT(8), IN `in_login_name` VARCHAR(50), IN `in_password` VARCHAR(60), IN `in_bcrypt_password` VARCHAR(60), IN `in_bulk_upload_status` TINYINT(3), IN `in_emp_status` VARCHAR(20), IN `emp_bulk_file_upload_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_emp_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_employee_bulk_upload';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
    declare l_emp_id mediumint(8);
    declare l_emp_num varchar(50);
	 declare t_emp_num varchar(50);

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

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

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_dml_mode 
        
        when 'I' then
          begin
          set l_routine_block = 'insert';
		      set l_emp_id = fn_sequence_generator('EMPLOYEE_MASTER');

        	set l_emp_num =in_emp_num;

  				IF ( in_emp_num_gen_mode='Y' AND length(trim(in_emp_num)) = 0 AND  in_emp_status=100 ) THEN 
  					call sp_custom_seq_generator(in_inst_id,'EMP_GUID','',in_created_by,l_emp_num) ;
  					IF length(trim(l_emp_num)) = 0 THEN
  					   SIGNAL SQLSTATE '10012' 
  					  SET MESSAGE_TEXT = 'An error occurred while generating Employee Number';
  					END IF;
  				END IF;		
  				IF ( in_emp_num_gen_mode='N' AND length(trim(in_emp_num)) > 0 AND  in_emp_status=100 ) THEN 
  					SELECT emp_num INTO t_emp_num  FROM employee_master where emp_id=in_emp_id  and inst_id=in_inst_id;
  					IF (length(trim(t_emp_num)) = 0  ) THEN
  									select emp_num INTO t_emp_num FROM employee_master where emp_num=in_emp_num and inst_id=in_inst_id;
  									IF (t_emp_num=in_emp_num) THEN
  										SIGNAL SQLSTATE '10013'
  										SET MESSAGE_TEXT = 'Employee Number is already present';
  									END IF;
  					END IF;
  				ELSEIF ( in_emp_num_gen_mode='N' AND  in_emp_status>=100  AND length(trim(in_emp_num)) = 0 ) THEN 
  					SIGNAL SQLSTATE '10014'
  					SET MESSAGE_TEXT = 'Please Enter Employee Number';
  				END IF;	
           
           insert into  employee_master ( inst_id,emp_id,  emp_num,salutation,  first_name,  middle_name, 
            last_name,  gender, birth_date, mobile_phone_1, email_main, emp_status, bulk_upload_status,
            emp_bulk_file_upload_id, created_by, updated_by,  is_active)  	 						
           values( in_inst_id,l_emp_id,  l_emp_num, in_salutation, in_first_name,  in_middle_name, 
            in_last_name,  in_gender, in_birth_date, in_mobile_phone_1, in_email_main, in_emp_status, 
            bulk_upload_status, emp_bulk_file_upload_id, in_created_by,
            in_created_by,  '1');

         CALL sp_ins_user_master('E','', in_inst_id, 'EMP', l_emp_id, in_role, in_login_name, in_bcrypt_password,'',
         '','1','1','','','','','','','','','','','1','1','SYSTEM', l_err_code, l_err_desc);

         INSERT INTO temp_user_employee_master(ay_id, inst_id, emp_id, login_name, password, mobile_phone_main, 
          email_main, emp_status, bulk_upload_status, notification_status, created_by, updated_by,
          is_active, is_deleted) 
          VALUES ('', in_inst_id, l_emp_id, in_login_name, in_password, in_mobile_phone_1, 
          in_email_main, in_emp_status, 100, 0, in_created_by, in_created_by,
          '1', 0);
             
          end; 
      end case;
    
    commit;
    
    set out_emp_id = l_emp_id;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_employee_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_employee_master`(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_emp_type` VARCHAR(15), IN `in_payroll_type` VARCHAR(15), IN `in_dept_id` VARCHAR(20), IN `in_emp_category` VARCHAR(25), IN `in_emp_designation` VARCHAR(25), IN `in_emp_num` VARCHAR(50), IN `in_joining_date` DATE, IN `in_resignation_date` DATE, IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(25), IN `in_middle_name` VARCHAR(25), IN `in_last_name` VARCHAR(25), IN `in_gender` CHAR(1), IN `in_emp_grade` VARCHAR(10), IN `in_edu_qual_degree1` VARCHAR(25), IN `in_edu_qual_stream1` VARCHAR(25), IN `in_edu_qual_degree2` VARCHAR(25), IN `in_edu_qual_stream2` VARCHAR(25), IN `in_previous_org` VARCHAR(50), IN `in_previous_designation` VARCHAR(25), IN `in_work_exp_desc` VARCHAR(150), IN `in_work_exp_years` TINYINT(2), IN `in_work_exp_months` TINYINT(2), IN `in_emp_desc` VARCHAR(150), IN `in_birth_date` DATE, IN `in_birth_place` VARCHAR(20), IN `in_marital_status` VARCHAR(10), IN `in_anniversary_date` DATE, IN `in_children_count` TINYINT(2), IN `in_father_name` VARCHAR(25), IN `in_mother_name` VARCHAR(25), IN `in_husband_name` VARCHAR(25), IN `in_blood_group` VARCHAR(5), IN `in_nationality` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_category` VARCHAR(20), IN `in_subcategory` VARCHAR(20), IN `in_address_line_1` VARCHAR(50), IN `in_address_line_2` VARCHAR(50), IN `in_locality` INT(4), IN `in_city` INT(4), IN `in_district` INT(4), IN `in_state` INT(4), IN `in_country` INT(4), IN `in_pincode` MEDIUMINT(7), IN `in_fixed_phone_1` VARCHAR(20), IN `in_mobile_phone_1` VARCHAR(20), IN `in_fixed_phone_2` VARCHAR(20), IN `in_mobile_phone_2` VARCHAR(20), IN `in_email_main` VARCHAR(50), IN `in_email_alt` VARCHAR(50), IN `in_fax_number` VARCHAR(20), IN `in_profile_logo_path` VARCHAR(100), IN `in_emp_num_gen_mode` VARCHAR(10), IN `in_emp_status` VARCHAR(20), IN `in_status_desc` VARCHAR(100), IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_aadhar_card_num` VARCHAR(12), OUT `out_emp_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_employee_master';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
    declare l_emp_id mediumint(8);
    declare l_emp_num varchar(50);
	 declare t_emp_num varchar(50);
  declare exit handler for sqlexception
	  begin
      rollback;
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log( inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        ( in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
          set l_routine_block = 'insert';
		      set l_emp_id = fn_sequence_generator('EMPLOYEE_MASTER');
           insert into  employee_master ( inst_id,emp_id,  emp_type, payroll_type, dept_id,  emp_category,  emp_designation, emp_num,  joining_date,  resignation_date, 
    				salutation,  first_name,  middle_name,  last_name,  gender,  emp_grade,  edu_qual_degree1,edu_qual_stream1,edu_qual_degree2,edu_qual_stream2, previous_org,previous_designation, work_exp_desc,  work_exp_years,  work_exp_months, emp_desc,  birth_date, birth_place,  marital_status, anniversary_date, children_count,  father_name,  mother_name,  husband_name,  blood_group,  nationality,  religion,  category,  subcategory,  address_line_1, address_line_2, locality,  city,  district, state,  country,  pincode,  fixed_phone_1,  mobile_phone_1,  fixed_phone_2,  mobile_phone_2,  email_main,  email_alt,  fax_number,profile_logo_path,   emp_status,  status_desc,  created_by,updated_by,  is_active,aadhar_card_num)  	 						
           values( in_inst_id,l_emp_id ,  in_emp_type, in_payroll_type, in_dept_id,  in_emp_category,  in_emp_designation, in_emp_num,  in_joining_date,  in_resignation_date, 
    				in_salutation,  in_first_name,  in_middle_name,  in_last_name,  in_gender,  in_emp_grade,  in_edu_qual_degree1,in_edu_qual_stream1,in_edu_qual_degree2,in_edu_qual_stream2,in_previous_org,in_previous_designation,  in_work_exp_desc,  in_work_exp_years,  in_work_exp_months, in_emp_desc,  in_birth_date, in_birth_place,  in_marital_status, in_anniversary_date, in_children_count,  in_father_name,  in_mother_name,  in_husband_name,  in_blood_group,  in_nationality,  in_religion,  in_category,  in_subcategory,  in_address_line_1, in_address_line_2, in_locality,  in_city, in_district,  in_state,  in_country,  in_pincode,  in_fixed_phone_1,  in_mobile_phone_1,  in_fixed_phone_2,  in_mobile_phone_2,  in_email_main,  in_email_alt,  in_fax_number, in_profile_logo_path, in_emp_status,  in_status_desc,  in_created_by,in_created_by,  in_is_active,in_aadhar_card_num  );
          end;    
  	    when 'R' then
	      	set l_routine_block = 'update_resource_profile';
          begin
          	set l_emp_num =in_emp_num;
				IF ( in_emp_num_gen_mode='Y' AND length(trim(in_emp_num)) = 0 AND  in_emp_status=100 ) THEN 
					call sp_custom_seq_generator(in_inst_id,'EMP_GUID',in_ay_id,in_created_by,l_emp_num) ;
					IF length(trim(l_emp_num)) = 0 THEN
					   SIGNAL SQLSTATE '10012' 
					  SET MESSAGE_TEXT = 'An error occurred while generating Employee Number';
					END IF;
				END IF;		
				IF ( in_emp_num_gen_mode='N' AND length(trim(in_emp_num)) > 0 AND  in_emp_status=100 ) THEN 
					SELECT emp_num INTO t_emp_num  FROM employee_master where emp_id=in_emp_id  and inst_id=in_inst_id;
					IF (length(trim(t_emp_num)) = 0  ) THEN
									select emp_num INTO t_emp_num FROM employee_master where emp_num=in_emp_num and inst_id=in_inst_id;
									IF (t_emp_num=in_emp_num) THEN
										SIGNAL SQLSTATE '10013'
										SET MESSAGE_TEXT = 'Employee Number is already present';
									END IF;
					END IF;
				ELSEIF ( in_emp_num_gen_mode='N' AND  in_emp_status>=100  AND length(trim(in_emp_num)) = 0 ) THEN 
					SIGNAL SQLSTATE '10014'
					SET MESSAGE_TEXT = 'Please Enter Employee Number';
				END IF;	
          update  employee_master set inst_id=in_inst_id,emp_id=in_emp_id,emp_num=l_emp_num,salutation=in_salutation,first_name=in_first_name,middle_name=in_middle_name,last_name=in_last_name,gender=in_gender,birth_date=in_birth_date,birth_place=in_birth_place,marital_status=in_marital_status,anniversary_date=in_anniversary_date,children_count=in_children_count,father_name=in_father_name,mother_name=in_mother_name,husband_name=in_husband_name,blood_group=in_blood_group,nationality=in_nationality,religion=in_religion,category=in_category,subcategory=in_subcategory,emp_status=in_emp_status,status_desc=in_status_desc,created_by=in_created_by,is_active=in_is_active,updated_by=in_created_by,aadhar_card_num=in_aadhar_card_num,updated_on=now() 
          where emp_id = in_emp_id   and is_deleted = '0' and inst_id = in_inst_id;       
			 IF ( in_emp_status>100 ) THEN 
	          update  user_master set is_active=0,updated_on=now() where user_type='EMP' and user_id = in_emp_id   and is_deleted = '0' and inst_id = in_inst_id;     
              
               update  employee_master set is_active=0,updated_on=now() where emp_id = in_emp_id   and is_deleted = '0' and inst_id = in_inst_id;           
          END IF;	
          end;  
  	   when 'W' then
        	set l_routine_block = 'update_resource_work_profile';
        	begin
            update  employee_master set dept_id=in_dept_id,emp_grade=in_emp_grade,emp_category=in_emp_category,emp_designation=in_emp_designation,emp_type=in_emp_type,payroll_type=in_payroll_type,edu_qual_degree1=in_edu_qual_degree1,edu_qual_stream1=in_edu_qual_stream1,edu_qual_degree2=in_edu_qual_degree2,edu_qual_stream2=in_edu_qual_stream2,joining_date=in_joining_date,resignation_date=in_resignation_date,emp_desc=in_emp_desc,previous_org=in_previous_org,previous_designation=in_previous_designation,work_exp_years=in_work_exp_years,work_exp_months=in_work_exp_months,work_exp_desc=in_work_exp_desc,updated_by=in_created_by,updated_on=now() 
            where emp_id = in_emp_id   and is_deleted = '0' and inst_id = in_inst_id;                
        	end;  
   	   when 'A' then
        	set l_routine_block = 'update_resource_address_profile';
        	begin
          update  employee_master set 
            address_line_1=in_address_line_1,address_line_2=in_address_line_2,locality=in_locality,city=in_city,district=in_district,state=in_state,country=in_country,
            pincode=in_pincode,fixed_phone_1=in_fixed_phone_1,mobile_phone_1=in_mobile_phone_1,fixed_phone_2=in_fixed_phone_2,mobile_phone_2=in_mobile_phone_2,
            email_main=in_email_main,email_alt=in_email_alt,fax_number=in_fax_number,updated_by=in_created_by ,updated_on=now()
          where emp_id = in_emp_id   and is_deleted = '0' and inst_id = in_inst_id;                
        	end;         
    	when 'P' then
        	set l_routine_block = 'update_resource_profile_picture';
        	begin
          update  employee_master set 
            profile_logo_path=in_profile_logo_path,updated_by=in_created_by,
            updated_on=now() 
          where emp_id = in_emp_id   and is_deleted = '0' and inst_id = in_inst_id;                
        	end;  
      end case;
    commit;
    set out_emp_id = l_emp_id;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_employee_profile_update_api`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_employee_profile_update_api`(IN `in_action` VARCHAR(50), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_emp_id` MEDIUMINT(8), IN `in_first_name` VARCHAR(25), IN `in_middle_name` VARCHAR(25), IN `in_last_name` VARCHAR(25), IN `in_gender` ENUM('M','F','O'), IN `in_birth_date` DATE, IN `in_birth_place` VARCHAR(20), IN `in_marital_status` VARCHAR(10), IN `in_anniversary_date` DATE, IN `in_children_count` TINYINT(2), IN `in_father_name` VARCHAR(25), IN `in_husband_name` VARCHAR(25), IN `in_mother_name` VARCHAR(25), IN `in_blood_group` VARCHAR(5), IN `in_nationality` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_category` VARCHAR(20), IN `in_subcategory` VARCHAR(20), IN `in_address_line_1` VARCHAR(50), IN `in_address_line_2` VARCHAR(50), IN `in_pincode` MEDIUMINT(7), IN `in_mobile_phone_1` VARCHAR(20), IN `in_email_main` VARCHAR(50), IN `in_fixed_phone_1` VARCHAR(20), IN `in_fixed_phone_2` VARCHAR(20), IN `in_fax_number` 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_employee_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_employee_profile_update_api';
  
  
  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_emp_id);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_action 
        
  
	    when 'employee_info' then
       set l_routine_block = 'update_employee_master';   
          begin
          

    			update employee_master set 	
                inst_id=in_inst_id,
                first_name =in_first_name ,
                middle_name =in_middle_name ,
                last_name =in_last_name ,
                gender=in_gender,
                birth_date=in_birth_date,
                birth_place =in_birth_place ,
                marital_status =in_marital_status ,
                anniversary_date =in_anniversary_date ,
                children_count =in_children_count ,
                father_name =in_father_name ,
                husband_name=in_husband_name,
                mother_name=in_mother_name,
                blood_group =in_blood_group ,
                nationality =in_nationality ,
                religion =in_religion ,
                category =in_category   ,
                subcategory=in_subcategory,
                created_by =in_emp_id ,
                updated_by=in_emp_id
    			where inst_id =in_inst_id and emp_id=in_emp_id and is_active=1 and is_deleted=0;             
           
      end;    

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


    			update employee_master set 
                address_line_1=in_address_line_1,
                address_line_2=in_address_line_2,
                pincode=in_pincode,
                mobile_phone_1=in_mobile_phone_1,
                email_main=in_email_main,
                fixed_phone_1=in_fixed_phone_1,
                fixed_phone_2=in_fixed_phone_2,
                fax_number=in_fax_number,
                created_by =in_emp_id ,
                updated_by=in_emp_id
    			where inst_id =in_inst_id and emp_id=in_emp_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_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_employee_quick_enrollment`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_employee_quick_enrollment`(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_emp_num` VARCHAR(50), IN `in_salutation` VARCHAR(10), IN `in_first_name` VARCHAR(25), IN `in_middle_name` VARCHAR(25), IN `in_last_name` VARCHAR(25), IN `in_gender` CHAR(1), IN `in_birth_date` DATE, IN `in_birth_place` VARCHAR(20), IN `in_marital_status` VARCHAR(10), IN `in_anniversary_date` DATE, IN `in_children_count` TINYINT(2), IN `in_blood_group` VARCHAR(5), IN `in_nationality` VARCHAR(20), IN `in_religion` VARCHAR(20), IN `in_category` VARCHAR(20), IN `in_subcategory` VARCHAR(20), IN `in_mobile_phone_1` VARCHAR(20), 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_pincode` MEDIUMINT(7), IN `in_emp_num_gen_mode` VARCHAR(10), IN `in_emp_status` VARCHAR(20), IN `in_dept_id` VARCHAR(20), IN `in_emp_grade` VARCHAR(10), IN `in_emp_category` VARCHAR(25), IN `in_emp_designation` VARCHAR(25), IN `in_role_id` VARCHAR(10), IN `in_login_name` VARCHAR(50), IN `in_password` VARCHAR(60), IN `in_api_token` VARCHAR(100), IN `in_is_web_enabled` TINYINT(1), IN `in_is_app_enabled` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_aadhar_card_num` VARCHAR(12), OUT `out_emp_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_employee_quick_enrollment';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
    declare l_emp_id mediumint(8);
    declare l_emp_num varchar(50);
	 declare t_emp_num varchar(50);
  declare l_user_id mediumint(8);

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

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

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_dml_mode 
        
        when 'I' then
          begin
          set l_routine_block = 'insert';
		      set l_emp_id = fn_sequence_generator('EMPLOYEE_MASTER');

          set l_emp_num =in_emp_num;
  				IF ( in_emp_num_gen_mode='Y' AND length(trim(in_emp_num)) = 0 AND  in_emp_status=100 ) THEN 
  					call sp_custom_seq_generator(in_inst_id,'EMP_GUID',in_ay_id,in_created_by,l_emp_num) ;
  					IF length(trim(l_emp_num)) = 0 THEN
  					   SIGNAL SQLSTATE '10012' 
  					  SET MESSAGE_TEXT = 'An error occurred while generating Employee Number';
  					END IF;
  				END IF;		
  				IF ( in_emp_num_gen_mode='N' AND length(trim(in_emp_num)) > 0 AND  in_emp_status=100 ) THEN 
  					SELECT emp_num INTO t_emp_num  FROM employee_master where emp_id=in_emp_id  and inst_id=in_inst_id;
  					IF (length(trim(t_emp_num)) = 0  ) THEN
  									select emp_num INTO t_emp_num FROM employee_master where emp_num=in_emp_num and inst_id=in_inst_id;
  									IF (t_emp_num=in_emp_num) THEN
  										SIGNAL SQLSTATE '10013'
  										SET MESSAGE_TEXT = 'Employee Number is already present';
  									END IF;
  					END IF;
  				ELSEIF ( in_emp_num_gen_mode='N' AND  in_emp_status>=100  AND length(trim(in_emp_num)) = 0 ) THEN 
  					SIGNAL SQLSTATE '10014'
  					SET MESSAGE_TEXT = 'Please Enter Employee Number';
  				END IF;	

              
           insert into  employee_master ( inst_id,emp_id,  emp_num, 
    				salutation,  first_name,  middle_name,  last_name,  gender, mobile_phone_1,   
            birth_date, birth_place,  marital_status, anniversary_date, children_count,  blood_group, 
            nationality,  religion,  category,  subcategory,  emp_status, 
            dept_id, emp_grade, emp_category,  emp_designation, 
            address_line_1, locality,  city,  district, state,  country,  pincode,  
            created_by,updated_by,  is_active,aadhar_card_num)  	 						
           values( in_inst_id,l_emp_id ,  l_emp_num,  
    				in_salutation,  in_first_name,  in_middle_name,  in_last_name,  in_gender, in_mobile_phone_1,
            in_birth_date, in_birth_place,  in_marital_status, in_anniversary_date, in_children_count, in_blood_group,  
            in_nationality,  in_religion,  in_category,  in_subcategory,  in_emp_status,  
            in_dept_id, in_emp_grade, in_emp_category, in_emp_designation,
            in_address_line_1, in_locality,  in_city,  in_district, in_state,  in_country,  in_pincode,
            in_created_by,in_created_by,  in_is_active ,in_aadhar_card_num );
             
          end;    

                
        insert into   user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,password,api_token,
              is_web_enabled,is_app_enabled,is_active,created_by, updated_by)  
				 values(in_ay_id,in_inst_id,l_emp_id, 'EMP', in_role_id,in_login_name,in_password,in_api_token,
              in_is_web_enabled,in_is_app_enabled,in_is_active,in_created_by, in_created_by);


			 CALL `sp_ins_user_role_map`('U', in_inst_id, 'EMP', l_emp_id, in_role_id, in_created_by, l_err_code, l_err_desc);			 
			
			CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, 'EMP', l_emp_id, in_created_by, l_err_code, l_err_desc);
          
   
      end case;
    
    commit;
    
    set out_emp_id = l_emp_id;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_assign_template_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_assign_template_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` MEDIUMINT(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_emp_assign_template_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_invoice_mst_id mediumint(8);
   declare l_party_type varchar(20);

  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 fin_emp_payroll_master(ay_id, inst_id, 
    template_id, emp_id,applied_date,is_active,created_by,updated_by,fin_acct_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 = 'fin_emp_payroll_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;


   case in_dml_mode 
    when 'I' then
      begin

--          set l_invoice_mst_id = fn_sequence_generator('FIN_INVOICE_MASTER');
      end;

    when 'U' then
      begin
        set l_invoice_mst_id = in_invoice_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 = 'invoice_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
--                 set l_template_col_value = fn_sequence_generator('FIN_INVOICE_DETAILS');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('FIN_INVOICE_DETAILS');
             
              end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'invoice_mst_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_invoice_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 data into fin_emp_payroll_master table
          call sp_execute_immediate (l_insert_sql_str); 

        commit;
      end;

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

    end case;

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

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

  declare l_insert_sql_str_dtl text default 'INSERT INTO  emp_attendance_details (ay_id, inst_id, attendance_mst_id, attendance_dtl_id, emp_id, is_half_day, leave_type,leave_reason,attendance_status,attendance_comments, created_by, updated_by,updated_on, is_active,created_on,emp_att_upload_type) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO emp_attendance_master (ay_id, inst_id, attendance_mst_id, file_upload_id, attendance_type, attendance_date, emp_count, present_count, halfday_count, absent_count, status, status_desc, attendance_comments,created_by, updated_by, is_active,attendance_upload_type) VALUES'; 
  declare l_insert_val_str_part text;
  declare l_insert_val_str_full text;

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

  declare exit handler for sqlexception
	  begin     
      rollback;

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

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

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

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

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

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

    open cur_json_template_mst;

    cursor_loop: loop
      fetch cur_json_template_mst into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

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

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_json_substr', l_json_substr);
      
      case l_template_col_name 
        when 'attendance_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = fn_sequence_generator('EMP_ATTENDANCE_MASTER');
                  set l_attendance_mst_id = l_template_col_value;
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end case;

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

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

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

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

    end loop;

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

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

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

    close cur_json_template_mst;

  end while;

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

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

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

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

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

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

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

    open cur_json_template_dtl;

    cursor_loop: loop
      fetch cur_json_template_dtl into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

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

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_json_substr', l_json_substr);
      
      case l_template_col_name        
        when 'attendance_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = l_attendance_mst_id;
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     

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

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

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

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

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

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

    end loop;

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

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

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

    close cur_json_template_dtl;

  end while;

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

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

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

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

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

                  

          update  emp_attendance_master set valid_to = NOW(), updated_by = in_created_by,
              updated_on = NOW(), is_deleted = 1
            where attendance_mst_id = in_attendance_mst_id  and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
          
                   
          update emp_attendance_details set valid_to = now(), updated_by = in_created_by, 
             is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0;

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

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

    end case;

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

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

  declare l_insert_sql_str_dtl text default 'INSERT INTO  emp_attendance_details (ay_id, inst_id, attendance_mst_id, attendance_dtl_id, emp_id, is_half_day, leave_type,leave_reason,attendance_status,attendance_comments, created_by, updated_by,updated_on, is_active,created_on,emp_att_upload_type,bio_type_id) VALUES'; 
  declare l_insert_sql_str_mst text default 'INSERT INTO emp_attendance_master (ay_id, inst_id, attendance_mst_id, file_upload_id, attendance_type, attendance_date, emp_count, present_count, halfday_count, absent_count, status, status_desc, attendance_comments,created_by, updated_by, is_active,attendance_upload_type) VALUES'; 
  declare l_insert_val_str_part text;
  declare l_insert_val_str_full text;

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

  declare exit handler for sqlexception
	  begin     
      rollback;

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

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

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

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

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

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

    open cur_json_template_mst;

    cursor_loop: loop
      fetch cur_json_template_mst into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

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

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_json_substr', l_json_substr);
      
      case l_template_col_name 
        when 'attendance_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = fn_sequence_generator('EMP_ATTENDANCE_MASTER');
                  set l_attendance_mst_id = l_template_col_value;
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;

                when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'M' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'N' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end case;

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

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

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

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

    end loop;

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

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

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

    close cur_json_template_mst;

  end while;

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

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

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

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

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

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

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

    open cur_json_template_dtl;

    cursor_loop: loop
      fetch cur_json_template_dtl into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

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

      #insert into proc_error_logs (routine_name, label_name, sql_log)
      #values(l_routine_name, 'l_json_substr', l_json_substr);
      
      case l_template_col_name        
        when 'attendance_mst_id' THEN
          begin
            case in_dml_mode 
              when 'I' then
                begin
                  set l_template_col_value = l_attendance_mst_id;
                end;
      
              when 'U' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                when 'B' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'M' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                  when 'N' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
                 when 'D' then
                begin
                  set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
                end;
            end case;
          end;     

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

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

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

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

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

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

    end loop;

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

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

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

    close cur_json_template_dtl;

  end while;

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

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

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

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

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

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

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


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

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

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

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

          set l_routine_block = 'Mode U : after insert';
        commit;
      end;
when 'N' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode F : before soft delete';
      
          update emp_attendance_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(), present_count = in_present_count
          where ay_id = in_ay_id and inst_id = in_inst_id and 	attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0 and is_active=1 ;
                   
        
          set l_routine_block = 'Mode F : before insert';
      
       
          call sp_execute_immediate (l_insert_sql_str_dtl);  

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

      when 'D' THEN
      begin
        start transaction;  
          set l_routine_block = 'Mode D : before soft delete';
      
           
          update emp_attendance_master set valid_to = now(), updated_by = in_created_by, 
            updated_on = now(),absent_count=in_present_count,status='PUBLISHED'
          where ay_id = in_ay_id and inst_id = in_inst_id and 	attendance_mst_id = in_attendance_mst_id
            and is_deleted = 0 ;
 
             set l_routine_block = 'Mode D : before insert';
      
       
          call sp_execute_immediate (l_insert_sql_str_dtl);  

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

    end case;

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

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

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

 declare l_insert_sql_str text default 'INSERT INTO  emp_attendance_details(ay_id, inst_id, attendance_mst_id, attendance_dtl_id, emp_id, is_half_day, leave_type,leave_reason,attendance_status,attendance_comments, created_by, updated_by,updated_on, is_active,created_on,emp_att_upload_type,bio_type_id) VALUES';

	declare l_insert_val_str_part  MEDIUMTEXT;
	declare l_insert_val_str_full  MEDIUMTEXT;

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

  declare continue handler for not found set l_looping_done = true;



  
  
  declare exit handler for sqlexception
	  begin     
      rollback;

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

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

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

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

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

     

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

      if (l_template_col_name = 'attendance_dtl_id') THEN
        begin
        
                set l_template_col_value = fn_sequence_generator('EMP_ATTENDANCE_DETAIL');
            
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

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

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

    end loop;

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

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

     

    close cur_json_template;

  end while;

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

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

        commit;
      end;

   



  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

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

  declare l_insert_sql_str text default 'INSERT INTO emp_attendance_master(ay_id, inst_id, attendance_mst_id, file_upload_id, attendance_type, attendance_date, emp_count, present_count, halfday_count, absent_count, status, status_desc, attendance_comments,created_by, updated_by, is_active,attendance_upload_type) VALUES';

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;

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

  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

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

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

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

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

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

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

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

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

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

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

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

    end loop;

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

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

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

    close cur_json_template;

  end while;

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

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

        commit;
      end;

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

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

    end case;

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

END$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_bank_account_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_bank_account_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_emp_id` INT(11), IN `in_	branch_id` VARCHAR(25), IN `in_	account_num` VARCHAR(50), IN `in_account_since` DATE, IN `in_account_type` VARCHAR(10), IN `in_created_by` VARCHAR(20), OUT `out_error_code` TINYINT(2))
    NO SQL
begin
	declare v_routine_name varchar(50) default 'sp_ins_emp_bank_account_details';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into emp_bank_account_details(ay_id, inst_id,emp_id,branch_id,	account_num, 
               	account_since,account_type,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_emp_id, in_branch_id, in_account_num, 
              in_account_since,in_account_type,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update emp_bank_account_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where emp_id = in_emp_id and branch_id=in_branch_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
         insert into emp_bank_account_details(ay_id, inst_id,emp_id,branch_id,	account_num, 
               	account_since,account_type,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_emp_id, in_branch_id, in_account_num, 
              in_account_since,in_account_type,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_dept_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_dept_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_emp_id` VARCHAR(25), IN `in_dept_id` VARCHAR(25), IN `in_emp_role` VARCHAR(25), IN `in_allocation_start_date` DATE, IN `in_allocation_end_date` DATE, IN `in_allocation_status` VARCHAR(25), IN `in_allocation_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_emp_dept_map';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into emp_dept_map(ay_id, inst_id,emp_id,dept_id,emp_role, 
               	allocation_start_date,allocation_end_date,allocation_status,allocation_status_desc,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_emp_id, in_dept_id, in_emp_role, 
              in_allocation_start_date,in_allocation_end_date,allocation_status,allocation_status_desc,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update emp_dept_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where emp_id = in_emp_id and dept_id=in_dept_id  and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
        insert into emp_dept_map(ay_id, inst_id,emp_id,dept_id,emp_role, 
               	allocation_start_date,allocation_end_date,allocation_status,allocation_status_desc,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_emp_id, in_dept_id, in_emp_role, 
              in_allocation_start_date,in_allocation_end_date,allocation_status,allocation_status_desc,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_in_User_Master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_in_User_Master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_user_id` MEDIUMINT(8), IN `in_user_type` VARCHAR(15), IN `in_role_id` VARCHAR(100), IN `in_login_name` VARCHAR(50), IN `in_password` VARCHAR(60), IN `in_api_token` VARCHAR(100), IN `in_remember_token` VARCHAR(100), IN `in_is_web_enabled` TINYINT(1), IN `in_is_app_enabled` TINYINT(1), IN `in_reset_pwd_hint` VARCHAR(50), IN `in_reset_pwd_ans` VARCHAR(20), IN `in_pwd_valid_from` TIMESTAMP, IN `in_pwd_valid_to` TIMESTAMP, IN `in_last_successful_login` TIMESTAMP, IN `in_last_failed_login` TIMESTAMP, IN `in_failed_login_attempts` TINYINT(1), IN `in_force_change_pwd_flag` TINYINT(1), IN `in_is_locked` TINYINT(1), IN `in_lock_reason` VARCHAR(50), IN `in_is_token_verified` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin                                                          
                      
	 declare l_routine_name varchar(50) default 'sp_ins_emp_in_User_Master';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
    declare l_emp_id mediumint(8);
    declare l_emp_num varchar(50);
	 declare t_emp_num varchar(50);
declare l_user_id mediumint(8);
  declare exit handler for sqlexception
	  begin
      rollback;
      
      get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_dml_mode 
        
        when 'I' then
          begin
       
 set l_routine_block = 'insert_user_master';

        set  l_user_id=0;
        select user_id INTO l_user_id FROM user_master where user_type=in_user_type and user_id=in_user_id and inst_id=in_inst_id and is_deleted = '0' ;
          IF l_user_id=0 THEN 
             insert into   user_master(ay_id, inst_id,user_id,user_type, role_id,login_name,password,api_token,remember_token, is_web_enabled,is_app_enabled,reset_pwd_hint,reset_pwd_ans,pwd_valid_from,pwd_valid_to,last_successful_login, last_failed_login,failed_login_attempts,force_change_pwd_flag,is_locked,lock_reason,is_active,is_token_verified,created_by, updated_by)  
				 values(in_ay_id,in_inst_id,in_user_id, in_user_type, in_role_id,in_login_name,in_password,in_api_token,in_remember_token, in_is_web_enabled,in_is_app_enabled,in_reset_pwd_hint,in_reset_pwd_ans,in_pwd_valid_from,in_pwd_valid_to,in_last_successful_login, in_last_failed_login,in_failed_login_attempts,in_force_change_pwd_flag,in_is_locked,in_lock_reason,in_is_active,in_is_token_verified,in_created_by, in_created_by);
          ELSE
	            update user_master set role_id=in_role_id,is_web_enabled=in_is_web_enabled,is_app_enabled=in_is_app_enabled,is_active=in_is_active  where  user_id=in_user_id and user_type=in_user_type and is_deleted = '0' and inst_id = in_inst_id;
          END IF;

				CALL `sp_ins_user_role_map`('U', in_inst_id, in_user_type, in_user_id, in_role_id, in_created_by, l_err_code, l_err_desc);
				CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, in_user_type, in_user_id, in_created_by, l_err_code, l_err_desc);        

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

end$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_leave_balance_update`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_leave_balance_update`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_emp_id` MEDIUMINT(8), IN `in_package_id` MEDIUMINT(8), IN `in_leave_type` VARCHAR(50), IN `in_leave_duration` DECIMAL(7,1), IN `in_credit` INT(20), IN `in_leave_balance` DECIMAL(7,1), IN `in_total_leave` INT(20), IN `in_used_leave` DECIMAL(7,1), IN `in_cary_forward_leave` INT(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_emp_leave_balance_update';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(100);
 declare l_count mediumint(8);
 declare l_acc_holder_mst_id mediumint(8);
 declare l_looping_done int default false;
 declare l_used_leave decimal(7,1);
 declare l_leave_balance decimal(7,1);
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
--             set l_acc_holder_mst_id = fn_sequence_generator('ADD_ACCOUNT_HOLDER');
            set l_routine_block = 'insert';
       
           update leave_package_emp_history set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where emp_id = in_emp_id  and leave_type=in_leave_type 
                 and is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id;

           set l_used_leave=in_used_leave+in_leave_duration;
           set l_leave_balance=in_leave_balance-in_leave_duration;

           insert into leave_package_emp_history (ay_id, inst_id,emp_id,package_id,
                  leave_type,credit,leave_balance,used_leave,cary_forward_leave,
                  is_active,created_by,updated_by)                               
           values(in_ay_id, in_inst_id,in_emp_id,in_package_id,in_leave_type,in_credit,
                  l_leave_balance,l_used_leave,in_cary_forward_leave,
                  in_is_active,in_created_by,in_created_by);

          
          update leave_real_time_emp_balance set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), used_leave=l_used_leave,leave_balance=l_leave_balance
           where emp_id = in_emp_id  and leave_type=in_leave_type 
                 and is_deleted = 0 and ay_id = in_ay_id and inst_id = in_inst_id;

      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_emp_leave_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_leave_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_emp_leave_id` MEDIUMINT(8), IN `in_emp_id` MEDIUMINT(8), IN `in_supervisor_id` VARCHAR(25), IN `in_leave_type` VARCHAR(25), IN `in_leave_status` VARCHAR(25), IN `in_leave_applied_on` DATE, IN `in_leave_start_date` DATE, IN `in_leave_end_date` DATE, IN `in_leave_duration` TINYINT(3), IN `in_is_half_day` TINYINT(1), IN `in_half_day_shift` VARCHAR(15), IN `in_is_back_dated` TINYINT(1), IN `in_initiator_comments` VARCHAR(100), IN `in_approved_on` DATE, IN `in_approved_by` VARCHAR(25), IN `in_approval_type` VARCHAR(25), IN `in_approver_comments` 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_emp_leave_id` MEDIUMINT(8))
    NO SQL
begin
  	declare l_routine_name varchar(50) default 'sp_ins_emp_leave_details';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_emp_leave_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_emp_leave_id = fn_sequence_generator('EMP_LEAVE_DETAILS');
           insert into   emp_leave_details(ay_id,
										inst_id,
										emp_leave_id,
										emp_id,
										supervisor_id,
										leave_type,
										leave_status,
										leave_applied_on,
										leave_start_date,
										leave_end_date,
										leave_duration,
										is_half_day,
            half_day_shift,
										is_back_dated,
										initiator_comments,
										approved_on,
										approved_by	,
										approval_type, 
										approver_comments,
										is_active,
										created_by,
										updated_by) 	 						
                       values(in_ay_id,
					   in_inst_id,
					   l_emp_leave_id,
					   in_emp_id,
					   in_supervisor_id,
					   in_leave_type,
					   in_leave_status,
					   in_leave_applied_on,
					   in_leave_start_date,
					   in_leave_end_date,
					   in_leave_duration,
					   in_is_half_day,
            in_half_day_shift,
					   in_is_back_dated,
					   in_initiator_comments,
					   in_approved_on,
					   in_approved_by,
					   in_approval_type,
					   in_approver_comments,
					  in_is_active,
					  in_created_by, 
					  in_created_by);
          end;    
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update emp_leave_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where  emp_leave_id = in_emp_leave_id and  is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
           insert into   emp_leave_details(ay_id,
										inst_id,
										emp_leave_id,
										emp_id,
										supervisor_id,
										leave_type,
										leave_status,
										leave_applied_on,
										leave_start_date,
										leave_end_date,
										leave_duration,
										is_half_day,
            half_day_shift,
										is_back_dated,
										initiator_comments,
										approved_on,
										approved_by	,
										approval_type, 
										approver_comments,
										is_active,
										created_by,
										updated_by) 	 						
                       values(in_ay_id,
					   in_inst_id,
					   in_emp_leave_id,
					   in_emp_id,
					   in_supervisor_id,
					   in_leave_type,
					   in_leave_status,
					   in_leave_applied_on,
					   in_leave_start_date,
					   in_leave_end_date,
					   in_leave_duration,
					   in_is_half_day,
            in_half_day_shift,
					   in_is_back_dated,
					   in_initiator_comments,
					   in_approved_on,
					   in_approved_by,
					   in_approval_type,
					   in_approver_comments,
					  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_emp_leave_id = l_emp_leave_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_leave_package_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_leave_package_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_package_id` MEDIUMINT(8), IN `in_package_name` VARCHAR(50), IN `in_package_display_name` VARCHAR(50), IN `in_start_date` DATE, IN `in_end_date` DATE, IN `in_package_desc` VARCHAR(100), IN `in_package_abbr` VARCHAR(10), IN `in_is_default` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_insert_row_count` MEDIUMINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_leave_year` MEDIUMINT(8), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_emp_leave_package_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

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

  declare l_insert_sql_str text default 'INSERT INTO emp_leave_package_details(ay_id, inst_id, 
                                         package_dtl_id, package_id,leave_type,no_of_leaves,
                                         is_active,created_by,updated_by,
    min_used_leave,total_max_cf_leave,credit_frequency,carry_forward_leave,is_reimbursement)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 = 'emp_leave_package_details' 
  order by col_pos;

  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
        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;


   case in_dml_mode 
    when 'I' then
      begin
        set l_package_id = fn_sequence_generator('EMP_LEAVE_PACKAGE_MASTER');
      end;

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

     when 'D' then
    begin
      set l_package_id = in_package_id;
    end;
  end case;

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

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

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

      if (l_template_col_name = 'package_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('EMP_LEAVE_PACKAGE_DETAILS');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('EMP_LEAVE_PACKAGE_DETAILS');
              end;

            when 'D' then
            begin
               set l_template_col_value = fn_sequence_generator('EMP_LEAVE_PACKAGE_DETAILS');          
            end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'package_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_package_id;
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              
              end;
             when 'D' then
            begin
               set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
            
            end;
          end case;
        end;     
        
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;

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

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

    end loop;

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

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

    close cur_json_template;

  end while;

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

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

             INSERT INTO emp_leave_package_master(ay_id, inst_id, package_id, 
                         package_name, package_display_name,start_date,end_date,package_desc, 
                         package_abbr,is_default,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_default,
                     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 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_default, 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_default,
              in_created_by,in_created_by, in_is_active);

                   
--           update emp_leave_package_details set valid_to = now(), updated_by = in_created_by, 
--             updated_on = now(), is_deleted = 0,min_used_leave=in_min 
--           where ay_id = in_ay_id and inst_id = in_inst_id and package_id = in_package_id
--             and is_deleted = 0;
--  
          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_emp_leave_package_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_leave_package_map`(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), 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_emp_leave_package_map';
  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_package_emp_history(ay_id,inst_id, 
                                        emp_id,package_id,leave_type,credit,leave_balance,used_leave,
                                         cary_forward_leave,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 = 'leave_package_emp_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;
        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_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,created_by, 
              updated_by,is_active) 
            values(
              in_ay_id,in_inst_id,in_emp_id,in_package_id,
             in_created_by,in_created_by,in_is_active);

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


--              select COUNT(emp_id) as totalcount INTO l_emp_id_data from leave_package_emp_history
--           where inst_id=in_inst_id and is_active=1 and is_deleted=0 and emp_id=in_emp_id ;
-- 
--            IF(l_emp_id_data=0) then
--             call sp_execute_immediate (l_insert_sql_str);  
--            ELSE
--               update leave_package_emp_history set valid_to = now(), updated_by = in_created_by, 
--                       updated_on = now(), is_active=0,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);  
--           END IF;             
        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_emp_leave_pack_mapping_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_leave_pack_mapping_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_package_id` MEDIUMINT(8), IN `in_emp_id` MEDIUMINT(8), IN `in_is_custom` TINYINT(1), 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, OUT `out_package_id` MEDIUMINT(8))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_emp_leave_pack_mapping_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

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

  declare l_package_name varchar(50) default '''';
  declare l_package_display_name varchar(50) default '''';
  declare l_package_desc varchar(100) default '''';
  declare l_package_abbr varchar(10) default '''';


  declare l_insert_sql_str text default 'INSERT INTO emp_leave_package_details(ay_id, inst_id, 
                                                     package_dtl_id, package_id,leave_type,no_of_leaves,
                                                     is_active,created_by,updated_by,min_used_leave,max_cf_leave)VALUES'; 

  declare l_insert_sql_str1 text default 'INSERT INTO emp_leave_package_history(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) 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 = 'emp_leave_package_details' 
  order by col_pos;


  declare continue handler for not found set l_looping_done = true;

  declare exit handler for sqlexception
	  begin     
      rollback;

      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
        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;


   case in_dml_mode 
    when 'I' then
      begin
        set l_package_id = fn_sequence_generator('EMP_LEAVE_PACKAGE_MASTER');
      end;
  end case;

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

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

    set l_insert_val_str_part = '';

    open cur_json_template;

    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;

        if l_looping_done then
          leave cursor_loop;
        end if;

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

      if (l_template_col_name = 'package_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('EMP_LEAVE_PACKAGE_DETAILS');
            end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'package_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_package_id;
              end;
          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 l_package_name = concat('Custum leave package ', l_package_id);
          set l_package_display_name = l_package_name;
          set l_package_desc = l_package_name;
          set l_package_abbr = concat('CTMPKG', l_package_id);
          set out_package_id=l_package_id;
       
          # store data in emp_leave_package_master

            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,l_package_name, 
                                     l_package_display_name,'','',l_package_desc, l_package_abbr,
                                     in_is_custom, in_created_by, in_created_by, in_is_active);

          
          # store data in emp_leave_package_details
            call sp_execute_immediate (l_insert_sql_str); 
--              call sp_execute_immediate (l_insert_sql_str); 
          

          # store data in emp_leave_package_map

            update  emp_leave_package_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  emp_leave_package_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,l_package_id,
                                 in_is_active,in_created_by,in_created_by);
        commit;
      end;

    when 'U' 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;

           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;
  set out_package_id=l_package_id;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_payroll_template_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_payroll_template_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_payroll_mst_id` MEDIUMINT(8), IN `in_payroll_dtl_id` MEDIUMINT(8), IN `in_payroll_template_name` VARCHAR(50), IN `in_comments` VARCHAR(50), IN `in_salary_allowance_total_amount` BIGINT(50), IN `in_deduction_total_amount` BIGINT(50), IN `in_net_amount` BIGINT(50), IN `in_payroll_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_emp_payroll_template_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_payroll_mst_id mediumint(8);
  declare l_party_type varchar(20);

  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 fin_payroll_template_details(ay_id, inst_id, payroll_mst_id,
    payroll_dtl_id,component_name,component_type,amount, is_active, created_by, updated_by,component_id,is_leave_deduct) 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 = 'fin_payroll_template_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_payroll_mst_id = fn_sequence_generator('FIN_EMP_PAYROLL_MASTER');
      end;

    when 'U' then
      begin
        set l_payroll_mst_id = in_payroll_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 = 'payroll_dtl_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('FIN_EMP_PAYROLL_DETAILS');
              end;
    
            when 'U' then
              begin
                  set l_template_col_value = fn_sequence_generator('FIN_EMP_PAYROLL_DETAILS');
             
              end;
          end case;
        end;     
        
      elseif (l_template_col_name = 'payroll_mst_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = l_payroll_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 data into the finance payroll template master 
          INSERT INTO fin_payroll_template_master(ay_id, inst_id, payroll_mst_id,template_id,
            payroll_template_name,comments,salary_allowance_amount, salary_deduction_amount,
            net_amount,payroll_date,created_by, updated_by, is_active) 
          VALUES (in_ay_id, in_inst_id, l_payroll_mst_id,l_payroll_mst_id, in_payroll_template_name, 
          in_comments,in_salary_allowance_total_amount, in_deduction_total_amount,in_net_amount,
            in_payroll_date,in_created_by,in_created_by,in_is_active);

--             insert data into the finance payroll template details           
          call sp_execute_immediate (l_insert_sql_str); 

        commit;
      end;

    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
            update fin_payroll_template_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted=1 
            where payroll_mst_id=in_payroll_mst_id AND ay_id = in_ay_id 
            	and inst_id = in_inst_id and is_deleted=0;

             INSERT INTO fin_payroll_template_master(ay_id, inst_id, payroll_mst_id,template_id,
            payroll_template_name,comments,salary_allowance_amount, salary_deduction_amount,
            net_amount,payroll_date,created_by, updated_by, is_active) 
          VALUES (in_ay_id, in_inst_id, in_payroll_mst_id,in_payroll_mst_id, in_payroll_template_name, 
          in_comments,in_salary_allowance_total_amount, in_deduction_total_amount,in_net_amount,
            in_payroll_date,in_created_by,in_created_by,in_is_active);

            update fin_payroll_template_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted=1 
            where payroll_mst_id=in_payroll_mst_id AND ay_id = in_ay_id 
            	and inst_id = in_inst_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_emp_salary_package_data`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_salary_package_data`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_sal_mst_id` MEDIUMINT(8), IN `in_fin_acct_id` MEDIUMINT(8), IN `in_salary_name` VARCHAR(100), IN `in_comments` VARCHAR(50), IN `in_salary_year` MEDIUMINT(8), IN `in_salary_month` VARCHAR(50), IN `in_salary_type` VARCHAR(20), IN `in_fromDate` DATE, IN `in_toDate` DATE, IN `in_salary_date` DATE, IN `in_salary_status` VARCHAR(50), IN `in_total_amount` BIGINT(50), IN `in_sal_dtl_id` MEDIUMINT(8), IN `in_emp_id` MEDIUMINT(8), IN `in_template_id` MEDIUMINT(8), IN `in_gross` BIGINT(50), IN `in_deduction` BIGINT(50), IN `in_net_amount` BIGINT(50), IN `in_details_salary_status` MEDIUMINT(8), IN `in_sal_dtl_id_component` SMALLINT(5), IN `in_component_type` VARCHAR(50), IN `in_component_id` MEDIUMINT(8), IN `in_amount` BIGINT(50), IN `in_leave_deduct_amount` BIGINT(30), IN `in_consume_days` MEDIUMINT(8), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_status` TINYINT(2), IN `in_status_desc` VARCHAR(100), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_id` MEDIUMINT(8))
    NO SQL
begin

declare l_routine_name varchar(50) default 'sp_ins_emp_salary_package_data';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_sal_mst_id mediumint(8); 	
  declare l_sal_dtl_id mediumint(8);
  declare l_deduction bigint(50);
  declare l_net_amount bigint(50);
  declare l_component_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, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

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

    start transaction;
   
      case in_dml_mode 
         when 'M' then
          begin

          set l_routine_block = 'insert';
          set l_sal_mst_id = fn_sequence_generator('FIN_EMP_SALARY_MASTER');
          set out_id = l_sal_mst_id ;
           INSERT INTO fin_salary_master(ay_id, inst_id, sal_mst_id,fin_acct_id,salary_name,comments,
            salary_year, salary_month,salary_type,fromDate,toDate,salary_status,
            total_salary,salary_date,created_by, updated_by, is_active) 
          VALUES (in_ay_id, in_inst_id,l_sal_mst_id,in_fin_acct_id,in_salary_name,in_comments,
            in_salary_year,in_salary_month,in_salary_type,in_fromDate,in_toDate,
           in_salary_status,in_total_amount,in_salary_date,in_created_by, in_created_by, in_is_active);

          end;
        when 'I' then
          begin

          IF(in_sal_dtl_id='')THEN
               set l_sal_dtl_id = fn_sequence_generator('FIN_EMP_SALARY_DETAILS');
                SET out_id = l_sal_dtl_id ;
               INSERT INTO fin_salary_details(ay_id, inst_id, sal_mst_id, sal_dtl_id,emp_id,template_id,
                  gross,deduction,net_amount,salary_status,is_active, created_by, updated_by) 
               VALUES (in_ay_id, in_inst_id, in_sal_mst_id, l_sal_dtl_id,in_emp_id,in_template_id,
                  in_gross,in_deduction, in_net_amount,in_details_salary_status, in_is_active,in_created_by, in_created_by);

          ELSE
              set l_sal_dtl_id = in_sal_dtl_id;
              IF(in_deduction=0)THEN  
                 
                  SELECT deduction INTO l_deduction from fin_salary_details 
                  WHERE ay_id=in_ay_id AND inst_id=in_inst_id AND sal_dtl_id=in_sal_dtl_id
                      AND is_deleted=0 AND is_active=1;
                  SET l_net_amount =in_gross - l_deduction;
    
                  UPDATE fin_salary_details SET gross=in_gross,deduction=l_deduction,net_amount=l_net_amount
                       WHERE ay_id=in_ay_id AND inst_id=in_inst_id AND sal_dtl_id=l_sal_dtl_id
                       AND is_deleted=0 AND is_active=1;
              ELSE
--                 if leave deduct count resubmit then make changes in salary_setails table
                  SET l_net_amount =in_gross - in_deduction;
                  UPDATE fin_salary_details SET gross=in_gross,deduction=in_deduction,net_amount=l_net_amount
                       WHERE ay_id=in_ay_id AND inst_id=in_inst_id AND sal_dtl_id=l_sal_dtl_id
                       AND is_deleted=0 AND is_active=1;
              END IF;

          END IF;
         
         
          end;   
          
          
          
  	    when 'C' then
          set l_routine_block = 'update';

          begin

            SELECT count(component_id) INTO l_component_id FROM fin_salary_details_components 
            WHERE ay_id=in_ay_id AND inst_id=in_inst_id AND sal_dtl_id=in_sal_dtl_id
                  AND emp_id=in_emp_id AND component_id=in_component_id AND is_deleted=0 
                  AND is_active=1;
             
           IF(l_component_id=0)THEN
                
             INSERT INTO  fin_salary_details_components(ay_id, inst_id, sal_dtl_id,emp_id,
                        component_type,component_id,amount,status,status_desc,
                        is_active, created_by, updated_by,leave_deduct_amount,consume_days) 
                VALUES (in_ay_id, in_inst_id,in_sal_dtl_id_component,in_emp_id,
                     in_component_type,in_component_id,in_amount,in_status,
                     in_status_desc,in_is_active,in_created_by,in_created_by,in_leave_deduct_amount,
                     in_consume_days);
             
           ELSE
                 UPDATE fin_salary_details_components SET amount=in_amount,
                  leave_deduct_amount=in_leave_deduct_amount,consume_days=in_consume_days
                 WHERE ay_id=in_ay_id AND inst_id=in_inst_id AND sal_dtl_id=in_sal_dtl_id
                  AND emp_id=in_emp_id AND component_id=in_component_id AND is_deleted=0 
                  AND is_active=1 AND component_type=in_component_type;
                
            END IF;
            SET out_id = in_sal_dtl_id ;
          end;   
          
          when 'U' then
          set l_routine_block = 'update';

          begin
-- 	        update fin_salary_master set 
--             salary_name=in_salary_name,comments=in_comments,salary_year=in_salary_year,
--             salary_month=in_salary_month,salary_type=in_salary_type,fromDate=in_fromDate,
--            toDate=in_toDate,salary_status=in_salary_status,salary_date=in_salary_date,
--             valid_to = NOW(), updated_by = in_created_by, 
--               updated_on = NOW(), is_deleted=0,is_active=1 
--             where sal_mst_id=in_sal_mst_id AND ay_id = in_ay_id 
--           	and inst_id = in_inst_id and is_deleted=0 and is_active=1;
          set out_id = in_sal_mst_id ;
            update fin_salary_master set   
              valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted=1
            where sal_mst_id=in_sal_mst_id AND ay_id = in_ay_id 
          	AND inst_id = in_inst_id AND is_deleted=0 AND is_active=1;

           INSERT INTO fin_salary_master(ay_id, inst_id, sal_mst_id,fin_acct_id,salary_name,comments,
            salary_year, salary_month,salary_type,fromDate,toDate,salary_status,
            total_salary,salary_date,created_by, updated_by, is_active) 
           VALUES (in_ay_id, in_inst_id, in_sal_mst_id,in_fin_acct_id,
            in_salary_name,in_comments,in_salary_year,in_salary_month,
            'MONTHLY',in_fromDate,in_toDate,"1",in_total_amount,in_salary_date,
            in_created_by, in_created_by, in_is_active);
 
           update fin_salary_details set valid_to = NOW(),updated_by = in_created_by, 
              updated_on = NOW(), is_deleted=1
            where sal_mst_id=in_sal_mst_id AND ay_id = in_ay_id 
          	AND inst_id = in_inst_id AND is_deleted=0 AND is_active=1;
 
          end;  
           
      end case;
    
    commit;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
    set out_id = out_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_subject_map`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_subject_map`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_emp_sub_map_id` MEDIUMINT(8), IN `in_standard_id` CHAR(2), IN `in_division_id` CHAR(1), IN `in_emp_id` MEDIUMINT(8), IN `in_group_type` CHAR(3), IN `in_group_id` CHAR(8), IN `in_sub_std_map_id` MEDIUMINT(8), IN `in_allocation_start_date` DATE, IN `in_allocation_end_date` DATE, IN `in_is_allocation_temp` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
   declare l_routine_name varchar(50) default 'sp_ins_emp_subject_map';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare exit handler for sqlexception
	 begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
             set l_routine_block = 'insert';
          end;    
  	   when 'U' then
          set l_routine_block = 'update';
          begin
          		update emp_subject_map set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted=1 
            where emp_sub_map_id=in_emp_sub_map_id AND ay_id = in_ay_id 
            	and inst_id = in_inst_id and is_deleted=0;
            insert into  emp_subject_map (ay_id, inst_id,emp_sub_map_id,standard_id,division_id,emp_id, group_type,group_id, sub_std_map_id, 
               allocation_start_date,	allocation_end_date,is_allocation_temp,is_active, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_emp_sub_map_id,in_standard_id,in_division_id ,in_emp_id, in_group_type,in_group_id,in_sub_std_map_id, 
              in_allocation_start_date,in_allocation_end_date ,in_is_allocation_temp,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_emp_subject_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_subject_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_emp_sub_map_id` MEDIUMINT(8), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_emp_subject_map_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_json_str text;
  declare l_json_str_len int;
  declare l_json_substr text;
  declare l_separator_idx int default 1;
  declare l_json_key_val_sep_len tinyint(1) default 3;
  declare l_template_col_name varchar(25);
  declare l_template_col_value text;
  declare l_looping_done int default false;
  declare l_insert_row_count tinyint(3);
  declare l_single_quot_const varchar(5) default '''';
  declare l_val_sep_const varchar(5) default ',';
  declare l_json_val_dbl_quot_const varchar(5) default '"';
  declare l_val_str_start char(1) default '(';
  declare l_val_str_end char(1) default ')';
  declare l_insert_sql_str text default 'INSERT INTO emp_subject_map(ay_id, inst_id, standard_id, division_id,emp_id,
    group_type,sub_std_map_id,  allocation_start_date, allocation_end_date, is_allocation_temp, is_active, created_by, 
    updated_by ,emp_sub_map_id,group_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 = 'emp_subject_map' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  while (l_insert_row_count > 0) do
    set l_routine_block = 'inside while loop';
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Open Cursor', l_insert_row_count);
    set l_insert_val_str_part = '';
    open cur_json_template;
    cursor_loop: loop
      fetch cur_json_template into l_template_col_name;
        if l_looping_done then
          leave cursor_loop;
        end if;
      set l_separator_idx = instr(l_json_str, l_template_col_name) + 
        length(l_template_col_name) + l_json_key_val_sep_len;
      set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
      set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
      #insert into proc_error_log (routine_name, label_name, sql_log)
      #values(l_routine_name, 'Before Case', l_template_col_name);
      if (l_template_col_name = 'emp_sub_map_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('EMP_SUBJECT_MAP');
              end;
            when 'U' then
              begin
                set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);
              end;
          end case;
        end;     
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
    #insert into sp_error_log (routine_name, label_name, sql_log)
    #values(l_routine_name, 'Before Close Cursor', l_insert_val_str_full);
    close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
  #insert into proc_error_logs (routine_name, label_name, sql_log)
  #values(l_routine_name, 'Before Close Cursor', l_insert_sql_str);
  case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
          set l_routine_block = 'before execute immediate';
              call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
         update emp_subject_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 emp_sub_map_id = in_emp_sub_map_id
            and is_deleted = 0;
          set l_routine_block = 'before execute immediate';
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
    end case;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_emp_temp_users_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_emp_temp_users_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_emp_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_employee_master(ay_id, inst_id, emp_id, login_name, password, mobile_phone_main, 
          email_main, emp_status, bulk_upload_status,  is_active,created_by, updated_by,
          is_deleted ) 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_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(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 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.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.parent_id=pm.parent_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 pm.stud_bulk_file_upload_id=in_stud_bulk_file_upload_id;

     end;     

   
    end case;

  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;

END$$

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

DROP PROCEDURE IF EXISTS `sp_ins_event_participant_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_event_participant_map_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_event_id` MEDIUMINT(8), IN `in_event_cat` VARCHAR(25), IN `in_event_sub_cat` VARCHAR(25), IN `in_event_title` VARCHAR(50), IN `in_event_desc` VARCHAR(5000), IN `in_client_type` VARCHAR(15), IN `in_client_id` INT(10), IN `in_start_date` DATETIME, IN `in_end_date` DATETIME, IN `in_is_mandatory` TINYINT(1), IN `in_is_global` TINYINT(1), IN `in_is_all_day` TINYINT(1), IN `in_is_notification` TINYINT(1), IN `in_notif_reminder_days` SMALLINT(2), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_updated_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_event_participant_map_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 event_participant_map(ay_id, inst_id, event_id, group_name,
    group_type, group_ids,is_active, created_by, updated_by ) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare l_event_id mediumint(8); 
  declare cur_json_template cursor for 
  select col_name from json_template_master 
  where tbl_name = 'event_participant_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_updated_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
	set l_routine_block = 'inserting event calendar master entry';	
	 case in_dml_mode 
      when 'I' then
        begin
          set l_event_id = fn_sequence_generator('EVENT_CALENDAR_MASTER');
        end;
      when 'U' then
        begin
           set l_event_id = in_event_id;
            update event_calendar_master set valid_to = now(), 
   	         updated_on = now(), is_deleted = 1 
	         where ay_id = in_ay_id and inst_id = in_inst_id and event_id = l_event_id
            and is_deleted = 0;
        end;
	  end case;
		insert into event_calendar_master(ay_id, inst_id, event_id, event_cat,event_sub_cat, event_title, event_desc, client_type,client_id,start_date,end_date,is_mandatory,is_global,is_all_day,is_notification,notif_reminder_days, created_by,updated_by,is_active) 
	   	   values 
	      	  (in_ay_id, in_inst_id, l_event_id, in_event_cat, in_event_sub_cat, in_event_title,in_event_desc,in_client_type,in_client_id,in_start_date,in_end_date,in_is_mandatory,in_is_global,in_is_all_day,in_is_notification,in_notif_reminder_days, in_created_by,in_updated_by,in_is_active);
  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 = 'event_id') THEN
        begin
	         set l_template_col_value=l_event_id;
        end;     
      else
        set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);             
      end if;
      set l_template_col_value = concat(l_single_quot_const, l_template_col_value, 
        l_single_quot_const);
      set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part, 
        l_template_col_value);
      set l_json_str = l_json_substr;
      set l_json_str_len = length(l_json_str);
    end loop;
    set l_insert_row_count = l_insert_row_count - 1;
    set l_looping_done = false;
    if length(trim(l_insert_val_str_full)) > 0 then        
      set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start, 
        l_insert_val_str_part, l_val_str_end, ',');
    else
      set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part, 
        l_val_str_end, ',');
    end if;
    set l_insert_val_str_part = '';
    set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '(');
            close cur_json_template;
  end while;
  set l_insert_sql_str = concat(l_insert_sql_str, 
    substring(l_insert_val_str_full, 1, length(l_insert_val_str_full) - 1));
      case in_dml_mode
    when 'I' THEN
      begin
        start transaction;  
				set l_routine_block = 'before execute immediate';
				call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
          update event_participant_map set valid_to = now(), 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and event_id = in_event_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_exam_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_exam_mst_id` INT, 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_exam_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 exam_details(
		ay_id,inst_id,
		exam_mst_id,exam_dtl_id,
		standard_id,division_id,group_type,group_id,
		curriculum_type,grading_system,gradeset_mst_id,evaluation_type,
		sub_std_map_id,exam_name,exam_desc,exam_abbr,
		exam_start_time,exam_end_time,exam_max_marks,exam_min_marks,exam_weightage,
		status,status_desc,created_by) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text; 
	declare cur_json_template cursor for 
		select col_name from json_template_master where tbl_name = 'exam_details' order by col_pos; 
	declare continue handler for not found set l_looping_done = true; 
	declare exit handler for sqlexception 
		begin   
			rollback; 
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,err_desc, err_type, err_severity, created_by)  
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
	set l_insert_row_count = in_insert_row_count;
	set l_json_str = trim(in_json_str);
	set l_json_str_len = length(l_json_str);  
	while (l_insert_row_count > 0) do
		set l_routine_block = 'inside while loop'; 
		set l_insert_val_str_part = ''; 
		open cur_json_template;  
			cursor_loop: loop 
				fetch cur_json_template into l_template_col_name; 
				if l_looping_done then 
				  leave cursor_loop; 
				end if; 
				set l_separator_idx = instr(l_json_str, l_template_col_name) + length(l_template_col_name) + l_json_key_val_sep_len;  
				set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);   
				set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const); 
				if (l_template_col_name = 'exam_dtl_id') THEN 
					set l_template_col_value = fn_sequence_generator('EXAM_DETAILS'); 
					/*
					begin 
						case in_dml_mode 
							when 'I' then 
							  begin 
								set l_template_col_value = fn_sequence_generator('EXAM_DETAILS'); 
							  end; 
							when 'U' then 
							  begin 
								set l_template_col_value = fn_sequence_generator('EXAM_DETAILS'); 
							  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)); 
	start transaction;    
		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 
						set l_routine_block = 'before soft delete'; 
						update exam_details 
								set valid_to = now(), 
									updated_by = in_created_by, 
									updated_on = now(), 
									is_active = 1  , 
									is_deleted = 1
							where  
								inst_id = in_inst_id 
								and exam_mst_id = in_exam_mst_id 
								and is_active = 1; 
						set l_routine_block = 'before execute immediate'; 
						call sp_execute_immediate (l_insert_sql_str);  
				end; 
		end case;
		update exam_master set status='30'
            where exam_mst_id = in_exam_mst_id  
            	and inst_id = in_inst_id
				and is_active = 1
				and is_deleted = 0 ;  
	commit; 
  set out_err_code = l_err_code;  
  set out_err_desc = l_err_desc; 
end$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_groups_copy`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_groups_copy`(IN `in_inst_id` SMALLINT(5), IN `in_inst_board_type` VARCHAR(50), IN `in_inst_grading_system` VARCHAR(50), IN `in_template_id` VARCHAR(10), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_exam_mst_id_min mediumint(8);  
	declare l_routine_name varchar(50) default 'sp_ins_exam_groups_copy';
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_routine_block varchar(15);
	declare l_fee_struct_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 ('2016-17', in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
		set out_err_code = l_err_code; 
		set out_err_desc = l_err_desc;
	end; 
     start transaction;   
		begin
            set l_routine_block = 'duplicate'; 
			SET @selectInsertExamMaster = CONCAT_WS("" , "insert into exam_master( 
			ay_id, 
			inst_id, 
			exam_mst_id, 
			standard_id, division_id, group_type, group_id, gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, is_system_def, status, status_desc, valid_from, valid_to, created_by, updated_by, is_active, is_deleted) 
			SELECT 	ay_id,", 
					in_inst_id, " as inst_id,fn_sequence_generator('EXAM_MASTER') as exam_mst_id, standard_id, division_id, group_type, group_id, gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, is_system_def, status, status_desc, valid_from, valid_to,", in_created_by, " as created_by,", in_created_by , " as updated_by,'1' as is_active,'0' as is_deleted from exam_master where inst_id = '0' and ay_id='*' and is_active = 1 and is_deleted = 0" );
			/*INSERT INTO proc_error_logs VALUES('1','selectInsertExamMaster',@selectInsertExamMaster);*/
			PREPARE stmt FROM @selectInsertExamMaster;  
			EXECUTE stmt;  
			/* Get minimum exam_mst_id for the school into local variable */ 
			SELECT min(exam_mst_id) INTO l_exam_mst_id_min FROM exam_master WHERE inst_id = in_inst_id ;
			SET @selectInsertExamGroupDetails = CONCAT_WS("" , "insert into exam_group_details( 
			ay_id, 
			inst_id, 
			exam_grp_mst_id, 
			exam_grp_dtl_id, 
			exam_mst_id, 
			exam_weightage, valid_from, valid_to, created_by, updated_by, is_active, is_deleted) 
			SELECT 	ay_id,", 
					in_inst_id, " as inst_id, 
					exam_grp_mst_id, 
					fn_sequence_generator('EXAM_GROUP_DETAILS') as exam_grp_dtl_id, 
					(exam_mst_id - 1 + ", l_exam_mst_id_min ," ) as exam_mst_id, 
					exam_weightage, valid_from, valid_to,", in_created_by, " as created_by,", in_created_by , " as updated_by,'1' as is_active,'0' as is_deleted from exam_group_details where inst_id = '0' and ay_id='*' and is_active = 1 and is_deleted = 0" );
			/*INSERT INTO proc_error_logs VALUES('1','selectInsertExamGroupDetails',@selectInsertExamGroupDetails);*/
			PREPARE stmt FROM @selectInsertExamGroupDetails;  
			EXECUTE stmt;  
		end;     
    commit;  
    set out_err_code = l_err_code; 
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_group_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_group_details_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` SMALLINT(5), 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_exam_group_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 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 exam_group_details(
				ay_id, 
				inst_id, 
				exam_grp_mst_id, 
				exam_grp_dtl_id, 
				exam_mst_id,
				exam_weightage,   
				exam_grp_type,  
				exam_best_of,  
				exam_grp_name,
				created_by ) VALUES'; 
	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text; 
	declare cur_json_template cursor for 
		select col_name from json_template_master where tbl_name = 'exam_group_details' order by col_pos; 
	declare continue handler for not found set l_looping_done = true; 
	declare exit handler for sqlexception 
		begin   
			rollback; 
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,err_desc, err_type, err_severity, created_by)  
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);  
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = ''; 
			open cur_json_template;  
				cursor_loop: loop 
					fetch cur_json_template into l_template_col_name; 
					if l_looping_done then 
					  leave cursor_loop; 
					end if; 
					set l_separator_idx = instr(l_json_str, l_template_col_name) + length(l_template_col_name) + l_json_key_val_sep_len;  
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);   
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);  
					if (l_template_col_name = 'exam_grp_dtl_id') THEN 
						set l_template_col_value = fn_sequence_generator('EXAM_GROUP_DETAILS'); 
					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)); 
		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_exam_group_score_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_group_score_details_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` INT, IN `in_mode` CHAR(1), IN `in_exam_grp_mst_id` INT, IN `in_group_type` CHAR(10), IN `in_group_id` CHAR(50), IN `in_insert_row_count` INT, IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
	declare l_routine_name varchar(50) default 'sp_ins_exam_group_score_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 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 exam_group_score_details(
			ay_id,
			inst_id,
			exam_grp_mst_id,
			student_id,
			sub_std_map_id,
			exam_marks,
			exam_points,
			exam_grade,
			gradset_dtl_id,
			exam_remarks,
			is_fail, 
			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 = 'exam_group_score_details' order by col_pos; 
	declare continue handler for not found set l_looping_done = true; 
	declare exit handler for sqlexception 
		begin   
			rollback; 
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,err_desc, err_type, err_severity, created_by)  
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);
		set l_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;    
			/* Update Exam_Group_Summary table */
			/* Confirm */ 
			if (in_mode = 'C') then
				UPDATE exam_group_summary set status='20' 
					WHERE inst_id=in_inst_id
						AND exam_grp_mst_id = in_exam_grp_mst_id
						AND group_type = in_group_type 
						AND group_id = in_group_id ; 
      /* Remarks */       
			elseif(in_mode = 'R') then
				UPDATE exam_group_summary set status='25' 
					WHERE inst_id=in_inst_id
						AND exam_grp_mst_id = in_exam_grp_mst_id
						AND group_type = in_group_type 
						AND group_id = in_group_id ;
      /* Publish */       
			elseif(in_mode = 'P') then
				UPDATE exam_group_summary set status='30' 
					WHERE inst_id=in_inst_id
						AND exam_grp_mst_id = in_exam_grp_mst_id
						AND group_type = in_group_type 
						AND group_id = in_group_id ; 
			end if; 
			set l_routine_block = 'before execute immediate';   
			if(in_insert_row_count > 0) then
				call sp_execute_immediate (l_insert_sql_str);        
			end if;
		commit;  
	set out_err_code = l_err_code;  
	set out_err_desc = l_err_desc; 
END$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_exam_mst_id` MEDIUMINT(8), IN `in_standard_id` CHAR(3), IN `in_division_id` CHAR(1), IN `in_group_type` CHAR(3), IN `in_group_id` VARCHAR(10), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_evaluation_type` VARCHAR(20), IN `in_exam_cat_id` VARCHAR(10), IN `in_exam_term` VARCHAR(10), IN `in_exam_name` VARCHAR(50), IN `in_exam_start_date` DATE, IN `in_exam_end_date` DATE, IN `in_exam_weightage` TINYINT(3), IN `in_is_system_def` TINYINT(1), IN `in_exam_visibility` CHAR(1), IN `in_student_report_format` VARCHAR(20), IN `in_section_levels` TINYINT(1), 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_exam_master'; 
	declare l_err_code char(5) default '00000'; 
	declare l_err_desc text default '';    	 
	declare l_routine_block varchar(50); 
	declare l_exam_mst_id MEDIUMINT(8); 
	declare l_exam_actual_start_date DATE; 
	declare l_exam_actual_end_date DATE; 
	/* Exception Handler Block */
	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_exam_mst_id = fn_sequence_generator('EXAM_MASTER');
			insert into exam_master (ay_id, inst_id, exam_mst_id, standard_id, division_id, group_type, group_id, 
				gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, 
				is_system_def, exam_visibility, student_report_format, section_levels, status, status_desc, created_by, is_active)  
			values(in_ay_id, in_inst_id, l_exam_mst_id, in_standard_id, in_division_id, in_group_type, in_group_id,
				in_gradeset_mst_id, in_evaluation_type, in_exam_cat_id, in_exam_term, in_exam_name, in_exam_start_date, in_exam_end_date, in_exam_weightage,
				in_is_system_def, in_exam_visibility, in_student_report_format, in_section_levels, in_status, in_status_desc,in_created_by, in_is_active); 
          end;    
		  
		  
		/* Update */	
  	    when 'S' then
         set l_routine_block = 'statusChange'; 
          begin
			SET @selectInsertExamMaster = CONCAT_WS("" , "insert into exam_master( 
			ay_id, inst_id, exam_mst_id,  standard_id, division_id, group_type, group_id, gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, is_system_def, exam_visibility, student_report_format, section_levels, 
			status, 
			status_desc, 
			valid_from, valid_to, created_by, 
			updated_by, 
			is_active, is_deleted) 
			SELECT 	ay_id, inst_id, exam_mst_id, standard_id, division_id, group_type, group_id, gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, is_system_def, exam_visibility, student_report_format, section_levels,", in_status , " as status,", in_status_desc , " as status_desc, valid_from, valid_to,created_by,", in_created_by , " as updated_by, '1' as is_active,'5' as is_deleted from exam_master WHERE 
			exam_mst_id = ", in_exam_mst_id ," and 
			inst_id = '", in_inst_id ,"' and 
			ay_id= '", in_ay_id ,"' and 
			is_active = 1 and is_deleted = 0" );
			 	 
			PREPARE stmt FROM @selectInsertExamMaster;  
			EXECUTE stmt;  
			update exam_master set valid_to = NOW(), updated_by = in_created_by,  
				updated_on = NOW(), is_deleted = 1 
            where exam_mst_id = in_exam_mst_id 
				and is_deleted = 0  
            	and inst_id = in_inst_id; 
			
			/* If Schedule Published Status (50), Then change the exam dates */	
			 
			if (in_status= '50') then        
			 SELECT MIN(exam_start_time), MAX(exam_end_time) INTO l_exam_actual_start_date,  l_exam_actual_end_date 
				FROM exam_details 
				WHERE exam_mst_id = in_exam_mst_id 
				AND is_deleted = 0  
            	AND inst_id = in_inst_id; 
               
				update exam_master set valid_to = NOW(),exam_start_date=l_exam_actual_start_date, exam_end_date=l_exam_actual_end_date, updated_by = in_created_by,  
					updated_on = NOW(), is_deleted = 0
				where exam_mst_id = in_exam_mst_id 
					and is_deleted = 5  
					and inst_id = in_inst_id; 
			else
				update exam_master set valid_to = NOW(), updated_by = in_created_by,  
					updated_on = NOW(), is_deleted = 0
				where exam_mst_id = in_exam_mst_id 
					and is_deleted = 5  
					and inst_id = in_inst_id; 
			end if; 
          end;     
		/* Status Change */	
		when 'U' then
         set l_routine_block = 'update'; 
          begin
          	update exam_master set valid_to = NOW(), updated_by = in_created_by,  
				updated_on = NOW(), is_deleted = 1 
            where exam_mst_id = in_exam_mst_id 
				and is_deleted = 0  
            	and inst_id = in_inst_id; 
			 insert into exam_master (ay_id, inst_id, exam_mst_id, standard_id, division_id, group_type, group_id, 
				gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, 
				is_system_def, exam_visibility, student_report_format, section_levels, status, status_desc, created_by, is_active)  
			values(in_ay_id, in_inst_id, in_exam_mst_id, in_standard_id, in_division_id, in_group_type, in_group_id,
				in_gradeset_mst_id, in_evaluation_type, in_exam_cat_id, in_exam_term, in_exam_name, in_exam_start_date, in_exam_end_date, in_exam_weightage,
				in_is_system_def, in_exam_visibility, in_student_report_format, in_section_levels, in_status, in_status_desc, 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_exam_master_and_groups`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_master_and_groups`(IN `in_inst_id` SMALLINT(5), IN `in_ay_id` VARCHAR(10), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
	declare l_exam_mst_id_min mediumint(8);  
	declare l_routine_name varchar(50) default 'sp_ins_exam_groups_copy';
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_routine_block varchar(15);
	declare l_fee_struct_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 ('2016-17', in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
		set out_err_code = l_err_code; 
		set out_err_desc = l_err_desc;
	end; 
     start transaction;   
		begin
            set l_routine_block = 'duplicate'; 
			SET @selectInsertExamMaster = CONCAT_WS("" , "insert into exam_master( 
			ay_id, 
			inst_id, 
			exam_mst_id, 
			standard_id, division_id, group_type, group_id, gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, is_system_def, status, status_desc, valid_from, valid_to, created_by, updated_by, is_active, is_deleted) 
			SELECT 	ay_id,", 
					in_inst_id, " as inst_id,fn_sequence_generator('EXAM_MASTER') as exam_mst_id, standard_id, division_id, group_type, group_id, gradeset_mst_id, evaluation_type, exam_cat_id, exam_term, exam_name, exam_start_date, exam_end_date, exam_weightage, is_system_def, status, status_desc, valid_from, valid_to,", in_created_by, " as created_by,", in_created_by , " as updated_by,'1' as is_active,'0' as is_deleted from exam_master where inst_id = '0' and ay_id='*' and is_active = 1 and is_deleted = 0" );
			/*INSERT INTO proc_error_logs VALUES('1','selectInsertExamMaster',@selectInsertExamMaster);*/
			PREPARE stmt FROM @selectInsertExamMaster;  
			EXECUTE stmt;  
			/* Get minimum exam_mst_id for the school into local variable */ 
			SELECT min(exam_mst_id) INTO l_exam_mst_id_min FROM exam_master WHERE inst_id = in_inst_id ;
			SET @selectInsertExamGroupDetails = CONCAT_WS("" , "insert into exam_group_details( 
			ay_id, 
			inst_id, 
			exam_grp_mst_id, 
			exam_grp_dtl_id, 
			exam_mst_id, 
			exam_weightage, valid_from, valid_to, created_by, updated_by, is_active, is_deleted) 
			SELECT 	ay_id,", 
					in_inst_id, " as inst_id, 
					exam_grp_mst_id, 
					fn_sequence_generator('EXAM_GROUP_DETAILS') as exam_grp_dtl_id, 
					(exam_mst_id - 1 + ", l_exam_mst_id_min ," ) as exam_mst_id, 
					exam_weightage, valid_from, valid_to,", in_created_by, " as created_by,", in_created_by , " as updated_by,'1' as is_active,'0' as is_deleted from exam_group_details where inst_id = '0' and ay_id='*' and is_active = 1 and is_deleted = 0" );
			/*INSERT INTO proc_error_logs VALUES('1','selectInsertExamGroupDetails',@selectInsertExamGroupDetails);*/
			PREPARE stmt FROM @selectInsertExamGroupDetails;  
			EXECUTE stmt;  
		end;     
    commit;  
    set out_err_code = l_err_code; 
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_master_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_master_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_insert_row_count` SMALLINT(5), IN `in_json_str` LONGTEXT, 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_exam_master_json';
	declare l_routine_block varchar(50) default '';
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_json_str LONGTEXT;
	declare l_json_str_len int;
	declare l_json_substr LONGTEXT;
	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 exam_master(
				ay_id, 
				inst_id, 
				exam_mst_id, 
				standard_id, 
				division_id, 
				group_type, 
				group_id, 
				gradeset_mst_id, 
				evaluation_type, 
				exam_cat_id, 
				exam_term, 
				exam_name, 
				exam_start_date, 
				exam_end_date, 
				exam_weightage, 
				is_system_def, 
				status, 
				status_desc, 
				created_by ) VALUES'; 
	declare l_insert_val_str_part LONGTEXT;
	declare l_insert_val_str_full LONGTEXT; 
	declare cur_json_template cursor for 
		select col_name from json_template_master where tbl_name = 'exam_master' order by col_pos; 
	declare continue handler for not found set l_looping_done = true; 
	declare exit handler for sqlexception 
		begin   
			rollback; 
			get diagnostics condition 1
             
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,err_desc, err_type, err_severity, created_by)  
			values (in_ay_id, in_inst_id, l_routine_name, 'X', l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);  
		while (l_insert_row_count > 0) do
			set l_routine_block = 'inside while loop'; 
			set l_insert_val_str_part = ''; 
			open cur_json_template;  
				cursor_loop: loop 
					fetch cur_json_template into l_template_col_name; 
					if l_looping_done then 
					  leave cursor_loop; 
					end if; 
					set l_separator_idx = instr(l_json_str, l_template_col_name) + length(l_template_col_name) + l_json_key_val_sep_len;  
					set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);   
					set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);  
					if (l_template_col_name = 'exam_mst_id') THEN 
						set l_template_col_value = fn_sequence_generator('EXAM_MASTER'); 
					else 
						set l_template_col_value = substring(l_json_substr, 1, l_separator_idx - 1);  
					end if; 
 					set l_template_col_value = concat(l_single_quot_const, l_template_col_value,l_single_quot_const);  
					set l_insert_val_str_part = concat_ws(l_val_sep_const, l_insert_val_str_part,l_template_col_value); 
					set l_json_str = l_json_substr; 
					set l_json_str_len = length(l_json_str); 
				end loop; 
				set l_insert_row_count = l_insert_row_count - 1; 
				set l_looping_done = false; 
				if length(trim(l_insert_val_str_full)) > 0 then        
					set l_insert_val_str_full = concat(l_insert_val_str_full, l_val_str_start,l_insert_val_str_part, l_val_str_end, ',');
				else
					set l_insert_val_str_full = concat(l_val_str_start, l_insert_val_str_part,l_val_str_end, ',');
				end if; 
				set l_insert_val_str_part = ''; 
				set l_insert_val_str_full = replace(l_insert_val_str_full, '(,', '('); 
 			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_exam_remarks_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_remarks_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_exam_id` INT(11), IN `in_group_id` VARCHAR(20), IN `in_exam_type` CHAR(1), 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_exam_remarks_json';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_json_str text;
	declare l_json_str_len int;
	declare l_json_substr text;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count tinyint(3);
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';
	declare l_insert_sql_str text default 'INSERT INTO exam_remarks(inst_id, 
		ay_id,
		exam_id,
		exam_type,
		student_id,
		remarks_meta, 
		remarks,
		remarks_by,
		created_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 = 'exam_remarks' 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));
	begin
		start transaction;  
		  set l_routine_block = 'before execute immediate'; 
		  /* Update Existing Data with is_deleted=1 */
			UPDATE exam_remarks SET is_deleted = '1' 
				WHERE exam_type = in_exam_type
					AND exam_id = in_exam_id
					AND inst_id = in_inst_id
					AND student_id in (select distinct(student_id) from student_master where inst_id = in_inst_id and class_id= in_group_id ) 
					AND remarks_by = in_created_by
					AND is_active = 1 
					AND is_deleted = 0; 
			/* Insert new data */
			call sp_execute_immediate (l_insert_sql_str);  
			/* Change Exam Status */
			UPDATE exam_master 
				SET status = '94' ,
					updated_on = now()  
				WHERE exam_mst_id = in_exam_id
					AND inst_id = in_inst_id
					AND is_active = 1 
					AND is_deleted = 0; 
		commit;
	end; 
	set out_err_code = l_err_code;
	set out_err_desc = l_err_desc;  
END$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_results_summary_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_results_summary_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_class_id` VARCHAR(20), IN `in_exam_type` CHAR(1), IN `in_exam_id` MEDIUMINT(8), IN `in_insert_row_count` SMALLINT(5), IN `in_json_str` LONGTEXT, IN `in_is_active` TINYINT(1), IN `is_first_json_array` TINYINT(1), IN `is_last_json_array` 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_exam_results_summary_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 LONGTEXT;
  declare l_json_str_len int;
  declare l_json_substr LONGTEXT;
  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 exam_results_summary(
			inst_id, 
			ay_id,
			class_id,
			exam_id,
			exam_type,
			exam_subjects_count,
			exam_total_marks, 
			exam_gradeset_id,
			student_id,
			student_marks_total,
			student_percentage,
			student_grade,
			student_grade_points,
			student_rank,
			created_by, 
			updated_by,
			is_active) VALUES'; 
	declare l_insert_val_str_part LONGTEXT;
	declare l_insert_val_str_full LONGTEXT;
	declare cur_json_template cursor for 
	select col_name from json_template_master where tbl_name = 'exam_results_summary' 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)); 
	begin
        start transaction;  
			set l_routine_block = 'before execute immediate'; 
			/* INSERT INTO proc_error_logs VALUES('1','l_insert_sql_str',l_insert_sql_str); */
			/* Individual Exam */
			if (in_exam_type = 'E') THEN  
				/* Update Existing Data with is_deleted=1 */
				if (is_first_json_array = '1') THEN  
					UPDATE exam_results_summary SET is_deleted = '1' 
						WHERE exam_type = in_exam_type
							AND exam_id = in_exam_id
							AND inst_id = in_inst_id 
							AND is_active = 1 
							AND is_deleted = 0; 
				end if;		
				
				
				/* Insert new data */
				call sp_execute_immediate (l_insert_sql_str);  
				
				
				/* Update Timestamps */
				if (is_last_json_array = '1') THEN  
					UPDATE exam_results_summary 
								SET  
									updated_by = in_created_by, 
									created_on = now(), 
									updated_on = now() 
							WHERE  
									exam_type = in_exam_type
								AND exam_id = in_exam_id
								AND inst_id = in_inst_id 
								AND is_active = 1 
								AND is_deleted = 0;  
								
					/* Change Exam Status */
					UPDATE exam_master 
						SET status = '92' ,
							updated_on = now()  
						WHERE exam_mst_id = in_exam_id
							AND inst_id = in_inst_id
							AND is_active = 1 
							AND is_deleted = 0; 
						
				end if;			
				
			/* Group Exam */			
			elseif (in_exam_type = 'G') THEN 
				/* Update Existing Data with is_deleted=1 */
				if (is_first_json_array = '1') THEN  
					UPDATE exam_results_summary SET is_deleted = '1' 
						WHERE exam_type = in_exam_type
							AND exam_id = in_exam_id
							AND inst_id = in_inst_id
							AND class_id = in_class_id
							AND is_active = 1 
							AND is_deleted = 0; 
				end if;		
				
				/* Insert new data */
				call sp_execute_immediate (l_insert_sql_str);  
				
				
				/* Update Timestamps */
				if (is_last_json_array = '1') THEN  
					UPDATE exam_results_summary 
								SET  
									updated_by = in_created_by, 
									created_on = now(), 
									updated_on = now(), 
									is_active = 1 , 
									is_deleted = 0
							WHERE   exam_type = in_exam_type
								AND exam_id = in_exam_id
								AND inst_id = in_inst_id
								AND class_id = in_class_id
								AND is_active = 1 
								AND is_deleted = 0;  
					/* Change Exam Status */
					UPDATE exam_group_summary set status='25' 
						WHERE 	inst_id=in_inst_id
							AND exam_grp_mst_id = in_exam_id
							AND group_type = 'CLS' 
							AND group_id = in_class_id ;   
				end if;		
			end if;  
        commit;
      end; 
	set out_err_code = l_err_code;
	set out_err_desc = l_err_desc; 
END$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_scores_final`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_scores_final`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_exam_mst_id` MEDIUMINT(8), IN `in_exam_dtl_id` MEDIUMINT(8), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
begin 
	declare l_routine_name varchar(50) default 'sp_ins_exam_score_details';
	declare l_routine_block varchar(15);
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_total_finished_exam_dtl_count int;
	declare l_total_exam_dtl_count int;
	/* Exception Handler Block */
	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; 
			/* Update exam_details tables for status */
			UPDATE exam_details SET status = '30' 
				WHERE exam_dtl_id = in_exam_dtl_id
					AND exam_mst_id = in_exam_mst_id
					AND inst_id = in_inst_id
					AND is_active = 1 
					AND is_deleted = 0; 
			/* Select total number of exam_dtl for a exam_master */		
			SELECT count(1) INTO l_total_exam_dtl_count FROM exam_details 
				WHERE exam_mst_id = in_exam_mst_id
					AND inst_id = in_inst_id 
					AND is_active = 1 
					AND is_deleted = 0; 
			/* Select total number of 'finished score entry' exam_dtl for a exam_master */				
			SELECT count(1) INTO l_total_finished_exam_dtl_count FROM exam_details 
				WHERE  exam_mst_id = in_exam_mst_id
					AND inst_id = in_inst_id
					AND status = '30' 
					AND is_active = 1 
					AND is_deleted = 0; 
			/*insert into proc_error_logs values ('l_total_exam_dtl_count','-',l_total_exam_dtl_count );	
				insert into proc_error_logs values ('l_total_finished_exam_dtl_count','-',l_total_finished_exam_dtl_count);	
				*/
			/* If scores for all exam_dtl_id are finished, update exam_master status to 90 */		
			if(l_total_exam_dtl_count = l_total_finished_exam_dtl_count )THEN
				UPDATE exam_master SET status = '90' 
					WHERE exam_mst_id = in_exam_mst_id
						AND inst_id = in_inst_id 
						AND is_active = 1 
						AND is_deleted = 0;  
			end if;  
    commit;
    set out_err_code = l_err_code; 
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_exam_score_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_exam_score_details_json`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_exam_mst_id` INT, IN `in_exam_dtl_id` INT, IN `in_insert_row_count` INT, IN `in_json_str` LONGTEXT, IN `in_is_group_score` CHAR(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_exam_score_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 LONGTEXT;
	declare l_json_str_len int;
	declare l_json_substr LONGTEXT;
	declare l_separator_idx int default 1;
	declare l_json_key_val_sep_len tinyint(1) default 3;
	declare l_template_col_name varchar(25);
	declare l_template_col_value text;
	declare l_looping_done int default false;
	declare l_insert_row_count INT;
	declare l_single_quot_const varchar(5) default '''';
	declare l_val_sep_const varchar(5) default ',';
	declare l_json_val_dbl_quot_const varchar(5) default '"';
	declare l_val_str_start char(1) default '(';
	declare l_val_str_end char(1) default ')';
	declare l_insert_sql_str LONGTEXT default 'insert into exam_score_details(
			ay_id,
			inst_id,
			exam_dtl_id,
			student_id,
			exam_marks,
			exam_points,
			exam_grade,
			gradset_dtl_id, 
			exam_remarks,
			exam_status,
			is_fail,
			created_by 
			) VALUES'; 
	declare l_insert_val_str_part LONGTEXT;
	declare l_insert_val_str_full LONGTEXT; 
	declare cur_json_template cursor for 
		select col_name from json_template_master where tbl_name = 'exam_score_details' order by col_pos; 
	declare continue handler for not found set l_looping_done = true; 
	declare exit handler for sqlexception 
		begin   
			rollback; 
			get diagnostics condition 1
			l_err_code = returned_sqlstate, l_err_desc = message_text; 
			insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code,err_desc, err_type, err_severity, created_by)  
			values (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc,'ERROR', 0, in_created_by); 
			set out_err_code = l_err_code;
			set out_err_desc = l_err_desc;
		end;
		set l_insert_row_count = in_insert_row_count;
		set l_json_str = trim(in_json_str);
		set l_json_str_len = length(l_json_str);
		set l_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 soft delete'; 
			/* IF Group Score - Swap Data */ 
			if (in_is_group_score = 'Y') then 
				update exam_score_details SET
					valid_to = now(), 
					updated_by = in_created_by,  
					updated_on = now(), 
					is_active = 1 ,
					is_deleted = 5
				where  
					inst_id = in_inst_id 
					and exam_dtl_id = in_exam_dtl_id 
					and is_active = 1 
					and is_deleted = 0
					and exam_status = 'B' ;  
			end if; 
			
			/* Update previous rows with is_deleted = 1 */
			update exam_score_details SET
				valid_to = now(), 
				updated_by = in_created_by,  
				updated_on = now(), 
				is_active = 1 ,
				is_deleted = 1
			where  
				inst_id = in_inst_id 
				and exam_dtl_id = in_exam_dtl_id 
				and is_active = 1 
				and is_deleted = 0; 
			set l_routine_block = 'before execute immediate';   
			call sp_execute_immediate (l_insert_sql_str);   
			
			/* Reset Group Exam Score */
			if (in_is_group_score = 'Y') then 
				update exam_score_details SET
					valid_to = now(), 
					updated_by = in_created_by,  
					updated_on = now(), 
					is_active = 1 ,
					is_deleted = 0
				where  
					inst_id = in_inst_id 
					and exam_dtl_id = in_exam_dtl_id 
					and is_active = 1 
					and is_deleted = 5
					and exam_status = 'B' ;  
			end if;  
			
			
			/* Update exam_master table and exam_details tables for status */
			UPDATE exam_details SET status = '20' 
				WHERE exam_dtl_id = in_exam_dtl_id
					AND exam_mst_id = in_exam_mst_id
					AND inst_id = in_inst_id
					AND is_active = 1 
					AND is_deleted = 0; 
			/* Update exam_master table and exam_details tables for status */
			UPDATE exam_master SET status = '80' 
				WHERE exam_mst_id = in_exam_mst_id
					AND inst_id = in_inst_id
					AND is_active = 1 
					AND is_deleted = 0; 		
		commit;  
	set out_err_code = l_err_code;  
	set out_err_desc = l_err_desc; 
END$$

DROP PROCEDURE IF EXISTS `sp_ins_facebook_post`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_facebook_post`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_facebook_user_id` BIGINT(20), IN `in_facebook_page_id` BIGINT(20), IN `in_app_id` BIGINT(20), IN `in_fb_app_secret` VARCHAR(100), IN `in_fb_default_graph_version` VARCHAR(100), IN `in_user_access_token` VARCHAR(300), IN `in_long_lived_access_token` VARCHAR(300), IN `in_token_update_date` DATE, IN `in_state` VARCHAR(100), IN `in_is_active` VARCHAR(20), IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_facebook_post';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare l_book_id mediumint(8);
 declare l_stage_id     mediumint(8);
 declare l_book_chpt_map_id mediumint(8);  
   
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

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

             insert into  social_post(ay_id,inst_id,facebook_user_id,facebook_page_id,app_id,fb_app_secret,fb_default_graph_version,user_access_token,
                          long_lived_access_token,state,is_active,created_by,updated_by)
                  values (in_ay_id,in_inst_id,in_facebook_user_id,in_facebook_page_id,in_app_id,in_fb_app_secret,in_fb_default_graph_version,in_user_access_token,
                         in_long_lived_access_token,in_state,in_is_active,in_created_by,in_updated_by);
           
                             
      end;
       
      when 'U' then    
       set l_routine_block = 'update';      
         begin  
                  update social_post 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 ;

             
            insert into social_post(ay_id,inst_id,facebook_user_id,facebook_page_id,app_id,fb_app_secret,fb_default_graph_version,user_access_token,
                          long_lived_access_token,token_update_date,state,is_active,created_by,updated_by)
                  values (in_ay_id,in_inst_id,in_facebook_user_id,in_facebook_page_id,in_app_id,in_fb_app_secret,in_fb_default_graph_version,in_user_access_token,
                         in_long_lived_access_token,in_token_update_date,in_state,in_is_active,in_created_by,in_updated_by);
           
     end;          
   end case;
   
   commit;
    set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_feedback_management_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_feedback_management_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_feedback_id` MEDIUMINT(8), IN `in_sender_user_type` VARCHAR(20), IN `in_feedback_from` VARCHAR(40), IN `in_feedback_date` DATE, IN `in_type` VARCHAR(20), IN `in_feedback_for` VARCHAR(20), IN `in_receiver_user_type` VARCHAR(20), IN `in_feedback_for_person` VARCHAR(40), IN `in_feedback_for_direct_person` VARCHAR(15), IN `in_rating` INT(11), IN `in_feedback_comment` VARCHAR(100), IN `in_status` 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, OUT `out_feedback_id` MEDIUMINT(8))
    NO SQL
begin

declare l_routine_name varchar(50) default 'sp_ins_feedback_management_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
declare l_routine_block varchar(15);
 declare l_feedback_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_feedback_id = fn_sequence_generator('FEEDBACK_MASTER');
         insert into  feedback_management_master(
                         ay_id,inst_id,feedback_id,sender_user_type,feedback_from,
                        feedback_date,type,feedback_for,receiver_user_type,feedback_for_person,feedback_for_direct_person,rating,
           status,feedback_comment,is_active,created_by,updated_by)  
           values(
                 in_ay_id,in_inst_id,l_feedback_id,in_sender_user_type,in_feedback_from,in_feedback_date,in_type,in_feedback_for,
                       in_receiver_user_type,in_feedback_for_person,in_feedback_for_direct_person,
              in_rating,in_status,
              in_feedback_comment,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_feedback_id = l_feedback_id;
  

end$$

DROP PROCEDURE IF EXISTS `sp_ins_feedback_reply_detail`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_feedback_reply_detail`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_feedback_id` MEDIUMINT(8), IN `in_reply_from` VARCHAR(20), IN `in_reply_user_type` VARCHAR(20), IN `in_reply_date` DATE, IN `in_reply` VARCHAR(1000), 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_feedback_management_detail';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
declare l_routine_block varchar(15);
 declare l_feedback_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';
                   insert into  feedback_reply_detail(
                         ay_id,inst_id,feedback_id,reply_from,reply_user_type,reply_date,
                        reply,is_active,created_by,updated_by)  
           values(
                 in_ay_id,in_inst_id,in_feedback_id,in_reply_from,in_reply_user_type,in_reply_date,
                 in_reply,
                 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_fee_quick_structure_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_fee_quick_structure_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_fin_acct_id` SMALLINT(5), IN `in_fee_struct_mst_id` MEDIUMINT(8), IN `in_shift_type` ENUM('MORNING','AFTERNOON','EVENING'), IN `in_fee_linkage_type` ENUM('SCH','ADH','STD','CLS','GRP'), IN `in_fee_linkage_id` VARCHAR(25), IN `in_fee_pmt_term` VARCHAR(25), IN `in_fee_term_num` TINYINT(2), IN `in_fee_date_from` DATE, IN `in_fee_date_to` DATE, IN `in_fee_due_date` DATE, IN `in_fee_grace_period` TINYINT(3), IN `in_fee_struct_name` VARCHAR(50), IN `in_fee_struct_desc` VARCHAR(50), IN `in_fee_struct_abbr` VARCHAR(10), IN `in_fee_struct_status` VARCHAR(25), IN `in_installment_count` TINYINT(2), IN `in_is_stud_cat_based` TINYINT(1), IN `in_fee_amt` DECIMAL(12,2), IN `in_tax_amt` DOUBLE(12,2), IN `in_fee_options` VARCHAR(100), IN `in_fee_display_name` VARCHAR(100), IN `in_auto_reminder` TINYINT(3), IN `in_reminder_options` VARCHAR(50), IN `in_created_by` VARCHAR(20), IN `in_copy_details` TINYINT(1), OUT `out_fee_struct_mst_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_fee_structure_master';
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_routine_block varchar(15);
	declare l_fee_struct_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_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_fee_struct_mst_id = fn_sequence_generator('FEE_STRUCTURE_MASTER');
            insert into fee_structure_master(ay_id, inst_id, fin_acct_id, fee_struct_mst_id, shift_type,
              group_type, group_id, fee_pmt_term, fee_term_num, 
              fee_date_from, fee_date_to,fee_due_date, fee_grace_period ,fee_struct_name,fee_struct_desc,fee_struct_abbr, 
              is_installment_based, installment_count, is_stud_cat_based,fee_amt,tax_amt,status,status_desc,fee_options,fee_display_name,auto_reminder,reminder_options,created_by, updated_by) 
            values (in_ay_id, in_inst_id, in_fin_acct_id, l_fee_struct_mst_id, in_shift_type,
				in_fee_linkage_type, in_fee_linkage_id, in_fee_pmt_term, in_fee_term_num, 
				in_fee_date_from, in_fee_date_to,in_fee_due_date, in_fee_grace_period,in_fee_struct_name,in_fee_struct_desc,in_fee_struct_abbr,
			    '1',in_installment_count,in_is_stud_cat_based,in_fee_amt,in_tax_amt, in_fee_struct_status,'', in_fee_options, in_fee_display_name,in_auto_reminder,in_reminder_options,in_created_by, in_created_by);
          end;    
		/* Duplicate Stucture Master and Details data */  
        when 'C' then
          begin
            set l_routine_block = 'duplicate';
			      set l_fee_struct_mst_id = fn_sequence_generator('FEE_STRUCTURE_MASTER');
			insert into fee_structure_master(ay_id, inst_id, fin_acct_id, fee_struct_mst_id, shift_type,
              group_type, group_id, fee_pmt_term, fee_term_num, 
              fee_date_from, fee_date_to,fee_due_date, fee_grace_period ,fee_struct_name,fee_struct_desc,fee_struct_abbr, 
              is_installment_based, installment_count, is_stud_cat_based,fee_amt,tax_amt,status,status_desc,fee_options,fee_display_name,auto_reminder,reminder_options,created_by, updated_by) 
            values (in_ay_id, in_inst_id, in_fin_acct_id, l_fee_struct_mst_id, in_shift_type,
				in_fee_linkage_type, in_fee_linkage_id, in_fee_pmt_term, in_fee_term_num, 
				in_fee_date_from, in_fee_date_to,in_fee_due_date, in_fee_grace_period,in_fee_struct_name,in_fee_struct_desc,in_fee_struct_abbr,
			    '1',in_installment_count,in_is_stud_cat_based,in_fee_amt,in_tax_amt, in_fee_struct_status,'', in_fee_options, in_fee_display_name,in_auto_reminder,in_reminder_options,in_created_by, in_created_by);
			SET @selectInsert = CONCAT_WS("" , "insert into fee_structure_details(
				ay_id,inst_id,
				fee_struct_mst_id,fee_struct_dtl_id,acct_head_id, student_cat_id,
				fee_date_from,fee_date_to,fee_due_date,fee_grace_period,installment_name,installment_num,
				fee_amt,disc_type,disc_name,disc_desc,disc_abbr,disc_rate,disc_amt,
				net_fee_amt,tax_amt,total_fee_amt,
				valid_from,valid_to,created_by, updated_by, is_active,is_deleted) 
				SELECT ay_id,inst_id,", l_fee_struct_mst_id, " as fee_struct_mst_id,fee_struct_dtl_id,acct_head_id,student_cat_id,
				fee_date_from,fee_date_to,fee_due_date,fee_grace_period,installment_name,installment_num,
				fee_amt,disc_type,disc_name,disc_desc,disc_abbr,disc_rate,disc_amt,
				net_fee_amt,tax_amt,total_fee_amt,
				valid_from,valid_to,", in_created_by, " as created_by,", in_created_by , " as updated_by,'1' as is_active,'0' as is_deleted 
				from fee_structure_details 
				where fee_struct_mst_id = '", in_fee_struct_mst_id , "' and is_active = 1 and is_deleted = 0 and inst_id = '",in_inst_id, "'" );
			PREPARE stmt FROM @selectInsert;  
			EXECUTE stmt; 
          end;   
  	    when 'U' then
          set l_routine_block = 'update'; 
          begin
          	update fee_structure_master set  is_deleted = 1 ,  valid_to = NOW(), updated_by = in_created_by, updated_on = NOW()
            where fee_struct_mst_id = in_fee_struct_mst_id and is_deleted = "0" and ay_id = in_ay_id 
            	and inst_id = in_inst_id; 
            insert into fee_structure_master(ay_id, inst_id, fin_acct_id, fee_struct_mst_id,shift_type,
              group_type, group_id, fee_pmt_term, fee_term_num, 
              fee_date_from, fee_date_to,fee_due_date, fee_grace_period ,fee_struct_name,fee_struct_desc,fee_struct_abbr,
              is_installment_based, installment_count, is_stud_cat_based,fee_amt,tax_amt,status,status_desc,fee_options,fee_display_name,auto_reminder,reminder_options,created_by, updated_by) 
            values (in_ay_id, in_inst_id, in_fin_acct_id, in_fee_struct_mst_id, in_shift_type,
				in_fee_linkage_type, in_fee_linkage_id, in_fee_pmt_term, in_fee_term_num, 
				in_fee_date_from, in_fee_date_to,in_fee_due_date, in_fee_grace_period,in_fee_struct_name,in_fee_struct_desc,in_fee_struct_abbr,
			    '1',in_installment_count,in_is_stud_cat_based,in_fee_amt,in_tax_amt,in_fee_struct_status, '', in_fee_options, in_fee_display_name,in_auto_reminder,in_reminder_options,in_created_by, in_created_by); 
          end;    
		ELSE 
			BEGIN 
			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); 
			END;  		  
      end case; 
    commit;
	set out_fee_struct_mst_id = l_fee_struct_mst_id;
    set out_err_code = l_err_code; 
    set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_fee_structure_details_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_fee_structure_details_json`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_fee_struct_mst_id` CHAR(25), IN `in_fee_type_id` CHAR(25), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_fee_structure_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 fee_structure_details ( 
												ay_id,
												inst_id, 
												fee_struct_mst_id, 
												fee_struct_dtl_id,
												acct_head_id, 
												student_cat_id, 
												fee_date_from,
												fee_date_to,
												fee_due_date,
												fee_grace_period,
												installment_name,
												installment_num, 
												fee_amt ,
												disc_type, 
												disc_name, 
												disc_desc,
												disc_abbr,
												disc_rate, 
												disc_amt,
												net_fee_amt,
												tax_amt, 
												total_fee_amt,
												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 = 'fee_structure_details' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
	  begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
	while (l_insert_row_count > 0) do
		set l_routine_block = 'inside while loop'; 
		set l_insert_val_str_part = '';
		open cur_json_template;
		cursor_loop: loop
			fetch cur_json_template into l_template_col_name;
			if l_looping_done then
			  leave cursor_loop;
			end if;
			set l_separator_idx = instr(l_json_str, l_template_col_name) +  length(l_template_col_name) + l_json_key_val_sep_len; 
			set l_json_substr = substring(l_json_str, l_separator_idx, l_json_str_len);      
			set l_separator_idx = instr(l_json_substr, l_json_val_dbl_quot_const);
			if (l_template_col_name = 'fee_struct_dtl_id') THEN
				begin  
					set l_template_col_value = fn_sequence_generator('FEE_STRUCTURE_DETAILS'); 
				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;
	  /* insert into proc_error_logs values(l_val_str_start,l_insert_val_str_part,l_insert_val_str_full); */
  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 soft delete';
    update fee_structure_details set valid_to = now() , updated_by = in_created_by,
      updated_on = now(), is_active = 1 , is_deleted = 1 
      where  is_active = 1 and is_deleted = 0
  				and inst_id = in_inst_id 
  				and fee_struct_mst_id=in_fee_struct_mst_id  ;
    set l_routine_block = 'before execute immediate';
		  /* insert into proc_error_logs values(l_val_str_start,l_insert_val_str_part,l_insert_sql_str); */
    call sp_execute_immediate (l_insert_sql_str);        
	/*	Change Fee Struct Status = 1 ("Fee Component Added") */ 
	update fee_structure_master set status = 1 
      where  is_active = 1 and is_deleted = 0
  				and inst_id = in_inst_id 
  				and fee_struct_mst_id=in_fee_struct_mst_id  ;
  commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_fee_structure_details_new`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_fee_structure_details_new`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_fee_struct_id` INT, 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_fee_structure_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_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 fee_structure_details(ay_id, inst_id, fee_struct_id, fee_type_id, student_cat_id, fee_date_from, fee_date_to, fee_due_date, fee_grace_period, installment_freq, installment_num, gross_fee_amt, disc_type, disc_name, disc_desc, disc_abbr, disc_rate, disc_amt, net_fee_amt, net_tax_amt) 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 = 'fee_structure_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);
      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 sp_error_log (routine_name, label_name, sql_log)
  #values(l_routine_name, 'Before Close Cursor', l_insert_sql_str);
  start transaction;  
    set l_routine_block = 'before soft delete';
    update fee_structure_details set valid_to = now(), updated_by = in_created_by, 
      updated_on = now(), is_active = 0 
    where ay_id = in_ay_id and inst_id = in_inst_id and fee_struct_id = in_fee_struct_id
      and is_active = 1;
    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_fee_structure_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_fee_structure_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_fin_acct_id` SMALLINT(5), IN `in_fee_struct_mst_id` MEDIUMINT(8), IN `in_shift_type` ENUM('MORNING','AFTERNOON','EVENING'), IN `in_fee_linkage_type` ENUM('SCH','ADH','STD','CLS','GRP'), IN `in_fee_linkage_id` VARCHAR(25), IN `in_fee_pmt_term` VARCHAR(25), IN `in_fee_term_num` TINYINT(2), IN `in_fee_date_from` DATE, IN `in_fee_date_to` DATE, IN `in_fee_due_date` DATE, IN `in_fee_grace_period` TINYINT(3), IN `in_fee_struct_name` VARCHAR(50), IN `in_fee_struct_desc` VARCHAR(50), IN `in_fee_struct_abbr` VARCHAR(10), IN `in_fee_struct_status` VARCHAR(25), IN `in_installment_count` TINYINT(2), IN `in_is_stud_cat_based` TINYINT(1), IN `in_fee_amt` DECIMAL(12,2), IN `in_tax_amt` DOUBLE(12,2), IN `in_fee_options` VARCHAR(100), IN `in_fee_display_name` VARCHAR(100), IN `in_auto_reminder` TINYINT(3), IN `in_reminder_options` VARCHAR(50), IN `in_created_by` VARCHAR(20), IN `in_copy_details` 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_fee_structure_master';
	declare l_err_code char(5) default '00000';
	declare l_err_desc text default '';    	
	declare l_routine_block varchar(15);
	declare l_fee_struct_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_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_fee_struct_mst_id = fn_sequence_generator('FEE_STRUCTURE_MASTER');
            insert into fee_structure_master(ay_id, inst_id, fin_acct_id, fee_struct_mst_id, shift_type,
              group_type, group_id, fee_pmt_term, fee_term_num, 
              fee_date_from, fee_date_to,fee_due_date, fee_grace_period ,fee_struct_name,fee_struct_desc,fee_struct_abbr, 
              is_installment_based, installment_count, is_stud_cat_based,fee_amt,tax_amt,status,status_desc,fee_options,fee_display_name,auto_reminder,reminder_options,created_by, updated_by) 
            values (in_ay_id, in_inst_id, in_fin_acct_id, l_fee_struct_mst_id, in_shift_type,
				in_fee_linkage_type, in_fee_linkage_id, in_fee_pmt_term, in_fee_term_num, 
				in_fee_date_from, in_fee_date_to,in_fee_due_date, in_fee_grace_period,in_fee_struct_name,in_fee_struct_desc,in_fee_struct_abbr,
			    '1',in_installment_count,in_is_stud_cat_based,in_fee_amt,in_tax_amt, in_fee_struct_status,'', in_fee_options, in_fee_display_name,in_auto_reminder,in_reminder_options,in_created_by, in_created_by);
          end;    
		/* Duplicate Stucture Master and Details data */  
        when 'C' then
          begin
            set l_routine_block = 'duplicate';
			      set l_fee_struct_mst_id = fn_sequence_generator('FEE_STRUCTURE_MASTER');
			insert into fee_structure_master(ay_id, inst_id, fin_acct_id, fee_struct_mst_id, shift_type,
              group_type, group_id, fee_pmt_term, fee_term_num, 
              fee_date_from, fee_date_to,fee_due_date, fee_grace_period ,fee_struct_name,fee_struct_desc,fee_struct_abbr, 
              is_installment_based, installment_count, is_stud_cat_based,fee_amt,tax_amt,status,status_desc,fee_options,fee_display_name,auto_reminder,reminder_options,created_by, updated_by) 
            values (in_ay_id, in_inst_id, in_fin_acct_id, l_fee_struct_mst_id, in_shift_type,
				in_fee_linkage_type, in_fee_linkage_id, in_fee_pmt_term, in_fee_term_num, 
				in_fee_date_from, in_fee_date_to,in_fee_due_date, in_fee_grace_period,in_fee_struct_name,in_fee_struct_desc,in_fee_struct_abbr,
			    '1',in_installment_count,in_is_stud_cat_based,in_fee_amt,in_tax_amt, in_fee_struct_status,'', in_fee_options, in_fee_display_name,in_auto_reminder,in_reminder_options,in_created_by, in_created_by);
			SET @selectInsert = CONCAT_WS("" , "insert into fee_structure_details(
				ay_id,inst_id,
				fee_struct_mst_id,fee_struct_dtl_id,acct_head_id, student_cat_id,
				fee_date_from,fee_date_to,fee_due_date,fee_grace_period,installment_name,installment_num,
				fee_amt,disc_type,disc_name,disc_desc,disc_abbr,disc_rate,disc_amt,
				net_fee_amt,tax_amt,total_fee_amt,
				valid_from,valid_to,created_by, updated_by, is_active,is_deleted) 
				SELECT ay_id,inst_id,", l_fee_struct_mst_id, " as fee_struct_mst_id,fee_struct_dtl_id,acct_head_id,student_cat_id,
				fee_date_from,fee_date_to,fee_due_date,fee_grace_period,installment_name,installment_num,
				fee_amt,disc_type,disc_name,disc_desc,disc_abbr,disc_rate,disc_amt,
				net_fee_amt,tax_amt,total_fee_amt,
				valid_from,valid_to,", in_created_by, " as created_by,", in_created_by , " as updated_by,'1' as is_active,'0' as is_deleted 
				from fee_structure_details 
				where fee_struct_mst_id = '", in_fee_struct_mst_id , "' and is_active = 1 and is_deleted = 0 and inst_id = '",in_inst_id, "'" );
			PREPARE stmt FROM @selectInsert;  
			EXECUTE stmt; 
          end;   
  	    when 'U' then
          set l_routine_block = 'update'; 
          begin
          	update fee_structure_master set  is_deleted = 1 ,  valid_to = NOW(), updated_by = in_created_by, updated_on = NOW()
            where fee_struct_mst_id = in_fee_struct_mst_id and is_deleted = "0" and ay_id = in_ay_id 
            	and inst_id = in_inst_id; 
            insert into fee_structure_master(ay_id, inst_id, fin_acct_id, fee_struct_mst_id,shift_type,
              group_type, group_id, fee_pmt_term, fee_term_num, 
              fee_date_from, fee_date_to,fee_due_date, fee_grace_period ,fee_struct_name,fee_struct_desc,fee_struct_abbr,
              is_installment_based, installment_count, is_stud_cat_based,fee_amt,tax_amt,status,status_desc,fee_options,fee_display_name,auto_reminder,reminder_options,created_by, updated_by) 
            values (in_ay_id, in_inst_id, in_fin_acct_id, in_fee_struct_mst_id, in_shift_type,
				in_fee_linkage_type, in_fee_linkage_id, in_fee_pmt_term, in_fee_term_num, 
				in_fee_date_from, in_fee_date_to,in_fee_due_date, in_fee_grace_period,in_fee_struct_name,in_fee_struct_desc,in_fee_struct_abbr,
			    '1',in_installment_count,in_is_stud_cat_based,in_fee_amt,in_tax_amt,in_fee_struct_status, '', in_fee_options, in_fee_display_name,in_auto_reminder,in_reminder_options,in_created_by, in_created_by); 
          end;    
		ELSE 
			BEGIN 
			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); 
			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_file_uploads`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_file_uploads`(IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_file_upload_id` MEDIUMINT(8), IN `in_file_category` VARCHAR(200), IN `in_file_name` VARCHAR(200), IN `in_file_type` VARCHAR(20), IN `in_file_size` VARCHAR(20), IN `in_file_path` VARCHAR(200), IN `in_original_file_name` VARCHAR(200), IN `in_thumbnail_name` VARCHAR(200), IN `in_thumbnail_path` VARCHAR(200), IN `in_ip_address` VARCHAR(15), IN `in_description` VARCHAR(20), IN `short_url` VARCHAR(200), IN `in_created_by` VARCHAR(20), OUT `out_file_upload_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_file_uploads';
  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_fileupload_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;
          begin
           set l_routine_block = 'insert';
			  set l_fileupload_id = fn_sequence_generator('FILE_UPLOAD_MASTER');
          insert into  file_uploads (ay_id ,inst_id ,file_upload_id ,file_category ,file_name ,file_type ,
            file_size ,file_path ,original_file_name ,thumbnail_name ,thumbnail_path ,ip_address ,description ,
            short_url, created_by ,updated_by ) 	 						
            values(in_ay_id , in_inst_id , l_fileupload_id , in_file_category , in_file_name , 
            in_file_type , in_file_size , in_file_path , in_original_file_name , in_thumbnail_name ,
            in_thumbnail_path , in_ip_address , in_description ,short_url, in_created_by , in_created_by );
          end;    
    commit;
	 set out_err_code = l_err_code;
    set out_err_desc = l_err_desc;
   set out_file_upload_id= l_fileupload_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_file_upload_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_file_upload_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_file_upload_id` VARCHAR(25), IN `in_class_id` VARCHAR(25), IN `in_file_name` VARCHAR(25), IN `in_file_type` VARCHAR(25), IN `in_upload_path` VARCHAR(25), IN `in_uploaded_by` VARCHAR(25), IN `in_upload_date` VARCHAR(25), IN `in_upload_status` VARCHAR(25), IN `in_upload_comments` 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_file_upload_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
            set l_routine_block = 'insert';
          insert into  file_upload_details(ay_id, inst_id,file_upload_id,class_id,file_name, 
               	file_type,upload_path,uploaded_by,upload_date,upload_status,upload_comments,is_active,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_file_upload_id, in_class_id,in_file_name, 
              in_file_type,in_upload_path ,	in_uploaded_by,in_upload_date,in_upload_status,in_upload_comments ,in_is_active,in_created_by, in_created_by);
          end;    
  	    when 'U' then
            set l_routine_block = 'update';      
          begin
          	update  file_upload_details set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_deleted = 1 
            where file_upload_id = in_file_upload_id and class_id=in_class_id and is_deleted = 0 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
           insert into  file_upload_details(ay_id, inst_id,file_upload_id,class_id,file_name, 
               	file_type,upload_path,uploaded_by,upload_date,upload_status,upload_comments,is_active,created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, in_file_upload_id, in_class_id,in_file_name, 
              in_file_type,in_upload_path ,	in_uploaded_by,in_upload_date,in_upload_status,in_upload_comments ,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_finance_debit_demand_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_finance_debit_demand_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_fin_acct_id` MEDIUMINT(8), IN `in_debit_demand_mst_id` MEDIUMINT(8), IN `in_debit_demand_grp_id` MEDIUMINT(8), IN `in_exp_name` VARCHAR(50), IN `in_exp_type` VARCHAR(50), IN `in_exp_desc` VARCHAR(100), IN `in_party_type` VARCHAR(50), IN `in_party_id` MEDIUMINT(8), IN `in_party_name` VARCHAR(50), IN `in_gen_date` DATE, IN `in_total_amt_paid` DOUBLE(10,2), IN `in_acct_head_id` SMALLINT(5), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_status` VARCHAR(20), IN `in_status_desc` VARCHAR(50), IN `in_is_bill_pending` TINYINT(1), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_debit_demand_mst_id` MEDIUMINT(8), OUT `out_debit_demand_grp_id` MEDIUMINT(8))
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_finance_debit_demand_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_debit_demand_mst_id mediumint(8);
 declare l_debit_demand_grp_id mediumint(8);
 declare l_looping_done int default false;
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
            set l_debit_demand_mst_id = fn_sequence_generator('FIN_DEBIT_DEMAND_MASTER');
            set l_debit_demand_grp_id = fn_sequence_generator('FIN_DEBIT_DEMAND_GROUP');
            set l_routine_block = 'insert';
       
           insert into fin_debit_demand_master (ay_id,inst_id,fin_acct_id,
                       debit_demand_mst_id,debit_demand_grp_id,exp_name,exp_type,exp_desc,
                       party_type,party_id,party_name,acct_head_id,gen_date,
                       amt_payble,is_active,created_by,updated_by,status,status_desc,is_bill_pending) 
                                        
           values(in_ay_id,in_inst_id,in_fin_acct_id,
                 l_debit_demand_mst_id,l_debit_demand_grp_id,in_exp_name,in_exp_type,
                 in_exp_desc,in_party_type,in_party_id,in_party_name,in_acct_head_id,
                 in_gen_date,in_total_amt_paid,in_is_active,in_created_by, in_created_by,
                 in_status,in_status_desc,in_is_bill_pending);
             
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update  fin_account_heads_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where acc_head_mst_id = in_acc_head_mst_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

            insert into   fin_account_heads_master (ay_id, inst_id,acc_head_mst_id,
                   account_head_name,account_head_type,parent,is_default_transcation,
                   is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,in_acc_head_mst_id,in_account_head_name,
                 in_account_head_type,in_parent,in_is_default_transcation,
                 in_is_active,in_created_by, in_created_by);
        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_debit_demand_mst_id = l_debit_demand_mst_id;
  set out_debit_demand_grp_id = l_debit_demand_grp_id;

end$$

DROP PROCEDURE IF EXISTS `sp_ins_fin_store_debit_direct_payment`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_fin_store_debit_direct_payment`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_file_upload_id` MEDIUMINT(8), IN `in_fin_acct_id` MEDIUMINT(8), IN `in_debit_mst_id` MEDIUMINT(8), IN `in_debit_dtl_id` MEDIUMINT(8), IN `in_debit_demand_mst_id` MEDIUMINT(8), IN `in_debit_demand_grp_id` MEDIUMINT(8), IN `in_fin_receipt` VARCHAR(100), IN `in_exp_name` VARCHAR(50), IN `in_exp_type` VARCHAR(50), IN `in_exp_desc` VARCHAR(100), IN `in_party_id` MEDIUMINT(8), IN `in_party_type` VARCHAR(50), IN `in_party_name` VARCHAR(50), IN `in_pmt_date` DATE, IN `in_total_pmt_amt` DOUBLE(10,2), IN `in_pmt_mode` VARCHAR(15), IN `in_pmt_mode_desc` VARCHAR(50), IN `in_pmt_instru_num` VARCHAR(20), IN `in_pmt_instru_bank` VARCHAR(50), IN `in_pmt_instru_branch` VARCHAR(50), IN `in_sequence_entity_mode` VARCHAR(10), IN `in_sequence_entity_id` VARCHAR(30), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_status` VARCHAR(25), IN `in_status_desc` VARCHAR(50), IN `in_is_bill_pending` TINYINT(1), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_debit_mst_id` MEDIUMINT(8))
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_fin_store_debit_direct_payment';
 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_debit_mst_id mediumint(8);
 declare l_debit_dtl_id mediumint(8);
 declare l_debit_demand_grp_id mediumint(8);
 declare l_fin_receipt_num varchar(100);
 declare l_looping_done int default false;
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
           
            set l_routine_block = 'insert';
       
       set l_fin_receipt_num =in_fin_receipt;
          IF ( in_sequence_entity_mode='AUTO' AND length(trim(in_fin_receipt)) = '' ) THEN 
					    call sp_custom_seq_generator(in_inst_id,in_sequence_entity_id,in_ay_id,in_created_by,l_fin_receipt_num) ;
             IF length(trim(l_fin_receipt_num)) = 0 THEN
					     SIGNAL SQLSTATE '10012' 
					   SET MESSAGE_TEXT = 'An error occurred while generating expense receipt number';
             END IF;
	        END IF;

        set l_debit_mst_id = fn_sequence_generator('FIN_DEBIT_MASTER');
           
        insert into fin_debit_master (ay_id,inst_id,file_upload_id,fin_acct_id,
                       debit_mst_id,debit_demand_grp_id,fin_receipt,exp_name,exp_type,
                       exp_desc,party_id,party_type,party_name,pmt_date,
                       total_pmt_amt,pmt_mode,pmt_mode_desc,pmt_instru_num,
                       pmt_instru_bank,pmt_instru_branch,is_active,created_by,updated_by,
                       status,status_desc,is_bill_pending) 
                                        
           values(in_ay_id,in_inst_id,in_file_upload_id,in_fin_acct_id,l_debit_mst_id,
                  in_debit_demand_grp_id,l_fin_receipt_num,in_exp_name,in_exp_type,
                  in_exp_desc,in_party_id,in_party_type,in_party_name,in_pmt_date,
                  in_total_pmt_amt,
                  in_pmt_mode,in_pmt_mode_desc,in_pmt_instru_num,in_pmt_instru_bank,
                  in_pmt_instru_branch,in_is_active,in_created_by,in_created_by,
                 in_status,in_status_desc,in_is_bill_pending);

          set l_debit_dtl_id = fn_sequence_generator('FIN_DEBIT_DETAILS');
             
          insert into fin_debit_details (ay_id,inst_id,fin_acct_id,debit_dtl_id,
                      debit_mst_id,debit_demand_mst_id,debit_demand_grp_id,exp_desc,
                       total_pmt_amt,is_active,created_by,updated_by) 
                                        
           values(in_ay_id,in_inst_id,in_fin_acct_id,l_debit_dtl_id,
                l_debit_mst_id,in_debit_demand_mst_id,in_debit_demand_grp_id,in_exp_desc,
                in_total_pmt_amt,in_is_active,in_created_by, in_created_by);
      end;    
 
       when 'U' then   
       set l_routine_block = 'update';
         begin
        
             update  fin_account_heads_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where acc_head_mst_id = in_acc_head_mst_id  and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;

            insert into   fin_account_heads_master (ay_id, inst_id,acc_head_mst_id,
                   account_head_name,account_head_type,parent,is_default_transcation,
                   is_active,created_by,updated_by) 
                                        
           values(in_ay_id, in_inst_id,in_acc_head_mst_id,in_account_head_name,
                 in_account_head_type,in_parent,in_is_default_transcation,
                 in_is_active,in_created_by, in_created_by);
        end; 
         
     end case;
   
   commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  set out_debit_mst_id = l_debit_mst_id;
 
end$$

DROP PROCEDURE IF EXISTS `sp_ins_free_trial_setup_new_institute`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_free_trial_setup_new_institute`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_user_id` MEDIUMINT(8), IN `in_inst_abbr` VARCHAR(10), IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), 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_emp_num_gen_mode` VARCHAR(10), IN `in_emp_num` VARCHAR(50), IN `in_emp_status` 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_free_trial_setup_new_institute';
	 declare l_err_code char(5) default '00000';
	 declare l_err_desc text default '';    	
	 declare l_routine_block varchar(15);
   declare l_emp_id mediumint(8);
   declare l_emp_num varchar(50);
	 declare t_emp_num varchar(50);
   declare l_looping_done int default false;
   declare l_looping_sub_done int default false;
   declare l_looping_div_done int default false;
   declare l_looping_class_done int default false;
   declare l_looping_sub_teacher_done int default false;
   declare l_looping_user_done int default false;
   declare l_looping_libraryModule_user_done int default false;
   declare l_id mediumint(8);

   declare l_salutation varchar(50);
   declare l_first_name varchar(50);
   declare l_last_name varchar(50);
   declare l_gender varchar(50);
   declare l_mobile_phone_1 varchar(50);
   declare l_emp_category varchar(25);
   declare l_sub_id mediumint(8);
   declare l_subject_id mediumint(8);
   declare l_subject_name varchar(50); 
   declare l_std_id char(2); 
   declare l_std_name varchar(25); 
   declare l_division_id 	char(1);
   declare l_subject_standard_map_id mediumint(8);
   declare l_sub_struct_map_id mediumint(8);
   declare l_standard_id char(2);
   declare l_div_id char(1);
   declare l_class_id char(8);
   declare l_employee_id mediumint(8);
   declare l_class_name varchar(30); 
   declare l_standard_division_map_id mediumint(8);
   declare l_emp_subject_map_id mediumint(8);
   declare l_teacher_class_id char(8);

   declare l_teacher_std_id char(2);
   declare l_teacher_div_id char(1);
   declare l_teacher_sub_new_id mediumint(8);
   declare l_teacher_emp_id mediumint(8);
   declare l_teacher_subject_id mediumint(8);
   declare l_emp_sub_map_emp_id mediumint(8);
   declare l_teacher_sub_std_id mediumint(8);
   declare l_emp_role  varchar(25);
   declare l_su_userID mediumint(8);
   declare l_division_master_id char(1);
   declare l_gradeset_id smallint(5);
   declare l_inst_second_admin mediumint(8);
   declare l_sub_strct_ID_new mediumint(8);
  
   declare l_is_active tinyint(1) default 0;
   declare l_inst_id mediumint(8);
   declare l_user_inst_id mediumint(8);

   declare l_param_inst_id mediumint(8);
   declare l_sms_credit_balance bigint(50);
   declare l_new_sms_credit_balance bigint(50);
   declare l_vidyalekha_sms_credit_balance bigint(50);
   declare l_sms_credit_id mediumint(8);
   declare l_rate bigint(30);

  declare l_userType varchar(10); 
  declare l_userId mediumint(8); 
  declare l_user_id mediumint(8); 
  declare l_standard_name  varchar(25);
  declare l_standard_desc varchar(50);
  declare l_standard_abbr varchar(10);
   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_name, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_dml_mode 
        
      when 'I' then
        begin
        set l_routine_block = 'insert';

              select is_active into l_is_active
                  from institution_master
                  where inst_id = in_inst_id 
                  and is_deleted = 0 ;  
         
            if (l_is_active = 1) then

            DELETE FROM appl_txn_master 
            WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO appl_txn_master(ay_id, inst_id, txn_id, parent_id, txn_type, txn_name,
                    txn_abbr, route_url, icon_class, txn_desc, txn_lvl, txn_seq, is_menu_txn, is_blacked_out,
					          created_by,updated_by,is_active)
                  select '', in_inst_id, txn_id, parent_id, txn_type, txn_name,
                    txn_abbr, route_url, icon_class, txn_desc, txn_lvl, txn_seq, is_menu_txn, is_blacked_out,
					          in_created_by,in_created_by,is_active
                  from appl_txn_master where ay_id = '*******' and inst_id = 0
                    and is_deleted = 0 and is_active=1;

            DELETE FROM appl_data_master 
            WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

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

            DELETE FROM role_master 
            WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

               INSERT INTO role_master(ay_id, inst_id, role_id ,role_type, parent_id, role_level,
               role_name, role_display_name, role_desc, role_abbr,is_default,inst_alerts_allowed, created_by, updated_by)
                 select in_ay_id, in_inst_id, role_id ,role_type, parent_id, role_level,
               role_name, role_display_name, role_desc, role_abbr, is_default,inst_alerts_allowed, in_created_by, in_created_by
                 from role_master where ay_id = '*******' and inst_id = 0
                    and is_deleted = 0 and is_active=1;
  
            DELETE FROM role_txn_map 
            WHERE inst_id=in_inst_id and is_active=1 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 '', in_inst_id, role_id, txn_id, is_txn_allowed, is_create_allowed,
                is_read_allowed, is_update_allowed, is_delete_allowed, create_auth_type, update_auth_type, 
                delete_auth_type, in_created_by, in_created_by
                  from role_txn_map where ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;

            DELETE FROM notification_config 
            WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

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

            DELETE FROM notif_app_template_master 
            WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

               INSERT INTO notif_app_template_master(app_template_id, ay_id, inst_id, push_message, push_title, push_subtitle,
                push_vibrate, push_sound, push_large_icon, push_small_icon, push_registration_id, push_params, push_opt1, 
                push_opt2, recipient_type, created_by, updated_by)
                  select app_template_id, '', in_inst_id,push_message, push_title, push_subtitle,
                push_vibrate, push_sound, push_large_icon, push_small_icon, push_registration_id, push_params, push_opt1, 
                push_opt2, recipient_type, in_created_by, in_created_by
                  from notif_app_template_master where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;

           DELETE FROM notif_web_template_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

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

           DELETE FROM notif_email_template_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

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

              
           DELETE FROM notif_sms_template_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO notif_sms_template_master(sms_template_id, ay_id, inst_id, sms_from_mobile_no, sms_body, sms_params, sms_opt1, sms_opt2,
                recipient_type, created_by, updated_by)
                  select sms_template_id, '', in_inst_id,sms_from_mobile_no, sms_body, sms_params, sms_opt1, sms_opt2,
                recipient_type, in_created_by, in_created_by
                  from notif_sms_template_master where ay_id = '*******' and inst_id = 0 
                       and is_deleted = 0 and is_active=1;

           DELETE FROM gradeset_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

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

           DELETE FROM gradeset_details 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

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

           DELETE FROM account_head_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO account_head_master(ay_id, inst_id, acct_head_id ,parent_id, acct_head_level,
               acct_head_category, acct_head_type, acct_head_name , acct_head_display_name,acct_head_desc,
                acct_head_abbr,is_system_def, is_discountable, is_waivable, is_taxable, created_by, updated_by)
                  select in_ay_id, in_inst_id, acct_head_id ,parent_id, acct_head_level,
               acct_head_category, acct_head_type, acct_head_name , acct_head_display_name,acct_head_desc,
                acct_head_abbr,is_system_def, is_discountable, is_waivable, is_taxable, in_created_by,
                    in_created_by
                  from account_head_master where ay_id = '*******' and inst_id = 0
                       and is_deleted = 0 and is_active=1;

           DELETE FROM event_calendar_category 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO event_calendar_category(inst_id, event_cat, cat_name, cat_icon, cat_class, cat_order,
                created_by, updated_by)
                select in_inst_id,event_cat, cat_name, cat_icon, cat_class, cat_order, in_created_by, in_created_by
                from event_calendar_category where inst_id = 0
                     and is_deleted = 0 and is_active=1;

           DELETE FROM event_calendar_subcategory 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO event_calendar_subcategory(inst_id, event_cat, event_sub_cat, subcat_name, subcat_icon, subcat_class,
                subcat_order, created_by, updated_by)
                select in_inst_id, event_cat, event_sub_cat, subcat_name, subcat_icon, subcat_class,
                subcat_order, in_created_by, in_created_by
                from event_calendar_subcategory where inst_id = 0
                     and is_deleted = 0 and is_active=1;

           DELETE FROM user_groups_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO user_groups_master(inst_id, grp_name, grp_type, grp_display_name, grp_icon, grp_class, grp_order,
                created_by, updated_by)
                select in_inst_id, grp_name, grp_type, grp_display_name, grp_icon, grp_class, grp_order, in_created_by,
                  in_created_by
                from user_groups_master where inst_id = 0
                     and is_deleted = 0 and is_active=1;

	         DELETE FROM document_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO document_master(ay_id, inst_id, entity_type, entity_id, file_upload_id, module_name, doc_category,
                doc_subcategory, doc_name, is_mandatory, doc_upload_status, doc_submit_status, status_desc,
                created_by, updated_by)
                select '', in_inst_id, entity_type, entity_id, file_upload_id, module_name, doc_category,
                doc_subcategory, doc_name, is_mandatory, doc_upload_status, doc_submit_status, status_desc,
                in_created_by, in_created_by
                from document_master where inst_id = 0
                     and is_deleted = 0 and is_active=1;

           DELETE FROM appl_data_notif_templates 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO appl_data_notif_templates (ay_id, inst_id, data_type, data_key, subject,
                message_body, created_by, updated_by, is_active) 
              select '', in_inst_id, data_type, data_key, subject,
                message_body, in_created_by, in_created_by, is_active
                    from appl_data_notif_templates where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;

           DELETE FROM fin_accounts 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO fin_accounts(ay_id, inst_id, fin_acct_id,sequence_entity_id, sequence_entity_mode, acct_name,
                acct_display_name, acct_short_name, address, pan_card_no, gst_reg_no, logo_path,is_default,
					      created_by,updated_by,is_active)
              select '', in_inst_id, fin_acct_id,sequence_entity_id, sequence_entity_mode,acct_name,
                acct_display_name,acct_short_name, address, pan_card_no,gst_reg_no,logo_path,is_default,
					      in_created_by,in_created_by,is_active
              from fin_accounts where ay_id = '*******' and inst_id = 0
                and is_deleted = 0 and is_active=1;

DELETE FROM library_accounts 
             WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

            INSERT INTO library_accounts(ay_id, inst_id, lib_acct_id,acct_name, acct_display_name, 
              acct_abbr, logo_path, is_default,created_by,updated_by,is_active,is_deleted)
            select '', in_inst_id,lib_acct_id,acct_name, acct_display_name,acct_abbr,
              '',is_default,in_created_by,in_created_by,is_active,is_deleted
            from library_accounts where ay_id = '*******' and inst_id = 0
              and is_deleted = 0 and is_active=1;

           DELETE FROM department_master 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO department_master(ay_id, inst_id,dept_id,parent_id, dept_name, dept_display_name,dept_desc,dept_abbr,dept_level,   
					      created_by,updated_by,is_active)
              select '', in_inst_id, dept_id,parent_id, dept_name, dept_display_name,dept_desc,dept_abbr,dept_level,   
					      in_created_by,in_created_by,is_active
              from department_master where ay_id = '*******' and inst_id = 0
                and is_deleted = 0 and is_active=1;

           DELETE FROM sub_module_notif_config 
           WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;

              INSERT INTO sub_module_notif_config(inst_id, module_name, module_display_name, 
                role_id, role_users, send, created_by, updated_by)
              select in_inst_id,module_name, module_display_name, 
                role_id, role_users, send, in_created_by, in_created_by
              from sub_module_notif_config where inst_id = 0 
                and is_deleted = 0 and is_active=1 ;

              select count(inst_id) into l_inst_id from sequence_generator_master where inst_id=in_inst_id 
              and is_active=1 and is_deleted=0;

              if(l_inst_id!=0)then
                delete from sequence_generator_master where inst_id=in_inst_id ;
              end if; 
                  
              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) 
              select '', in_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,in_created_by, in_created_by
                    from sequence_generator_master where ay_id = '*******' and inst_id = 0
                         and is_deleted = 0 and is_active=1;
             
             select count(inst_id) into l_param_inst_id from institution_sequence_params where inst_id=in_inst_id 
              and is_active=1 and is_deleted=0;
             if(l_param_inst_id!=0)then
                delete from institution_sequence_params where inst_id=in_inst_id ;
             end if; 
            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_is_active,in_created_by);
     end if;


    BEGIN
      declare cur_emp_master cursor for 
        select id,salutation,first_name,last_name,gender,mobile_phone_1,role
        from setup_employee_master 
        where  inst_id=in_inst_id and role='TEACHER' ;
     
        open cur_emp_master;     
          cursor_loop_new:loop
              set l_emp_id = fn_sequence_generator('EMPLOYEE_MASTER');
	        
          set l_emp_num =in_emp_num;
  				IF ( in_emp_num_gen_mode='Y' AND length(trim(in_emp_num)) = 0 AND  in_emp_status=100 ) THEN 
  					call sp_custom_seq_generator(in_inst_id,'EMP_GUID','',in_created_by,l_emp_num) ;
  					IF length(trim(l_emp_num)) = 0 THEN
  					   SIGNAL SQLSTATE '10012' 
  					  SET MESSAGE_TEXT = 'An error occurred while generating Employee Number';
  					END IF;
  				END IF;		
  				IF ( in_emp_num_gen_mode='N' AND length(trim(in_emp_num)) > 0 AND  in_emp_status=100 ) THEN 
  					SELECT emp_num INTO t_emp_num  FROM employee_master where emp_id=in_emp_id  and inst_id=in_inst_id;
  					IF (length(trim(t_emp_num)) = 0  ) THEN
  									select emp_num INTO t_emp_num FROM employee_master where emp_num=in_emp_num and inst_id=in_inst_id;
  									IF (t_emp_num=in_emp_num) THEN
  										SIGNAL SQLSTATE '10013'
  										SET MESSAGE_TEXT = 'Employee Number is already present';
  									END IF;
  					END IF;
  				ELSEIF ( in_emp_num_gen_mode='N' AND  in_emp_status>=100  AND length(trim(in_emp_num)) = 0 ) THEN 
  					SIGNAL SQLSTATE '10014'
  					SET MESSAGE_TEXT = 'Please Enter Employee Number';
  				END IF;	

            fetch cur_emp_master into l_id,l_salutation,l_first_name,l_last_name,l_gender,l_mobile_phone_1,l_emp_category;
             if l_looping_done then
               leave cursor_loop_new;
             end if;

            if(l_emp_category!='ADMIN') then
              insert into  employee_master ( inst_id,emp_id,  emp_type, payroll_type, dept_id,  emp_category,  emp_designation, emp_num,  joining_date,  resignation_date, 
      				salutation,  first_name,  middle_name,  last_name,  gender,  emp_grade,  edu_qual_degree1,edu_qual_stream1,
                edu_qual_degree2,edu_qual_stream2, previous_org,
              previous_designation, work_exp_desc,  work_exp_years,  work_exp_months, emp_desc,  
                birth_date, birth_place,  marital_status, anniversary_date, children_count,  
                father_name,  mother_name,  husband_name,  blood_group,  nationality,  religion,  
                category,  subcategory,  address_line_1, address_line_2, locality,  city,  district, 
                state,  country,  pincode,  fixed_phone_1,  mobile_phone_1,  fixed_phone_2,  mobile_phone_2,  email_main,  email_alt,  fax_number,profile_logo_path,   emp_status,  status_desc,  created_by,updated_by,  is_active)  	 						
              values( in_inst_id,l_emp_id ,  '', '', '',  l_emp_category,  '', l_emp_num,  '',  '', 
      				l_salutation,  l_first_name,  '',  l_last_name,  l_gender,  '',  '','','','',
              '','',  '',  '',  '', '',  '', '',  '', '', '',  '',  '',  '',  '',  
               '',   '',   '',   '',   in_address_line_1,  '',  in_locality,in_city,  in_district, in_state,
               in_country,   '',   '',  l_mobile_phone_1,
               '',   '',   '',   '',   '',  '', 100,   '',  in_created_by,in_created_by,  in_is_active  );
   

               update setup_employee_master set  created_by = in_created_by,
                     emp_id=l_emp_id 
               where inst_id = in_inst_id and id=l_id;    
        
               update setup_class_master set emp_id=l_emp_id where inst_id=in_inst_id and emp_id=l_id;
            end if;
         end loop;  
        close cur_emp_master;
       
     END;

        delete FROM standard_master where inst_id=in_inst_id;

        select standard_id,gradeset_mst_id
          into l_std_id,l_gradeset_id from setup_standard_master where inst_id=in_inst_id;
        
        if(l_std_id='01')then
          SET   l_standard_name='I';  SET l_standard_desc='I';SET l_standard_abbr='I';
        elseif(l_std_id='02')then
          SET l_standard_name='II';SET l_standard_desc='II';SET l_standard_abbr='II'; 
        elseif(l_std_id='03')then
          SET l_standard_name='III';SET l_standard_desc='III';SET l_standard_abbr='III';
        elseif(l_std_id='04')then
          SET l_standard_name='IV';SET l_standard_desc='IV';SET l_standard_abbr='IV';
        elseif(l_std_id='05')then
          SET l_standard_name='V';SET l_standard_desc='V';SET l_standard_abbr='V';
        elseif(l_std_id='06')then
          SET l_standard_name='VI';SET l_standard_desc='VI';SET l_standard_abbr='VI';
        elseif(l_std_id='07')then
          SET l_standard_name='VII';SET l_standard_desc='VII';SET l_standard_abbr='VII';
        elseif(l_std_id='08')then
          SET l_standard_name='VIII';SET l_standard_desc='VIII';SET l_standard_abbr='VIII';
        elseif(l_std_id='09')then
          SET l_standard_name='IX';SET l_standard_desc='IX';SET l_standard_abbr='IX';
        elseif(l_std_id='10')then
          SET l_standard_name='X';SET l_standard_desc='X';SET l_standard_abbr='X';
        elseif(l_std_id='11')then
          SET l_standard_name='XI';SET l_standard_desc='XI';SET l_standard_abbr='XI';
        elseif(l_std_id='12')then
          SET l_standard_name='XII';SET l_standard_desc='XII';SET l_standard_abbr='XII';
        else
          SET l_standard_name=l_std_id;SET l_standard_desc=l_std_id;SET l_standard_abbr=l_std_id;
        end if;

         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,l_gradeset_id, 
                l_std_id,l_standard_name,l_standard_desc,l_standard_abbr,
                '','','',
                in_is_active,in_created_by, in_created_by);

       delete FROM division_master where inst_id=in_inst_id;    
 BEGIN
   declare cur_div_master cursor for 
   select division_id from setup_division_master  where  inst_id=in_inst_id ;
   declare continue handler for not found set l_looping_div_done = true;
     open cur_div_master;
          cursor_loop_new:loop
          
          fetch cur_div_master into l_division_id;
           if l_looping_div_done then
             leave cursor_loop_new;
          end if;

            insert into division_master (ay_id, inst_id,division_id,division_name,division_desc, 
               division_abbr, is_active, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id, l_division_id, l_division_id, l_division_id, 
              l_division_id,in_is_active, in_created_by, in_created_by);  
            
            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,l_std_id,in_curriculum_type, 
              l_division_id,l_division_id,l_division_id,l_division_id,'Morning',in_grading_system,
              in_is_active,in_created_by, in_created_by);
            
 
        end loop;
        close cur_div_master;
   END;

 
        delete FROM subject_master where inst_id=in_inst_id;  
        delete FROM subject_standard_map where inst_id=in_inst_id;  
        delete FROM subject_structure_map where inst_id=in_inst_id;  
BEGIN
           declare cur_sub_master cursor for 
            select id,subject_name from setup_subject_master  where  inst_id=in_inst_id ;
               
          declare continue handler for not found set l_looping_sub_done = true;
            open cur_sub_master;
            cursor_loop_new:loop
         set l_subject_id = fn_sequence_generator('SUBJECT_MASTER');
         set l_subject_standard_map_id = fn_sequence_generator('SUBJECT_STANDARD_MAP');
         set l_sub_struct_map_id = fn_sequence_generator('SUBJECT_STRUCTURE_MAP');
            fetch cur_sub_master into l_sub_id,l_subject_name;
             if l_looping_sub_done then
               leave cursor_loop_new;
            end if;

            insert into  subject_master(
              ay_id, inst_id,curriculum_type,
              grading_system,subject_id,subject_name,
              subject_display_name,subject_desc,subject_abbr,
              subject_group_name,is_system_def,is_active,created_by, 
              updated_by) 
            values(
              in_ay_id, in_inst_id,in_curriculum_type, 
              in_grading_system,l_subject_id,l_subject_name,
              l_subject_name,l_subject_name,l_subject_name,
              '',1, in_is_active,in_created_by, in_created_by);
              
              update setup_subject_teacher_map set created_by = in_created_by,
                   subject_id_new=l_subject_id 
            where inst_id = in_inst_id and subject_id=l_sub_id; 

               update setup_subject_master set created_by = in_created_by,
                   subject_id=l_subject_id ,sub_std_map_id=l_subject_standard_map_id
            where inst_id = in_inst_id and id=l_sub_id;  
       
                insert into  subject_standard_map(ay_id, inst_id, sub_std_map_id, curriculum_type, grading_system
              ,standard_id,division_id, group_type, group_id, subject_id, subject_type_id, 
              subject_category_id, gradeset_mst_id, evaluation_type, subject_level, max_weekly_classes,
              credit_hours,  is_mandatory, exam_type, is_book_based, is_consecutive_preferred,
              is_system_def, is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id,l_subject_standard_map_id,in_curriculum_type, in_grading_system ,
             l_std_id,'*','STD', l_std_id, l_subject_id ,
              '','',l_gradeset_id,'',0,'', 1,1, 'E',1,1, 1,in_is_active,in_created_by, in_created_by);

             
           insert into  subject_structure_map(ay_id, inst_id, sub_struct_map_id , sub_std_map_id,
              curriculum_type , grading_system, standard_id, division_id, group_type, group_id, subject_id, parent_id, 
               subject_level, subject_pos, is_system_def, time_table_enabled, exam_enabled, homework_enabled,
              is_active,created_by, updated_by) 
            values(in_ay_id, in_inst_id,l_sub_struct_map_id ,l_subject_standard_map_id, in_curriculum_type ,
              in_grading_system,l_std_id,'*', 'STD', l_std_id,l_subject_id,l_sub_struct_map_id,  '',
              0, 1, 'Y', 'Y', 'Y', in_is_active,in_created_by, in_created_by);
               
       end loop;  
      close cur_sub_master;
     END;

   delete FROM class_master where inst_id=in_inst_id;  
  BEGIN
      declare cur_class_master cursor for 
      select standard_id,division_id,class_id,emp_id,class_name from setup_class_master 
      where  inst_id=in_inst_id ;
      declare continue handler for not found set l_looping_class_done = true;
      open cur_class_master;
          cursor_loop_new:loop
          
          fetch cur_class_master into l_standard_id,l_div_id,l_class_id,l_employee_id,l_class_name;
           if l_looping_class_done then
             leave cursor_loop_new;
          end if;
 
             insert into class_master (ay_id, inst_id,class_id,standard_id, division_id,curriculum_type,
              grading_system,gradeset_mst_id,	emp_id,class_name,class_abbr,class_desc,attendance_type,
              shift_type,is_active,created_by, updated_by) 							
            values(in_ay_id, in_inst_id, l_class_id,l_std_id, l_div_id,in_curriculum_type,
              in_grading_system,l_gradeset_id, l_employee_id,l_class_name,l_class_name ,
              l_class_name,'DAILY','Morning',in_is_active,in_created_by, in_created_by);

        end loop;
          close cur_class_master;
    END;

   delete FROM emp_subject_map where inst_id=in_inst_id;  
   BEGIN
   declare cur_sub_teacher_map cursor for 
   select standard_id,division_id,class_id,subject_id,subject_id_new,emp_id from  setup_subject_teacher_map 
   where  inst_id=in_inst_id ;
   declare continue handler for not found set l_looping_sub_teacher_done = true;
   open cur_sub_teacher_map;
        cursor_loop_new:loop
        
        fetch cur_sub_teacher_map into l_teacher_std_id,l_teacher_div_id,l_teacher_class_id,
               l_teacher_subject_id,l_teacher_sub_new_id,l_teacher_emp_id;
         if l_looping_sub_teacher_done then
           leave cursor_loop_new;
        end if;

          select sub_std_map_id into l_teacher_sub_std_id from setup_subject_master
            where inst_id=in_inst_id and subject_id=l_teacher_sub_new_id;

          select emp_id into l_emp_sub_map_emp_id from setup_employee_master
            where inst_id=in_inst_id and id=l_teacher_emp_id;
          
          select sub_struct_map_id into l_sub_strct_ID_new from subject_structure_map
            where inst_id=in_inst_id and subject_id=l_teacher_sub_new_id;

         set l_emp_subject_map_id = fn_sequence_generator('EMP_SUBJECT_MAP');
        insert into emp_subject_map (ay_id, inst_id,emp_sub_map_id,standard_id, division_id,emp_id,
          group_type,group_id,sub_std_map_id,	allocation_start_date,allocation_end_date,
          is_allocation_temp,is_active,  updated_by  ) 							
        values(in_ay_id, in_inst_id, l_emp_subject_map_id, l_teacher_std_id, l_teacher_div_id,l_emp_sub_map_emp_id,
           'CLS', l_teacher_class_id,l_sub_strct_ID_new, '','','',in_is_active,in_created_by);
        
      end loop;
        close cur_sub_teacher_map;
   END;
        select sms_credit_balance INTO l_sms_credit_balance from sms_credit_status
        where inst_id=in_inst_id and is_active=1 and is_deleted=0; 
        set l_new_sms_credit_balance=l_sms_credit_balance+100;
          update  sms_credit_status set sms_credit_balance=l_new_sms_credit_balance
          where is_deleted = '0' and inst_id = in_inst_id and is_active=1;  
     
        select sms_credit_balance INTO l_vidyalekha_sms_credit_balance 
        from sms_credit_status
        where inst_id=0 and is_active=1 and is_deleted=0; 
        
        update  sms_credit_status set sms_credit_balance=l_vidyalekha_sms_credit_balance-100
        where is_deleted = '0' and inst_id = 0 and is_active=1;  
       
--         get maximum sms credit id from the table
        SELECT max(id_num)+1 INTO l_sms_credit_id from add_sms_credit_mst_seq_generator ;

--           get vidyalekha inst 0 sms rate
       SELECT rate INTO l_rate from  sms_credit_status
       where is_deleted = '0' and inst_id = 0 and is_active=1;  
       
       insert into sms_credit_history(sms_credit_id,ay_id,inst_id,sms_credit_no,rate,amount,payment_type,bank_account_no,
                bank_name,remark,credit_date,is_active,created_by,updated_by) 
       values(l_sms_credit_id,in_ay_id,in_inst_id,100,l_rate,0,'FREE_CREDIT',0,
                '','New School Enrollment Free Credits',date(now()),in_is_active,in_created_by,in_created_by);
  
       insert into add_sms_credit_mst_seq_generator(id_num,id_ts)
       values (l_sms_credit_id,date(now()));
   
   BEGIN
      declare cur_user_master cursor for 
        select user_type,user_id
        from user_master 
        where  inst_id=in_inst_id and is_deleted=0 ;
       declare continue handler for not found set l_looping_user_done = true;
   
       open cur_user_master;     
          cursor_loop_new_user:loop
              
            fetch cur_user_master into l_userType,l_userId;
             if l_looping_user_done then
               leave cursor_loop_new_user;
             end if;
	          CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, l_userType, l_userId, in_created_by, l_err_code, l_err_desc);
         
         end loop;  
        close cur_user_master;
   END;

DELETE FROM module_user_master 
      WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0;
BEGIN
   declare cur_moduleUser_master cursor for 
   select user_id from user_master  where  inst_id=in_inst_id and role_id=11 
    or inst_id=in_inst_id and role_id=10;
   declare continue handler for not found set l_looping_libraryModule_user_done = true;
     open cur_moduleUser_master;
          cursor_loop_new:loop
          
          fetch cur_moduleUser_master into l_user_id;
           if l_looping_libraryModule_user_done then
             leave cursor_loop_new;
          end if;
            insert into module_user_master (ay_id, inst_id,user_id, module_acct_id, 
              module_name,is_create_allowed,is_read_allowed,is_update_allowed,
              is_delete_allowed,
              created_by,updated_by,is_active) 	 						
            values(in_ay_id, in_inst_id, l_user_id, '1', 'library', 
             '1','1','1','1', in_created_by, in_created_by,in_is_active);  

        end loop;
        close cur_moduleUser_master;
   END;

       INSERT INTO inventory_department_master(ay_id, inst_id, inventory_dept_id ,dept_issue_type, 
        inventory_dept_name,inventory_dept_display_name,inventory_dept_desc,inventory_dept_abbr,
        is_default_dept,item_label,created_by, updated_by)
       select in_ay_id, in_inst_id, inventory_dept_id ,dept_issue_type, 
        inventory_dept_name,inventory_dept_display_name,inventory_dept_desc,inventory_dept_abbr,
         is_default_dept, item_label,in_created_by, in_created_by 
      from inventory_department_master where ay_id = '*******' and inst_id = 0
              and is_deleted = 0 and is_active=1;

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



end$$

DROP PROCEDURE IF EXISTS `sp_ins_free_trial_setup_student_info`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_free_trial_setup_student_info`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_user_id` MEDIUMINT(8), IN `in_role_id` MEDIUMINT(8), IN `in_user_type` VARCHAR(15), IN `in_curriculum_type` VARCHAR(10), IN `in_grading_system` VARCHAR(4), IN `in_enrollment_num_gen_mode` VARCHAR(10), IN `in_enrollment_num` VARCHAR(50), IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_stud_status` VARCHAR(25), IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), 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), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin                                                          
                      
	 declare l_routine_name varchar(50) default 'sp_ins_free_trial_setup_student_info';
	 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_class_id char(8);
	 declare t_emp_num varchar(50);
   declare l_looping_done int default false;
  
   declare l_stud_id mediumint(8);
   declare l_first_name varchar(50);
   declare l_last_name varchar(50);
   declare l_gender varchar(50);
   declare l_mobile_phone_main varchar(20);
   declare l_birth_date date;
 
  declare t_enrollment_num varchar(50);
  declare l_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_std_id char(2); 
   declare l_std_name varchar(25); 
   declare l_division_id 	char(1);
   declare l_subject_standard_map_id mediumint(8);
   declare l_sub_struct_map_id mediumint(8);
   declare l_standard_id char(2);
   declare l_div_id_new char(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;

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

      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;

		end;
        
    start transaction;
    
      case in_dml_mode 
        
      when 'I' then
        begin
        set l_routine_block = 'insert';

	CALL `sp_ins_user_role_map`('U', in_inst_id, in_user_type, in_user_id, in_role_id, in_created_by, l_err_code, l_err_desc);
	CALL `sp_ins_user_role_map_entitlements`('U', in_inst_id, in_user_type, in_user_id, in_created_by, l_err_code, l_err_desc);
                
   delete FROM student_master where inst_id=in_inst_id;  
		    BEGIN
          declare cur_student_master cursor for 
           select student_id,class_id,first_name,last_name,birth_date,gender,mobile_phone_main
            from setup_student_master 
            where  inst_id=in_inst_id ;

           open cur_student_master;
            cursor_loop_new:loop
                  set l_student_id = fn_sequence_generator('STUDENT_MASTER');
  
              fetch cur_student_master into l_stud_id,l_class_id,l_first_name,l_last_name,l_birth_date,
                l_gender,l_mobile_phone_main;
               if l_looping_done then
                 leave cursor_loop_new;
               end if;
  
              	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;


               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;	
        				END IF;	


               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;
      				END IF;	
          

              select standard_id into l_std_id from setup_standard_master where inst_id=in_inst_id;
set l_div_id_new=RIGHT(l_class_id, 1);
            insert into student_master(ay_id, inst_id,student_id,standard_id,division_id,class_id,student_num,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, bulk_upload_status,stud_bulk_file_upload_id,
              student_admission_score,password,is_new_admission,boarding_type,course_group, 
              gr_number,is_active,
              created_by, updated_by, distance_from_school, special_interest, 
              is_sibling, sibling_detail, is_rte, rte_category) 
    	 			values(in_ay_id, in_inst_id,l_student_id,l_std_id,l_div_id_new,l_class_id,l_stud_num,l_admission_num,
              '', l_enrollment_num,'','',
              UPPER(l_first_name),'', UPPER(l_last_name), l_birth_date,l_gender,  
              '','','','','','','','','',   
              in_address_line_1,'', in_locality,  in_city, in_district,  in_state,  in_country, 
              '',l_mobile_phone_main,'','','','','','','',
              in_stud_status,'', '','','','','','','','', in_is_active,
              in_created_by, in_created_by,'', '','', '', '', '');
            
            
            end loop;  
          close cur_student_master;
      END;

     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_gallery_album`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_gallery_album`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_album_id` INT(11), IN `in_fb_album_id` VARCHAR(100), IN `in_album_title` VARCHAR(100), IN `in_album_slug` VARCHAR(200), IN `in_album_description` VARCHAR(2000), IN `in_group_type` VARCHAR(20), IN `in_group_id` VARCHAR(20), IN `in_cover_image` VARCHAR(100), IN `in_status` VARCHAR(20), IN `in_is_social_media` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_album_id` 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_gallery_album';
   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 in_album_id = fn_sequence_generator('GALLARY_ALBUM');
             set out_album_id = in_album_id ;
               insert into gallery_album (
                   ay_id, inst_id,
                   album_id,    fb_album_id, album_title, album_slug, album_description,
                   group_type, group_id,
                   cover_image, status,
                   is_social_media,
                   created_by, updated_by)                              

               values(in_ay_id,
                   in_inst_id, in_album_id,in_fb_album_id,
                   in_album_title, in_album_slug, in_album_description,
                   in_group_type, in_group_id,
                   in_cover_image, in_status,
                   in_is_social_media, 
                   in_created_by,  in_created_by);
           end;    


        when 'U' then
           begin

               update gallery_album
                   set updated_by = in_created_by,  
                       updated_on = NOW(),
                       is_active = '0'

               where album_id = in_album_id  
                   and ay_id = in_ay_id
                   and inst_id = in_inst_id
                   and is_active = '1' ;



               insert into gallery_album (
                       ay_id, inst_id,
                       album_id,    fb_album_id, album_title, album_slug, album_description,
                       group_type, group_id,
                       cover_image, status,
                       is_social_media, 
                       created_by, updated_by)                              

               values(in_ay_id,
                       in_inst_id, in_album_id,in_fb_album_id,
                       in_album_title, in_album_slug, in_album_description,
                       in_group_type, in_group_id,
                       in_cover_image, in_status,
                       in_is_social_media, 
                       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_gallery_participant_map_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_gallery_participant_map_json`(
IN `in_dml_mode` CHAR(1), 
IN `in_ay_id` CHAR(7), 
IN `in_inst_id` SMALLINT(5), 
IN `in_album_id` INT(11), 
IN `in_fb_album_id` VARCHAR(100), 
IN `in_album_title` VARCHAR(100), 
IN `in_album_slug` VARCHAR(100), 
IN `in_album_description` VARCHAR(5000),
IN `in_group_type` CHAR(3), 
IN `in_group_id` VARCHAR(8), 
IN `in_cover_image` VARCHAR(100), 
IN `in_status` VARCHAR(10), 
IN `in_is_social_media` TINYINT(1), 
IN `in_insert_row_count` TINYINT(3), 
IN `in_json_str` TEXT, 
IN `in_created_by` VARCHAR(20), 
IN `in_updated_by` VARCHAR(20), 
IN `in_is_website` TINYINT(1), 
IN `in_seq_number` SMALLINT(5), 
IN `in_is_active` TINYINT(1), 
OUT `out_err_code` CHAR(7), 
OUT `out_err_desc` TEXT,
 OUT `out_album_id` VARCHAR(20))
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_gallery_participant_map_json';
  declare l_routine_block varchar(15);
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	

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

  declare l_insert_sql_str text default 'INSERT INTO gallery_participant_map(ay_id, inst_id, album_id, group_name,
    group_type, group_ids,is_active, created_by, updated_by ) VALUES'; 

	declare l_insert_val_str_part text;
	declare l_insert_val_str_full text;
	declare l_album_id int(11); 

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

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

	set l_routine_block = 'inserting album  master entry';	
	 case in_dml_mode 
      when 'I' then
        begin
          set l_album_id = fn_sequence_generator('GALLARY_ALBUM');
        end;
      when 'U' then
        begin
           set l_album_id = in_album_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 = 'album_id') THEN
        begin
	         set l_template_col_value=l_album_id;
        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); 
				insert into gallery_album(ay_id, inst_id, album_id, fb_album_id,album_title, album_slug, album_description, group_type,group_id,cover_image,status,is_social_media, created_by,updated_by,is_website,is_active,seq_number) 
	   	   values 
	      	  (in_ay_id, in_inst_id, l_album_id, in_fb_album_id, in_album_title, in_album_slug, in_album_description, in_group_type,in_group_id,in_cover_image,in_status,in_is_social_media, in_created_by,in_updated_by,
          in_is_website,in_is_active,in_seq_number);
        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;
   set out_album_id = l_album_id;
  

END$$

DROP PROCEDURE IF EXISTS `sp_ins_gallery_photos_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_gallery_photos_json`( 
IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_album_id` INT(11), IN `in_is_social_media` TINYINT(1), IN `in_insert_row_count` TINYINT(3), IN `in_json_str` TEXT, IN `in_created_by` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_fb_album_id` VARCHAR(100), IN `in_album_title` VARCHAR(100), IN `in_album_slug` VARCHAR(200), IN `in_album_description` VARCHAR(2000), IN `in_group_type` VARCHAR(20), IN `in_group_id` VARCHAR(20), IN `in_cover_image` VARCHAR(100), IN `in_status` VARCHAR(20), IN `in_is_website` TINYINT(1), OUT `out_album_id` INT(11), OUT `out_err_code` CHAR(7), OUT `out_err_desc` TEXT)
BEGIN
  declare l_routine_name varchar(50) default 'sp_ins_gallery_photos_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 gallery_photos(ay_id, 
                                              inst_id, 
                                              album_id,
                                               photo_id, 
                                                      photo_name,
                                                    photo_path, 
                                               photo_extension,
                                                                photo_mime,
                                                                  photo_width,
                                              photo_height,
                                              thumb_width,
                                              thumb_height,   
                                              original_width,original_height,filesize,
                                              title,  caption,alt_text,source,credit,description,featured,
                                              sequence,
                                                                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 = 'gallery_photos' 
  order by col_pos;
  declare continue handler for not found set l_looping_done = true;
  declare exit handler for sqlexception
      begin     
      rollback;
      get diagnostics condition 1
        l_err_code = returned_sqlstate, l_err_desc = message_text;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, l_routine_name, l_routine_block, l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        end;
  set l_insert_row_count = in_insert_row_count;
  set l_json_str = trim(in_json_str);
  set l_json_str_len = length(l_json_str);
  set out_album_id=in_album_id;
  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 = 'photo_id') THEN
        begin
          case in_dml_mode 
            when 'I' then
              begin
                set l_template_col_value = fn_sequence_generator('GALLARY_PHOTO');
              end;
    
            when 'U' then
              begin
                 set l_template_col_value = fn_sequence_generator('GALLARY_PHOTO'); 
              end;
            when 'M' then
              begin
              set l_template_col_value = fn_sequence_generator('GALLARY_PHOTO');
            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';
          update  gallery_album set updated_by = in_created_by, 
            updated_on = now(),is_social_media=in_is_social_media
          where ay_id = in_ay_id and inst_id = in_inst_id and album_id = in_album_id 
            and is_deleted = 0;
          call sp_execute_immediate (l_insert_sql_str); 
        commit;
      end;
    when 'U' THEN
      begin
        start transaction;  
          set l_routine_block = 'before soft delete';
           update  gallery_album set updated_by = in_created_by, 
            updated_on = now(), is_deleted = 1 
          where ay_id = in_ay_id and inst_id = in_inst_id and album_id = in_album_id
            and is_deleted = 0;
			
			
			 insert into gallery_album (
                       ay_id, inst_id,
                       album_id,    fb_album_id, album_title, album_slug, album_description,
                       group_type, group_id,
                       cover_image, status,
                       is_social_media,is_website,
                       created_by, updated_by)                              

               values(in_ay_id,
                       in_inst_id, in_album_id,in_fb_album_id,
                       in_album_title, in_album_slug, in_album_description,
                       in_group_type, in_group_id,
                       in_cover_image, in_status,
                       in_is_social_media,in_is_website,
                       in_created_by, in_created_by);
                   
          set l_routine_block = 'before execute immediate';
      
          call sp_execute_immediate (l_insert_sql_str);        
        commit;
      end;
     when 'M' 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_album_id=in_album_id;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
END$$

DROP PROCEDURE IF EXISTS `sp_ins_generate_issue_receiptNumber`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_generate_issue_receiptNumber`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(8), IN `in_fin_receipt` VARCHAR(100), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_receipt_num` TEXT)
    NO SQL
begin

 declare l_routine_name varchar(50) default 'sp_ins_generate_issue_receiptNumber';
 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_fin_receipt_num varchar(100);
 declare l_looping_done int default false;
 
 declare exit handler for sqlexception
      begin
     rollback;
     
    get diagnostics condition 1
       l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;

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

     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
        end;
       
   start transaction;
   
     case in_dml_mode
       when 'I' then
         begin 
           
            set l_routine_block = 'insert';
       
       set l_fin_receipt_num =in_fin_receipt;
          IF ( length(trim(in_fin_receipt)) = '' ) THEN 
					    call sp_custom_seq_generator(in_inst_id,'ISSUE_RCPT_NUM',in_ay_id,in_created_by,l_fin_receipt_num) ;
             IF length(trim(l_fin_receipt_num)) = 0 THEN
					     SIGNAL SQLSTATE '10012' 
					   SET MESSAGE_TEXT = 'An error occurred while generating expense receipt number';
             END IF;
	        END IF;

      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;
  set out_receipt_num = l_fin_receipt_num;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_generate_meta_mst_id`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_generate_meta_mst_id`(IN `in_dml_mode` CHAR(1), IN `in_meta_mst_id` MEDIUMINT(8), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT, OUT `out_meta_mst_id` CHAR(5))
    NO SQL
begin

  declare l_routine_name varchar(50) default 'sp_ins_generate_meta_mst_id';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_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_mst_id = fn_sequence_generator('EXAM_META');
           set out_meta_mst_id = l_mst_id ;
          
       end; 
  	   
       
    end case;
    
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
    set  out_meta_mst_id=l_mst_id;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_grade_details`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_grade_details`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_gradeset_dtl_id` MEDIUMINT(8), IN `in_grade_name` VARCHAR(10), IN `in_grade_desc` VARCHAR(25), IN `in_grade_abbr` VARCHAR(15), IN `in_score_range_from` DECIMAL(5,2), IN `in_score_range_to` DECIMAL(5,2), IN `in_grade_points` DECIMAL(5,2), IN `in_grade_pos` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
 declare l_routine_name varchar(50) default 'sp_ins_grade_details';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare l_gradeset_dtl_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_gradeset_dtl_id = fn_sequence_generator('GRADE_DETAILS');
           insert into gradeset_details (ay_id, inst_id,gradeset_mst_id,gradeset_dtl_id,grade_name,grade_desc,
              grade_abbr,score_range_from,score_range_to,grade_points,grade_pos, is_active, created_by, updated_by)                              
           values(in_ay_id, in_inst_id, in_gradeset_mst_id,l_gradeset_dtl_id,
              in_grade_name, in_grade_desc,in_grade_abbr,
             in_score_range_from,in_score_range_to,in_grade_points,in_grade_pos,in_is_active, in_created_by,in_created_by);
         end;    
         when 'U' then
        set l_routine_block = 'update';
         begin
             update gradeset_details set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where gradeset_dtl_id = in_gradeset_dtl_id and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;
          insert into gradeset_details (ay_id, inst_id,gradeset_mst_id,gradeset_dtl_id,grade_name,grade_desc,
              grade_abbr,score_range_from,score_range_to,grade_points,grade_pos, is_active, created_by, updated_by)                              
           values(in_ay_id, in_inst_id, in_gradeset_mst_id, in_gradeset_dtl_id,in_grade_name, in_grade_desc,in_grade_abbr,
             in_score_range_from,in_score_range_to,in_grade_points,in_grade_pos,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_grade_set_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_grade_set_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_gradeset_mst_id` SMALLINT(5), IN `in_curriculum_type` VARCHAR(5), IN `in_grading_system` VARCHAR(4), IN `in_gradeset_name` VARCHAR(25), IN `in_gradeset_display_name` VARCHAR(50), IN `in_gradeset_abbr` VARCHAR(15), IN `in_is_system_def` TINYINT(1), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
 declare l_routine_name varchar(50) default 'sp_ins_grade_set_master';
 declare l_err_code char(5) default '00000';
 declare l_err_desc text default '';        
 declare l_routine_block varchar(15);
 declare l_gradeset_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_gradeset_mst_id = fn_sequence_generator('GRADESET_MASTER');
           insert into gradeset_master (ay_id, inst_id,gradeset_mst_id,curriculum_type,grading_system,
              gradeset_name,gradeset_display_name,gradeset_abbr,is_active, created_by, updated_by)                              
           values(in_ay_id, in_inst_id, l_gradeset_mst_id, in_curriculum_type, in_grading_system,
             in_gradeset_name,in_gradeset_display_name,in_gradeset_abbr,in_is_active, in_created_by,in_updated_by);
         end;    
         when 'U' then
        set l_routine_block = 'update';
         begin
             update gradeset_master set valid_to = NOW(), updated_by = in_created_by,
             updated_on = NOW(), is_deleted = 1
           where gradeset_mst_id = in_gradeset_mst_id and is_deleted = 0 and ay_id = in_ay_id
               and inst_id = in_inst_id;
          insert into gradeset_master (ay_id, inst_id,gradeset_mst_id,curriculum_type,grading_system,
              gradeset_name,gradeset_display_name,gradeset_abbr, is_active, created_by, updated_by)                              
           values(in_ay_id, in_inst_id, in_gradeset_mst_id, in_curriculum_type, in_grading_system,
             in_gradeset_name,in_gradeset_display_name,in_gradeset_abbr,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_holiday_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_holiday_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_holiday_id` MEDIUMINT(8), IN `in_holiday_type` VARCHAR(15), IN `in_holiday_name` VARCHAR(25), IN `in_holiday_desc` VARCHAR(50), IN `in_holiday_abbr` VARCHAR(10), IN `in_holiday_start_date` DATE, IN `in_holiday_end_date` DATE, IN `in_holiday_duration` TINYINT(2), 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_holiday_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_holiday_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_holiday_id = fn_sequence_generator('HOLIDAY_MASTER');
            insert into holiday_master (ay_id, inst_id, holiday_id, holiday_type,
              holiday_name, holiday_desc, holiday_abbr, holiday_start_date, 
              holiday_end_date, holiday_duration, created_by, updated_by) 	 						
            values (in_ay_id, in_inst_id, l_holiday_id, in_holiday_type, in_holiday_name, 
              in_holiday_desc, in_holiday_abbr, in_holiday_start_date, in_holiday_end_date,
              in_holiday_duration, in_created_by, in_created_by);
          end;    
  	    when 'U' then
          set l_routine_block = 'update';
          begin
          	update holiday_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 0 
            where holiday_id = in_holiday_id  and is_active = 1 and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
            insert into holiday_master (ay_id, inst_id, holiday_id, holiday_type,
              holiday_name, holiday_desc, holiday_abbr, holiday_start_date, 
              holiday_end_date, holiday_duration, created_by, updated_by) 	 						
            values (in_ay_id, in_inst_id, in_holiday_id, in_holiday_type, in_holiday_name, 
              in_holiday_desc, in_holiday_abbr, in_holiday_start_date, in_holiday_end_date,
              in_holiday_duration, 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_house_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_house_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` VARCHAR(7), IN `in_inst_id` SMALLINT(5), IN `in_house_id` TINYINT(2), IN `in_house_name` VARCHAR(25), IN `in_house_desc` VARCHAR(100), IN `in_house_logo_path` VARCHAR(100), IN `in_house_slogan` VARCHAR(100), IN `in_house_color` VARCHAR(25), IN `in_house_abbr` 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_house_master';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_house_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, 'SQL Exception Handler', l_err_code, l_err_desc, 
        'ERROR', 0, in_created_by);
      set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
		end;  
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
          set l_routine_block = 'insert';
          set l_house_id = fn_sequence_generator('HOUSE_MASTER');
            insert into  house_master (
              ay_id, 
              inst_id,
              house_id,
              house_name,
              house_desc, 
              house_logo_path,
              house_slogan,
              house_color,
              house_abbr,
              is_active ,            
              created_by, 
              updated_by) 	 						
            values(
              in_ay_id, 
              in_inst_id,
              l_house_id,
              in_house_name,
              in_house_desc, 
              in_house_logo_path,
              in_house_slogan ,
              in_house_color,
              in_house_abbr,
              in_is_active, 
              in_created_by, 
              in_created_by);
          end;    
  	    when 'U' then
          begin
             set l_routine_block = 'update';
          	update house_master set valid_to = NOW(), updated_by = in_created_by,updated_on = NOW(), is_deleted = 1 
            where house_id = in_house_id  
              and is_deleted = 0 
              and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
              insert into  house_master (
              ay_id, 
              inst_id,
              house_id,
              house_name,
              house_desc, 
              house_logo_path,
              house_slogan,
              house_color,
              house_abbr,
              is_active ,
              created_by, 
              updated_by) 	 						
            values(
              in_ay_id, 
              in_inst_id,
              in_house_id,
              in_house_name,
              in_house_desc, 
              in_house_logo_path,
              in_house_slogan ,
              in_house_color,
              in_house_abbr,
              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_id_generator_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_id_generator_master`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_id_category` VARCHAR(10), IN `in_id_cycle` VARCHAR(10), IN `in_id_prefix` VARCHAR(15), IN `in_id_seperator` VARCHAR(15), IN `in_id_starts_from` 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_id_generator_master';
  declare exit handler for sqlexception
	  begin
      rollback;
      insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
        err_desc, err_type, err_severity, created_by) 
      values 
        (in_ay_id, in_inst_id, v_routine_name, 'SQL Exception Handler', 100, 'ERROR', 
        'ERROR', 0, in_created_by);
      set out_error_code = 100;
		end;
    start transaction;
      case in_dml_mode 
        when 'I' then
          begin
            insert into  id_generator_master (ay_id, inst_id,id_category,id_cycle,id_prefix, 
               	id_seperator,id_starts_from, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_id_category, in_id_cycle,in_id_prefix, 
              in_id_seperator,in_id_starts_from,in_created_by, in_created_by);
          end;    
  	    when 'U' then
          begin
          	update id_generator_master set valid_to = NOW(), updated_by = in_created_by, 
              updated_on = NOW(), is_active = 'N' 
            where id_category = in_id_category and id_cycle=in_id_cycle and  id_prefix=in_id_prefix and id_seperator=in_id_seperator and id_starts_from=in_id_starts_from and is_active = 'Y' and ay_id = in_ay_id 
            	and inst_id = in_inst_id;
                   insert into  id_generator_master (ay_id, inst_id,id_category,id_cycle,id_prefix, 
               	id_seperator,id_starts_from, created_by, updated_by) 	 						
            values(in_ay_id, in_inst_id,in_id_category, in_id_cycle,in_id_prefix, 
              in_id_seperator,in_id_starts_from,in_created_by, in_created_by);
          end;    
      end case;
    commit;
    set out_error_code = 0;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_information_category_json`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_information_category_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_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_information_category_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  information_category(ay_id, 
                                                                           inst_id,
                                                                           category_id,
                                                                           category_name,                                                                           
                                                                           category_description, 
                                                                           position,
                                                                           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 = 'information_category' 
  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  information_category 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_information_post`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_information_post`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), 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_positions` TINYINT(2), IN `in_scope` VARCHAR(10), IN `in_is_facebook` CHAR(1), IN `in_level` TINYINT(1), IN `in_status` VARCHAR(20), IN `in_is_active` TINYINT(1), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin

  	declare l_routine_name varchar(50) default 'sp_ins_information_post';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_post_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_post_id = fn_sequence_generator('INFORMATION_POST');
   insert into  information_posts(
					             inst_id,
    post_id,
							post_category,
							post_title,
							post_slug,
							post_content,
							positions,
							scope,
							is_facebook,
							level,
							status,
							created_by,
							is_active,updated_by
							) 	 						
           values(in_inst_id,l_post_id,
							in_post_category,
							in_post_title,
							in_post_slug,
							in_post_content,
							in_positions,
							in_scope,
							in_is_facebook,
							in_level,
							in_status,
							in_created_by,
							in_is_active,in_created_by);
            
          end;    
  
  	    when 'U' then
      set l_routine_block = 'update';      
          begin
          	update information_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 information_posts(
					             inst_id,
    post_id,
							post_category,
							post_title,
							post_slug,
							post_content,
							positions,
							scope,
							is_facebook,
							level,
							status,
							created_by,
							is_active,updated_by
							) 	 						
           values(in_inst_id,in_post_id,
							in_post_category,
							in_post_title,
							in_post_slug,
							in_post_content,
							in_positions,
							in_scope,
							in_is_facebook,
							in_level,
							in_status,
							in_created_by,
							in_is_active,in_created_by);
            
            
     end;    
      end case;
    
    commit;
     set out_err_code = l_err_code;
      set out_err_desc = l_err_desc;
        
 

END$$

DROP PROCEDURE IF EXISTS `sp_ins_initialize_admission_process`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_initialize_admission_process`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_ad_ay_id` CHAR(7), IN `in_created_by` VARCHAR(20), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
begin
  declare l_routine_name varchar(50) default 'sp_setup_new_institute';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_is_active tinyint(1) default 0;
  declare exit handler for sqlexception
	  begin
      rollback;
     get diagnostics condition 1
        l_err_code = RETURNED_SQLSTATE, l_err_desc = MESSAGE_TEXT;
        insert into db_error_log(ay_id, inst_id, routine_name, routine_block, err_code, 
                    err_desc, err_type, err_severity, created_by) 
             values (in_current_ay, in_inst_id, l_routine_name, l_routine_name, l_err_code, l_err_desc, 
                    'ERROR', 0, in_created_by);
        set out_err_code = l_err_code;
        set out_err_desc = l_err_desc;
		end;
    start transaction;
      case in_dml_mode 
       when 'S' then          
          begin
             set l_routine_block = 'Admission Setup'; 
              #First of all delete data if by chance present in tables to avoid duplicate entries
              DELETE FROM admission_stage_master WHERE ay_id=in_ad_ay_id and inst_id=in_inst_id;
              DELETE FROM admission_stage_status_master WHERE ay_id=in_ad_ay_id and inst_id=in_inst_id;
              #1 admission_stage_master data
              INSERT INTO admission_stage_master(ay_id, inst_id, stage_id, stage_name, 
                stage_seq, stage_desc, stage_abbr, stage_icon, stage_color, 
                created_by, updated_by, is_active) 
              SELECT in_ad_ay_id, in_inst_id, stage_id, stage_name, 
                stage_seq, stage_desc, stage_abbr, stage_icon, stage_color, 
                in_created_by, in_created_by, is_active
              FROM admission_stage_master 
              WHERE ay_id='*******' and inst_id=0;
              #2 admission_stage_status_master data
              INSERT INTO admission_stage_status_master(ay_id, inst_id, stage_id, status_id, 
                status_name, status_type, status_desc, status_abbr, status_pos, status_seq, 
                created_by, updated_by, is_active) 
              SELECT in_ad_ay_id, in_inst_id, stage_id, status_id, 
                status_name, status_type, status_desc, status_abbr, status_pos, status_seq, 
                in_created_by, in_created_by, is_active 
              FROM admission_stage_status_master 
              WHERE ay_id='*******' and inst_id=0;
      end;    
    end case; 
    commit;
     set out_err_code = l_err_code;
     set out_err_desc = l_err_desc;
end$$

DROP PROCEDURE IF EXISTS `sp_ins_institution_config`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_institution_config`(IN `in_dml_mode` CHAR(1), IN `in_ay_id` CHAR(7), IN `in_inst_id` CHAR(15), IN `in_inst_type` VARCHAR(100), IN `in_edu_board` VARCHAR(10), IN `in_fy_start_date` DATE, IN `in_fy_end_date` DATE, IN `in_ay_start_date` DATE, IN `in_ay_end_date` DATE, IN `in_current_ay` VARCHAR(11), IN `in_next_ay` VARCHAR(11), IN `in_attendance_type` VARCHAR(20), IN `in_first_day_of_week` VARCHAR(10), IN `in_weekly_holiday` VARCHAR(50), IN `in_date_format` VARCHAR(10), IN `in_currency_code` VARCHAR(5), IN `in_class_display_format` VARCHAR(25), IN `in_instruction_mode` VARCHAR(10), IN `in_grading_system` VARCHAR(10), IN `in_terms_per_year` INT(1), IN `in_enrollment_num_gen_mode` VARCHAR(10), IN `in_enrollment_num_gen_id` VARCHAR(10), IN `in_stud_num_gen_mode` VARCHAR(10), IN `in_stud_num_gen_id` VARCHAR(10), IN `in_emp_num_gen_mode` VARCHAR(10), IN `in_emp_num_gen_id` VARCHAR(10), IN `in_admission_num_gen_mode` VARCHAR(10), IN `in_admission_num_gen_id` VARCHAR(10), IN `in_demand_num_gen_mode` VARCHAR(10), IN `in_demand_num_gen_id` VARCHAR(10), IN `in_pmt_rcpt_num_gen_mode` VARCHAR(10), IN `in_pmt_rcpt_num_gen_id` VARCHAR(10), IN `in_lib_book_num_gen_mode` VARCHAR(10), IN `in_lib_book_num_gen_id` VARCHAR(10), IN `in_theme_id` VARCHAR(25), IN `in_inst_house_flag` VARCHAR(1), IN `in_records_per_page` TINYINT(3), IN `in_online_payment_enabled` VARCHAR(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_config';
  declare l_err_code char(5) default '00000';
  declare l_err_desc text default '';    	
  declare l_routine_block varchar(15);
  declare l_sms_sender_id 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  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, inst_house_flag,records_per_page,online_payment_enabled,created_by, updated_by) 	 						
			values(in_ay_id,in_inst_id,in_inst_type,in_edu_board,in_fy_start_date ,in_fy_end_date ,in_ay_start_date ,in_ay_end_date , in_current_ay ,in_next_ay ,in_attendance_type ,in_first_day_of_week ,in_weekly_holiday, in_date_format,in_currency_code,in_class_display_format,in_instruction_mode,in_grading_system, in_terms_per_year,
			in_enrollment_num_gen_mode,in_enrollment_num_gen_id,
			in_stud_num_gen_mode,in_stud_num_gen_id,
			in_emp_num_gen_mode ,in_emp_num_gen_id  ,
			in_admission_num_gen_mode, in_admission_num_gen_id,
			in_demand_num_gen_mode, in_demand_num_gen_id,
			in_pmt_rcpt_num_gen_mode, in_pmt_rcpt_num_gen_id,
      in_lib_book_num_gen_mode,in_lib_book_num_gen_id,
			in_theme_id,in_inst_house_flag,in_records_per_page,in_online_payment_enabled,in_created_by, in_created_by);
            
          end;    
  
  	    when 'U' then
      
          begin
             set l_routine_block = 'update';      
            
                       
--             Select sms_sender_id INTO l_sms_sender_id  from institution_config 
--               WHERE inst_id=in_inst_id and is_active=1 and is_deleted=0 LIMIT 1;
-- 
--           	update institution_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;
--           	          
-- 				 	  
-- 	            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,
-- 				  inst_house_flag,records_per_page,online_payment_enabled, created_by, updated_by, 
--           sms_sender_id,sms_override,force_stop_notifications,inst_sms_master_stop) 	 						
-- 	            values(in_ay_id,in_inst_id,in_inst_type,in_edu_board,in_fy_start_date ,in_fy_end_date ,in_ay_start_date ,in_ay_end_date , in_current_ay , in_next_ay ,in_attendance_type , in_first_day_of_week ,in_weekly_holiday, in_date_format,in_currency_code,in_class_display_format,in_instruction_mode,in_grading_system, in_terms_per_year,in_enrollment_num_gen_mode,in_enrollment_num_gen_id,in_stud_num_gen_mode,in_stud_num_gen_id,in_emp_num_gen_mode ,in_emp_num_gen_id  ,in_admission_num_gen_mode,
--   				in_admission_num_gen_id,
--   				in_demand_num_gen_mode, in_demand_num_gen_id,
--   				in_pmt_rcpt_num_gen_mode, in_pmt_rcpt_num_gen_id,
--           in_lib_book_num_gen_mode,in_lib_book_num_gen_id,
--   				in_theme_id,in_inst_house_flag,in_records_per_page,in_online_payment_enabled,in_created_by, in_created_by,
--           sms_sender_id,sms_override,force_stop_notifications,inst_sms_master_stop);

          	update institution_config set 
                  ay_id=in_ay_id,
                  inst_id= in_inst_id,
                  inst_type= in_inst_type,
                  edu_board= in_edu_board,
                  fy_start_date= in_fy_start_date,
                  fy_end_date = in_fy_end_date,
                  ay_start_date = in_ay_start_date,
                  ay_end_date= in_ay_end_date,
                  current_ay= in_current_ay,
                  next_ay = in_next_ay,
                  attendance_type= in_attendance_type,
                  first_day_of_week = in_first_day_of_week,
                  weekly_holiday = in_weekly_holiday,
                  date_format = in_date_format,
                  currency_code = in_currency_code,
                  class_display_format= in_class_display_format,
                  instruction_mode= in_instruction_mode,
                  grading_system= in_grading_system,
                  terms_per_year= in_terms_per_year,
                  enrollment_num_gen_mode= in_enrollment_num_gen_mode,
                  enrollment_num_gen_id= in_enrollment_num_gen_id,
                  stud_num_gen_mode= in_stud_num_gen_mode,
                  stud_num_gen_id= in_stud_num_gen_id,
                  emp_num_gen_mode= in_emp_num_gen_mode,
                  emp_num_gen_id = in_emp_num_gen_id,
                  admission_num_gen_mode= in_admission_num_gen_mode,
                  admission_num_gen_id= in_admission_num_gen_id,
                  demand_num_gen_mode= in_demand_num_gen_mode, 
                  demand_num_gen_id= in_demand_num_gen_id,
                  pmt_rcpt_num_gen_mode= in_pmt_rcpt_num_gen_mode,
                  pmt_rcpt_num_gen_id= in_pmt_rcpt_num_gen_id,
                  lib_book_num_gen_mode= in_lib_book_num_gen_mode,
                  lib_book_num_gen_id= in_lib_book_num_gen_id,
                  web_theme_id= in_theme_id,
                  inst_house_flag= in_inst_house_flag,
                  records_per_page= in_records_per_page,
                  online_payment_enabled= in_online_payment_enabled,
                  valid_to = NOW(), 
                  updated_by = in_created_by, 
                  updated_on = NOW()
    				where inst_id = in_inst_id  and is_active=1  and is_deleted = 0;
            
          end;    
      end case;
    
    commit;
  set out_err_code = l_err_code;
  set out_err_desc = l_err_desc;
  
END$$

DROP PROCEDURE IF EXISTS `sp_ins_institution_master`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ins_institution_master`(IN `in_dml_mode` CHAR(1), IN `in_inst_id` SMALLINT(5), IN `in_org_id` SMALLINT(5), IN `in_inst_name` VARCHAR(100), IN `in_inst_display_name` VARCHAR(100), IN `in_inst_abbr` VARCHAR(10), IN `in_inst_desc` VARCHAR(250), IN `in_inst_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_current_year` CHAR(7), IN `in_edu_board` VARCHAR(100), IN `in_grading_system` VARCHAR(4), IN `in_registration_num` VARCHAR(25), IN `in_udise_code` VARCHAR(20), IN `in_affiliation_number` VARCHAR(50), 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_contact_salutation_1` VARCHAR(10), IN `in_first_name_1` VARCHAR(25), IN `in_last_name_1` VARCHAR(25), IN `in_contact_role_1` VARCHAR(25), IN `in_contact_salutation_2` VARCHAR(10), IN `in_first_name_2` VARCHAR(25), IN `in_last_name_2` VARCHAR(25), IN `in_contact_role_2` VARCHAR(25), IN `in_contact_salutation_3` VARCHAR(10), IN `in_first_name_3` VARCHAR(25), IN `in_last_name_3` VARCHAR(25), IN `in_contact_role_3` VARCHAR(25), IN `in_tel_country_code_1` TINYINT(3), IN `in_tel_area_code_1` SMALLINT(5), IN `in_tel_number_1` VARCHAR(10), IN `in_tel_type_1` VARCHAR(10), IN `in_tel_country_code_2` TINYINT(3), IN `in_tel_area_code_2` SMALLINT(5), IN `in_tel_number_2` VARCHAR(10), IN `in_tel_type_2` VARCHAR(10), IN `in_tel_country_code_3` TINYINT(3), IN `in_tel_area_code_3` SMALLINT(5), IN `in_tel_number_3` VARCHAR(10), IN `in_tel_type_3` VARCHAR(10), IN `in_referral_id` VARCHAR(20), IN `in_website_reference` VARCHAR(20), IN `in_created_by` VARCHAR(20), IN `in_updated_by` VARCHAR(20), IN `in_next_ay` CHAR(7), OUT `out_inst_id` SMALLINT(5), OUT `out_err_code` CHAR(5), OUT `out_err_desc` TEXT)
    NO SQL
