Sindbad~EG File Manager

Current Path : /home/numerotech/profile.aios-scientificcommittee.org/aios_profile_v1/core/model/
Upload File :
Current File : //home/numerotech/profile.aios-scientificcommittee.org/aios_profile_v1/core/model/UserModel.py

from sqlalchemy import create_engine, MetaData, Table, insert, select,update,delete,text
from sqlalchemy.sql import and_, or_,text
from core import app
from core.library.helper import Helper
import json
import sqlite3 
import pandas as pd

engine = create_engine(app.config['DATABASE_URI'],pool_size=5000,pool_recycle=3600)
engine_sqlite = create_engine('sqlite:///sqlite_database.db')



class UserModel():
	def __init__(self):
		try:
			self.meta = MetaData()
			self.users = Table("users", self.meta, autoload_with=engine)
			self.user_qualification = Table("user_qualification", self.meta, autoload_with=engine)
			self.user_works = Table("user_works", self.meta, autoload_with=engine)
			self.users_participate_sections = Table("users_participate_sections", self.meta, autoload_with=engine)
			self.users_fellowship_speciality = Table("users_fellowship_speciality", self.meta, autoload_with=engine)
			self.users_specializations = Table("users_specializations", self.meta, autoload_with=engine)
			self.judge_preference_date = Table("judge_preference_date", self.meta, autoload_with=engine)
		except Exception as e:
			print(e)



	def get_users_email_data(self,email,society_id,profile_member_type):
		with engine.connect() as conn:
			stmt    = f"select * from users where email = '{email}' and society_id = {society_id} "
			if profile_member_type:
				stmt    += f" and member_type_id in ({profile_member_type})"
				
			# stmt = ("select * from users where email = '{}' and society_id = {} ;".format(email,society_id))
			results = conn.execute(text(stmt)).first()
			conn.close()
			if results : 
				return dict(results._mapping)
			else:
				return None

	def update_member(self,user_id,data):
		with engine.connect() as conn:
			stmt   = self.users.update().where(self.users.c.user_id.in_([user_id])).values(data)
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result
	

	def get_user_data_by_uuid(self,uuid):
		with engine.connect() as conn:
			stmt    = text(f"select * from users where user_uuid = '{uuid}' ;")
			result  = conn.execute(stmt).first()
			conn.close()
			return  dict(result._mapping) if result else None
		
	def get_society_contents(self,society_id):
		with engine.connect() as conn:
			stmt    = str(f"select sa.index_content,sa.profile_content from society_applications sa where society_id = {society_id}")
			result = conn.execute(text(stmt)).first()
			conn.close()
			return  dict(result._mapping) if result else None


	def get_society(self,society_id,society_key,host=None):
		with engine_sqlite.connect() as conn:
			stmt    = str("select app_id,app_type_id,app_title,app_host,s.society_id,sa.is_active,society_name,society_title,email_logo,society_style,society_key,e_support_mail,society_intial,e_backup_mails,e_from_mail_id,e_reply_mail_id,profile_member_type,aws_bucket,sa.mail_setting_id,s.profile_lock_at,s.profile_lock_message,m.* ,s.e_from_mail_name,sa.app_url,s.secretary_name,s.secretary_mobile,s.e_secretary_mail_id,s.favicon_url,sa.ms_approved_status_id,sa.index_content,sa.profile_content,mat.attach_type_id,mat.attach_type from society_applications sa "+
						" inner join societies s on s.society_id=sa.society_id"+
						" inner join mail_setting m on m.mail_setting_id=sa.mail_setting_id"+
						" left join m_attachment_type mat on mat.society_id=sa.society_id "+
						" where sa.app_type_id=4 and mat.attach_type='Photograph'")
			
			if host:
				stmt 	=  stmt + f"  and sa.app_host='{host}'"
			if society_id:
				stmt 	=  stmt + f"  and s.society_id={society_id}"
			if society_key:
				stmt 	=  stmt + f"  and s.society_key='{society_key}'"
			
			result = conn.execute(text(stmt)).first()
			conn.close()
			return  dict(result._mapping) if result else None
			
	

	def get_society_data(self,society_id):
		with engine.connect() as conn:
			stmt    = text("select app_id,app_type_id,app_title,app_host,s.society_id,sa.is_active,society_name,society_title,email_logo,society_style,society_key,e_support_mail,society_intial,e_backup_mails,e_from_mail_id,e_reply_mail_id,profile_member_type,aws_bucket,sa.mail_setting_id,s.profile_lock_at,s.profile_lock_message,m.* ,s.e_from_mail_name,sa.app_url,s.secretary_name,s.secretary_mobile,s.e_secretary_mail_id,s.favicon_url,sa.ms_approved_status_id,sa.index_content from society_applications sa "+
						" inner join societies s on s.society_id=sa.society_id"+
						" inner join mail_setting m on m.mail_setting_id=sa.mail_setting_id"+
						" where sa.app_type_id=4 and s.society_id={}".format(society_id))
			results = conn.execute(stmt).first()
			conn.close()
			if results : 
				return dict(results._mapping)
			else:
				return None


	def update_attachemant(self,user_id,data,datetime):
		connection  = engine.raw_connection()
		cursor      = connection.cursor()
		cursor.callproc("usp_attachement_update",[user_id,data["attach_type_id"],data["attach_path"],data["attach_file_name"],datetime])
		if cursor.description :
			columns = [column[0] for column in cursor.description]
			results = []
			for row in cursor.fetchall():
				results.append(dict(zip(columns, row)))
			cursor.close()
			connection.commit()
			connection.close()
		return "success"


	def get_otp_random(self,user_id):
		with engine.connect() as conn:
			stmt    = text(f"select otp from users where user_id = {user_id} ")
			results = conn.execute(stmt).first()
			conn.close()
			if results : 
				return dict(results._mapping)
			else:
				return None

	def get_member_attachment(self,user_id,attch_type_id):
		with engine.connect() as conn:
			stmt    = text(f"select u.*,ua.attach_path,ua.attach_file_name,c.country_name,s.state_name,mcs.state_name as mc_state   from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {attch_type_id} left join countries c on u.country_id = c.country_id left join states s on u.state_id = s.state_id  left join states mcs on u.mc_state_id = mcs.state_id where u.user_id = {user_id} ")
			results = conn.execute(stmt).first()
			conn.close()
			if results : 
				return dict(results._mapping)
			else:
				return None

	def get_member(self,user_id):
		with engine.connect() as conn:
			stmt    = text(f"select *  from users  where user_id = {user_id} ")
			results = conn.execute(stmt).first()
			conn.close()
			if results : 
				return dict(results._mapping)
			else:
				return None

	def get_state(self):
		with engine.connect() as conn:
			stmt    = text("select * from states where country_id = 101")
			result  = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None

	def get_country(self):
		with engine.connect() as conn:
			stmt    = text("select * from countries")
			result  = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None
	
	def get_mobile_count(self,mobile,user_id,society_id):
		with engine.connect() as conn:
			stmt   = text(f"select count(*) as mobile_count from users where mobile = {mobile} and user_id != {user_id} and society_id = {society_id} and user_society = 'AIOS'")
			result = conn.execute(stmt).first()
			conn.close()
			if result:
				results = dict(result._mapping)
				return results["mobile_count"]
			else:
				return 0

	def count_whatsapp_num(self,whatsapp_number,user_id,society_id):
		with engine.connect() as conn:
			stmt    = text(f"select count(*) as count from users where user_id <> :user_id and (mobile= :whatsapp_number or whatsapp_number=:whatsapp_number) and society_id={society_id} and user_society = 'AIOS' ;")
			result  = conn.execute(stmt.bindparams(user_id=user_id,whatsapp_number=whatsapp_number)).first()
			conn.close()
			if result:
				results = dict(result._mapping)
				return results["count"]
			else:
				return 0

	def get_country_data(self,country_id):
		with engine.connect() as conn:
			stmt   = text(f"select * from states where country_id = {country_id}")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None


	def get_user_data(self,user_id,society_id,attach_type_id):
		with engine.connect() as conn:
			stmt   = text(f"select ua.*,u.*,c.country_name,s.state_name,mcs.state_name as mc_state from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {attach_type_id} left join countries c on u.country_id = c.country_id left join states s on u.state_id = s.state_id  left join states mcs on u.mc_state_id = mcs.state_id where u.user_id = {user_id} and society_id = {society_id}")
			result = conn.execute(stmt).first()
			conn.close()
			if result:
				return dict(result._mapping)
			else:
				return None



