Sindbad~EG File Manager

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

from sqlalchemy import create_engine, MetaData, Table, insert, select,update,delete,text
from sqlalchemy.sql import and_, or_
from sqlalchemy import asc, desc
from core import app
import json

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


class UserModel():
    def __init__(self):
        try:
            self.meta                   = MetaData()
            self.users                  = Table("users", self.meta,  autoload_with=engine)
            self.societies              = Table("societies", self.meta,  autoload_with=engine)
            self.logapi                 = Table("logapi", self.meta,  autoload_with=engine)
            self.m_attachment_type      = Table("m_attachment_type", self.meta,  autoload_with=engine)
            self.upload_credit_point    = Table("upload_credit_point", self.meta,  autoload_with=engine)
            self.user_program_book_opt_in    = Table("user_program_book_opt_in", self.meta,  autoload_with=engine)
           
        except Exception as e:
            print(e)
    
    def get_data(self,email,pwd_difference):
        with engine.connect() as conn:
            stmt = text(f"select * from users where email= '{email}' and password = '{pwd_difference}';")       
            result = conn.execute(stmt).first()
            conn.close()
            results=  dict(result._mapping) if result else None
            return results
        
    def apilog(self,logdata):
        with engine.connect() as conn:
            result = conn.execute(self.logapi.insert(), logdata)
            # conn.commit()
            return "success"
            
    def get_society_by_host(self,host):
        with engine.connect() as conn:
            stmt = text(f"select * from societies s  inner join mail_setting m on m.mail_setting_id = 1 where  society_host = '{host}' ;")       
            result = conn.execute(stmt)
            results = result.first()
            results = dict(results._mapping) if results else None  
            conn.close()
            return results

    def get_membership_password(self,society_id,membership_no,password):
        with engine.connect() as conn:
            stmt = text(f"select * from users where society_id={society_id} and membership_no='{membership_no}' and password='{password}';")       
            result = conn.execute(stmt).first()
            results = dict(result._mapping) if result else None
            conn.close()  
            return results
    
    def check_if_profileupdated(self,user_uuid):
        with engine.connect() as conn:
            stmt = text(f"select * from users where user_uuid = '{user_uuid}' and profile_updated_at is not null ;")       
            result = conn.execute(stmt).first()
            results = dict(result._mapping) if result else None
            conn.close()
            return results

    def get_attach_type_id(self,society_id,attach_type):
        with engine.connect() as conn:
            stmt = text(f"select * from m_attachment_type where society_id= {society_id} and attach_type='{attach_type}';")       
            result = conn.execute(stmt).first()
            conn.close()
            return result if result else None

    def get_dashboard_content(self,society_id,user_id):
        with engine.connect() as conn:
