Sindbad~EG File Manager

Current Path : /home/numerotech/abs.numerotech.com/common_abs_v2-/core/model/
Upload File :
Current File : //home/numerotech/abs.numerotech.com/common_abs_v2-/core/model/BoModel-old.py

from sqlalchemy import create_engine, MetaData, Table, insert, select,update,delete,text
from sqlalchemy.sql import and_, or_
from .. import Cryptography,Auth
from core import app
import json
from .. import engine


class BoModel():
	def __init__(self):
		try:
			self.meta = MetaData()
			self.abstracts              = Table("abstracts", self.meta, autoload_with=engine)
			self.date_config            = Table("abs_types",self.meta,  autoload_with=engine)
			self.abs_session_types      = Table("abs_session_types", self.meta,  autoload_with=engine)
			self.author                 = Table("abs_topics", self.meta,  autoload_with=engine)
			self.setting                = Table("abs_settings",self.meta,  autoload_with=engine)
			self.abs_judges             = Table("abs_judges",self.meta,  autoload_with=engine)
			self.template               = Table("abs_mail_templete",self.meta,  autoload_with=engine)
			self.mail_templates         = Table("mail_templates",self.meta,  autoload_with=engine)
			self.abs_whatsapp_template  = Table("abs_whatsapp_template",self.meta,  autoload_with=engine)
			self.export_filter_cols     = Table("export_filter_cols",self.meta,  autoload_with=engine)
			self.custom_user_abs_types  = Table("custom_user_abs_types",self.meta,  autoload_with=engine)
			self.users                  = Table("users",self.meta,  autoload_with=engine)
			self.abs_halls              = Table("abs_halls",self.meta,  autoload_with=engine)
			self.abs_templates          = Table("abs_templates",self.meta,  autoload_with=engine)
			self.abs_marksheet_template = Table("abs_marksheet_template",self.meta,  autoload_with=engine)
			self.abs_judges_marks       = Table("abs_judges_marks",self.meta,  autoload_with=engine)
			self.abs_categories         = Table("abs_categories",self.meta,  autoload_with=engine)
			self.print_temp             = Table("abs_print_template",self.meta,  autoload_with=engine)
		except Exception as e:
			print(e)

	def admin_check(self,user_id):
		with engine.connect() as conn:
			stmt = text("select is_admin from users where user_id = {}".format(user_id))
			result = conn.execute(stmt).one_or_none()
			return dict(result._mapping) if result else None

	def get_abstract(self,conf_id,conf_schema):
		with engine.connect() as conn:
			# stmt = text("select abs_type_id,abs_type,title from  abs_types  where is_visible = 1 and is_abs = 1 and conf_id = {} group by abs_type order by order_by".format(conf_id))
			stmt = text("select abs_type_id,ast.abs_type,ast.title,ast.is_abs from  abs_types  ast left join {}.abstracts a on a.abs_type=ast.abs_type and a.conf_id={} where  ast.conf_id = {} group by a.abs_type order by order_by asc".format(conf_schema,conf_id,conf_id))
