Sindbad~EG File Manager

Current Path : /home/numerotech/sa.aios-scientificcommittee.org/aios_sa_app/core/model/
Upload File :
Current File : //home/numerotech/sa.aios-scientificcommittee.org/aios_sa_app/core/model/BoModel.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

engine = create_engine(app.config['DATABASE_URI'],pool_size=5000,pool_pre_ping=True,pool_recycle=3600)



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.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_awards          = Table("abs_awards",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).first()
            conn.close()
            return dict(result._mapping) if result else None

    def get_abstract(self):
        with engine.connect() as conn:
            stmt = text("select * from sa_abs_types  where is_visible = 1 and is_abs = 1  group by abs_type order by order_by")
            result = conn.execute(stmt).all()
            conn.close()
            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()
            conn.close()
            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):
        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 abstracts ab "+
                        " inner join 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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_abstract_count(self):
        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 sa_abstracts ab join users u on ab.user_id = u.user_id  where ab.abs_status_id >= {}  group by abs_type".format(i))
                else:
                    stmt = text ("select abs_type,count(abs_id) as abs_count  from sa_abstracts ab join users u on ab.user_id = u.user_id  where ab.abs_status_id = {}  group by abs_type".format(i))
                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,parent_category_id,presentation_type,selection_type,status_type,conf_id):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("get_record_by_type_v2",[abs_type,category_id,parent_category_id,presentation_type,selection_type,status_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()
        connection.close()
        if results :
            return results
        else :
            return None 
    
    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_abs_details_v3(self,abs_type,category_id,presentation_type,selection_type,status_type):
        sets = []
        try:
            connection = engine.raw_connection()
            cursor = connection.cursor()
            cursor.callproc("get_sa_record_by_type_v3",[abs_type,category_id,presentation_type,selection_type,status_type])
            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_parent_category_name(self,parent_category_id):
        with engine.connect() as conn:
            stmt = text("select parent_category from abs_categories where parent_category_id = {}".format(parent_category_id))
            result = conn.execute(stmt).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    def get_physical_poster_abs(self,conf_id):
        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,st.end_date,st.session_name from abstracts a inner join 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 abs_session_types st on a.abs_session_id = st.abs_session_id where a.conf_id = {conf_id} and s.selection_type_id = 4 and abs_status_id = 2 order by a.sno,st.session_name,st.start_date,a.abs_type,a.abs_no" )
            result = conn.execute(stmt).all()
            conn.close()
            results= [dict(r._mapping) for r in result] if result else None
            return results
    
    
    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).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    def get_display_abstracts_type(self,abs_type,conf_id):
        with engine.connect() as conn:
            stmt = text("select title from abs_types where abs_type = '{}' and conf_id = {}".format(abs_type,conf_id))
            result = conn.execute(stmt).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    def get_categories_by_selection_type(self,selection_type_id,conf_id,abs_status_id):
        with engine.connect() as conn:
            stmt = text(f"select c.parent_category_id,c.parent_category,count(*) as count from abstracts a  inner join abs_categories  c on c.category_id = a.category_id  where a.conf_id = {conf_id} and a.abs_status_id ={abs_status_id} and a.selection_type_id = {selection_type_id}  group by c.parent_category_id order by parent_category asc;")
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def get_categories_by_abs_type(self,abs_type,conf_id,abs_status_id):
        with engine.connect() as conn:
            stmt = text(f"select c.parent_category_id,c.parent_category,count(*) as count from abstracts a  inner join abs_categories  c on c.category_id = a.category_id where a.conf_id = {conf_id} and a.abs_status_id ={abs_status_id} and a.abs_type = '{abs_type}' group by c.parent_category_id order by parent_category asc; ")
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    
    def get_status_selection_type_of_presentation_abs_types(self):
        sets = []
        try:
            connection = engine.raw_connection()
            cursor     = connection.cursor()
            cursor.callproc("usp_get_status_selection_type_of_presentation_abs_types_sa")
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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).all()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            return None

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

    def get_abs_type_for_eva(self,conf_id):
        with engine.connect() as conn:
            stmt = text(f"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 = {conf_id} group by t.abs_type")
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results
    
    def get_eva_abs_type_for_eva(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()
            conn.close()
            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()
            conn.close()
            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,completed,assigned from (select * from view_find_evaluator where conf_id = {conf_id} {where_con}) as t1 group by 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_categories_for_eva(self,abs_type,conf_id):
        with engine.connect() as conn:
            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 >= 1 and ab.abs_status_id != 4 and ab.conf_id = {} group by ab.category_id order by display_name".format(abs_type,conf_id))
            
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def get_presentation_type_for_eva(self,abs_type,conf_id):
        with engine.connect() as conn:
            stmt = text(f"select p.* from abs_presentation_type p inner join abstracts a on a.presentation_type_id = p.presentation_type_id where a.conf_id = {conf_id} and a.abs_type = '{abs_type}'  group by  p.presentation_type_id order by p.type ; ")
            result = conn.execute(stmt).all()
            conn.close()
            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()
        connection.close()
        if results :
            return results
        else :
            return None

    def get_search_evaluator_to_assign(self,search,conf_id,society_id,cat_ids=None,report_type_id=None,report_abs_type=None,email_ids=None):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("use_eva_get_evaluators_for_assignment",[society_id,cat_ids,conf_id,search,report_type_id,report_abs_type,email_ids])
         
        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_eva_by_catid(self,abs_type,cat_id,eva_abs_type,conf_id):
        with engine.connect() as conn:
            if abs_type == "IC":
                stmt = text("select ab.*,u.*,m.eva_abs_type,c.category_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,concat(parent_category,' / ',count(m.abs_id)) as cat_count from users u "+
                " join abs_marks m on u.user_id = eva_id "+
                " join 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 c.parent_category_id in ({}) and ab.conf_id = {} and m.eva_abs_type = '{}' group by parent_category_id,eva_id ".format(abs_type,cat_id,conf_id,eva_abs_type))
            else:
                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 abs_marks m on u.user_id = eva_id "+
                " join 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()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results


    def delete_evaluator(self,user_id,conf_id,eva_abs_type):
        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(user_id,conf_id,eva_abs_type))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            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)
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return "success"
        
    def get_abs_for_eval(self,abs_type,cat_id,eval_id,eva_abs_type,abs_no,conf_id,presentation_id):
        with engine.connect() as conn:
            abs_no_where = ""
            if abs_no:
                abs_no_where = " and ab.abs_no in ({}) ".format(abs_no)
            if presentation_id:
                abs_no_where = abs_no_where + " and presentation_type_id in ({}) ".format(presentation_id)
            for eva in eval_id:
                if abs_type == 'IC':
                    stmt = text("select ab.abs_id from abstracts ab inner join abs_categories c on ab.category_id = c.category_id"+
                            " where abs_type='{}' and c.parent_category_id in ({}) and abs_id not in ( select abs_id from abs_marks where  eva_id = {} )  and abs_status_id = 1  and ab.conf_id = {} {} order by ab.abs_no".format(abs_type,cat_id,eva,conf_id,abs_no_where))
                else:
                    stmt = text("select ab.abs_id from abstracts ab"+
                            " where abs_type='{}' and category_id in ({}) and abs_id not in ( select abs_id from abs_marks where  eva_id = {} )  and abs_status_id = 1  and ab.conf_id = {} {} order by ab.abs_no".format(abs_type,cat_id,eva,conf_id,abs_no_where))
                result = conn.execute(stmt).all()
                data=[dict(r._mapping) for r in result] if result else None
                if data:
                    stmt_1 = ('''INSERT INTO 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'],eva,eva_abs_type,group_count))
                    stmt_1 = stmt_1 +  ",".join(row_val)
                    stmt_1 = stmt_1 + ''
                    result = conn.execute(text(stmt_1))
                conn.commit()
                conn.close()
            return None
    
    def delete_eva_abs(self,mark_id):
        with engine.connect() as conn:
            stmt = text("delete from abs_marks where mark_id = {}".format(mark_id))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return "success"

    def get_evaluators(self,abs_type,cat_id,conf_id,percent_filter_start,percent_filter_end,order_by,is_mail=0):
        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,is_mail])
            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):
        with engine.connect() as conn:
            if cat_id :
                    if abs_type == "ICVAL":
                        where_con = "and c.parent_category_id = {}".format(cat_id)    
                    else:
                        where_con = "and c.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(abs_type,where_con,user_id,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            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()
        connection.close()
        if results :
            return results
        else :
            return None

    def get_evaluators_mail(self,user_ids,abs_type,conf_id):
        with engine.connect() as conn:
            if abs_type == 'ICVAL':
                stmt   = text("select  email,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as evaluator_name,u.user_uuid,group_concat(distinct(parent_category)) 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=concat(ab.abs_type,'VAL') and abt.conf_id={} where m.eva_abs_type = '{}' and u.user_id in ({}) group by u.user_id".format(conf_id,abs_type,user_ids))
            else:
                stmt   = text("select  email,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as evaluator_name,u.user_uuid,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=concat(ab.abs_type,'VAL') and abt.conf_id={} where m.eva_abs_type = '{}' and ab.conf_id = {} and u.user_id in ({}) group by u.user_id".format(conf_id,abs_type,conf_id,user_ids))
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def get_mail_ids_by_abs_id(self,abs_ids):
        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(abs_ids))
            stmt = text("select null 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(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()
            conn.close()
            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):
        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(ifnull(u.prefix,''),ifnull(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 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 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  average_mark desc ;".format(abs_type,cat_id,conf_id))
            else:
                stmt = text("select ab.*,u.*,c.category_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,concat(display_name,' / ',count(ab.abs_id)) as cat_count ,concat(round((sum(ifnull(marks_total,0))/ed.evaluated),2)) as average_mark from users u  "+
                        " inner join 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 abs_marks m on m.abs_id = ab.abs_id "+
                        " left join (select count(*) evaluated,abs_id from abs_marks t1 where t1.marks_total > 0 group by abs_id) ed on m.abs_id = ed.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()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt = text("update abstracts set abs_status_id = {},selection_type_id = {} where abs_id in ({});".format(abs_status_id,selection_id,abs_ids))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return result

    def get_categories_for_verify(self,abs_type):
        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(abs_type))
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def get_category_with_abstract(self,abs_type,conf_id):
        with engine.connect() as conn:
            stmt = text("select u.prefix,u.full_name,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 "+
                " from abstracts ab "+
                " left join 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 "+
                " 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()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

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

    def get_templates_data(self):
        with engine.connect() as conn:
            stmt = text("select * from abs_mail_templete where conf_id = {}".format(Auth.get_conference(conf_id).get('conf_id')))
            result = conn.execute(stmt).all()
            conn.close()
            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).first()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def store_hall_assignment(self,data,abs_ids):
        with engine.connect() as conn:
            stmt = 'UPDATE 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)+' )'
            conn = engine.connect()
            result = conn.execute(text(stmt))
            conn.commit()
            conn.close()
            return "Success"

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

    def get_abstract_data(self,abs_id):
        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(abs_id))
            result = conn.execute(stmt).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    def get_abstract_data_for_keynote(self,abs_type,conf_id):
        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 = 2'.format(abs_type,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_gp_abstract_data(self,abs_id):
        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(abs_id))
            result = conn.execute(stmt).first()
            conn.close()
            results = dict(result._mapping) if result else None
            return results

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

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


    def update_GP_co_author(self,data,topic_ids):
        with engine.connect() as conn:
            for i in data:
                stmt = self.author.update().values(i).where(self.author.c.topic_id.in_([i["topic_id"]]))
                result = conn.execute(stmt)
            conn.commit()
            conn.close()
            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()
            conn.close()
            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,conf_id):
        with engine.connect() as conn:
            selection_type_stmt = ''
            if selection_type_id :
                selection_type_stmt = ('and selection_type_id = '+str(selection_type_id))
            stmt = text("SELECT group_concat(distinct(concat(ifnull(cu.prefix,''),ifnull(cu.full_name,''),'(',YEAR(CURDATE())-year(cu.dob),')'))) as co,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as chief,YEAR(CURDATE())-year(u.dob) as chief_age,u.dob,u.membership_no,pu.prefix as present_prefix,pu.full_name as present,pu.dob as present_dob,c.display_name,abpt.type,ab.*,ast.* 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_session_types ast on  ast.abs_session_id = ab.abs_session_id "+
                        " where 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,status,conf_id))
            result  = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_podium_consent_data(self,selection_type_id,status,abs_type,conf_id,consent_status):
        with engine.connect() as conn:
            selection_type_stmt = ''
            consent_status_stmt = ''
            if int(consent_status) == 1: # pending
                consent_status_stmt=('AND podium_consent_at IS NULL')   
            if int(consent_status) == 2: # consented
                consent_status_stmt=('AND podium_consent_at IS NOT NULL')   
            if selection_type_id :
                selection_type_stmt = ('and selection_type_id = '+str(selection_type_id))
            stmt = text("SELECT group_concat(distinct(concat(ifnull(cu.prefix,''),ifnull(cu.full_name,''),'(',YEAR(CURDATE())-year(cu.dob),')'))) as co,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as chief,YEAR(CURDATE())-year(u.dob) as chief_age,u.dob,u.membership_no,pu.prefix as present_prefix,pu.full_name as present,pu.membership_no as presenting_membershipno,pu.email as presenting_email,pu.mobile as presenting_mobile,pu.dob as present_dob,c.display_name,abpt.type,ab.*,ast.session_name,podium_consent_at 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_session_types ast on  ast.abs_session_id = ab.abs_session_id "+
                        " where 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,status,conf_id,consent_status_stmt))
            result  = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

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

    def get_abs_session(self,conf_id,abs_type):
        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 is not null ;'.format(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 abstracts a left join 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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def insert_new_session(self,data):
        with engine.connect() as conn:
            stmt  = self.abs_session_types.insert().values(data)
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return result

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

    def delete_session(self,session_id):
        with engine.connect() as conn:
            stmt = text('delete from abs_session_types where abs_session_id = {}; '.format(session_id))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return result
    
    def add_new_IC_sessions(self,insert_data,conf_id):
        with engine.connect() as conn:
            stmt = ("Insert into 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 abstracts a inner join 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()
                conn.close()
            return "success"
        
    def update_IC_sessions(self,update_data):
        with engine.connect() as conn:
            stmt = 'UPDATE 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':
                        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):
        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 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 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 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 ;".format(session_id,abs_type,conf_id))
            result  = conn.execute(stmt).all()
            conn.close()
            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):
        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 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 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 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 ab.selection_type_id = {} and abs_status_id > 0  group by abs_id order by abs_no;".format(abs_type,conf_id,sel_type_id))
            result  = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_session_data(self,session_id):
        with engine.connect() as conn:
            stmt    = text("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 abs_session_types abst left join abs_halls abh on abst.hall_id = abh.hall_id left join abstracts a on abst.abs_session_id = a.abs_session_id where abst.abs_session_id = {} group by abst.abs_session_id  ".format(session_id)) 
            result  = conn.execute(stmt).first()
            conn.close()
            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()
        connection.close()
        if results :
            return results
        else :
            return None

    def add_session_abstract(self,session_id,abs_id,btn_val):
        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(session_id,abs_id))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            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_v1",[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()
        connection.close()
        if results :
            return results
        else :
            return None

    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_v1",[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()
        connection.close()
        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_print_int_faculty(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_international_faculty",[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 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()
        connection.close()
        if results :
            return results
        else :
            return None

    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_v1",[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_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 update_gp_session(self,data,abs_id):
        with engine.connect() as conn:
            get_stmt    = text("select * from abstracts where abs_id = {}".format(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  = self.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(data["session_name"],data["conf_id"]))).one_or_none()
            update_stmt = text("update abstracts set abs_session_id = {} where abs_id = {}".format(session_id.abs_session_id,abs_id))
            result = conn.execute(update_stmt)
            conn.commit()
            conn.close()
            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).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    def get_keynote_abstract(self,abs_id):
        with engine.connect() as conn:
            stmt = text("select * from abstracts where abs_id = {}".format(abs_id))
            result = conn.execute(stmt).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results
            
    def get_keynote_abstract_data(self,abs_type,conf_id):
        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(abs_type,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt   = text("update abstracts set user_id = {} where abs_id = {}".format(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(abs_id))
            conn.execute(stmt)
            conn.commit()
            result = conn.execute(stmt_1).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def New_keynote_abstract(self,abs_type,conf_id):
        with engine.connect() as conn:
            stmt   = text("insert into abstracts (abs_type,abs_status_id,conf_id) VALUES('KA{}',2,{})".format(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(abs_type,conf_id))
            conn.execute(stmt)
            conn.commit()
            result = conn.execute(stmt_1).first()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    def Get_old_Keynote_abs_id(self,abs_id,conf_id):
        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(abs_id,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def generate_keynote_session(self,abs_type,conf_id):
        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(abs_type,conf_id))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return result

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

    def get_marksheet_data(self,session_id,abs_type):
        sets = []
        try:
            connection = engine.raw_connection()
            cursor     = connection.cursor()
            cursor.callproc("usp_generate_abs_marksheet_v1",[session_id,abs_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_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_session_judge_data(self,session_id):
        with engine.connect() as conn:
            stmt = text("select * 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(session_id))
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def get_preferred_judge_data(self,conf_id,session_id,filter_value):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("usp_abs_judges_for_assignment",[conf_id,session_id,filter_value])
        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_judge_abs_types(self,conf_id):
        with engine.connect() as conn:
            stmt = text(f"select s.*,a.abs_type from abs_selection_type s inner join 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()
            conn.close()
            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):
        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 abstracts a 
                            inner join 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 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()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

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

    def delete_judge(self,session_id,user_id):
        with engine.connect() as conn:
            stmt = text("delete from abs_judges where session_id = {} and user_id = {}".format(session_id,user_id))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            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()
        connection.close()
        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()
            conn.close()
            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):
        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 u.prefix,u.full_name,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 from abstracts ab left join abs_categories c on c.category_id = ab.category_id '+
                ' left join 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 '
                ' {} order by ab.abs_no asc;'.format(str_where))
            result = conn.execute(stmt).all()
            conn.close()
            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("select * from abs_types where  conf_id =:conf_id and abs_type=:abs_type")
            result = conn.execute(stmt).all()
            conn.close()
            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):
        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.user_uuid,u.full_name,display_name,u.prefix,ab.abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,group_concat(distinct concat(ct.topic,\" : \",concat(ifnull(ctu.prefix,''),ifnull(ctu.full_name,'')),\" : \",ct.duration,\" Mins\") separator \"<br>\" ) as co_ins_topics,ab.level,ab.panel_discussion,ab.sno from abstracts ab left join 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 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_topics ct on ab.abs_id = ct.abs_id and t.role_id in (33) left join users ctu on ct.user_id = ctu.user_id left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by ab.abs_id ".format(abs_ids))
            stmt = text("select null as co_email,u.email,u.user_uuid,u.full_name,display_name,u.prefix,ab.abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,group_concat(distinct concat(ct.topic,\" : \",concat(ifnull(ctu.prefix,''),ifnull(ctu.full_name,'')),\" : \",ct.duration,\" Mins\") separator \"<br>\" ) as co_ins_topics,ab.level,ab.panel_discussion,ab.sno from abstracts ab left join 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 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_topics ct on ab.abs_id = ct.abs_id and t.role_id in (33) left join users ctu on ct.user_id = ctu.user_id left join abs_categories c on ab.category_id = c.category_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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_mail_ids_by_abs_id_v3(self,abs_ids):
        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 null as co_email,u.email,u.user_uuid,u.full_name,display_name,u.prefix,ab.abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,group_concat(distinct concat(ct.topic,\" : \",concat(ifnull(ctu.prefix,''),ifnull(ctu.full_name,'')),\" : \",ct.duration,\" Mins\") separator \"<br>\" ) as co_ins_topics,ab.level,ab.panel_discussion from abstracts ab left join 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 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_topics ct on ab.abs_id = ct.abs_id and t.role_id in (33) left join users ctu on ct.user_id = ctu.user_id left join abs_categories c on ab.category_id = c.category_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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_mail_ids_by_abs_id_v2(self,abs_ids):
        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.user_uuid,u.full_name,display_name,u.prefix,ab.abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,group_concat(distinct concat(ct.topic,\" : \",concat(ifnull(ctu.prefix,''),ifnull(ctu.full_name,'')),\" : \",ct.duration,\" Mins\") separator \"<br><br>\" ) as co_ins_topics,ab.level,ab.panel_discussion from abstracts ab left join abs_topics abt on abt.abs_id=ab.abs_id and abt.role_id in (32,35) inner join users u on abt.user_id = u.user_id left join 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,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_topics ct on ab.abs_id = ct.abs_id and t.role_id in (33) left join users ctu on ct.user_id = ctu.user_id left join abs_categories c on ab.category_id = c.category_id where ab.abs_id in ({}) group by ab.abs_id ".format(abs_ids))
            stmt = text("select null as co_email,u.email,u.user_uuid,u.full_name,display_name,u.prefix,ab.abs_id,abs_type,abs_no,title,abs_status_id,abs.*,ah.name as hall_name,group_concat(distinct concat(ct.topic,\" : \",concat(ifnull(ctu.prefix,''),ifnull(ctu.full_name,'')),\" : \",ct.duration,\" Mins\") separator \"<br><br>\" ) as co_ins_topics,ab.level,ab.panel_discussion from abstracts ab left join abs_topics abt on abt.abs_id=ab.abs_id and abt.role_id in (32,35) inner join users u on abt.user_id = u.user_id left join 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,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_topics ct on ab.abs_id = ct.abs_id and t.role_id in (33) left join users ctu on ct.user_id = ctu.user_id left join abs_categories c on ab.category_id = c.category_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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def getAbsNosType(self,abs_type,conf_id):
        with engine.connect() as conn:
            stmt = text(f"select abs_id,concat(abs_type,ifnull(abs_no,'')) as abst_no from 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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
            
# END

############# Harini ###########################
    def getMailTemplate(self,conf_id):
        with engine.connect() as conn:
            stmt = text(f"select * from mail_templates where conf_ids = {conf_id} ;")
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
            
    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 mail_template_id = {mail_template_id} ;")
            result = conn.execute(stmt).first()
            conn.close()
            results = dict(result._mapping) if result else None
            return results
            
    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()
            conn.close()
            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()
            conn.close()
            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):
        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 as co_instructor_email,u1.mobile as co_instructor_mobile,concat(ifnull(u.prefix,''),u.full_name) as cheif_instuctor,u.email,abs.consent_status_id,astatus.status"
                    +" from abstracts a inner join 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"
                    +" left join abs_status astatus on a.abs_status_id=astatus.abs_status_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()
            conn.close()
            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):
        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 abs_topics AS a"
                +" inner JOIN abstracts AS ab ON ab.abs_id = a.abs_id "
                +" inner join 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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def consent_reminder_mail_users(self,topic_ids):
        with engine.connect() as conn:
            stmt = text("select u.user_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as co_inst_name,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_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(topic_ids))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_chiefinstructor_mail(self,topic_ids):
        with engine.connect() as conn:
            stmt = text("SELECT ab.abs_type,ab.abs_no,ab.title,a.topic,concat(ci.prefix,ci.full_name) as chief_ins_name,ci.email as ci_email,concat(coi.prefix,coi.full_name) as co_ins_name FROM abs_topics AS a " 
                    +" inner JOIN abstracts AS ab ON ab.abs_id = a.abs_id "
                    +" inner join 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 "
                    +" WHERE a.role_id = 33 and a.topic_id in ({}) ;".format(topic_ids))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            
            return results
        
# Find Abstract 

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

    def find_abs(self,conf_id,abs_type,abs_no):
        with engine.connect() as conn:
            if abs_type=='Any':
                abs_type=''
            else:
                abs_type=' and abs_type="'+str(abs_type)+'"'
            if abs_no:
                stmt=text("select * from abstracts ab left join abs_status abs on abs.abs_status_id=ab.abs_status_id left join abs_selection_type ast on ast.selection_type_id=ab.selection_type_id where conf_id="+str(conf_id)+ str(abs_type) +" and abs_no="+str(abs_no)+" order by abs_no desc;")
            else:
                stmt=text("select * from abstracts ab left join abs_status abs on abs.abs_status_id=ab.abs_status_id left join abs_selection_type ast on ast.selection_type_id=ab.selection_type_id where conf_id="+str(conf_id)+ str(abs_type)+" order by abs_no desc;")
            result  = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
            
# END #

# Next and previous
    def Getprevious(self,abs_no,abs_type,conf_id,page,abs_id):
        with engine.connect() as conn:
            if page=='0':
                if abs_no:
                    stmt=text("select * from abstracts where conf_id="+str(conf_id)+" and abs_type='"+str(abs_type)+"' and abs_no >"+str(abs_no)+" order by abs_no asc limit 1;")
                else:
                    stmt=text("select * from abstracts where conf_id="+str(conf_id)+" and abs_type='"+str(abs_type)+"' and abs_status_id=0 and abs_id <"+str(abs_id)+" order by abs_id desc limit 1;")
            else:
                if abs_no:
                    stmt=text("select * from abstracts where conf_id="+str(conf_id)+" and abs_type='"+str(abs_type)+"' and abs_no <"+str(abs_no)+" order by abs_no desc limit 1;")
                else:
                    stmt=text("select * from abstracts where conf_id="+str(conf_id)+" and abs_type='"+str(abs_type)+"' and abs_status_id=0 and abs_id >"+str(abs_id)+" order by abs_id asc limit 1;")
            result  = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def Get_next_previous(self,abs_type,category_id,presentation_type,selection_type,status_type,conf_id,page,abs_no,abs_id):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("usp_abs_get_next_previous",[abs_type,category_id,presentation_type,selection_type,status_type,conf_id,page,abs_no,abs_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()
        connection.close()
        if results :
            return results
        else :
            return None

    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_abs_type_from_selection_type(self,selection_type_id):
        with engine.connect() as conn:
            stmt = text("select selection_abs_type from abs_selection_type where selection_type_id= :selection_type_id ")
            result = conn.execute(stmt.bindparams(selection_type_id=selection_type_id)).first()
            conn.close()
            results = dict(result._mapping) if result else None
            return results
        
    def get_book_print_abstracts_data(self,abs_type,selection_type,conf_id):
        sets = []
        try:
            connection = engine.raw_connection()
            cursor     = connection.cursor()
            cursor.callproc("usp_get_book_print_abstract",[abs_type,selection_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_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_type_id(self,conf_id):
        with engine.connect() as conn:
            stmt=text("select abs.abs_type,abt.abs_type_id,abt.title from abstracts abs inner join abs_types abt on abt.abs_type = abs.abs_type where abs.conf_id={} group by abs.abs_type order by abs.abs_type asc;".format(conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_abs_session_id(self,is_semi_final,is_final,is_winner,conf_id):
        with engine.connect() as conn:
            if is_semi_final:
                stmt=text("SELECT ast.type, a.selection_type_id,ast.selection_abs_type FROM 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 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 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 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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
        
    def get_abs_selection_id_by_semifinal(self,conf_id):
        with engine.connect() as conn:
            stmt=text("SELECT ast.type, a.selection_type_id,ast.selection_abs_type FROM 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.is_semi_final is not null 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()
            conn.close()
            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()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt=text(f"select session_name, abs_session_id from abs_session_types where abs_session_id in(select a.abs_session_id from abstracts a where a.selection_type_id={selection_type_id} and conf_id={conf_id});")
            result = conn.execute(stmt).all()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt=text("SELECT session_name,name,start_date,end_date FROM 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()
            conn.close()
            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()
        connection.close()
        if results :
            return results
        else :
            return None


    def get_cateories_by_abs_type(self,conf_id,selection_type_id,is_semi_final):
        with engine.connect() as conn:
            stmt=text(f"select distinct ac.display_name,ac.category_id from abs_categories ac left join 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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results


    def update_selected_abs_ids_by_category_id(self,selected_abs_ids,selection_type_id,abs_category_id,conf_id):
        with engine.connect() as conn:
            if selected_abs_ids:
                stmt_1 = text("update abstracts set is_final = NULL where abs_id not in ({}) and selection_type_id={} and category_id={} and conf_id={} ;".format(selected_abs_ids,selection_type_id,abs_category_id,conf_id))
                stmt = text("update abstracts set is_final = 1 where abs_id in ({}) and selection_type_id={} and category_id={} and conf_id={} ;".format(selected_abs_ids,selection_type_id,abs_category_id,conf_id))
                result = conn.execute(stmt)
                result1 = conn.execute(stmt_1)
                conn.commit()
                conn.close()
                return result
            else:
                stmt_1=text("update abstracts set is_final = NULL where selection_type_id={} and category_id={} and conf_id={};".format(selection_type_id,abs_category_id,conf_id))
                result = conn.execute(stmt_1)
                conn.commit()
                conn.close()
                return result 
            
    def check_awards_by_selection_type_id(self,selection_type_id,conf_id):
        with engine.connect() as conn:
            stmt=text(f"select * from abs_awards where selection_type_id={selection_type_id} and conf_id={conf_id};")
            result = conn.execute(stmt).first()
            conn.close()
            results = dict(result._mapping) if result else None
            return results		
    
    def insert_award_by_selection_type_id(self,data):
        with engine.connect() as conn:
            # result   = text(f"insert into abs_awards (selection_type_id,award_name,conf_id) VALUES({selection_type_id},'{award_name}',{conf_id});")
            result = conn.execute(self.abs_awards.insert(), data)
            conn.commit()
            conn.close()
            pk_id = result.inserted_primary_key[0] if result.inserted_primary_key[0] else None
            return pk_id

    def update_selected_abs_ids(self,selected_abs_ids,selection_type_id,conf_id):
        with engine.connect() as conn:
            if selected_abs_ids:
                stmt_1 = text(f"update 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 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()
                conn.close()
                return result
            else:
                stmt_1=text(f"update abstracts set is_winner = NULL where selection_type_id={selection_type_id} and conf_id={conf_id};")
                result = conn.execute(stmt_1)
                conn.commit()
                conn.close()
                return result 

    def update_selected_abs_ids_v1(self,selected_col,abs_session_id,selected_abs_id,conf_id):
        with engine.connect() as conn:
            if selected_abs_id:
                stmt_1 = text("update abstracts set "+selected_col+" = NULL where abs_id not in ({}) and abs_session_id={} and conf_id={};".format(selected_abs_id,abs_session_id,conf_id))
                stmt = text("update abstracts set "+selected_col+" = 1 where abs_id in ({}) and abs_session_id={} and conf_id ={} ;".format(selected_abs_id,abs_session_id,conf_id))
                result1 = conn.execute(stmt_1)
                result = conn.execute(stmt)
                conn.commit()
                conn.close()
                return result
            else:
                stmt_1=text("update abstracts set "+selected_col+" = NULL where abs_session_id={} and conf_id={};".format(abs_session_id,conf_id))
                result = conn.execute(stmt_1)
                conn.commit()
                conn.close()
                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()
        connection.close()
        if results :
            return results
        else :
            return None

    def get_data_by_abs_session_id(self,abs_session_id,conf_id):
        with engine.connect() as conn:
            stmt=text("select abs.*,ast.session_name,concat(cu.prefix,cu.full_name) as chief_author,cu.user_id as chief_author_user_id,pu.user_id as presenting_author_user_id,concat('' '',ifnull(pu.prefix,''''),''  '',pu.full_name) as presenting_author,pu.membership_no as presenting_author_membership_no from abstracts abs "
                        +" left join abs_session_types ast on ast.abs_session_id=abs.abs_session_id "
                        +" left join abs_topics abt on abt.abs_id = abs.abs_id and abt.role_id=34 "
                        +" left join users cu on cu.user_id = abs.user_id "
                        +" left join abs_topics abtp on abtp.abs_id = abs.abs_id and abtp.role_id=35 "
                        +" left join users pu on pu.user_id = abtp.user_id "
                        +" where abs.is_semi_final=1 and abs.abs_session_id={} and abs.conf_id={};".format(abs_session_id,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_data_by_category_id(self,col_name,abs_category_id,conf_id):
        with engine.connect() as conn:
            stmt=text("select abs.*,ast.session_name,concat(cu.prefix,cu.full_name) as chief_author,cu.user_id as chief_author_user_id,pu.user_id as presenting_author_user_id,concat('' '',ifnull(pu.prefix,''''),''  '',pu.full_name) as presenting_author,pu.membership_no as presenting_author_membership_no,ac.display_name from abstracts abs "
                        +" left join abs_session_types ast on ast.abs_session_id=abs.abs_session_id "
                        +" left join abs_topics abt on abt.abs_id = abs.abs_id and abt.role_id=34 "
                        +" left join users cu on cu.user_id = abs.user_id "
                        +" left join abs_topics abtp on abtp.abs_id = abs.abs_id and abtp.role_id=35 "
                        +" left join users pu on pu.user_id = abtp.user_id "
                        +" left join abs_categories ac on ac.category_id = abs.category_id "
                        +" where "+col_name+"=1 and abs.category_id={} and abs.conf_id={};".format(abs_category_id,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] 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 
        
    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()
            conn.close()
            results= dict(result._mapping) if result else None
            return results
    
    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} and user_society = 'AIOS'")
            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()         
                conn.close()      
            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()
                conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            pk_id = result.inserted_primary_key[0] if result.inserted_primary_key[0] else None
            return pk_id

    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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            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()
        connection.close()
        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()
        connection.close()
        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()
        connection.close()
        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()
        connection.close()
        if results :
            return results
        else :
            return None
    
    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()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_selected_abstacts(self,conf_id,selection_type_id):
        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_id,selection_type_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_uploaded_image_type(self,abs_id,img_type):
        with engine.connect() as conn:
            stmt = text("select * from abs_uploads where abs_id = {} and img_type ='{}' ".format(abs_id,img_type))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
        
    def get_selection_count(self,cat_id,abs_type,conf_id):
        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 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()
            conn.close()
            results = dict(result._mapping) if result else None
            return results
    
    def get_selection_summary_data(self,abs_type,conf_id,selection_type_id):
        with engine.connect() as conn:
            if selection_type_id:
                stmt = text(f'select parent_category,st.total_count as submitted_count,count(parent_category) as category_count,concat(round((count(parent_category) /t.total_count)*100,1)) as percent from abstracts a inner join abs_categories c on a.category_id = c.category_id left join (select count(*) as total_count,category_id from abstracts where conf_id = {conf_id} and abs_type = "{abs_type}" and selection_type_id = {selection_type_id} and abs_status_id = 2  ) as t on t.category_id=t.category_id left join (select count(*) as total_count,c.parent_category_id from abstracts a inner join abs_categories c on a.category_id = c.category_id where a.conf_id = {conf_id} and abs_type = "{abs_type}" and abs_status_id > 0 and abs_status_id != 4 group by parent_category_id ) as st on st.parent_category_id=c.parent_category_id where a.conf_id = {conf_id} and a.abs_type = "{abs_type}" and abs_status_id = 2 and selection_type_id={selection_type_id} group by c.parent_category order by c.parent_category;')
            else:
                stmt = text(f'select parent_category,st.total_count as submitted_count,count(parent_category) as category_count,concat(round((count(parent_category) /t.total_count)*100,1)) as percent from abstracts a inner join abs_categories c on a.category_id = c.category_id left join (select count(*) as total_count,category_id from abstracts where conf_id = {conf_id} and abs_type = "{abs_type}" and abs_status_id = 2  ) as t on t.category_id=t.category_id left join (select count(*) as total_count,c.parent_category_id from abstracts a inner join abs_categories c on a.category_id = c.category_id where a.conf_id = {conf_id} and abs_type = "{abs_type}" and abs_status_id > 0 and abs_status_id != 4 group by parent_category_id ) as st on st.parent_category_id=c.parent_category_id where a.conf_id = {conf_id} and a.abs_type = "{abs_type}" and abs_status_id = 2 group by c.parent_category order by c.parent_category;')
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
        
    def get_display_selection_type_selected(self,conf_id,abs_type):
        with engine.connect() as conn:
            stmt = text(f'select s.selection_type_id,type as selection_type from abstracts a inner join abs_selection_type s on a.selection_type_id = s.selection_type_id where conf_id = {conf_id} and abs_status_id = 2 and abs_type = "{abs_type}" group by a.selection_type_id')
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_other_id_selected_by_user(self,conf_id,user_id,abs_type):
        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 abstracts a inner join abs_topics t on a.abs_id = t.abs_id and t.user_id = {user_id} and consent_status_id = 2 inner join 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 abstracts a  inner join 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 inner 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 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 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} and s.selection_type_id = 4')
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_count_by_selection_type(self,conf_id,cat_id):
        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 abstracts a   on a.selection_type_id = s.selection_type_id and abs_status_id = 2 where conf_id = {conf_id}  and abs_type = "FP" and s.selection_type_id in (2,4,11) group by s.selection_type_id;') 
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def Update_Consent_Status(self,topic_id,data):
        with engine.connect() as conn:
            stmt = self.author.update().where(self.author.c.topic_id.in_([topic_id])).values(data)
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return "success"

    def get_abstract_for_hyde_park(self,conf_id,presentation_ids):
        with engine.connect() as conn:
            stmt = text(""" select a.abs_type,a.abs_no,a.abs_id,a.title,p.type,c.display_name,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as presenting_author,u.membership_no,u.email,u.mobile,u.user_id,concat(round((total_marks/ed.evaluated),2)) as percentage from abstracts a 
                inner join abs_topics t on t.abs_id = a.abs_id and t.role_id = 35
                inner join users u on u.user_id = t.user_id
                inner join abs_presentation_type p on a.presentation_type_id = p.presentation_type_id
                inner join abs_categories c on a.category_id = c.category_id
                left join (select count(*) evaluated,abs_id from 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 abs_marks t2 group by abs_id) mt on a.abs_id = mt.abs_id
                where a.conf_id = {} and abs_no is not null and abs_type = "FP" and abs_status_id = 1 and a.presentation_type_id in ({}) and u.user_id not in (select t.user_id from abstracts a inner join abs_topics t on a.abs_id = t.abs_id and t.role_id = 35 where abs_status_id = 2 and conf_id = {} and abs_type = 'FP') order by percentage desc; """.format(conf_id,presentation_ids,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
    
    def get_selected_abstract_for_hyde_park(self,conf_id):
        with engine.connect() as conn:
            stmt = text(""" select a.abs_type,a.abs_no,a.abs_id,a.title,p.type,c.display_name,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as presenting_author,u.membership_no,u.email,u.mobile,u.user_id from abstracts a 
                inner join abs_topics t on t.abs_id = a.abs_id and t.role_id = 35
                inner join users u on u.user_id = t.user_id
                inner join abs_presentation_type p on a.presentation_type_id = p.presentation_type_id
                inner join abs_categories c on a.category_id = c.category_id
                where a.conf_id = {} and abs_no is not null and abs_type = "FP" and abs_status_id = 2 and a.selection_type_id = 5 order by a.abs_no; """.format(conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            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):
        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 abs_session_types s  left join 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()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt = text(f'update abs_session_types t1 left join 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 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()
            conn.close()
            return "success"
    
    def get_session_data_swapping(self,conf_id):
        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 abs_session_types abst left join abs_halls abh on abst.hall_id = abh.hall_id left join 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()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt = text(f'select * from 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 abs_session_types t1 left join 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 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()
            conn.close()
            return "success"
        
    def get_duplicate_session_clash_data(self,session_id,conf_id):
        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 abs_session_types s inner join 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 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()
            conn.close()
            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()
        connection.close()
        if results :
            return results
        else :
            return None
    
    
    def get_judge_preference(self,conf_id,pref_date,cate_id):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("usp_get_judge_preference",[conf_id,pref_date,cate_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()
        connection.close()
        if results :
            return results
        else :
            return None

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

    def get_comp_session_types(self,conf_id):
        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_id))
            result = conn.execute(stmt).all()
            conn.close()
            results=[dict(r._mapping) for r in result] if result else None
            return results

    def insert_scoring_marks(self,data):
        with engine.connect() as conn:
            if data:
                stmt_1 = ("INSERT INTO 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()
            conn.close()
            return None

    def update_scoring_marks(self,data):
        with engine.connect() as conn:
            stmt = 'UPDATE 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()
                conn.close()
                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 update_attendance(self,speaker_data,judge_data):
        with engine.connect() as conn:
            stmt = 'UPDATE abs_topics SET '
            stmt1 = 'UPDATE 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))
            elif len(abs_id)!=0:
                result = conn.execute(text(stmt))
            conn.commit()
            conn.close()
            return "Success"

    def update_judges(self,data,judges_id):
        with engine.connect() as conn:
            stmt = self.abs_judges.update().values(data).where(self.abs_judges.c.judges_id.in_([judges_id]))
            result = conn.execute(stmt)
            conn.commit()
            conn.close()
            return None

    def usp_generate_abs_scoring_marksheet(self,session_id,abs_type):
        sets = []
        try:
            connection = engine.raw_connection()
            cursor     = connection.cursor()
            cursor.callproc("usp_generate_abs_scoring_marksheet",[session_id,abs_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

    # -------------------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()
            conn.close()
            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()
            conn.close()
            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()
            conn.close()
            results=dict(result._mapping) if result else None
            return results

    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()
            conn.close()
            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()
            conn.close()
            results= dict(result._mapping) if result else None
            return results
    
    def get_abs_session_with_judges(self,conf_id,abs_type,session_type):
        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 abs_session_types s inner join abs_judges j on s.abs_session_id = j.session_id inner join  users u on j.user_id = u.user_id inner 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()
            conn.close()
            results= [dict(r._mapping) for r in result] 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()
            conn.close()
            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()
            conn.close()
            return "success"
            
    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()
            conn.close()
            results= dict(result._mapping) if result else None
            return results

    def get_session_date_and_hall_wise(self,date_wise,hall_wise,conf_id):
        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_id,date_wise,hall_wise))
            result  = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
            
    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_judgedata_fulltext(self,conf_id):
        with engine.connect() as conn:
            stmt = text(""" select aj.user_id,aj.role_id,abs_session_id,concat(ifnull(u.prefix,''),u.full_name)  as judge_name,u.email,u.mobile,group_concat(distinct(ar.role)) as role,group_concat(distinct(session_name)) as session_name from abs_judges aj
                left join users u on u.user_id=aj.user_id
                left join abs_roles ar on ar.role_id=aj.role_id
                left join abs_session_types ast on ast.abs_session_id=aj.session_id
                where session_id in (select abs_session_id from abstracts where  abs_type='FP' and selection_type_id=2 and conf_id={} and abs_status_id=2) 
                group by aj.user_id  order by session_name  ; """.format(conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results

    def get_session_details(self,user_ids,conf_id):
        with engine.connect() as conn:
            stmt = text("""select session_name,start_date,end_date,name as hall_name,concat(ifnull(u.prefix,''),u.full_name)  as judge_name,u.email from abs_judges aj
            left join abs_session_types ass on ass.abs_session_id=aj.session_id 
            left join abs_halls ah on ah.hall_id=ass.hall_id 
            left join users u on u.user_id = aj.user_id
            where session_name like '%Free Paper%'   and aj.user_id in ({})and ass.conf_id={}; """.format(user_ids,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
            
    def get_sessions_judgedata(self,conf_id,selection_type_id,abs_type):
        with engine.connect() as conn:
            stmt = text(""" select aj.user_id,aj.role_id,abs_session_id,concat(ifnull(u.prefix,''),u.full_name)  as judge_name,u.email,u.mobile,ar.role,session_name from abs_judges aj
                left join users u on u.user_id=aj.user_id
                left join abs_roles ar on ar.role_id=aj.role_id
                left join abs_session_types ast on ast.abs_session_id=aj.session_id
                where session_id in (select abs_session_id from abstracts where  abs_type='{}' and selection_type_id={} and conf_id={} and abs_status_id=2)   order by session_name  ; """.format(abs_type,selection_type_id,conf_id))
            result = conn.execute(stmt).all()
            conn.close()
            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):
        with engine.connect() as conn:
            stmt=text(f"""
                    select s.*,count(distinct judges_id) as judges_count,a.selection_type_id   from abs_session_types s 
                    inner join abstracts a on s.abs_session_id = a.abs_session_id 
                    left join abs_judges j on s.abs_session_id = j.session_id
                    where s_abs_type is not null and a.conf_id = {conf_id} and a.abs_type = "{abs_type}" group by a.abs_session_id order by judges_count,session_name ; 
                    """)
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
            
    def get_session_selection_types(self,abs_type,conf_id):
        with engine.connect() as conn:
            stmt=text(f"""
                    select s.* from abstracts a 
                    inner join abs_selection_type s on a.selection_type_id = s.selection_type_id 
                    where conf_id = {conf_id} and abs_type = "{abs_type}" and abs_status_id = 2 group by a.selection_type_id;
                    """)
            result = conn.execute(stmt).all()
            conn.close()
            results = [dict(r._mapping) for r in result] if result else None
            return results
        
app.jinja_env.globals.update(BoModel=BoModel) 

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