## Harini ###
# for common profile update ##
	# def getSociety(self,society_id,society_key):
	# 	with engine.connect() as conn:
	# 		stmt     = text("select app_id,app_type_id,app_title,app_host,s.society_id,sa.is_active,society_name,society_title,email_logo,society_style,society_key,e_support_mail,society_intial,e_backup_mails,e_from_mail_id,e_reply_mail_id,profile_member_type,aws_bucket,sa.mail_setting_id,s.profile_lock_at,s.profile_lock_message,m.* ,s.e_from_mail_name,sa.app_url,s.secretary_name,s.secretary_mobile,s.e_secretary_mail_id,s.favicon_url from society_applications sa "+
	# 					" inner join societies s on s.society_id=sa.society_id"+
	# 					" inner join mail_setting m on m.mail_setting_id=sa.mail_setting_id"+
	# 					" where sa.app_type_id=4  and s.society_id=:society_id and s.society_key=:society_key;")
	# 		results  = conn.execute(stmt.bindparams(society_id=society_id,society_key=society_key)).first()
	# 		if results :
	# 			return dict(results._mapping)
	# 		else:
	# 			return None  

	def get_mail_template(self,society_id,template_name):
		with engine.connect() as conn:
			stmt    = text("select * from mail_templates where society_id=:society_id and template_name=:template_name;")
			result  = conn.execute(stmt.bindparams(society_id=society_id,template_name=template_name)).first()
			conn.close()
			if result:
				return result
			else:
				return None


	def get_users_data(self,society_id,attch_type_id):
		with engine.connect() as conn:
			stmt   = text("select u.*,ua.attach_path,ua.attach_file_name,c.country_name,s.state_name,mcs.state_name as mc_state from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {attch_type_id} left join countries c on u.country_id = c.country_id left join states s on u.state_id = s.state_id  left join states mcs on u.mc_state_id = mcs.state_id  where u.profile_updated_at != 'null' and society_id = {society_id} order by u.profile_updated_at desc; ")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None


	def usp_get_profile_bo_data(self,society_id,status_id,attach_type_id,offset,limit):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_get_profile_bo_data",[society_id,status_id,attach_type_id,offset,limit])
			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 usp_district_list(self,society_id, user_society):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_district_list",[society_id, user_society])
			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 usp_data_for_district_wise(self,society_id,attach_type_id,district):
	# 	sets = []
	# 	try:
	# 		connection = engine.raw_connection()
	# 		cursor = connection.cursor()
	# 		cursor.callproc("usp_data_for_district_wise",[society_id,attach_type_id,district])
	# 		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 usp_data_for_district_wise_v1(self,society_id,user_society,search_text,attach_type_id,district,in_filter,fromdate,todate,exp_from,exp_to,specialities_list,participate_as_judge,participate_as_mentor,participate_as_evaluation,in_order,offset,limit):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_data_for_district_wise_v2",[society_id,user_society,search_text,attach_type_id,district,in_filter,fromdate,todate,exp_from,exp_to,specialities_list,participate_as_judge,participate_as_mentor,participate_as_evaluation,in_order,offset,limit])
			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_bo_dashboard_count(self,society_id,user_society):
		connection = engine.raw_connection()
		cursor = connection.cursor()
		cursor.callproc("usp_get_bo_dashboard_count",[society_id,user_society])
		columns = [column[0] for column in cursor.description]
		results = []
		for row in cursor.fetchall():
			results.append(dict(zip(columns, row)))
		cursor.close()
		connection.commit()
		connection.close()
		if results :
			return results
		else :
			return None

	def get_total_member_data(self,society_id,attch_type_id):
		with engine.connect() as conn:
			stmt   = text(f"select u.*,ua.attach_path,ua.attach_file_name from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {attch_type_id} where u.status_id = 14 and society_id = {society_id} order by u.profile_updated_at desc; ")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None

	def get_profile_updated_data(self,society_id,attch_type_id):
		with engine.connect() as conn:
			stmt   = text(f"select u.*,ua.attach_path,ua.attach_file_name from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {attch_type_id} where u.profile_updated_at !='null' and society_id = {society_id} order by u.profile_updated_at desc; ")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None

	def get_incomplete_data(self,society_id,attch_type_id):
		with engine.connect() as conn:
			stmt   = text(f"select u.*,ua.attach_path,ua.attach_file_name from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {attch_type_id} where u.profile_updated_at is null and u.status_id=14 and society_id = {society_id} order by u.profile_updated_at desc; ")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None

	# def search_data(self,search_data,society_id,attach_type_id):
	# 	conn = engine.connect()
	# 	stmt = text("SELECT *, u.user_id from users u left join  user_attachments ua on  u.user_id = ua.user_id and attach_type_id =:attach_type_id WHERE (full_name LIKE '%"+search_data+"%' OR email LIKE '%"+search_data+"%' OR mobile LIKE '%"+search_data+"%' OR membership_no LIKE '%"+search_data+"%' OR city LIKE '%"+search_data+"%')   and society_id=:society_id;")
	# 	# stmt = text("SELECT * from users WHERE (full_name LIKE '%{}%' OR email LIKE '%{}%' OR mobile LIKE '%{}%' OR membership_no LIKE '%{}%' OR city LIKE '%{}%') and member_type_id=1 and society_id=:society_id".format(search_data,search_data,search_data,search_data,search_data))	
	# 	results = conn.execute(stmt,society_id=society_id,attach_type_id=attach_type_id)
	# 	conn.close()
	# 	results=  [dict(r) for r in results] if results else None
	# 	if results :
	# 		return results
	# 	else:
	# 		return None

	# def get_search_data(self,search_data,order_by,society_id,attch_type_id):
	# 	stmt   = text("select *,u.user_id from users u left join user_attachments ua on u.user_id = ua.user_id and attach_type_id = {} where email like '%{}%' or full_name like '%{}%' or mobile like '%{}%' or membership_no like '%{}%' and society_id = {} order by  {} ;".format(attch_type_id,search_data,search_data,search_data,search_data,society_id,order_by))
	# 	conn   =engine.connect()
	# 	result = conn.execute(stmt)
	# 	conn.close()
	# 	results = [dict(r) for r in result] if result else None
	# 	return results

	# def getPage(self,society_id,offset,limit):
	# 	conn =  engine.connect()
	# 	stmt    = text("select app_id,app_type_id,app_title,app_host,s.society_id,is_active,sa.ms_approved_status_id,index_content,profile_content,society_name,society_title,email_logo,society_style,society_key,e_support_mail,society_intial,e_backup_mails,e_from_mail_id,e_reply_mail_id,profile_member_type,s.secretary_name,s.secretary_mobile,s.e_secretary_mail_id,s.favicon_url from society_applications sa "+
	# 				" inner join societies s on s.society_id=sa.society_id"+
	# 				" where sa.app_type_id=4 and s.society_id={} limit {},{}; ".format(society_id,offset,limit))
	# 	result = conn.execute(stmt)
	# 	results = [dict(r) for r in result] if result else None
	# 	conn.close()
	# 	if results : 
	# 		return results[0]
	# 	else:
	# 		return None

	# def get_society_data_bo(self,society_id,offset,limit):
	# 	stmt    = text("select app_id,app_type_id,app_title,app_host,s.society_id,is_active,sa.ms_approved_status_id,index_content,profile_content,society_name,society_title,email_logo,society_style,society_key,e_support_mail,society_intial,e_backup_mails,e_from_mail_id,e_reply_mail_id,profile_member_type,s.secretary_name,s.secretary_mobile,s.e_secretary_mail_id,s.favicon_url from society_applications sa "+
	# 				" inner join societies s on s.society_id=sa.society_id"+
	# 				" where sa.app_type_id=4 and s.society_id="+str(society_id)+" limit "+str(offset)+","+str(limit)+";")
	# 	conn    = engine.connect()
	# 	results = conn.execute(stmt)
	# 	results = [dict(r) for r in results] if results else None
	# 	conn.close()
	# 	if results : 
	# 		return results[0]
	# 	else:
	# 		return None

	# insert or update qualification
	def update_or_insert(self,user_id,uq_id,data):
		conn = engine.connect()
		if (int(uq_id) > 0):
			data.pop("created_at")
			stmt = self.user_qualification.update().where(self.user_qualification.c.uq_id.in_([uq_id])).values(data)
			result = conn.execute(stmt)
		else :
			# insert block
			result = conn.execute(self.user_qualification.insert(), data)
		conn.commit()
		
		stmt = text(f"select * from  user_qualification where user_id={user_id};")
		result = conn.execute(stmt).all()
		conn.close()
		results = [dict(r._mapping) for r in result] if result else None
		return results

	def get_qulification_by_user(self,user_id):
		with engine.connect() as conn:
			stmt = text(f"select * from user_qualification where user_id= {user_id};")
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None

	def get_qualification(self,uq_id):    
		# print(uq_id)
		with engine.connect() as conn:
			stmt = select(self.user_qualification).where(self.user_qualification.c.uq_id.in_([uq_id]))
			result = conn.execute(stmt).first()
			conn.close()
			if result:
				return dict(result._mapping)
			else:
				return None

	def delete_qualification(self,uq_id):
		with engine.connect() as conn:
			stmt = text(f"delete from user_qualification WHERE uq_id IN({uq_id})")
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result

	def get_main_work_type(self,society_id):
		with engine.connect() as conn:
			stmt = text("select * from m_work_type where is_parent = 1 and society_id=:society_id")
			result = conn.execute(stmt.bindparams(society_id=society_id)).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None
	
	def get_work_type(self,society_id):
		with engine.connect() as conn:
			stmt = text("select * from m_work_type where is_parent is null  and society_id=:society_id")
			result = conn.execute(stmt.bindparams(society_id=society_id)).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None
	
	def get_position_type(self,society_id):
		with engine.connect() as conn:
			stmt = text("select * from m_position_type where society_id=:society_id order by position_type ")
			result = conn.execute(stmt.bindparams(society_id=society_id)).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None

	def update_or_insert_work(self,user_id,work_id,data):
		with engine.connect() as conn:
			if (int(work_id) > 0):
				data.pop("created_at")
				stmt = self.user_works.update().where(self.user_works.c.work_id.in_([work_id])).values(data)
				result = conn.execute(stmt)
			else :
				# insert block
				result = conn.execute(self.user_works.insert(), data)
			conn.commit()
			stmt=text(f"select * from m_work_type as mw inner join user_works as uw  on mw.work_type_id=uw.work_type_id left join m_position_type mp on mp.position_type_id=uw.position_type_id  where user_id={user_id};")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None

	def get_work_type_by_user(self,user_id):
		with engine.connect() as conn:
			stmt=text(f"select * from m_work_type as mw inner join user_works as uw  on mw.work_type_id=uw.work_type_id left join m_position_type mp on mp.position_type_id=uw.position_type_id where user_id= {user_id};")
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None

	def get_work(self,work_id):
		with engine.connect() as conn:
			stmt = select(self.user_works).where(self.user_works.c.work_id.in_([work_id]))
			result = conn.execute(stmt).first()
			conn.close()
			if result:
				return dict(result._mapping)
			else:
				return None

	def delete_work(self,work_id):
		with engine.connect() as conn:
			stmt = text(f"delete from user_works WHERE work_id IN({work_id})")
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result 

	def get_specialization(self):
		with engine.connect() as conn:
			# stmt = text("select c.*,s.user_id, s.category_id from abs_categories c "
					# + " left join users_specializations s on c.category_id = s.category_id and user_id = :user_id "
					# + " where (is_vt=1 or s.category_id = 322) and is_parent=1 "
					# + " order by display_name;")
			stmt = text("select * from abs_categories where (is_vt=1 or category_id = 322) and is_parent=1 order by category_id;")
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None

	def get_specialization_v1(self,user_id):
		with engine.connect() as conn:
			stmt = text("select c.*,s.user_id from abs_categories c "
					+ " left join users_specializations s on c.category_id = s.category_id and user_id = :user_id "
					+ " where (is_vt=1 or c.category_id = 322) and is_parent=1 "
					+ " order by category_id;")
			# stmt = text("select * from abs_categories where (is_vt=1 or category_id = 322) and is_parent=1 order by display_name;")
			results = conn.execute(stmt.bindparams(user_id=user_id)).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None
	
	def get_fellowshipdata(self,user_id):
		with engine.connect() as conn:
			stmt = text("select c.*,s.user_id from abs_categories c "
					+ " left join users_fellowship_speciality s on c.category_id = s.category_id and user_id = :user_id "
					+ " where is_fp=1  and is_parent=1 "
					+ " order by display_name;")
			results = conn.execute(stmt.bindparams(user_id=user_id)).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None

	def get_old_specialization(self,user_id):
		with engine.connect() as conn:
			stmt = text("select * from users_specializations where user_id = {};".format(user_id))
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None
	
	def get_old_fellowship(self,user_id):
		with engine.connect() as conn:
			stmt = text(f"select * from users_specializations where user_id = {user_id};")
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None

	# def insert_specialization_db(self,insert_specialization,user_id):
	# 	with engine.connect() as conn:
	# 		stmt_1 = ('''INSERT INTO users_specializations (category_id,user_id) VALUES''')
	# 		row_val = []
	# 		for i in insert_specialization:
	# 			row_val.append(('(' + '''{},{}''' +')').format(i,user_id))
	# 		stmt_1 = stmt_1 +  ",".join(row_val)
	# 		stmt_1 = stmt_1 + ';'
	# 		result = conn.execute(stmt_1)
	# 		conn.commit()
	# 		return result

	def insert_specialization_db(self,insert_specialization,user_id):
		with engine.connect() as conn:
			row_val = []
			for i in insert_specialization:
				row_val.append({'category_id':i,'user_id':user_id})

			stmt_1 = insert(self.users_specializations).values(row_val)
			result = conn.execute(text(stmt_1))
			conn.commit()
			conn.close()
			return result

	def delete_specialization_db(self,delete_specialization,user_id):
		with engine.connect() as conn:
			stmt = text("delete from users_specializations WHERE category_id IN("+str(delete_specialization)+") and user_id = "+str(user_id))
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result

	# def insert_fellowship_db(self,insert_specialization,user_id):
	# 		with engine.connect() as conn:
	# 			stmt_1 = ('''INSERT INTO users_fellowship_speciality (category_id,user_id) VALUES''')
	# 			row_val = []
	# 			for i in insert_specialization:
	# 				row_val.append(('(' + '''{},{}''' +')').format(i,user_id))
	# 			stmt_1 = stmt_1 +  ",".join(row_val)
	# 			stmt_1 = stmt_1 + ';'
	# 			result = conn.execute(stmt_1)
	# 			conn.commit()
	# 			return result

	def insert_fellowship_db(self,insert_specialization,user_id):
		with engine.connect() as conn:
			row_val = []
			for i in insert_specialization:
				row_val.append({'category_id':i,'user_id':user_id})

			stmt_1 = insert(self.users_fellowship_speciality).values(row_val)
			result = conn.execute(stmt_1)
			conn.commit()
			conn.close()
			return result

	def delete_fellowship_db(self,delete_fellowship,user_id):
		with engine.connect() as conn:
			stmt = text("delete from users_fellowship_speciality WHERE category_id IN("+str(delete_fellowship)+") and user_id = "+str(user_id))
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result

	def get_delete_fellow(self,user_id):
		with engine.connect() as conn:
			stmt = text(f"delete from users_fellowship_speciality WHERE  user_id = {user_id}")
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result

	def get_specialities(self,user_id):
		with engine.connect() as conn:
			stmt = text("select c.*,s.user_id from abs_categories c "
					+ " left join users_participate_sections s on c.category_id = s.category_id and user_id = :user_id "
					+ " where c.is_fp=1 and c.is_parent=1 "
					+ " order by display_name;")
			results = conn.execute(stmt.bindparams(user_id=user_id)).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None
		
	def get_old_specialities(self,user_id):
		with engine.connect() as conn:
			stmt = text(f"select * from users_participate_sections where user_id = {user_id};")
			results = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in results] if results else None

	# def insert_specialities_db(self,insert_specialities,user_id):
	# 	with engine.connect() as conn:
	# 		stmt_1 = text('''INSERT INTO users_participate_sections (category_id,user_id) VALUES''')
	# 		row_val = []
	# 		for i in insert_specialities:
	# 			row_val.append(('(' + '''{},{}''' +')').format(i,user_id))
	# 		print("$$$$",type(row_val))
	# 		stmt_1 = stmt_1 +  ",".join(row_val)
	# 		stmt_1 = stmt_1 + ';'
	# 		result = conn.execute(text(stmt_1))
	# 		conn.commit()
	# 		return result

	def insert_specialities_db(self,insert_specialities,user_id):
		with engine.connect() as conn:
			row_val = []
			for i in insert_specialities:
				row_val.append({'category_id':i,'user_id':user_id})

			stmt_1 = insert(self.users_participate_sections).values(row_val)
			result = conn.execute(stmt_1)
			conn.commit()
			conn.close()
			return result

	def delete_specialities_db(self,delete_specialities,user_id):
		with engine.connect() as conn:
			stmt = text(f"delete from users_participate_sections WHERE category_id IN({delete_specialities}) and user_id = {user_id}")
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result

	def get_delete_participate(self,user_id):
		with engine.connect() as conn:
			stmt = text("delete from users_participate_sections WHERE  user_id = "+str(user_id))
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result

	def AllUserData(self,user_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_user_all_data",[user_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_user_all_data(self,user_id):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_steps_profile_update_userdata",[user_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_qualification_by_userid(self,user_id):
		with engine.connect() as conn:
			stmt    = text("select * from user_qualification where user_id={} ;".format(user_id))
			result  = conn.execute(stmt).first()
			conn.close()
			if result :
				return result
			else:
				return None

	def get_bo_specialities(self):
		with engine.connect() as conn:
			stmt = text("select c.* from abs_categories c  where c.is_fp=1 and c.is_parent=1  order by display_name;")
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None

	# def get_experiences_by_userid(self,user_id):
	# 	conn    = engine.connect()
	# 	stmt    = text("select * from user_works where user_id={} ;".format(user_id))
	# 	result  = conn.execute(stmt)
	# 	results = result.fetchone()
	# 	conn.close()
	# 	if results :
	# 		return results
	# 	else:
	# 		return None



	# 	def get_userdata(self,society_id,member_type_id):
# # 		stmt = self.users.select().where(self.users.c.email.in_([email]))
# 		stmt = ("select * from users where email = '{}' and society_id = {} and member_type_id in (1,6);".format(email,Helper.society_id))
# 		# stmt = ("select * from users where  society_id = {} and member_type_id = {};".format(society_id,member_type_id))
# 		conn = engine.connect()
# 		results = conn.execute(stmt)
# 		results = [dict(r) for r in results] if results else None
# 		conn.close()
# 		if results : 
# 			return results[0]
# 		else:
# 			return None

	# def get_society(self,society_id):
	# 	stmt    = text("select app_id,app_type_id,app_title,app_host,s.society_id,is_active,index_content,profile_content,society_name,society_title,email_logo,society_style,society_key,e_support_mail,society_intial,e_backup_mails,e_from_mail_id,e_reply_mail_id,profile_member_type from society_applications sa "+
	# 				" inner join societies s on s.society_id=sa.society_id"+
	# 				" where sa.app_type_id=4 and s.society_id={}".format(society_id))
	# 	conn    = engine.connect()
	# 	results = conn.execute(stmt)
	# 	results = [dict(r) for r in results] if results else None
	# 	conn.close()
	# 	if results : 
	# 		return results[0]
	# 	else:
	# 		return None

	# def get_email_count(self,email,user_id):
	# 	stmt    = text("select count(*) as email_count from users where email = '{}' and user_id != {} and society_id = {} ".format(email,user_id,Helper.society_id))
	# 	conn    =engine.connect()
	# 	result  = conn.execute(stmt)
	# 	conn.close()
	# 	results = [dict(r) for r in result] if result else None
	# 	return results[0]["email_count"]
		


#-Judge Preference-------------------------------------------------------------------------------------------------------------------------------	

	def delete_judge_preference_specialities_db(self,user_id):
		with engine.connect() as conn:
			stmt = text(f"delete from users_participate_sections WHERE user_id = {user_id}")
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result
		
	def delete_judge_preference_dates(self,user_id):
		with engine.connect() as conn:
			stmt = text(f"delete from judge_preference_date WHERE user_id = {user_id}")
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result
		
	def get_conference_date(self,conf_id):
		with engine.connect() as conn:
			stmt = text(f"select conf_id, conf_name, conf_key,conf_start_dt,conf_end_dt from conference where conf_id={conf_id};")
			result = conn.execute(stmt).first()
			conn.close()
			return  dict(result._mapping) if result else None
		
	def insert_dates(self,data):
		with engine.connect() as conn:
			stmt_1 = insert(self.judge_preference_date).values(data)
			result = conn.execute(stmt_1)
			conn.commit()
			conn.close()
			return result
		
	def get_user_judge_preference_date(self,user_id,conf_id):
		with engine.connect() as conn:
			stmt = text(f"select user_id, pref_date,morning_session,afternoon_session from judge_preference_date where user_id={user_id} and conf_id={conf_id};")
			results = conn.execute(stmt).all()
			conn.close()
			return  [dict(r._mapping) for r in results] if results else None
		
	def delete_judge_preference(self,user_id):
		with engine.connect() as conn:
# 			stmt = text(f"delete from judge_preference_date WHERE pref_date IN ('{delete}') and user_id = {user_id}")
			stmt = text(f"delete from judge_preference_date WHERE user_id = {user_id}")
			# print(stmt)
			result = conn.execute(stmt)
			conn.commit()
			conn.close()
			return result
		
	def get_selected_section(self,user_id):
		with engine.connect() as conn:
			stmt = text("select ups.*, ac.display_name from users_participate_sections ups "
							+" left join abs_categories ac on ac.category_id=ups.category_id "
							+f" where user_id = {user_id};")
			results = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in results] if results else None
			
	def usp_profile_analytics_v1(self,society_id,in_count,in_filter,in_from,in_to,user_society):
		sets = []
		try:
			connection = engine.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_profile_analytics_v1",[society_id,in_count,in_filter,in_from,in_to,user_society])
			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_country_isd_code(self):
		with engine.connect() as conn:
			stmt = text("select * from countries where isd_code is not null order by country_name")
			result = conn.execute(stmt).all()
			conn.close()
			return [dict(r._mapping) for r in result] if result else None
			
	def check_bo_access(self,user_name,society_id):
		with engine.connect() as conn:
			stmt = text(f"select * from users where email='{user_name}' and society_id= {society_id};")
			result = conn.execute(stmt).first()
			conn.close()
			return  dict(result._mapping) if result else None
			
	def session_data_InsertToSqlite_1(self):
		sqlite_conn = sqlite3.connect('sqlite_database.db')
		tables = ['societies', 'm_attachment_type', 'society_applications', 'mail_setting']
		for table in tables:
			mysql_query = f"SELECT * FROM {table}"
			df = pd.read_sql(mysql_query, engine)
			df.to_sql(table, sqlite_conn, if_exists='replace', index=False)
		sqlite_conn.commit()
		engine.dispose()
		sqlite_conn.close()
		return "success"

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