# 			print(stmt)
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
	
	def get_abstract_custome(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from  abs_types  where is_visible = 1 and conf_id = {} group by abs_type order by order_by".format(conf_id))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_consent_status_data(self,abs_no,consent_status_id,conf_schema):
		with engine.connect() as conn:
			abs_no_stmt = ""
			consent_status_id_stmt = ""
			if abs_no:
				abs_no_stmt = "  and abs_no = "+str(abs_no)
			if consent_status_id:
				consent_status_id_stmt = " and consent_status_id = "+str(consent_status_id)
			stmt = text("select abs_type,abs_no,title,u.full_name as chief_instructor,topic,cu.full_name as co_instructor,consent_status_id from "+str(conf_schema)+".abstracts ab "+
						" inner join "+str(conf_schema)+".abs_topics abst on ab.abs_id = abst.abs_id "+
						" inner join users u on ab.user_id = u.user_id"+
						" inner join users cu on abst.user_id = cu.user_id"+
						" where abs_type = 'IC' and abs_status_id > 0 and abst.role_id in (33)"+abs_no_stmt+consent_status_id_stmt)
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_abstract_count(self,conf_id,conf_schema):
		with engine.connect() as conn:
			count=[]
			for i in range (2):
				if i == 1 :
					stmt = text ("select abs_type,count(abs_id) as abs_count  from {}.abstracts ab join users u on ab.user_id = u.user_id  where ab.abs_status_id >= {} and conf_id = {} group by abs_type".format(conf_schema,i,conf_id))
				else:
					stmt = text ("select abs_type,count(abs_id) as abs_count  from {}.abstracts ab join users u on ab.user_id = u.user_id  where ab.abs_status_id = {} and conf_id = {} group by abs_type".format(conf_schema,i,conf_id))
				result = conn.execute(stmt).all()
				results = [dict(r._mapping) for r in result] if result else None
				count.append(results)
			return count

	def get_abs_details(self,abs_type,category_id,presentation_type,selection_type,status_type,award_list,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("get_record_by_type_v2",[abs_type,category_id,presentation_type,selection_type,status_type,award_list,conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None 
	
	def get_display_selection_type(self,selection_type_id):
		with engine.connect() as conn:
			stmt = text("select type as title from abs_selection_type where selection_type_id = {}".format(selection_type_id))
			result = conn.execute(stmt).one_or_none()
			results=dict(result._mapping) if result else None
			return results

	def get_display_abstracts_type(self,abs_type):
		with engine.connect() as conn:
			stmt = text("select title from abs_types where abs_type = '{}' limit 1".format(abs_type))
			result = conn.execute(stmt).one_or_none()
			results=dict(result._mapping) if result else None
			return results
	
	def get_status_selection_type_of_presentation_abs_types(self,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_status_selection_type_of_presentation_abs_types",[conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_selection(self):
		with engine.connect() as conn:
			stmt = text("select * from abs_selection_type")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_status(self):
		with engine.connect() as conn:
			stmt = text("select * from abs_status")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_date_config(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where conf_id = {} order by end_date desc".format(conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_config_id(self,config_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where abs_type_id = {}".format(config_id))
			result = conn.execute(stmt)
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def sent_config(self,config_id,data):
		with engine.connect() as conn:
			stmt = self.date_config.update().values(data).where(self.date_config.c.abs_type_id.in_([config_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None

	def get_setting_config(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_settings where conf_id = {}".format(conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_setting_id(self,setting_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_settings where setting_id  = {}".format(setting_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def sent_project_config(self,setting_id,data):
		with engine.connect() as conn:
			stmt = self.setting.update().values(data).where(self.setting.c.setting_id.in_([setting_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None

	def get_abs_type(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where conf_id = {} and is_abs = 1 group by abs_type".format(conf_id))
			result = conn.execute(stmt)
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_abs_type_for_eva(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select t.abs_type,t.title from {}.abstracts a inner join abs_types t on a.abs_type = t.abs_type where t.conf_id = {} group by t.abs_type".format(conf_schema,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results
	
	def get_eva_abs_type_for_eva(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where conf_id = {} and abs_type like '%VAL' group by abs_type".format(conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results
	
	def get_eva_abs_type_for_eva_v1(self,abs_type,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where conf_id = {} and abs_type like '{}%VAL%' group by abs_type".format(conf_id,abs_type))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results
			
	def get_abstract_typebyabstype(self,conf_id,abs_type):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where conf_id = {} and abs_type = '{}'".format(conf_id,abs_type))
			result = conn.execute(stmt).first()
			results = dict(result._mapping)  if result else None
			return results
	
	def get_evaluators_seach(self,conf_id,conf_key,host_url,abs_type):
		with engine.connect() as conn:
			where_con = ""
			if abs_type:
				where_con = " and abs_type = '"+abs_type+"'"
			atag = f"""<a href='{host_url}bo/eva_view/{conf_id}/{conf_key}?abs_type=",abs_type,"&user_id=",user_id,"' target='_blank' >"""
			stmt = text(f"""select full_name1, membership_no, email, mobile, user_id, user_uuid, group_concat( concat("{atag}",evaluation,'</a>') separator "<br>") as evaluation from (select * from view_find_evaluator where conf_id = {conf_id} {where_con}) as t1 group by user_id""")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_categories_for_eva(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			if (conf_id == 13 or conf_id == '13'):
				stmt = text("select concat(type,' / ',count(abs_id)) as cat_count,ab.presentation_type_id as category_id from {}.abstracts ab join abs_presentation_type c on ab.presentation_type_id = c.presentation_type_id where abs_type = '{}' and ab.abs_status_id >= 1 and ab.conf_id = {} group by ab.presentation_type_id".format(conf_schema,abs_type,conf_id))
			else:
				stmt = text("select concat(display_name,' / ',count(abs_id)) as cat_count,ab.category_id  from {}.abstracts ab join abs_categories c on ab.category_id = c.category_id where abs_type = '{}'  and ab.abs_status_id in (1,2) and ab.conf_id = {} group by ab.category_id".format(conf_schema,abs_type,conf_id))
			
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_search(self,search,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_search",[search,Auth.get_conference(conf_id).get('society_id')])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def get_eva_by_catid(self,abs_type,cat_id,eva_abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select ab.*,u.*,m.eva_abs_type,c.category_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,concat(display_name,' / ',count(m.abs_id)) as cat_count from users u "+
			" join "+str(conf_schema)+".abs_marks m on u.user_id = eva_id "+
			" join "+str(conf_schema)+".abstracts ab on m.abs_id = ab.abs_id "+
			" join abs_categories c on ab.category_id = c.category_id"+
			" where ab.abs_type = '{}' and ab.category_id in ({}) and ab.conf_id = {} and m.eva_abs_type = '{}' group by ab.category_id,eva_id ".format(abs_type,cat_id,conf_id,eva_abs_type))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def delete_evaluator(self,user_id,eva_abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("delete m.* from {}.abs_marks m inner join {}.abstracts ab on m.abs_id = ab.abs_id where eva_id = {} and ab.conf_id = {} and m.eva_abs_type = '{}' ".format(conf_schema,conf_schema,user_id,conf_id,eva_abs_type))
			result = conn.execute(stmt)
			conn.commit()
			return None
	
	def Add_eva_abstract_type(self,data,abs_type_id):
		with engine.connect() as conn:
			if abs_type_id:
				stmt = self.date_config.update().values(data).where(self.date_config.c.abs_type_id.in_([abs_type_id]))
			else:
				stmt  = self.date_config.insert().values(data)
			conn.execute(stmt)
			conn.commit()
			return 1

	def get_abs_for_eval(self,abs_type,cat_id,eval_id,eva_abs_type,abs_no,conf_id,conf_schema):
		with engine.connect() as conn:
			abs_no_where = ""
			if abs_no:
				abs_no_where = " and ab.abs_no in ({}) ".format(abs_no)
			stmt = text("select ab.abs_id from "+str(conf_schema)+".abstracts ab"+
						" where abs_type='"+str(abs_type)+"' and category_id in ("+str(cat_id)+") and abs_id not in ( select abs_id from "+str(conf_schema)+".abs_marks where  eva_id = {} and eva_abs_type ='{}') and ab.abs_status_id > 0 and ab.abs_status_id  != 4 and ab.conf_id = {} {} order by ab.abs_no".format(eval_id,eva_abs_type,conf_id,abs_no_where))
# 			print(stmt)
			result = conn.execute(stmt).all()
			data=[dict(r._mapping) for r in result] if result else None
			if data:
				stmt_1 = ('''INSERT INTO ''' +str(conf_schema)+ '''.abs_marks (abs_id,eva_id,eva_abs_type,order_by) VALUES''')
				row_val = []
				group_count = 0
				for i in data:
					group_count+=1
					row_val.append(('(' + ''''{}','{}','{}',{} ''' +')').format(i['abs_id'],eval_id,eva_abs_type,group_count))
				stmt_1 = stmt_1 +  ",".join(row_val)
				stmt_1 = stmt_1 + ''
				result = conn.execute(text(stmt_1))
			conn.commit()
			return None
	
	def delete_eva_abs(self,mark_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("delete from {}.abs_marks where mark_id = {}".format(conf_schema,mark_id))
			result = conn.execute(stmt)
			conn.commit()
			return "success"

	def get_evaluators(self,abs_type,cat_id,conf_id,percent_filter_start,percent_filter_end,order_by):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_eva_evaluation_status_report",[conf_id,abs_type,cat_id,percent_filter_start,percent_filter_end,order_by])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_eva_by_user_id(self,abs_type,cat_id,user_id,conf_id,conf_schema):
		with engine.connect() as conn:
			if cat_id :
					where_con = "and ab.category_id = {}".format(cat_id)
			else:
					where_con = ""
			stmt = text("select ab.*,m.*,u.*,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,concat(ifnull(pu.prefix,''),ifnull(pu.full_name,'')) as presenting_name,pu.membership_no as presenting_author_membership_no,display_name as cat_count  from {}.abs_marks m left join {}.abstracts ab on m.abs_id = ab.abs_id left join users u on eva_id = u.user_id left join {}.abs_topics abt on abt.abs_id = ab.abs_id and abt.role_id in (32,35) left join users pu on abt.user_id = pu.user_id left join abs_categories c on ab.category_id = c.category_id where m.eva_abs_type = '{}' {} and eva_id = {} and ab.conf_id = {} group by pu.user_id,ab.abs_id order by ab.abs_no".format(conf_schema,conf_schema,conf_schema,abs_type,where_con,user_id,conf_id))
			result = conn.execute(stmt)
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def Regen_evaluator_by_id(self,abs_type,cat_id,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_regenerate_eva",[abs_type,cat_id,conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def get_evaluators_mail(self,user_ids,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select  email,concat(ifnull(u.prefix,''),' ',ifnull(u.full_name,'')) as evaluator_name,u.password,u.user_uuid,u.user_id,group_concat(distinct(display_name)) as display_name,mobile,abt.end_date from {}.abs_marks m join {}.abstracts ab on m.abs_id = ab.abs_id join users u on eva_id = u.user_id  left join abs_categories c on ab.category_id = c.category_id left join abs_types abt on abt.abs_type = m.eva_abs_type and abt.conf_id={} where m.eva_abs_type = '{}' and u.user_id in ({}) group by u.user_id".format(conf_schema,conf_schema,conf_id,abs_type,user_ids))
			result = conn.execute(stmt)
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_mail_ids_by_abs_id(self,abs_ids,conf_schema):
		with engine.connect() as conn:
			#stmt = text("select email,full_name,display_name,prefix,abs_id,abs_type,abs_no,title,abs_status_id from abstracts ab  join users u on ab.user_id = u.user_id  left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by abs_id".format(abs_ids))
			stmt = text("select group_concat(distinct(tu.email)) as co_email,u.email,u.full_name,display_name,u.prefix,ab.abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name from {}.abstracts ab inner join users u on ab.user_id = u.user_id left join abs_topics t on ab.abs_id = t.abs_id and role_id in (33,36) and t.user_id != ab.user_id left join users tu on t.user_id = tu.user_id left join {}.abs_session_types abs on ab.abs_session_id = abs.abs_session_id  left join abs_halls ah on abs.hall_id = ah.hall_id left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by abs_id ".format(conf_schema,conf_schema,abs_ids))
			# stmt = text("select email,full_name,display_name,prefix,abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,ab.name_in_grid,ab.starts_by,ab.ends_by from abstracts ab inner join users u on ab.user_id = u.user_id left join abs_session_types abs on ab.abs_session_id = abs.abs_session_id left join abs_halls ah on ab.hall_id = ah.hall_id left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by abs_id ".format(abs_ids))
			result = conn.execute(stmt)
			results=[dict(r._mapping) for r in result] if result else None
			return results


	def get_paper_for_selection(self,abs_type,cat_id,conf_id,conf_schema):
		with engine.connect() as conn:
			# stmt = text("select ab.*,u.*,c.category_id,concat(u.prefix ,'' '',u.full_name) as full_name,concat(display_name,' / ',count(m.abs_id)) as cat_count ,avg(m1+m2+m3) as average_mark from users u "+
			#             " join abs_marks m on u.user_id = eva_id"+
			#              " join abstracts ab on m.abs_id = ab.abs_id and ab.abs_status_id = 1"+
			#              " join abs_categories c on ab.category_id = c.category_id"+
			#              " where ab.abs_type = '{}' and ab.category_id in ({}) group by abs_id order by  average_mark desc ".format(abs_type,cat_id))
			if (conf_id == 13 or conf_id == '13'):
				stmt = text("select ab.*,u.*,c.presentation_type_id as category_id,concat(u.prefix ,'' '',u.full_name) as full_name,concat(type ,' / ',count(ab.abs_id)) as cat_count ,avg(m1+m2+m3) as average_mark from users u  "+
						" inner join "+str(conf_schema)+".abstracts ab on u.user_id = ab.user_id and ab.abs_status_id = 1 "+
						"left join abs_presentation_type c on ab.presentation_type_id = c.presentation_type_id"+
						" left join "+str(conf_schema)+".abs_marks m on m.abs_id = ab.abs_id "+
						" where ab.abs_type = '{}' and ab.presentation_type_id in ({}) and ab.conf_id = {} group by abs_id order by  ab.abs_no,average_mark desc ".format(abs_type,cat_id,conf_id))
			else:
				stmt = text("select ab.*,u.*,c.category_id,concat(u.prefix ,'' '',u.full_name) as full_name,concat(display_name,' / ',count(ab.abs_id)) as cat_count ,avg(m1+m2+m3) as average_mark from users u  "+
						" inner join "+str(conf_schema)+".abstracts ab on u.user_id = ab.user_id and ab.abs_status_id = 1 "+
						"left join abs_categories c on ab.category_id = c.category_id"+
						" left join "+str(conf_schema)+".abs_marks m on m.abs_id = ab.abs_id "+
						" where ab.abs_type = '{}' and ab.category_id in ({}) and ab.conf_id = {} group by abs_id order by  ab.abs_no,average_mark desc ".format(abs_type,cat_id,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def update_status_to_selected(self,abs_ids,abs_status_id,selection_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("update {}.abstracts set abs_status_id = {},selection_type_id = {} where abs_id in ({})".format(conf_schema,abs_status_id,selection_id,abs_ids))
			result = conn.execute(stmt)
			conn.commit()
			return result

	def get_categories_for_verify(self,abs_type,conf_schema):
		with engine.connect() as conn:
			stmt = text("select parent_category_id,parent_category from {}.abstracts ab inner join abs_categories c on c.category_id = ab.category_id where abs_type = '{}' and abs_status_id > 0 group by parent_category_id".format(conf_schema,abs_type))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_category_with_abstract(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select u.prefix,u.full_name,u.email,u.mobile,abs_type,abs_no,ab.abs_id,title,ab.user_id,parent_category_id,ab.category_id,display_name,parent_category,cd_received_at,abs_status_id,video_link "+
				" from "+str(conf_schema)+".abstracts ab "+
				" left join "+str(conf_schema)+".abs_topics abt on abt.abs_id=ab.abs_id and abt.role_id=35 "+
				" left join users u on u.user_id=abt.user_id "+
				" left join abs_categories c on c.category_id = ab.category_id "+
				" left join "+str(conf_schema)+".abs_uploads au on au.abs_id = ab.abs_id "+
				" where abs_type = '{}' and ab.conf_id = {} and abs_status_id > 0 order by abs_no".format(abs_type,conf_id))
	#       stmt = text("select abs_type,abs_no,abs_id,title,user_id,parent_category_id,ab.category_id,display_name,parent_category,cd_received_at,abs_status_id from abstracts ab left join abs_categories c on c.category_id = ab.category_id where abs_type = '{}' and ab.conf_id = {} and abs_status_id > 0 order by abs_no".format(abs_type,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def update_abstracts(self,abs_id,data,conf_schema):
		abstracts = Table("abstracts", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			stmt = abstracts.update().values(data).where(abstracts.c.abs_id.in_(abs_id))
			result = conn.execute(stmt)
			conn.commit()
			return None

	def get_templates_data(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_mail_templete where conf_id = {}".format(conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_template_data(self,template_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_mail_templete where template_id = {}".format(template_id))
			result = conn.execute(stmt).one_or_none()
			results=dict(result._mapping) if result else None
			return results


	def update_template(self,data,template_id):
		with engine.connect() as conn:
			stmt = self.template.update().values(data).where(self.template.c.template_id.in_([template_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None

	def get_halls(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_halls where conf_id = {}".format(conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_hall_wise_abstracts(self,abs_type,selection_type,conf_id):
		with engine.connect() as conn:
			abs_type_stmt = ""
			selection_type_stmt =""
			if abs_type:
				abs_type_stmt = " and abs_type = '{}' ".format(abs_type)
			if selection_type:
				selection_type_stmt = " and selection_type_id = {} ".format(selection_type)

			stmt = text('select u.full_name as chief ,pu.full_name as presenting,group_concat(cu.full_name) as co,absc.display_name,ab.*,date(starts_by) as start_date from abstracts ab '+
					' left join users u on ab.user_id = u.user_id  '+
					' left join abs_topics abp on  abp.abs_id = ab.abs_id  and abp.role_id = 35 '+
					' left join users pu on abp.user_id = pu.user_id '+
					' left join abs_topics abc on ab.abs_id = abc.abs_id and abc.role_id in (33,36) '+
					' left join users cu on abc.user_id = cu.user_id  '+
					' left join abs_categories absc on ab.category_id = absc.category_id '+
					' where abs_status_id > 1  and ab.conf_id = {} '.format(conf_id+ abs_type_stmt + selection_type_stmt +'group by ab.abs_id  '))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def store_hall_assignment(self,data,abs_ids,conf_schema):
		with engine.connect() as conn:
			stmt = 'UPDATE ' +str(conf_schema)+'.abstracts SET '
			keyname = ["hall_id","starts_by","ends_by"]
			for j in keyname:
				stmt = stmt + j +" = case "
				for i in data:
					stmt = stmt + ' When abs_id = ' + str(i["abs_id"]) + " then " + i[j]
				stmt = stmt + ' END, '
			stmt = stmt[:-2]
			abs_ids =  ','.join(str(e) for e in abs_ids)
			stmt = stmt + ' Where abs_id in (' +str(abs_ids)+' )'
			result = conn.execute(text(stmt))
			conn.commit()
			return "Success"

	def insert_new_gp(self,abs_type,conf_id,user_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("insert into {}.abstracts (abs_type,user_id,conf_id) values('{}',{},{})".format(conf_schema,abs_type,user_id,conf_id))
			conn = engine.connect()
			result = conn.execute(stmt).lastrowid
			conn.commit()
			return result

	def get_abstract_data(self,abs_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('select *,date(starts_by) as start_date,h.name as hall_name from {}.abstracts ab left join abs_halls h on h.hall_id = ab.hall_id where abs_id = {}'.format(conf_schema,abs_id))
			result = conn.execute(stmt).one_or_none
			results=dict(result._mapping) if result else None
			return results

	def get_abstract_data_for_keynote(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('select *,date(starts_by) as start_date,h.name as hall_name from {}.abstracts ab left join abs_halls h on h.hall_id = ab.hall_id where abs_type = "{}" and ab.conf_id = {} and ab.abs_status_id > 0 order by abs_no'.format(conf_schema,abs_type,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_gp_abstract_data(self,abs_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('select ab.abs_id,ab.abs_type as abs_type,ab.abs_no,ab.title,ab.synopsis,date(abs.start_date) as startdate ,abs.*,h.name as hall_name from {}.abstracts ab left join {}.abs_session_types abs on  ab.abs_session_id = abs.abs_session_id left join abs_halls h on h.hall_id = abs.hall_id where abs_id = {}'.format(conf_schema,conf_schema,abs_id))
			result = conn.execute(stmt).one_or_none()
			results = dict(result._mapping) if result else None
			return results

	def update_abs_session(self,data,session_id,conf_schema):
		abs_session_types = Table("abs_session_types", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			stmt = abs_session_types.update().values(data).where(abs_session_types.c.abs_session_id.in_([session_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None
		
	def get_role_for_desigination(self):
		with engine.connect() as conn:
			stmt    = text('select * from abs_roles ')
			result  = conn.execute(stmt)
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_gp_list(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt    = text('select *,u.full_name as chief,ast.start_date,ast.end_date,ah.name as hall_name from {}.abstracts ab join users u on ab.user_id = u.user_id join {}.abs_session_types ast on ab.abs_session_id = ast.abs_session_id join abs_halls ah on ast.hall_id = ah.hall_id where abs_type = "GP" and ab.conf_id = {} order by abs_no desc'.format(conf_schema,conf_schema,conf_id))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def update_GP_co_author(self,data,topic_ids,conf_schema):
		abs_topics = Table("abs_topics", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			for i in data:
				stmt = abs_topics.update().values(i).where(abs_topics.c.topic_id.in_([i["topic_id"]]))
				result = conn.execute(stmt)
			conn.commit()
			return "Success"

	def get_selection_type(self,abs_type):
		with engine.connect() as conn:
			stmt = text("SELECT * FROM abs_selection_type ")
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results


	def get_selection_data(self,selection_type_id,status,abs_type,delegate_reg,conf_id):
		with engine.connect() as conn:
			selection_type_stmt = ''
			delegate_reg_stmt   = ''
			if selection_type_id :
				selection_type_stmt = ('and selection_type_id = '+str(selection_type_id))
			if delegate_reg and int(delegate_reg) == 1 :
				delegate_reg_stmt = ('and d.del_status_id in (2,3) ')
			elif delegate_reg and int(delegate_reg) == 2 :
				delegate_reg_stmt = ('and (d.del_status_id not in (2,3) or d.del_status_id is null) and (abp.user_id not in (select user_id from delegates where conference_id ='+str(conf_id)+ ' and user_id is not null and del_status_id in (2,3)))')
			stmt = text("SELECT group_concat(distinct(concat(ifnull(cu.prefix,''),ifnull(cu.full_name,'')))) as co,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as chief,u.membership_no,concat(ifnull(pu.prefix,''),ifnull(pu.full_name,'')) as present,c.display_name,abpt.type,ab.*,aw.award_name,d.delegate_no from abstracts ab "+
						" left join abs_topics abt on ab.abs_id = abt.abs_id and abt.role_id in (33,36) "+
						" left join users u on ab.user_id = u.user_id "+
						" left join users cu on abt.user_id = cu.user_id "+
						" left join abs_topics abp on ab.abs_id = abp.abs_id and abp.role_id in (35) "+
						" left join users pu on abp.user_id = pu.user_id "+
						" left join abs_categories c on ab.category_id = c.category_id "+
						" left join abs_presentation_type abpt on ab.presentation_type_id = abpt.presentation_type_id "+
						" left join abs_awards aw on ab.award_id=aw.award_id "+
						" left join delegates d on d.user_id=abp.user_id   and d.conference_id= "+str(conf_id)+
						" where ab.abs_type = '{}' {} {} and abs_status_id = {} and ab.conf_id = {} group by ab.abs_id order by ab.abs_no ".format(abs_type,selection_type_stmt,delegate_reg_stmt,status,conf_id))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_all_session(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt    = text("select * from {}.abs_session_types where conf_id = {}".format(conf_schema,conf_id))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_abs_session(self,conf_id,abs_type,conf_schema):
		with engine.connect() as conn:
			stmt= text("select * from {}.abs_session_types ab_session left join abs_halls ab_h on ab_session.hall_id = ab_h.hall_id where ab_session.conf_id = {} and s_abs_type !='GP' ;".format(conf_schema,conf_id,abs_type))
			if abs_type == "IC":
				stmt = text(f'select a.abs_id,a.abs_session_id,a.title,a.abs_no,a.abs_type,concat(ifnull(u.prefix,""),ifnull(u.full_name,"")) as full_name,email,mobile,s.start_date,s.end_date,s.hall_id from {conf_schema}.abstracts a left join {conf_schema}.abs_session_types s on a.abs_session_id = s.abs_session_id inner join users u on a.user_id = u.user_id where a.conf_id = {conf_id} and abs_type = "IC" and abs_status_id = 2 order by abs_no;')
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def insert_new_session(self,data,conf_schema):
		abs_session_types = Table("abs_session_types", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			stmt  = abs_session_types.insert().values(data)
			result = conn.execute(stmt)
			conn.commit()
			return result

	def update_session(self,data,session_id,conf_schema):
		abs_session_types = Table("abs_session_types", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			stmt = abs_session_types.update().values(data).where(abs_session_types.c.abs_session_id.in_([session_id]))
			result = conn.execute(stmt)
			conn.commit()
			return result

	def delete_session(self,session_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('delete from {}.abs_session_types where abs_session_id = {} '.format(conf_schema,session_id))
			result = conn.execute(stmt)
			conn.commit()
			return result
	
	def add_new_IC_sessions(self,insert_data,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = ("Insert into "+str(conf_schema)+ ".abs_session_types (s_abs_id,start_date,end_date,hall_id,conf_id,s_abs_type) ")
			loop_index = 1
			abs_ids = []
			for i in insert_data:
				if loop_index == 1:
					if i['start_date'] and i['end_date']:
						loop_index = 0
						abs_ids.append(i['abs_id'])
						stmt = stmt + ("VALUES ('{}','{}', '{}',{},{},'IC')".format(i['abs_id'],i['start_date'] ,i['end_date'],i['hall_id'],conf_id))
				else:
					loop_index = 0
					if i['start_date'] and i['end_date']:
						abs_ids.append(i['abs_id'])
						stmt = stmt + (",('{}','{}', '{}',{},{},'IC')".format(i['abs_id'],i['start_date'],i['end_date'],i['hall_id'],conf_id))
			if abs_ids != []:
				result  = conn.execute(text(stmt))
				conn.commit()
				abs_ids =  ','.join(str(e) for e in abs_ids)
				stmt = text(f"update {conf_schema}.abstracts a inner join {conf_schema}.abs_session_types s on a.abs_id = s.s_abs_id and a.abs_session_id is null set a.abs_session_id = s.abs_session_id,s.session_name = concat(abs_type,abs_no,' - ',title) where s_abs_id in ({abs_ids}) and s.conf_id = {conf_id} and s_abs_type = 'IC'")
				result  = conn.execute(stmt)
				conn.commit()
			return "success"
		
	def update_IC_sessions(self,update_data,conf_schema):
		with engine.connect() as conn:
			stmt = 'UPDATE '+str(conf_schema)+ '.abs_session_types SET '
			keyname = ["hall_id","start_date","end_date"]
			abs_ids = []
			for j in keyname:
				stmt = stmt + j +" = case "
				for i in update_data:
					if i[j] != 'Null' and i[j]:
						con = "'"+i[j]+"'"
					else:
						con = "Null"
					stmt = stmt + ' When abs_session_id = ' + str(i["abs_session_id"]) + " then "+con 
					if i["abs_session_id"] not in abs_ids:
						abs_ids.append(i["abs_session_id"])
				stmt = stmt + ' END, '
			if abs_ids:
				stmt = stmt[:-2]
				abs_ids =  ','.join(str(e) for e in abs_ids)
				stmt = stmt + ' Where abs_session_id in (' +str(abs_ids)+' )'
				stmt = text(stmt)
				result = conn.execute(stmt)
				conn.commit()
				conn.close()
			return "Success"

	def get_session_abstract_data(self,session_id,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt    = text("select ab.abs_id,ab.abs_type,ab.abs_no,ab.title,c.display_name,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as ca_author,concat(ifnull(pu.prefix,''),ifnull(pu.full_name,'')) as pa_author,group_concat(ifnull(cau.prefix,''),ifnull(cau.full_name,'')) as co_author "+
						"from "+str(conf_schema)+".abstracts ab "+
						"inner join users u on ab.user_id = u.user_id "+
						"left join abs_categories c on ab.category_id = c.category_id "+
						"left join "+str(conf_schema)+".abs_topics abt on ab.abs_id = abt.abs_id and abt.role_id = 36 "+
						"left join users cau on abt.user_id = cau.user_id "+
						"left join "+str(conf_schema)+".abs_topics abtp on ab.abs_id = abtp.abs_id and abtp.role_id = 35 "+
						"left join users pu on abtp.user_id = pu.user_id "+
						"where ab.abs_session_id = {}  and ab.abs_type = '{}' and ab.conf_id = {} group by abs_id order by ab.sno,ab.abs_type,ab.abs_no".format(session_id,abs_type,conf_id))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_new_session_abstract_data(self,abs_type,conf_id,sel_type_id,conf_schema):
		with engine.connect() as conn:
			select_con = ""
			if sel_type_id:
				select_con = " and ab.selection_type_id = "+sel_type_id
			stmt    = text("select ab.abs_id,ab.abs_type,ab.abs_no,ab.title,c.display_name,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as ca_author,concat(ifnull(pu.prefix,''),ifnull(pu.full_name,'')) as pa_author,group_concat(ifnull(cau.prefix,''),ifnull(cau.full_name,'')) as co_author "+
						"from "+str(conf_schema)+".abstracts ab "+
						"inner join users u on ab.user_id = u.user_id "+
						"left join abs_categories c on ab.category_id = c.category_id "+
						"left join "+str(conf_schema)+".abs_topics abt on ab.abs_id = abt.abs_id and abt.role_id = 36 "+
						"left join users cau on abt.user_id = cau.user_id "+
						"left join "+str(conf_schema)+".abs_topics abtp on ab.abs_id = abtp.abs_id and abtp.role_id = 35 "+
						"left join users pu on abtp.user_id = pu.user_id "+
						"where ab.abs_session_id is null and ab.abs_type = '{}' and ab.conf_id = {} {} and abs_status_id = 2 group by abs_id order by abs_no".format(abs_type,conf_id,select_con))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_session_data(self,session_id,conf_schema):
		with engine.connect() as conn:
			stmt    = text("Select *,date(start_date) as date from {}.abs_session_types abst left join abs_halls abh on abst.hall_id = abh.hall_id where abs_session_id = {}".format(conf_schema,session_id)) 
			result  = conn.execute(stmt).one_or_none()
			results = dict(result._mapping) if result else None
			return results

	def search_session_abstracts(self,abs_search_text,abs_type,selection_type,presentation_type,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_search_abstract_v1",[abs_type,abs_search_text,presentation_type,selection_type,conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def add_session_abstract(self,session_id,abs_id,btn_val,conf_schema):
		with engine.connect() as conn:
			if int(btn_val) == 0:
				session_id = 'NULL'
			stmt = text("update {}.abstracts set abs_session_id = {} where abs_id in ({}) ".format(conf_schema,session_id,abs_id))
			result = conn.execute(stmt)
			conn.commit()
			return result

	def get_commitment_data(self,conf_id,report_type,start_date,end_date):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_commiment_users",[conf_id,report_type,start_date,end_date])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
	
	def get_commitment_data_session(self,conf_id,session_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_commiment_users_by_session",[conf_id,session_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
	

	def get_user_commitment_data_whatsapp(self,user_id,report_type,start_date,end_date,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_user_commmintment_whatsapp",[user_id,report_type,start_date,end_date,conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
			
	def get_user_commitment_data_print(self,conf_id,user_id,report_type,start_date,end_date):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_user_commmintment_print",[conf_id,user_id,report_type,start_date,end_date])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_user_commitment_data_public(self,conf_id,user_id,report_type,start_date,end_date):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_user_commmintment_public",[conf_id,user_id,report_type,start_date,end_date])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_user_commitment_data(self,conf_id,user_id,report_type,start_date,end_date):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_user_commmintment",[conf_id,user_id,report_type,start_date,end_date])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def update_gp_session(self,data,abs_id,conf_schema):
		abs_session_types = Table("abs_session_types", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			get_stmt    = text("select * from {}.abstracts where abs_id = {}".format(conf_schema,abs_id))
			result = conn.execute(get_stmt).one_or_none()
			result = dict(result._mapping) if result else None
			data["session_name"] = result["abs_type"]+str(result["abs_no"])
			insert_stmt  = abs_session_types.insert().values(data)
			conn.execute(insert_stmt)
			session_id=conn.execute(text('select abs_session_id from {}.abs_session_types where session_name = "{}" and conf_id = {}'.format(conf_schema,data["session_name"],data["conf_id"]))).first()
			update_stmt = text("update {}.abstracts set abs_session_id = {} where abs_id = {}".format(conf_schema,session_id.abs_session_id,abs_id))
			result = conn.execute(update_stmt)
			conn.commit()
			return 'Success'

	def get_mail_template(self,template_key,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_mail_templete where conf_id = {} and template_key = '{}'".format(conf_id,template_key))
			result = conn.execute(stmt).one_or_none()
			results=dict(result._mapping) if result else None
			return results

	def get_keynote_abstract(self,abs_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abstracts where abs_id = {}".format(conf_schema,abs_id))
			result = conn.execute(stmt).one_or_none()
			results=dict(result._mapping) if result else None
			if results:
				return results
			else:
				return results

	def get_keynote_abstract_data(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abstracts ab left join users u on u.user_id = ab.user_id where abs_type = 'KA{}' and conf_id = {} order by abs_id".format(conf_schema,abs_type,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def add_keynote_author(self,abs_id,user_id,abs_type,conf_schema):
		with engine.connect() as conn:
			stmt   = text("update {}.abstracts set user_id = {} where abs_id = {}".format(conf_schema,user_id,abs_id))
			stmt_1 = text("select * from {}.abstracts ab inner join users u on ab.user_id = u.user_id where abs_id = {}".format(conf_schema,abs_id))
			conn.execute(stmt)
			conn.commit()
			result = conn.execute(stmt_1).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def New_keynote_abstract(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt   = text("insert into {}.abstracts (abs_type,abs_status_id,conf_id) VALUES('KA{}',2,{})".format(conf_schema,abs_type,conf_id))
			stmt_1 = text("select * from {}.abstracts ab left join users u on ab.user_id = u.user_id where abs_type = 'KA{}' and conf_id = {}  order by abs_id desc limit 1".format(conf_schema,abs_type,conf_id))
			conn.execute(stmt)
			conn.commit()
			result = conn.execute(stmt_1).one_or_none()
			results=dict(result._mapping) if result else None
			return results

	def Get_old_Keynote_abs_id(self,abs_id,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abstracts ab left join users u on u.user_id = ab.user_id where keynote_abs_id = {} and conf_id = {}".format(conf_schema,abs_id,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def generate_keynote_session(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("update {}.abstracts kaabs inner join {}.abstracts abs on kaabs.keynote_abs_id = abs.abs_id set kaabs.abs_session_id = abs.abs_session_id   where kaabs.abs_type = 'KA{}' and kaabs.conf_id = {}".format(conf_schema,conf_schema,abs_type,conf_id))
			result = conn.execute(stmt)
			conn.commit()
			return result

	def get_session_types(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abs_session_types where s_abs_type is not null and conf_id = {}".format(conf_schema,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_marksheet_data(self,session_id,abs_type,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_generate_abs_marksheet",[session_id,abs_type,conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_print_abstracts_data(self,abs_type,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_print_abstract",[abs_type,conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
		
	def get_print_avcode_abstracts_data(self,abs_type,date_wise,hall_wise,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_print_abstract_avcode",[abs_type,hall_wise,date_wise,conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_session_judge_data(self,session_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select *,r.role as judge_role from {}.abs_judges aj left join abs_roles r on aj.role_id = r.role_id left join users u on aj.user_id=u.user_id where session_id = {}".format(conf_schema,session_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def insert_new_judge(self,data,conf_schema):
		abs_judges = Table("abs_judges", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			stmt   = text("select count(user_id) as count from {}.abs_judges where session_id = {} and user_id = {}".format(conf_schema,data["session_id"],data["user_id"]))
			stmt_1 = abs_judges.insert().values(data)
			count  = conn.execute(stmt).one_or_none() # this should be checked
			result = []
			if count[0] == 0:
				result = conn.execute(stmt_1)
				conn.commit()
			return result

	def delete_judge(self,session_id,user_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("delete from {}.abs_judges where session_id = {} and user_id = {}".format(conf_schema,session_id,user_id))
			result = conn.execute(stmt)
			conn.commit()
			return result

	def regen_judge(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_regenatrate_judges_marks",[conf_id])
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
			
	def get_speaker_attendance_list(self,conf_id,date,hall):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			abs_session_id = None
			cursor.callproc("usp_get_abstract_session_spakers",[conf_id,date,hall,abs_session_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
 
# Priyavarthana for getting attachement from abstract presentation type

	def get_attachement_reminder(self,conf_id):
		with engine.connect() as conn:
			stmt = text(f"select * from abs_types where  conf_id ={conf_id} and is_attachement=1")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_abstract_received_notreceived(self,abs_status_id,cd_status_id,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			abs_type_stmt = ""
			str_where = ''
			if cd_status_id and int(cd_status_id) == 1:
				abs_type_stmt = " and cd_received_at is not null  "
			elif cd_status_id and  int(cd_status_id)==2:
				abs_type_stmt = " and cd_received_at is null"
			if abs_status_id is not None:
				str_where = ' where abs_type = "{}" and ab.conf_id = {} and  abs_status_id ={}'.format(abs_type,conf_id+abs_type_stmt,abs_status_id)
			else:
				str_where = ' where abs_type = "{}" and ab.conf_id = {} and  abs_status_id >0'.format(abs_type,conf_id+abs_type_stmt)

			stmt = text('select concat(u.prefix,u.full_name) as presenting_author,u.email,u.mobile,concat(abs_type,abs_no) as abss_type,ab.abs_id,title,ab.user_id,parent_category_id,ab.category_id,display_name,parent_category,'+
				'cd_received_at,abs_status_id,video_link,au.upload_id,au.file_name,au.path,au.img_type from '+str(conf_schema)+'.abstracts ab left join abs_categories c on c.category_id = ab.category_id '+
				' left join '+str(conf_schema)+'.abs_topics abt on abt.abs_id=ab.abs_id and abt.role_id=35 '+
				' left join '+str(conf_schema)+'.abs_uploads au on au.abs_id=ab.abs_id '+
				' left join users u on u.user_id=abt.user_id '
				' {} order by ab.abs_no asc'.format(str_where))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_attachement_abstract_type(self,conf_id,abs_type):
		with engine.connect() as conn:
			stmt = text(f"select * from abs_types where  conf_id ={conf_id} and abs_type='{abs_type}'")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def usp_abs_get_user_data_bo(self,user_id,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_abs_get_user_data_bo",[user_id,conf_id])
			while 1:
				#(column_name, type_, ignore_, ignore_, ignore_, null_ok, column_flags)
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
						
					row = dict(zip(names, row_raw))
					set_.append(row)
	 
				sets.append(list(set_))
	 
				if cursor.nextset() is None:
					break
	 
				# nextset() doesn't seem to be sufficiant to tell the end.
				if cursor.description is None:
					break
		finally:
			# Return the connection to the pool (won't actually close).
			connection.close()
			
		return sets 
		
	def get_mail_ids_by_abs_id_v1(self,abs_ids,conf_schema):
		with engine.connect() as conn:
			#stmt   = text("select email,full_name,display_name,prefix,abs_id,abs_type,abs_no,title,abs_status_id from abstracts ab  join users u on ab.user_id = u.user_id  left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by abs_id".format(abs_ids))
			stmt    = text("select group_concat(distinct(tu.email)) as co_email,u.email,u.full_name,display_name,u.prefix,u.user_uuid,ab.abs_id,ab.abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,aw.award_name,awa.award_name as medal from "+str(conf_schema)+".abstracts ab left join "+str(conf_schema)+".abs_topics abt on abt.abs_id=ab.abs_id and abt.role_id in (32,34) inner join users u on abt.user_id = u.user_id "+
							" left join "+str(conf_schema)+".abs_session_types abs on ab.abs_session_id = abs.abs_session_id left join abs_topics t on ab.abs_id = t.abs_id and t.role_id in (33,35,36) and t.user_id != ab.user_id left join users tu on t.user_id = tu.user_id left join abs_halls ah on abs.hall_id = ah.hall_id "+
							" left join abs_categories c on ab.category_id = c.category_id left join abs_awards aw on aw.award_id=ab.award_id left join map_abs_award maw on maw.abs_id=ab.abs_id left join abs_awards awa on awa.award_id= maw.award_id  where ab.abs_id in ({}) group by ab.abs_id ".format(abs_ids))
			# stmt  = text("select email,full_name,display_name,prefix,abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,ab.name_in_grid,ab.starts_by,ab.ends_by from abstracts ab inner join users u on ab.user_id = u.user_id left join abs_session_types abs on ab.abs_session_id = abs.abs_session_id left join abs_halls ah on ab.hall_id = ah.hall_id left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by abs_id ".format(abs_ids))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def getAbsNosType(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"select abs_id,concat(abs_type,ifnull(abs_no,'')) as abst_no from {conf_schema}.abstracts where abs_type='{abs_type}' and conf_id = {conf_id} and abs_no is not null and cd_received_at is null order by abs_no")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			if results :
				return results
			else:
				return None
# END

############# Harini ###########################
	def getMailTemplate(self,conf_id):
		with engine.connect() as conn:
			stmt = text(f"select * from mail_templates where conf_ids = {conf_id} and app_type_id=3 ")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			if results :
				return results
			else:
				return None

	def getMailTemplateId(self,conf_id,mail_template_id):
		with engine.connect() as conn:
			stmt = text(f"select * from mail_templates where conf_ids = {conf_id} and app_type_id=3 and mail_template_id = {mail_template_id} ")
			result = conn.execute(stmt).one_or_none()
			results = dict(result._mapping) if result else None
			if results :
				return results
			else:
				return None 

	def update_mail_template(self,mail_template_id,data):
		with engine.connect() as conn:
			stmt = self.mail_templates.update().where(self.mail_templates.c.mail_template_id.in_([mail_template_id])).values(data)
			result = conn.execute(stmt)
			conn.commit()
			if result:
				return "success"
			else:
				return "fail"

	def insert_mail_template(self,data):
		with engine.connect() as conn:
			result = conn.execute(self.mail_templates.insert(), data)
			conn.commit()
			pk_id = result.inserted_primary_key[0] if result.inserted_primary_key[0] else None
			return pk_id
# END #

### Vimal ############
	def GetConsentStatus(self,consent_status,abs_no,conf_id,conf_schema):
		with engine.connect() as conn:
			where_con = ""
			if abs_no != 0:
				where_con = " and a.abs_no = "+str(abs_no)
			if consent_status : 
				where_con = where_con + " and abs.consent_status_id = "+str(consent_status)
			stmt    = text("select concat(a.abs_type,ifnull(a.abs_no,'')) as ic_no,a.title,abs.topic,abs.topic_id,u1.user_id as abs_topic_user_id,u.user_id as abstract_user_id,concat(ifnull(u1.prefix,''),u1.full_name) as co_instructor,u1.email,concat(ifnull(u.prefix,''),u.full_name) as cheif_instuctor,u.email,abs.consent_status_id"
						+" from "+str(conf_schema)+".abstracts a inner join "+str(conf_schema)+".abs_topics abs on a.abs_id=abs.abs_id" 
						+" left join users u on u.user_id=a.user_id left join users u1 on u1.user_id=abs.user_id"
						+" where conf_id="+str(conf_id)+" and a.abs_type='ic' and abs.role_id=33 and a.abs_status_id>0"
						+" "+where_con+"")  
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			if results:
				return results
			else:
				return None 

#   def consent_reminder_mail_data(self,topic_id):
#       stmt = text("SELECT ab.*,abss.setting_value,concat(u.prefix,u.full_name)as full_name,c.display_name,p.type,ab.abs_status_id as status_check,SUM(a.duration) + ab.panel_discussion AS total_duration,abu.path,abu.file_name,aw.award_name,au.user_id as co_user_id, concat(ifnull(au.prefix,''),ifnull(au.full_name,'')) as co_full_name, au.membership_no,a.abs_id,au.email,au.mobile,a.topic_id, a.topic ,a.duration,a.order_no,ab.panel_discussion,a.consent_status_id  FROM abstracts AS ab "
#            +" inner JOIN users u ON ab.user_id = u.user_id "
#            +" left JOIN abs_topics AS a ON a.abs_id = ab.abs_id left join users au on a.user_id = au.user_id"
#            +" left join abs_presentation_type p on ab.presentation_type_id=p.presentation_type_id "
#            +" left join abs_settings abss on abss.setting_key = concat(ab.abs_type,'_guideline') and abss.conf_id = ab.conf_id "
#            +" left join abs_uploads abu on abu.abs_id = ab.abs_id "
#            +" left JOIN  abs_categories c ON c.category_id = ab.category_id"
#            +" left JOIN  abs_awards aw ON aw.award_id = ab.award_id WHERE a.topic_id = {}".format(topic_id))
#       conn = engine.connect()
#       result = conn.execute(stmt)
#       results = [dict(r) for r in result] if result else None
#       # results = result.fetchone()
#       # results[0]['abs_id'] = abs_id
#       # print(results)
#       conn.close()
#       return results[0]
	def  consent_reminder_mail_datas(self,topic_ids,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("SELECT ab.*,abss.setting_value,concat(ci.prefix,ci.full_name)as full_name,c.display_name,p.type,ab.abs_status_id as status_check,SUM(a.duration) + ab.panel_discussion AS total_duration,coi.user_id as co_user_id, concat(ifnull(coi.prefix,''),ifnull(coi.full_name,'')) as co_full_name, coi.membership_no,a.abs_id,coi.email,coi.mobile,a.topic_id, a.topic ,a.duration,a.order_no,ab.panel_discussion,a.consent_status_id  "
				+" FROM "+str(conf_schema)+".abs_topics AS a"
				+" inner JOIN "+str(conf_schema)+".abstracts AS ab ON ab.abs_id = a.abs_id "
				+" inner join "+str(conf_schema)+".abs_topics as aci on aci.abs_id = ab.abs_id and aci.role_id = 32"
				+" inner JOIN users ci ON ci.user_id = aci.user_id "
				+" inner join users coi on coi.user_id = a.user_id"
				+" left join abs_presentation_type p on ab.presentation_type_id=p.presentation_type_id"
				+" left join abs_settings abss on abss.setting_key = concat(ab.abs_type,'_CONSENT_END_ON') and abss.conf_id = ab.conf_id"
				+" left JOIN  abs_categories c ON c.category_id = ab.category_id"
				+" WHERE a.role_id = 33 and a.topic_id in ({}) and ab.conf_id = {} group by topic_id".format(topic_ids,conf_id))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def consent_reminder_mail_users(self,topic_ids,conf_schema):
		with engine.connect() as conn:
			stmt = text("select u.user_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as co_inst_name,u.email,u.mobile,a.* from {}.abs_topics a inner join users u on a.user_id = u.user_id where a.role_id = 33 and a.topic_id in ({}) group by a.user_id".format(conf_schema,topic_ids))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
# Find Abstract 

	def get_abs_types(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt=text("select distinct abs_type from "+str(conf_schema)+".abstracts where conf_id="+str(conf_id)+" order by abs_type asc")
			result=conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			if results:
				return results
			else:
				return None

	def find_abs(self,conf_id,abs_type,abs_no,conf_schema):
		with engine.connect() as conn:
			if abs_type =='Any':
				abs_type = ''
			else:
				abs_type = ' and ab.abs_type="'+str(abs_type)+'"'

			if abs_no:
				abs_no = ' and ab.abs_no = '+abs_no+''
				
			else:
				abs_no = ''

			stmt = text("SELECT group_concat(distinct(concat(ifnull(cu.prefix,''),ifnull(cu.full_name,'')))) as co,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as chief, "+
			   " u.membership_no,concat(ifnull(pu.prefix,''),ifnull(pu.full_name,'')) as present,pu.membership_no as pa_memno,pu.email as pa_email,pu.mobile as pa_mobile,c.display_name,abpt.type,ab.*,aw.award_name,ass.type,ast.status from "+str(conf_schema)+".abstracts ab "+
									" left join "+str(conf_schema)+".abs_topics abt on ab.abs_id = abt.abs_id and abt.role_id in (33,36) "+
									" left join users u on ab.user_id = u.user_id "+
									" left join users cu on abt.user_id = cu.user_id "+
									" left join "+str(conf_schema)+".abs_topics abp on ab.abs_id = abp.abs_id and abp.role_id in (35) "+
									" left join users pu on abp.user_id = pu.user_id "+
									" left join abs_categories c on ab.category_id = c.category_id "+
									" left join abs_presentation_type abpt on ab.presentation_type_id = abpt.presentation_type_id "+
									" left join abs_awards aw on ab.award_id=aw.award_id "+
									" left join abs_selection_type ass on ass.selection_type_id=ab.selection_type_id "+
									" left join abs_status ast on ast.abs_status_id=ab.abs_status_id "+
									" where   ab.conf_id = {} {} {}  group by ab.abs_id order by ab.abs_no ".format(conf_id,abs_type,abs_no))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			if results:
				return results
			else:
				return None
# END #

	def get_evaluation_summary_data(self,abs_type,conf_id,cat_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_evaluation_summary_v1",[abs_type,conf_id,cat_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_export_cols(self,conf_id):
		with engine.connect() as conn:
			stmt    = text(f"select * from export_filter_cols  where is_visible = 1 and is_abs = 1 and FIND_IN_SET ({conf_id},conf_ids)  order by orderby")
# 			print("stmt - ",stmt)
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_select_columns(self,export_columns,conf_id):
		with engine.connect() as conn:
			stmt    = text(f"select * from export_filter_cols where FIND_IN_SET ({conf_id},conf_ids)  and is_visible =1 and is_abs =1 and cols_value_name in ("+str(export_columns)+") and orderby is not null order by FIELD(cols_value_name,"+str(export_columns)+")")
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			if results:
				return results
			else:
				return None
	
	def get_session_date_and_hall_wise(self,date_wise,hall_wise,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt    = text("select case when a.abs_type in ('GP','IC') then concat(a.abs_type,a.abs_no,' - ',a.title) else session_name end as session_title,s.start_date,s.end_date ,h.name as hall_name from {}.abs_session_types s  inner join {}.abstracts a on s.abs_session_id = a.abs_session_id inner join abs_halls h on s.hall_id = h.hall_id where s.conf_id={} and date(s.start_date) = '{}' and s.hall_id = {} group by s.abs_session_id order by s.start_date ".format(conf_schema,conf_schema,conf_id,date_wise,hall_wise))
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
	
	# -------------------whatscommitment-------------------------------

	def get_commitment_template(self,conf_id,template_name):
		with engine.connect() as conn:
			stmt    = text("select * from abs_whatsapp_template where conf_id = {} and template_name = '{}'".format(conf_id,template_name))
			result  = conn.execute(stmt).one_or_none()
			results = dict(result._mapping) if result else None
			if results :
				return results
			else:
				return None

	def update_commitment_and_getcommitment(self,data_for_update,template_id):
		with engine.connect() as conn:
			stmt      = self.abs_whatsapp_template.update().where(self.abs_whatsapp_template.c.template_id.in_([template_id])).values(data_for_update)
			restult_1 = conn.execute(stmt)
			conn.commit()
			stmt_2    = text(f"SELECT * from abs_whatsapp_template where template_id ={template_id}")
			result_2  = conn.execute(stmt_2).one_or_none()
			results   = dict(result_2._mapping)
			if results : 
				return results
			else:
				return None
			
	def get_abs_type_from_selection_type(self,selection_type_id):
		with engine.connect() as conn:
			stmt = text(f"select selection_abs_type from abs_selection_type where selection_type_id= {selection_type_id} ")
			result = conn.execute(stmt).one_or_none()
			results=dict(result._mapping) if result else None
			return results

	# ---------- get abstracts ---------
	def usp_get_abstracts(self,conf_id,user_ids,abs_ids,abs_status_ids):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_get_abstracts",[conf_id,user_ids,abs_ids,abs_status_ids])
			while 1:
				#(column_name, type_, ignore_, ignore_, ignore_, null_ok, column_flags)
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
						
					row = dict(zip(names, row_raw))
					set_.append(row)
	 
				sets.append(list(set_))
	 
				if cursor.nextset() is None:
					break
	 
				# nextset() doesn't seem to be sufficiant to tell the end.
				if cursor.description is None:
					break
		finally:
			# Return the connection to the pool (won't actually close).
			connection.close()
			
		return sets 
		
# -------------- Session clash report ----------------#


	def usp_abs_session_clash(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_abs_session_clash",[conf_id])
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
		
	def insert_custom_user(self,data,user_email,user_name,society_id):
		with engine.connect() as conn:
			user_stmt = text(f"select user_id from users where email = '{user_email}' and society_id = {society_id}")
			result = conn.execute(user_stmt).one_or_none()
			results=dict(result._mapping) if result else None
			if results:
				data['user_id'] = results["user_id"]
				stmt  = self.custom_user_abs_types.insert().values(data)
				result = conn.execute(stmt)
				conn.commit()               
			else:
				user_insert = text(f"insert into users (full_name,email,society_id) values('{user_name}','{user_email}',{society_id})")
				result = conn.execute(user_insert)
				conn.commit()
				result = conn.execute(user_stmt).one_or_none()
				results=dict(result._mapping) if result else None
				data['user_id'] = results["user_id"]
				stmt  = self.custom_user_abs_types.insert().values(data)
				result = conn.execute(stmt)
				conn.commit()
			return "success"

	def update_costom_user(self,data,cu_abs_type_id):
		with engine.connect() as conn:
			stmt = self.custom_user_abs_types.update().values(data).where(self.custom_user_abs_types.c.cu_abs_type_id.in_([cu_abs_type_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None

	def delete_costom_user(self,cu_abs_type_id):
		with engine.connect() as conn:
			stmt = text(f"delete from custom_user_abs_types where cu_abs_type_id = {cu_abs_type_id}")
			result = conn.execute(stmt)
			conn.commit()
			return None
		
	def get_costom_user(self,conf_id):
		with engine.connect() as conn:
			stmt    = text(f"select * from users u inner join custom_user_abs_types c on u.user_id = c.user_id where conf_id = {conf_id};")
			result  = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results  
		
	def get_marksheet_template(self,conf_id,abs_type,selection_type_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_marksheet_template where abs_type = '{}' and conf_id = {} and selection_type_id = {} ".format(abs_type,conf_id,selection_type_id))
			result = conn.execute(stmt).first()
			results= dict(result._mapping) if result else None
			return results
			
	def get_book_print_abstracts_data_v1(self,abs_type,selection_type,conf_id,report_type):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_book_print_abstract_v1",[abs_type,selection_type,conf_id,report_type])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
	
	def get_abs_session_with_judges(self,conf_id,abs_type,session_type,conf_schema):
		with engine.connect() as conn:
			wherecon = f" and s_abs_type = '{abs_type}'" if abs_type else " "
			wherecon = wherecon + f" and abs_session_id in ({session_type}) " if session_type else wherecon + " "
			stmt = text(f"select *,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name from {conf_schema}.abs_session_types s left join {conf_schema}.abs_judges j on s.abs_session_id = j.session_id and j.role_id not in (24) left join  users u on j.user_id = u.user_id left join abs_roles r on j.role_id = r.role_id  inner join abs_halls h on s.hall_id = h.hall_id where s.conf_id = {conf_id} " + wherecon )
			result = conn.execute(stmt).all()
			results= [dict(r._mapping) for r in result] if result else None
			return results
			
	def get_physical_poster_abs(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"select abs_type,abs_no,title,display_name,type,sno,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,u.email,u.mobile,membership_no,st.start_date from "+str(conf_schema)+".abstracts a inner join "+str(conf_schema)+".abs_topics t on a.abs_id = t.abs_id and t.role_id = 35 inner join users u on t.user_id = u.user_id left join abs_categories c on a.category_id = c.category_id left join abs_selection_type s on s.selection_type_id = a.selection_type_id inner join "+str(conf_schema)+".abs_session_types st on a.abs_session_id = st.abs_session_id where a.conf_id = "+str(conf_id)+" and s.selection_type_id = 4 and abs_status_id = 2 order by st.start_date,a.sno,a.abs_type,a.abs_no" )
			result = conn.execute(stmt).all()
			results= [dict(r._mapping) for r in result] if result else None
			return results
	
	def insert_users(self,data):
		with engine.connect() as conn:
			result = conn.execute(self.users.insert(), data)
			conn.commit()
			pk_id = result.inserted_primary_key[0] if result.inserted_primary_key[0] else None
			return pk_id

	def get_selected_upload_abstract(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_types where conf_id = {} and upload_selection_type is not null".format(conf_id))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_selected_abstacts(self,conf_id,selection_type_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abstracts where conf_id = {} and selection_type_id ={} and abs_status_id=2 order by abs_no".format(conf_schema,conf_id,selection_type_id))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_uploaded_image_type(self,abs_id,img_type,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abs_uploads where abs_id = {} and img_type ='{}' ".format(conf_schema,abs_id,img_type))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
	
	def insert_update_halls(self,conf_id,hall_id,data):
		with engine.connect() as conn:
			if (int(hall_id) > 0):
				data.pop("created_at")
				stmt = self.abs_halls.update().where(self.abs_halls.c.hall_id.in_([hall_id])).values(data)
				result = conn.execute(stmt)
			else:
				result = conn.execute(self.abs_halls.insert(),data)
			conn.commit()
			stmt = text("select * from  abs_halls  where conf_id= "+str(conf_id)+";")
			results = conn.execute(stmt).all()
			return [dict(r._mapping) for r in results] if results else None

	def delete_halls(self,hall_id):
		with engine.connect() as conn:
			stmt = text("delete from abs_halls where hall_id = {}".format(hall_id))
			result = conn.execute(stmt)
			conn.commit()
			return "success"

	def get_hall_by_hall_id(self,hall_id):    
		with engine.connect() as conn:
			stmt = select(self.abs_halls).where(self.abs_halls.c.hall_id.in_([hall_id]))
			result = conn.execute(stmt)
			output = result.first()
			if output:
				return dict(output._mapping)
			else:
				return None

	def check_hall_exist_or_not(self,hall_name,hall_id,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_halls where conf_id = {} and hall_id <> {} and name ='{}' ".format(conf_id,hall_id,hall_name))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def check_orderno_exist_or_not(self,order_no,hall_id,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_halls where conf_id = {} and hall_id <> {} and order_no ='{}' ".format(conf_id,hall_id,order_no))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
	
	def get_evaluation_template(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_templates where conf_id = {}".format(conf_id))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_evaluation_template_by_id(self,template_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_templates where template_id = {} ".format(template_id))
			result = conn.execute(stmt).first()
			results= dict(result._mapping) if result else None
			return results

	def insert_update_evaluation_template(self,data,template_id):
		with engine.connect() as conn:
			if template_id:
				stmt = self.abs_templates.update().where(self.abs_templates.c.template_id.in_([template_id])).values(data)
				result = conn.execute(stmt)
			else:
				result = conn.execute(self.abs_templates.insert(),data)
				result = result.inserted_primary_key[0] if result.inserted_primary_key[0] else None
			conn.commit()
			return result

	def delete_eva_template(self,template_id):
		with engine.connect() as conn:
			stmt = text("delete from abs_templates where template_id = {}".format(template_id))
			result = conn.execute(stmt)
			conn.commit()
			return "success"
	
	def get_e_abstracts(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_generate_eabstract_table",[conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def get_avcode(self,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_generate_avcode",[conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_agenda(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_populate_auto_agenda",[conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def get_certificate(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_generate_certificate_v1",[conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def get_badge(self,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_user_commmintment_badge_v2",[None,None,None,None,conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_whatsapp_commitment(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_user_commmintment_whatsapp_schedule",[None,None,conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def usp_get_delegate_commitment(self,conf_id,abs_type,role_id,is_delegate):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_get_delegate_commitment",[conf_id,abs_type,role_id,is_delegate])
			while 1:
				#(column_name, type_, ignore_, ignore_, ignore_, null_ok, column_flags)
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
						
					row = dict(zip(names, row_raw))
					set_.append(row)
	 
				sets.append(list(set_))
	 
				if cursor.nextset() is None:
					break
	 
				# nextset() doesn't seem to be sufficiant to tell the end.
				if cursor.description is None:
					break
		finally:
			# Return the connection to the pool (won't actually close).
			connection.close()
			
		return sets
	
	def get_marksheet_all_template(self,conf_id):
		with engine.connect() as conn:
			stmt = text("select am.*,type from abs_marksheet_template am left join abs_selection_type ast on ast.selection_type_id=am.selection_type_id where conf_id = {}".format(conf_id))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_marksheet_template_by_id(self,temp_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_marksheet_template where temp_id = {} ".format(temp_id))
			result = conn.execute(stmt).first()
			results= dict(result._mapping) if result else None
			return results

	def insert_update_marksheet_template(self,data,temp_id):
		with engine.connect() as conn:
			if temp_id:
				stmt = self.abs_marksheet_template.update().where(self.abs_marksheet_template.c.temp_id.in_([temp_id])).values(data)
				result = conn.execute(stmt)
			else:
				result = conn.execute(self.abs_marksheet_template.insert(),data)
				result = result.inserted_primary_key[0] if result.inserted_primary_key[0] else None
			conn.commit()
			return result

	def delete_marksheet_template(self,temp_id):
		with engine.connect() as conn:
			stmt = text("delete from abs_marksheet_template where temp_id = {}".format(temp_id))
			result = conn.execute(stmt)
			conn.commit()
			return "success"

	def get_distinct_selection(self,conf_id,abs_type,conf_schema):
		with engine.connect() as conn:
			stmt = text("select distinct(a.selection_type_id),type,selection_prefix  from {}.abstracts a inner join  abs_selection_type ast on ast.selection_type_id=a.selection_type_id where conf_id= {} and abs_type='{}' and a.selection_type_id!=0 order by selection_type_id ".format(conf_schema,conf_id,abs_type))
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_selection_prefix(self,selection_type_id):
		with engine.connect() as conn:
			stmt = text("select *  from  abs_selection_type where  selection_type_id = {}".format(selection_type_id))
			result = conn.execute(stmt).first()
			results= dict(result._mapping) if result else None
			return results

	def get_comp_session_types(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text("select * from {}.abs_session_types where s_abs_type not in ('IC','GP') and conf_id = {}".format(conf_schema,conf_id))
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def insert_scoring_marks(self,data,conf_schema):
		with engine.connect() as conn:
			if data:
				stmt_1 = ("INSERT INTO "+str(conf_schema)+".abs_judges_marks (user_id,abs_id,session_id,m1,m2,m3,m4,m5,total_mark,created_at) VALUES")
				row_val = []
				for i in data:
					
					row_val.append(('(' +''' {},{},{},{},{},{},{},{},{},"{}" '''+')').format(str(i['user_id']),i['abs_id'],i['session_id'],i['m1'],i['m2'],i['m3'],i['m4'],i['m5'],i['total_mark'],i['created_at']))
					
				stmt_1 = stmt_1 +  ",".join(row_val)
				stmt_1 = stmt_1 + ''
				result = conn.execute(text(stmt_1))
			conn.commit()
			return None

	def update_scoring_marks(self,data,conf_schema):
		with engine.connect() as conn:
			stmt = 'UPDATE ' +str(conf_schema)+'.abs_judges_marks SET '
			keyname = ["user_id","abs_id","session_id","m1","m2","m3","m4","m5","total_mark","updated_at"]
			judges_mark_ids = []
			for j in keyname:
				stmt = stmt + j +" = case "
				for i in data:
					if j == "updated_at":
						stmt = stmt + ' When judges_mark_id = ' + str(i["judges_mark_id"]) + " then '" + str(i[j]) + "'"
					else:
						stmt = stmt + ' When judges_mark_id = ' + str(i["judges_mark_id"]) + " then " + str(i[j]) + ""
					if i["judges_mark_id"] not in judges_mark_ids:
						judges_mark_ids.append(i["judges_mark_id"])
				stmt = stmt + ' END, '
			if judges_mark_ids:
				stmt = stmt[:-2]
				judges_mark_ids =  ','.join(str(e) for e in judges_mark_ids)
				stmt = stmt + ' Where judges_mark_id in (' +str(judges_mark_ids)+' )'
				result = conn.execute(text(stmt))
				conn.commit()
				return "Success"

	def usp_download_scoring_marksheet(self,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_download_scoring_marksheet",[conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
	
	def InsertFbCommitmentData_v1(self,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_fb_commitment_data",[conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.commit()
			connection.close()
		return sets


	def update_attendance(self,speaker_data,judge_data,conf_schema):
		with engine.connect() as conn:
			stmt = 'UPDATE '+str(conf_schema)+' abs_topics SET '
			stmt1 = 'UPDATE '+str(conf_schema)+' abs_judges SET '
			keyname = ["is_present"]
			judge_pkid = []
			abs_id = []
			for j in keyname:
				stmt = stmt + j +" = case "
				stmt1 = stmt1 + j +" = case "
				for i in speaker_data:
					if i[j]:
						stmt = stmt + ' When abs_id = ' + str(i["abs_id"]) + " then " + i[j]
						abs_id.append(i["abs_id"])
				stmt = stmt + ' END, '
				for i in judge_data:
					if i[j]:
						stmt1 = stmt1 + ' When judges_id = ' + str(i["judges_id"]) + " then " + i[j]
						judge_pkid.append(i["judges_id"])
				stmt1 = stmt1 + ' END, '

			stmt = stmt[:-2]
			stmt1 = stmt1[:-2]
			abs_id =  ','.join(str(e) for e in abs_id)
			judge_pkid =  ','.join(str(e) for e in judge_pkid)
			stmt = stmt + ' Where abs_id in (' +str(abs_id)+' );'
			stmt1 = stmt1 + ' Where judges_id in (' +str(judge_pkid)+' );'
			if len(judge_pkid)!=0:
				# stmt = stmt+stmt1
				result = conn.execute(text(stmt))
				result1 = conn.execute(text(stmt1))
			elif len(abs_id)!=0:
				result = conn.execute(text(stmt))
			conn.commit()
			return "Success"

	def update_judges(self,data,judges_id,conf_schema):
		abs_judges = Table("abs_judges", self.meta, schema=conf_schema, autoload_with=engine)
		with engine.connect() as conn:
			stmt = abs_judges.update().values(data).where(abs_judges.c.judges_id.in_([judges_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None
			
	def get_session_selection_types(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt=text(f"""
					select s.*,a.abs_type from {conf_schema}.abstracts a 
					inner join abs_selection_type s on a.selection_type_id = s.selection_type_id 
					inner join abs_marksheet_template m on s.selection_type_id = m.selection_type_id and a.conf_id = m.conf_id
					where a.conf_id = {conf_id} and a.abs_status_id = 2 group by a.selection_type_id;
					""")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
	
	def get_session_by_selection_types(self,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt=text(f"""
					select s.*,count(distinct judges_id) as judges_count,a.selection_type_id,a.abs_type  from {conf_schema}.abs_session_types s 
					inner join {conf_schema}.abstracts a on s.abs_session_id = a.abs_session_id 
					left join {conf_schema}.abs_judges j on s.abs_session_id = j.session_id
					where s_abs_type is not null and a.conf_id = {conf_id}  group by a.abs_session_id order by judges_count,session_name ; 
					""")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def usp_abs_files_received_status(self,conf_id,abs_type):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_abs_files_received_status",[conf_id,abs_type])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None


	def get_selection_count(self,cat_id,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"select count(*) as total,sum(case when a.category_id = {cat_id} then 1 else 0 end) as category_wise ,t.category_count,(select display_name from abs_categories where category_id = {cat_id}) as category_name,parent_category from {conf_schema}.abstracts a   left join (select count(*) as category_count,a1.category_id,display_name as category_name,parent_category as parent_category from abstracts a1 inner join abs_categories c on a1.category_id = c.category_id where parent_category_id =(select parent_category_id from abs_categories where category_id = {cat_id}) and a1.conf_id = {conf_id} and a1.abs_type = '{abs_type}' and a1.abs_status_id = 2) as t on t.category_id = t.category_id where conf_id = {conf_id} and abs_type = '{abs_type}'  and abs_status_id = 2;")    
			result = conn.execute(stmt).first()
			results = dict(result._mapping) if result else None
			return results

	def get_count_by_selection_type(self,conf_id,cat_id,abs_type,conf_schema):
		with engine.connect() as conn:
			stmt = text(f'select type as selection_type,count(abs_id) as selection_count,sum(case when a.category_id = {cat_id} then 1 else 0 end) as category_wise from abs_selection_type s left join {conf_schema}.abstracts a   on a.selection_type_id = s.selection_type_id and abs_status_id = 2 where conf_id = {conf_id}  and abs_type = "{abs_type}"  group by s.selection_type_id;') 
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_category_with_category_id(self,category_id):
		with engine.connect() as conn:
			stmt = text("select * from abs_categories where category_id = {}".format(category_id))
			result = conn.execute(stmt).first()
			results = dict(result._mapping) if result else None
			return results

	def update_cat_color_code(self,category_id,data):
		with engine.connect() as conn:
			stmt = self.abs_categories.update().values(data).where(self.abs_categories.c.category_id.in_([category_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None

	def usp_abs_selection_result_with_delegate(self,abs_type,selection_type_id,status,delegate_reg,role_id,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_abs_selection_result_with_delegate",[abs_type,selection_type_id,status,delegate_reg,role_id,conf_id])
			while 1:
				#(column_name, type_, ignore_, ignore_, ignore_, null_ok, column_flags)
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
						
					row = dict(zip(names, row_raw))
					set_.append(row)
	 
				sets.append(list(set_))
	 
				if cursor.nextset() is None:
					break
	 
				# nextset() doesn't seem to be sufficiant to tell the end.
				if cursor.description is None:
					break
		finally:
			# Return the connection to the pool (won't actually close).
			connection.close()
			
		return sets

	def get_statistic_data(self,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("get_abs_statistics_report",[conf_id])
			while 1:
				#(column_name, type_, ignore_, ignore_, ignore_, null_ok, column_flags)
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)     
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				# nextset() doesn't seem to be sufficiant to tell the end.
				if cursor.description is None:
					break
		finally:
			# Return the connection to the pool (won't actually close).
			connection.close()
		return sets
	
	def get_other_id_selected_by_user(self,conf_id,user_id,abs_type,conf_schema):
		with engine.connect() as conn:
			if abs_type == "IC":
				stmt = text(f'select a.*,concat(ifnull(u.prefix,""),ifnull(u.full_name,"")) as chief_name,u.email,u.mobile  from {conf_schema}.abstracts a inner join {conf_schema}.abs_topics t on a.abs_id = t.abs_id and t.user_id = {user_id} and consent_status_id = 2 inner join {conf_schema}.abs_topics ct on a.abs_id = ct.abs_id and ct.role_id = 32 inner join users u on ct.user_id = u.user_id where conf_id = {conf_id} and abs_type = "IC" and a.user_id != {user_id} and abs_status_id = 2;') 
			else:
				stmt = text(f'select a.*,concat(ifnull(u.prefix,""),ifnull(u.full_name,"")) as chief_name,u.email,u.mobile,c.display_name as category,s.type as selection_type,p.type as presentation_type,concat(round((total_marks/ed.evaluated),2)) as percentage from {conf_schema}.abstracts a  inner join {conf_schema}.abs_topics t on a.abs_id = t.abs_id  and consent_status_id = 2 and t.role_id in (35) inner join abs_categories c on a.category_id = c.category_id inner join abs_selection_type s on a.selection_type_id = s.selection_type_id left join abs_presentation_type p on a.presentation_type_id = p.presentation_type_id inner join users u on t.user_id = u.user_id left join (select count(*) evaluated,abs_id from {conf_schema}.abs_marks t1 where t1.marks_total > 0 group by abs_id) ed on a.abs_id = ed.abs_id left join (select sum(ifnull(marks_total,0)) as total_marks,abs_id from {conf_schema}.abs_marks t2 group by abs_id) mt on a.abs_id = mt.abs_id where a.conf_id = {conf_id} and abs_type = "{abs_type}"  and abs_status_id = 2 and t.user_id = {user_id} ')
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_judge_abs_types(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"select s.*,a.abs_type from abs_selection_type s inner join {conf_schema}.abstracts a on a.selection_type_id = s.selection_type_id where a.conf_id = {conf_id} and a.abs_type not in ('IC') group by s.selection_type_id;")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_session_by_selection_type(self,conf_id,selection_type_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"""select s.*,h.name as hall_name,group_concat(distinct ifnull(u.prefix,''),u.full_name,' - ',r.role separator '<br>') as judge_name,count(distinct u.user_id) as judge_count from {conf_schema}.abstracts a 
							inner join {conf_schema}.abs_session_types s on a.abs_session_id = s.abs_session_id 
							left join abs_halls h on s.hall_id = h.hall_id
							left join {conf_schema}.abs_judges j on s.abs_session_id = j.session_id
							left join abs_roles r on j.role_id = r.role_id
							left join users u on j.user_id = u.user_id
							where a.selection_type_id = {selection_type_id} and a.conf_id = {conf_id} group by a.abs_session_id order by session_name;""")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results
	
	def update_withdraw_abs(self,abs_id,updated_at,conf_schema):
		with engine.connect() as conn:
			stmt = text("update {}.abstracts set abs_status_id = {},updated_at='{}' where abs_id in ({})".format(conf_schema,4,updated_at,abs_id))
			result = conn.execute(stmt)
			conn.commit()
			if result:
				return "success"
			else:
				return "fail"

	def get_all_sessions(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"select * from {conf_schema}.abs_session_types ast inner join abs_halls ah on ast.hall_id = ah.hall_id where ast.conf_id = {conf_id} order by start_date;")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results

	def get_distinct_all_selectiontype(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f"select distinct(a.selection_type_id),type,abs_type from {conf_schema}.abstracts a left join abs_selection_type ast on ast.selection_type_id=a.selection_type_id where conf_id={conf_id} and abs_status_id=2 and a.selection_type_id!=0 group by a.selection_type_id;")
			result = conn.execute(stmt).all()
			results=[dict(r._mapping) for r in result] if result else None
			return results
	
	# program sheet functions
	def get_session_data_programsheet(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f'select s.abs_session_id,case when abs_type = "GP" then a.title else session_name end as session_name,a.abs_id,s.start_date,s.end_date,s.hall_id,h.name as hall_name from {conf_schema}.abs_session_types s  left join {conf_schema}.abstracts a on s.abs_session_id = a.abs_session_id and abs_type in ("IC","GP") and abs_status_id = 2 and a.conf_id = s.conf_id  left join abs_halls h on s.hall_id = h.hall_id where s.conf_id = {conf_id};') 
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
	def save_change_session(self,old_session_id,new_session_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f'update {conf_schema}.abs_session_types t1 left join {conf_schema}.abs_session_types t2 on t2.abs_session_id = {old_session_id} set t1.start_date = t2.start_date,t1.end_date = t2.end_date,t1.hall_id = t2.hall_id where t1.abs_session_id = {new_session_id};')  
			result = conn.execute(stmt)
			stmt = text(f'update {conf_schema}.abs_session_types t1  set t1.start_date = null,t1.end_date = null,t1.hall_id = null where t1.abs_session_id = {old_session_id};')  
			result = conn.execute(stmt)
			conn.commit()
			return "success"
	
	def get_session_data_swapping(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f'Select abst.*,date(start_date) as date,case when a.abs_type in ("IC","GP") then a.title else abst.session_name end as session_name,abh.name as hall_name from {conf_schema}.abs_session_types abst left join abs_halls abh on abst.hall_id = abh.hall_id left join {conf_schema}.abstracts a on abst.abs_session_id = a.abs_session_id where abst.conf_id = {conf_id} and abst.start_date is not null and abst.end_date is not null group by abst.abs_session_id')    
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
	def save_swapping_session_data(self,right_session_id,left_session_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f'select * from {conf_schema}.abs_session_types where abs_session_id = {right_session_id}')   
			result = conn.execute(stmt).first()
			data = dict(result._mapping) if result else None
			stmt = text(f'update {conf_schema}.abs_session_types t1 left join {conf_schema}.abs_session_types t2 on t2.abs_session_id = {left_session_id} set t1.start_date = t2.start_date,t1.end_date = t2.end_date,t1.hall_id = t2.hall_id where t1.abs_session_id = {right_session_id};')   
			result = conn.execute(stmt)
			start_date = data['start_date']
			end_date = data['end_date']
			hall_id = data['hall_id']
			stmt = text(f'update {conf_schema}.abs_session_types t1  set t1.start_date = "{start_date}",t1.end_date = "{end_date}",t1.hall_id = {hall_id} where t1.abs_session_id = {left_session_id};')  
			result = conn.execute(stmt)
			conn.commit()
			return "success"
		
	def get_duplicate_session_clash_data(self,session_id,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text(f'select s.abs_session_id, s.session_name, s.start_date, s.end_date, s.hall_id, h.name as hall_name from {conf_schema}.abs_session_types s inner join {conf_schema}.abs_session_types s1 on  (s1.start_date between s.start_date and s.end_date or s.start_date between s1.start_date and s1.end_date )  and s1.conf_id = s.conf_id and s1.start_date != s.end_date and s.start_date != s1.end_date inner join {conf_schema}.abstracts a on s.abs_session_id = a.abs_session_id and a.abs_status_id = 2 left join abs_halls h on h.hall_id = s.hall_id where s.conf_id = {conf_id} and s1.hall_id = s.hall_id and s1.abs_session_id = {session_id} group by s.abs_session_id order by s.start_date ;')  
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_session_clash_speaker_data(self,session_id,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_abs_session_clash_session_wise",[conf_id,session_id])
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
			
#	Searching data
	def get_searched_data(self,search_text,abs_types,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_abs_searched_record",[search_text,abs_types,conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None			
	
	def get_print_template_data(self):
		with engine.connect() as conn:
			data = conn.execute(text("select * from abs_print_template")).all()
			results = [dict(r._mapping) for r in data] if data else None
			return results
	
	def insert_print_template(self,data):
		with engine.connect() as conn: #print_temp
			data = conn.execute(self.print_temp.insert().values(data))
			conn.commit()
			return "success"
	
	def get_print_template(self,template_id):
		with engine.connect() as conn:
			result = conn.execute(text(f"select * from abs_print_template where template_id = {template_id} ")).first()
			results = dict(result._mapping) if result else None
			return results
	
	def update_print_template(self,data,template_id):
		with engine.connect() as conn:
			stmt = self.print_temp.update().values(data).where(self.print_temp.c.template_id.in_([template_id]))
			result = conn.execute(stmt)
			conn.commit()
			return None
	
	def get_abstracts_print_data(self,conf_id,abs_status,abs_types,selection,order_by):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_print_abstract_data",[conf_id,abs_status,abs_types,selection,order_by])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
	
	def get_cme_point_data(self,conf_id,is_signed_delegates):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_cme_point_report_v1",[conf_id,is_signed_delegates])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets

	def get_all_upload_attachment(self,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('''select a.abs_id,abs_type,abs_no,title,au.path,au.file_name,au.upload_id,u.prefix,u.full_name,u.email,u.mobile,ac.display_name from {}.abstracts a left JOIN {}.abs_topics ast ON ast.abs_id = a.abs_id and ast.role_id=35 left join users u on u.user_id=ast.user_id  left join abs_categories ac on a.category_id = ac.category_id left join {}.abs_uploads au on au.abs_id = a.abs_id and img_type is not null where a.conf_id = {} and abs_status_id in (1,2) and a.abs_type='OP'  order by a.abs_type,abs_no ;'''.format(conf_schema,conf_schema,conf_schema,conf_id))  
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_abstract_awards(self,award_id,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('''select a.abs_id,a.abs_type,abs_no,title,u.prefix,u.full_name,u.email,u.mobile,abw.award_name,u.user_id,u.dob from {}.abstracts a left JOIN {}.abs_topics ast ON ast.abs_id = a.abs_id and ast.role_id=35 left join users u on u.user_id=ast.user_id left join abs_awards abw on abw.award_id=a.award_id  where a.conf_id = {} and abs_status_id in (1) and a.abs_type='{}' and a.award_id ={} and a.misc2 is null order by a.abs_type,abs_no ;'''.format(conf_schema,conf_schema,conf_id,abs_type,award_id))  
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def get_verified_award(self,award_id,abs_type,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt = text('''select * from {}.abstracts  where conf_id = {} and abs_no is not null and abs_type='{}' and award_id ={} and misc2 is not null order by abs_type,abs_no ;'''.format(conf_schema,conf_id,abs_type,award_id))  
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
	
	def get_print_dig_podium_abstracts_data(self,abs_type,date_wise,hall_wise,conf_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor     = connection.cursor()
			cursor.callproc("usp_get_print_digital_podium",[abs_type,hall_wise,date_wise,conf_id])
			while 1:
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
					row = dict(zip(names, row_raw))
					set_.append(row)
				sets.append(list(set_))
				if cursor.nextset() is None:
					break
				if cursor.description is None:
					break
		finally:
			connection.close()
		return sets
		
	#---Result Announcements-----

	def get_abs_session_id(self,is_semi_final,is_final,is_winner,conf_id,conf_schema):
		with engine.connect() as conn:
			if is_semi_final:
				stmt=text("SELECT ast.type, a.selection_type_id,ast.selection_abs_type FROM "+str(conf_schema)+".abstracts a "
						+"left join abs_selection_type ast on ast.selection_type_id = a.selection_type_id "
						+f"where a.selection_type_id is not null and a.selection_type_id >0 and is_semi_final={is_semi_final} and a.conf_id={conf_id} and ast.selection_abs_type is not null and abs_id is not null and abs_status_id=2 group by selection_type_id ;")
			elif is_final:
				stmt=text("SELECT ast.type, a.selection_type_id,ast.selection_abs_type FROM "+str(conf_schema)+".abstracts a "
						+"left join abs_selection_type ast on ast.selection_type_id = a.selection_type_id "
						+f"where a.selection_type_id is not null and a.selection_type_id >0 and is_final={is_final} and a.conf_id={conf_id} and ast.selection_abs_type is not null and abs_id is not null and abs_status_id=2 group by selection_type_id ;")
			elif is_winner:
				stmt=text("SELECT ast.type, a.selection_type_id,ast.selection_abs_type FROM "+str(conf_schema)+".abstracts a "
						+"left join abs_selection_type ast on ast.selection_type_id = a.selection_type_id "
						+f"where a.selection_type_id is not null and a.selection_type_id >0 and is_winner={is_winner} and a.conf_id={conf_id} and ast.selection_abs_type is not null and abs_id is not null and abs_status_id=2 group by selection_type_id ;")
			else:
				stmt=text("SELECT ast.type, a.selection_type_id,ast.selection_abs_type FROM "+str(conf_schema)+".abstracts a "
						+"left join abs_selection_type ast on ast.selection_type_id = a.selection_type_id "
						+f"where a.selection_type_id is not null and a.selection_type_id >0 and a.conf_id={conf_id} and ast.selection_abs_type is not null and abs_id is not null and abs_status_id=2 group by selection_type_id ;")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
	def get_session_date_time(self,selection_type_id,conf_id,conf_schema):
		with engine.connect() as conn:
			stmt=text("SELECT session_name,name,start_date,end_date FROM "+str(conf_schema)+".abs_session_types ast"
						+" left join abs_halls ah on ah.hall_id=ast.hall_id"
						+f" where ast.conf_id={conf_id} and ast.abs_session_id={selection_type_id};")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
	def get_abs_session_name(self,conf_id,selection_type_id,conf_schema):
		with engine.connect() as conn:
			stmt=text(f"select session_name, abs_session_id from {conf_schema}.abs_session_types where abs_session_id in(select a.abs_session_id from {conf_schema}.abstracts a where a.selection_type_id={selection_type_id} and conf_id={conf_id});")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results

	def usp_get_bo_result_announcement(self,conf_id,selection_type_id,get_abs_session_id,abs_category,result_type):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_bo_result_announcement_v1",[conf_id,selection_type_id,get_abs_session_id,abs_category,result_type])
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
		
	def update_session_and_award_winner(self,selected_col,selected_abs_id,unselected_abs_id,conf_id,conf_schema):
		with engine.connect() as conn:
			try:
				if selected_abs_id:
					stmt = text(f"update {conf_schema}.abstracts set "+selected_col+f" = 1 where abs_id in ({selected_abs_id}) and conf_id={conf_id} ;")
					result = conn.execute(stmt)
					conn.commit()
					return "success"
				else:
					stmt = text(f"update {conf_schema}.abstracts set "+selected_col+f" = NULL where abs_id in ({unselected_abs_id}) and conf_id={conf_id} ;")
					result = conn.execute(stmt)
					conn.commit()
					return "success"
				# else:
				#     stmt_1=text("update abstracts set "+selected_col+f" = NULL where conf_id={conf_id};")
				#     result = conn.execute(stmt_1)
				#     conn.commit()
				#     return "success"
			except Exception as err:
				Log().Error('BOModel','update_award_winner',str(err))
				return "fail"
			
	def get_cateories_by_abs_type(self,conf_id,selection_type_id,is_semi_final,conf_schema):
		with engine.connect() as conn:
			stmt=text(f"select distinct ac.display_name,ac.category_id from abs_categories ac left join {conf_schema}.abstracts abs on abs.category_id=ac.category_id where abs.conf_id={conf_id} and abs.selection_type_id={selection_type_id} and is_semi_final={is_semi_final} and abs.abs_session_id is not null order by ac.category_id asc;")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
	def get_abs_award_winner(self,conf_id):
		with engine.connect() as conn:
			stmt=text("select aw.award_id,aw.conf_id,aw.selection_type_id,aw.award_name from abs_awards aw " 
						+" left join abs_selection_type ast on ast.selection_type_id = aw.selection_type_id "
						+f" where aw.conf_id={conf_id};")
			result = conn.execute(stmt).all()
			results = [dict(r._mapping) for r in result] if result else None
			return results
		
	def update_selected_abs_ids(self,selected_abs_ids,selection_type_id,conf_id,conf_schema):
		with engine.connect() as conn:
			if selected_abs_ids:
				stmt_1 = text(f"update {conf_schema}.abstracts set is_winner = NULL where abs_id not in ({selected_abs_ids}) and selection_type_id={selection_type_id} and conf_id={conf_id};")
				stmt = text(f"update {conf_schema}.abstracts set is_winner = 1 where abs_id in ({selected_abs_ids}) and selection_type_id={selection_type_id} and conf_id={conf_id} ;")
				result = conn.execute(stmt)
				result1 = conn.execute(stmt_1)
				conn.commit()
				return result
			else:
				stmt_1=text(f"update {conf_schema}.abstracts set is_winner = NULL where selection_type_id={selection_type_id} and conf_id={conf_id};")
				result = conn.execute(stmt_1)
				conn.commit()
				return result

	def usp_get_bo_selected_final_screen(self,conf_id,col_name,selection_type_id,abs_session_id,abs_category_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_bo_selected_final_screen_v1",[conf_id,col_name,selection_type_id,abs_session_id,abs_category_id])
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None

	def usp_generate_ic_sessions(self,conf_id):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_generate_ic_sessions",[conf_id])
		 
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		if results :
			return results
		else :
			return None
			
app.jinja_env.globals.update(BoModel=BoModel)

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists