Sindbad~EG File Manager

Current Path : /home/numerotech/mcq.numerotech.com/MCQ_APP/core/model/
Upload File :
Current File : //home/numerotech/mcq.numerotech.com/MCQ_APP/core/model/BoModel.py

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

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


class BoModel():
	def __init__(self):
		try:
			self.meta = MetaData()
			self.users = Table("users", self.meta, autoload_with=user_engine)
			self.q_options = Table("q_options", self.meta, autoload_with=engine)
			self.m_session = Table("m_session", self.meta, autoload_with=engine)

		except Exception as e:
			print(e)

	def get_admin_user(self,email,password):
		with engine.connect() as conn:
			stmt = text(f"select * from admin_users where email = '{email}' and password = '{password}' ")
			result = conn.execute(stmt).fetchone()
			result = dict(result._mapping) if result else None
			conn.close()
			return result

	def get_q_count_data(self):
		with engine.connect() as conn:
			stmt = text("""select count(distinct user_id) as total_users,count(*) as total_quesitons,
							sum(case when status_id = 0 then 1 else 0 end) as incomplete,
							sum(case when status_id = 1 then 1 else 0 end) as complete,
							sum(case when status_id = 2 then 1 else 0 end) as seleted 
							from questions; """)
			result = conn.execute(stmt).fetchone()
			result = dict(result._mapping) if result else None
			conn.close()
			return result
		

	def get_session_count_data(self,now):
		with engine.connect() as conn:
			stmt = text(f"""select count(*) as total_sessions,sum(case when startdate > STR_TO_DATE('{now}', '%Y-%m-%d %T') then 1 else 0 end) as upcoming,
							sum(case when enddate < STR_TO_DATE('{now}', '%Y-%m-%d %T') then 1 else 0 end) as completed,
							sum(case when STR_TO_DATE('{now}', '%Y-%m-%d %T') between startdate and enddate  then 1 else 0 end) as active_s
							from m_session;""")
			result = conn.execute(stmt).fetchone()
			result = dict(result._mapping) if result else None
			conn.close()
			return result
	
	def get_all_questions(self,status_id):
		with engine.connect() as conn:
			stmt = text(f'select *,group_concat( distinct display_name) as category_name  from questions q left join mcq_category mc on find_in_set(mc.mcq_category_id,q.category_ids) where status_id in ({status_id}) group by q.q_id;')
			result = conn.execute(stmt).fetchall()
			results = [ dict(r._mapping) for r in result ] if result else None
			conn.close()
			return results

	def get_all_sessions(self):
		with engine.connect() as conn:
			stmt = text('select * from m_session;')
			result = conn.execute(stmt).fetchall()
			results = [ dict(r._mapping) for r in result ] if result else None
			conn.close()
			return results
	
	def create_session(self,created_at):
		with engine.connect() as conn:
			stmt = text(f"insert into m_session (created_at) values('{created_at}')")
			conn.execute(stmt)
			conn.commit()
			stmt = text(f"select * from m_session where created_at = '{created_at}' order by session_id desc limit 1 ")
			result = conn.execute(stmt).fetchone()
			result = dict(result._mapping) if result else None
			conn.close()
			return result['session_id']
		
	def get_session_data(self,session_id):
		with engine.connect() as conn:
			stmt = text(f"select * from m_session where session_id = {session_id};")
			result = conn.execute(stmt).fetchone()
			result = dict(result._mapping) if result else None
			conn.close()
			return result
	
	def update_session(self,s_id,data):
		with engine.connect() as conn:
			stmt = self.m_session.update().where(self.m_session.c.session_id.in_([s_id])).values(data)
			conn.execute(stmt)
			conn.commit()
			conn.close()
			return True
	
	def get_session_questions(self,s_id):
		with engine.connect() as conn:
			stmt  = text(f"select * from map_session_questions m inner join questions q on m.q_id = q.q_id  where session_id = {s_id};")
			result = conn.execute(stmt).fetchall()
			results = [ dict(r._mapping) for r in result ] if result else None
			conn.close()
			return results
	
	def get_all_questions_for_session(self,s_id):
		with engine.connect() as conn:
			stmt = text(f"select q.*,m.msq_id from questions q left join map_session_questions m on m.q_id = q.q_id and session_id = {s_id} where m.q_id is null and status_id >= 1;")        
			result = conn.execute(stmt).fetchall()
			results = [ dict(r._mapping) for r in result ] if result else None
			conn.close()
			return results
		
	def add_question_to_session(self,s_id,q_ids):
		with engine.connect() as conn:
			for i in q_ids:
				stmt = text(f"insert into map_session_questions (session_id,q_id) values({s_id},{i});")
				conn.execute(stmt)
			conn.commit()
			conn.close()
			return True
	
	def remove_question_to_session(self,mq_id):
		with engine.connect() as conn:
			stmt = text(f"delete from map_session_questions where msq_id in ({mq_id})")
			conn.execute(stmt)
			conn.commit()
			conn.close()
			return True
	
	def get_question_data(self,q_id):
		with engine.connect() as conn:
			stmt = text(f"select *,group_concat(display_name) as category_name  FROM questions q left join mcq_category mc on find_in_set(mc.mcq_category_id,q.category_ids) where q_id = {q_id};")
			result = conn.execute(stmt).fetchone()
			result = dict(result._mapping) if result else None
			conn.close()
			return result
			
	def usp_search_users(self,searchData):
		connection  = engine.raw_connection()
		cursor      = connection.cursor()
		cursor.callproc("usp_search_mcq_users",[searchData])
		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()
			if results :
				return results
			else :
				return None 
		else :
			cursor.close()
			connection.commit()
			return None
		

app.jinja_env.globals.update(BoModel=BoModel)

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