#       stmt = text("select * from society_applications sa inner join m_app_type mat on sa.app_type_id = mat.app_type_id where society_id = {}  order by mat.app_type_id".format(society_id))
            stmt = text(f"""SELECT * FROM society_applications sa 
                         INNER JOIN m_app_type mat ON sa.app_type_id = mat.app_type_id 
                         Left JOIN users u on u.user_id = {user_id} 
                         WHERE sa.society_id = {society_id} and conf_id is null and is_active = 1
                         ORDER BY mat.app_type_id """)
            results = conn.execute(stmt).all()
            results = [dict(r._mapping) for r in results] if results else None
            conn.close()
            return results

    def get_dashboard_content_conference(self,society_id):
        with engine.connect() as conn:
            stmt = text(f"select * from conference where society_id = {society_id} and is_active = 1 order by conf_id desc;")
            results = conn.execute(stmt).all()
            results = [dict(r._mapping) for r in results] if results else None
            conn.close()
            return results

    def get_dashboard_conference_application(self,society_id):
        with engine.connect() as conn:
            stmt = text(f"select * from society_applications sa INNER JOIN m_app_type mat ON sa.app_type_id = mat.app_type_id  where society_id = {society_id} and conf_id is not null and is_active = 1 order by mat.app_type_id desc;")
            results = conn.execute(stmt).all()
            results = [dict(r._mapping) for r in results] if results else None
            conn.close()
            return results
            
    def get_userdata(self,email,society_id):
        with engine.connect() as conn:
            stmt = text(f"select * from users where email = '{email}' and society_id = {society_id} and user_society = 'AIOS';")       
            result = conn.execute(stmt).first()
            results = dict(result._mapping) if result else None
            conn.close()
            return results
    
    def get_userdata_v1(self,email,society_id):
        with engine.connect() as conn:
            # stmt = text(f"select * from users where membership_no = '{email}' and society_id = {society_id} and user_society = 'AIOS';")       
            stmt = text(f"select u.*,ifnull(l.password,u.password) as db_pass from users u left join logapi l on u.user_id = l.user_id where u.membership_no = '{email}' and u.society_id = {society_id} and u.user_society = 'AIOS' group by u.user_id order by id desc;")
            result = conn.execute(stmt).first()
            results = dict(result._mapping) if result else None
            conn.close()
            return results

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

    def update_member(self,user_id,data):
        with engine.connect() as conn:
            stmt = self.users.update().values(data).where(self.users.c.user_id.in_([user_id]))
            select_stmt = text("select *  from users where user_id = "+str(user_id)+" ")
            conn.execute(stmt)
            # conn.commit()
            select_result = conn.execute(select_stmt).first()
            result_2 = dict(select_result._mapping) if select_result else None
            conn.close()
            return result_2

   
    def insert_users(self,data):
        with engine.connect() as conn:
            result = conn.execute(self.users.insert(), data)
            # conn.commit()
            stmt = text("select * from users where email = '{}' and  user_society = 'AIOS' limit 1".format(data['email']))
            result = conn.execute(stmt).one_or_none()
            user_data = dict(result._mapping) 
            conn.close()
            return user_data["user_id"] if user_data else None
    
    def insert_new_user(self,email,society_id):
        with engine.connect() as conn:
            stmt = text("insert into users (email,society_id) values('{}',{})".format(email,society_id))
            result = conn.execute(stmt)
            # conn.commit()
            stmt = text("select * from users where email = '{}' and society_id = {} limit 1".format(email,society_id))
            result = conn.execute(stmt).one_or_none()
            conn.close()
            return dict(result._mapping) if result else None

    def get_email_count(self,email,society_id):
        with engine.connect() as conn:
            stmt = text("select count(*) as email_count from users where email = '{}' and society_id ={}".format(email,society_id))
            result = conn.execute(stmt).first()
            conn.close()
            return result.email_count


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

    
    def check_password(self,user_id):
        with engine.connect() as conn:
            stmt = self.users.select().where(self.users.c.user_id.in_([user_id]))
            result = conn.execute(stmt).first()
            conn.close()
            return result

    def get_society(self,society_id):
        with engine.connect() as conn:
            stmt = text(f"select * from societies s  inner join mail_setting m on m.mail_setting_id = 1 where  s.society_id={society_id};")       
            results = conn.execute(stmt).first()
            conn.close()
            result=  dict(results._mapping) if results else None
            return result

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

    def get_user(self,user_id,society_id):
        with engine.connect() as conn:
            stmt = text(f"select *,u.user_id as en_user_id from users u left join m_member_type m on u.member_type_id = m.member_type_id left join user_attachments ua on u.user_id=ua.user_id and attach_type_id = (select attach_type_id from m_attachment_type where attach_type='Photograph' and society_id = {society_id}) where u.user_id={user_id} ")
            result = conn.execute(stmt).first()
            conn.close()
            result = dict(result._mapping)
            return result if result else None
            
    def get_member_display_name(self,member_type_id,society_id):
        with engine.connect() as conn:
            stmt = text(f"select mt.member_type,smt.display_name,smt.amount from m_member_type as mt inner join society_map_member_type as smt on mt.member_type_id=smt.member_type_id where smt.member_type_id={member_type_id}  and smt.society_id={society_id}")
            results = conn.execute(stmt).first()
            conn.close()
            return results if results else None

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

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

    def get_state(self,country_id):
        with engine.connect() as conn:
            stmt = text("select * from states where country_id = {}".format(country_id))
            results = conn.execute(stmt).all()
            conn.close()
            result=  [dict(r._mapping) for r in results] if results else None
            return result
    
    def getSociety(self,society_id,society_key):
        with engine.connect() as conn:
            stmt = text(f"select * from societies s  inner join mail_setting m on m.mail_setting_id = 1 where  society_id = {society_id} and society_key='{society_key}';")
            results = conn.execute(stmt).first()
            conn.close()
            results=  dict(results._mapping) if results else None
            return results

    def setSociety(self,society_host):
        with engine.connect() as conn:
            stmt = text(f"select * from societies s  inner join mail_setting m on m.mail_setting_id = 1 where  society_host = '{society_host}';")
            results = conn.execute(stmt).first()
            conn.close()
            results=  dict(results._mapping) if results else None
            return results

    def get_data_mail(self,user_id):
        with engine.connect() as conn:
            stmt = text(f"""SELECT  u.* ,s.state_name,c.country_name from users u left join states s  on u.state_id = s.state_id left join countries  c  on c.country_id = s.country_id 
                         where u.user_id = {user_id};""")
            result = conn.execute(stmt).first()
            conn.close()
            return dict(result._mapping) if result else None

    def count_mobile_num(self,user_id,mobile,society_id):
        with engine.connect() as conn:
            stmt = text(f"select count(*) from users where user_id <> {user_id} and (mobile= '{mobile}' or whatsapp_number='{mobile}') and society_id={society_id};")
            result = conn.execute(stmt).first()
            conn.close()
            return result if result else None

    def count_whatsapp_num(self,user_id,whatsapp_number,society_id):
        with engine.connect() as conn:
            stmt = text(f"select count(*) from users where user_id <> {user_id} and (mobile= '{whatsapp_number}' or whatsapp_number='{whatsapp_number}') and society_id={society_id};")
            result = conn.execute(stmt).first()
            conn.close()
            return result if result else None
    
    def get_allstates(self):
        with engine.connect() as conn:
            stmt = text("select * from states")
            result = conn.execute(stmt).all()
            conn.close()
            result = [dict(r._mapping) for r in result] if result else None
            return result
    
    def get_states(self,country_id):
        with engine.connect() as conn:
            stmt = text("select * from states where country_id   = "+str(country_id)+" order by state_name asc;")
            results = conn.execute(stmt).all()
            conn.close()
            return  [dict(r._mapping) for r in results] if results else None
        
    def check_is_evaluator(self,user_id,conf_id=0):
        with engine.connect() as conn:
            stmt = text("select case when sum(t.is_evaluator) > 0 then 1 else 0 end is_evaluator from ( select m.eva_id, t.abs_type,  case when count(*)  > 0 and (convert_tz(utc_timestamp() ,'+00:00','+05:30') between min(t.start_date) and min(t.end_date) )  then 1 else 0 end as is_evaluator, convert_tz(utc_timestamp() ,'+00:00','+05:30'),min(t.start_date) as start_date , min(t.end_date) as end_date  from abs_marks m inner join abs_types t on  t.abs_type = m.eva_abs_type where m.eva_id = "+str(user_id)+" and t.conf_id = "+str(conf_id)+" group by t.abs_type ) as t group by t.eva_id;")
            results = conn.execute(stmt).first()
            conn.close()
            result = dict(results._mapping) if results else None
            return result['is_evaluator'] if result else None

    
    def usp_get_user_credit_points(self,user_id):
        sets = []
        try:
            connection = engine.raw_connection()
            cursor = connection.cursor()
            cursor.callproc("usp_get_user_credit_points",[user_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 insert_imge_to_db(self,data_1):
        with engine.connect() as conn:
            result = conn.execute(self.upload_credit_point.insert(), data_1)
            # conn.commit()
            return "success"

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

    def delete_image(self,user_id,conf_id,cp_id):
        with engine.connect() as conn:
            stmt = text(f"delete from upload_credit_point where conf_id = {conf_id} and user_id = {user_id} and cp_id = {cp_id}")
            result = conn.execute(stmt)
            # conn.commit()
            return "success"
    
    def get_creditpoind_data(self,report_type):
        with engine.connect() as conn:
            report_stmt = ''
            if report_type:
                if int(report_type) == 3:
                    report_stmt = report_stmt
                else:
                    report_stmt = "and is_verified = "+report_type
            else:
                report_stmt = "and is_verified is null "
            stmt = text(f"select u.user_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,u.email,u.mobile,cp.session_title,cp.session_name,cp.cp_id,ucp.id as upload_credit_id,is_verified,file_url,c.conf_title,c.conf_id,c.conf_key,ucp.remarks from upload_credit_point ucp  inner join m_credit_points cp on ucp.cp_id = cp.cp_id inner join users u on ucp.user_id = u.user_id inner join conference c on ucp.conf_id = c.conf_id where (1+1) {report_stmt} ;")
            result = conn.execute(stmt).all()
            conn.close()
            return  [dict(r._mapping) for r in result] if result else None
    
    def get_creditpoint_doc_data(self,upload_credit_id):
        with engine.connect() as conn:
            stmt = text(f"select u.user_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,u.email,u.mobile,cp.session_title,cp.session_name,cp.cp_id,ucp.id as upload_credit_id,is_verified,file_url,c.conf_title,c.conf_id,c.conf_key,ucp.remarks from upload_credit_point ucp  inner join m_credit_points cp on ucp.cp_id = cp.cp_id inner join users u on ucp.user_id = u.user_id inner join conference c on ucp.conf_id = c.conf_id where  ucp.id = {upload_credit_id}")
            results = conn.execute(stmt).all()
            conn.close()
            return  [dict(r._mapping) for r in results] if results else None

    def get_creditpoint_doc_data_for_mail(self,user_id,conf_id,cp_id):
        with engine.connect() as conn:
            stmt = text(f"select u.user_id,concat(ifnull(u.prefix,''),ifnull(u.full_name,'')) as full_name,u.email,u.mobile,cp.session_title,cp.session_name,cp.cp_id,ucp.id as upload_credit_id,is_verified,file_url,c.conf_title,c.conf_id,c.conf_key,ucp.remarks from upload_credit_point ucp  inner join m_credit_points cp on ucp.cp_id = cp.cp_id inner join users u on ucp.user_id = u.user_id inner join conference c on ucp.conf_id = c.conf_id where  ucp.conf_id = {conf_id} and ucp.user_id = {user_id} and ucp.cp_id = {cp_id}")
            results = conn.execute(stmt).all()
            conn.close()
            return  [dict(r._mapping) for r in results] if results else None

    def update_credit_point_data(self,data,upload_credit_id):
        with engine.connect() as conn:
            stmt = self.upload_credit_point.update().values(data).where(self.upload_credit_point.c.id.in_([upload_credit_id]))
            result = conn.execute(stmt)
            # conn.commit()
            return "success"
    
    def get_mail_template(self,society_id,template_name):
        with engine.connect() as conn:
            stmt    = text(f"select * from mail_templates where society_id={society_id} and template_name='{template_name}';")
            result  = conn.execute(stmt).first()
            conn.close()
            results = dict(result) if result else None
            return results
        
    def get_country_isd_code(self):
        with engine.connect() as conn:
            stmt = text("select * from countries where isd_code is not null order by country_name")
            result = conn.execute(stmt).all()
            conn.close()
            return [dict(r._mapping) for r in result] if result else None
    
    def check_opt_user_email(self,email):
        with engine.connect() as conn:
            stmt = text(f"select count(*) as email_count from user_program_book_opt_in where email = '{email}';")
            result = conn.execute(stmt).first()
            conn.close()
            return dict(result._mapping) if result else None
    
    def check_opt_user_mobile(self,mobile):
        with engine.connect() as conn:
            stmt = text(f"select count(*) as mobile_count from user_program_book_opt_in where mobile = '{mobile}';")
            result = conn.execute(stmt).first()
            conn.close()
            return dict(result._mapping) if result else None
    
    def check_opt_user_membership(self,mem_no):
        with engine.connect() as conn:
            stmt = text(f"select count(*) as mem_count from user_program_book_opt_in where membership_no = '{mem_no}';")
            result = conn.execute(stmt).first()
            conn.close()
            return dict(result._mapping) if result else None
    
    def insert_user_opt(self,data):
        with engine.connect() as conn:
            result = conn.execute(self.user_program_book_opt_in.insert(), data)
            return "success"
            
    def get_app_list(self):
        with engine.connect() as conn:
            stmt = text("select * from m_app_type;")
            results = conn.execute(stmt).all()
            conn.close()
            return  [dict(r._mapping) for r in results] if results else None
        
    def get_backoffice_access(self,email,society_id):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("usp_get_backoffice_access",[email,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 check_bo_access(self,email,app_type_id,society_id,conf_id):
        connection = engine.raw_connection()
        cursor = connection.cursor()
        cursor.callproc("usp_check_admin_access",[email,app_type_id,society_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[0]
        else :
            return None
            
app.jinja_env.globals.update(UserModel=UserModel)

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