def for_group(group_id, date_from = None, date_to = None): """ Retrives lessons for group filtered by date Keyword arguments: group_id - int ID of a group date_from - date in iso format string (!) or None (default: None) date_to - date in iso format string (!) or None (default: None) """ # Check if group exists try: Group.get_by_id(group_id) except Group.DoesNotExist: raise NoSuchDBRecordException("Group with id {} does not exist in database".format(group_id)) query = (Lesson .select(Lesson.name, Lesson.start, Lesson.end, Lesson.date, Room.name, Room.address, Group.name) .join(Group).switch(Lesson) .join(Lecturer).switch(Lesson) .join(Room).switch(Lesson) .where(Lesson.group == group_id) .order_by(Lesson.date, Lesson.start) ) if date_from != None: query = query.where(Lesson.date > date.fromisoformat(date_from)) if date_to != None: query = query.where(Lesson.date < date.fromisoformat(date_to)) return query_to_json_mapper(query)
def create_group(name=None, user_id): user = User.query.filter_by(id=user_id).first() if user is None: return None new_group = Group( name=name, organizer=user_id #should is save id? or user itself? ) db.session.add(new_group) db.session.commit() return new_group.serialize()
def create_group(): post_body = json.loads(request.data) group = Group( class_name=post_body.get("class_name"), description=post_body.get("description"), location=post_body.get("location"), time=post_body.get("time"), ) db.session.add(group) db.session.commit() return json.dumps({"success": True, "data": group.serialize2()}), 201
def get_groups(): arr = [] groups = Group.select() for group in groups: arr.append({"name": group.name, "display_name": group.display_name}) print("===SAVING {0} {1}===".format(len(arr), "Groups")) return arr
def create_group(creator_id, other_ids, name=None): main_user = User.query.filter_by(id=creator_id).first() if main_user is None: return None group = Group( name=name, members=[], messages=[] ) group.members.append(main_user) for user_id in other_ids: user = User.query.filter_by(id=user_id).first() if user is None: continue group.members.append(user) db.session.add(group) db.session.commit() return group.serialize(extended=True)
async def enter_group_direction_id(msg: types.Message, state: FSMContext): async with state.proxy() as data: if msg.text not in get_faculties(): return await msg.answer("Выберите факультет с клавиатуры!", reply_markup=faculty_kb) group = Group(data["group_name"], get_direction_id_by_name(data["group_faculty_name"])) insert_group(group) await state.finish() await msg.answer("Ура! Группа успешно добавлена!", reply_markup=admin_panel_kb)
def create_group(): try: post_body = json.loads(request.data) v = validate_json(post_body, ['group_members']) if v is not None: return v # name and is_private are optional for now? group = Group(name=post_body.get('group_name', '')) db.session.add(group) db.session.flush() print('group: ', group.serialize()) group_members = post_body.get('group_members') print('group_members: ', group_members) users = [] for member in group_members: user = User.query.filter_by(username=member).first() print('user: '******'association table: ', group.members) if user is None: continue group.members.all().append(user) db.session.flush() result = group.serialize() for member in group.members.all(): print('member serialize', member.serialize()) print('REACHES HERE?') result.append(member.username) db.session.commit() usernames = [u.username for u in group.members.all()] print('usernames', usernames) return json.dumps({'success': True, 'data': result}), 200 except Exception as e: print(e) return json.dumps({ 'success': False, 'error': 'haha something went wrong' }), 404
def send_message_to_user(sender_id, receiver_id, message): sender = User.query.filter_by(id=sender_id).first() receiver = User.query.filter_by(id=receiver_id).first() if sender is None or receiver is None: return None direct_message_id = sender.direct_message_with(receiver) if direct_message_id is not None: return send_message_to_group(sender_id, direct_message_id, message) new_group = Group( members=[], messages=[], direct_message=True ) new_group.members.append(sender) new_group.members.append(receiver) db.session.add(new_group) db.session.commit() return send_message_to_group(sender_id, new_group.id, message)
def setup_general_config(): ''' Is used to populate the database if it has been reset. :return: ''' long_string = ConfigType.get(type="long_string") long_string = ConfigType( type="long_string") if long_string is None else long_string string = ConfigType.get(type="string") string = ConfigType(type="string") if string is None else string number = ConfigType.get(type="number") number = ConfigType(type="number") if number is None else number config_list = [{ "key": "frontend_url", "value": "localhost:3001", "config_type": string, "description": "The url to this frontend page (used for links in the emails)" }, { "key": "archive_base_url", "value": "localhost:3001/api/archive/download", "config_type": string, "description": "The base url to download archives from (used in emails to the board)" }, { "key": "document_template_url", "value": "https://www.overleaf.com/read/ddjdhxnkxttj", "config_type": string, "description": "The template overleaf document for the different reports (used in the emails)" }, { "key": "gotify_url", "value": "http://*****:*****@chalmers.it", "config_type": string, "description": "The email to the secretary" }, { "key": "board_email", "value": "*****@*****.**", "config_type": string, "description": "The email to the board" }, { "key": "group_email_domain", "value": "@chalmers.it", "config_type": string, "description": "The domain to send emails to" }, { "key": "from_email_address", "value": "*****@*****.**", "config_type": string, "description": "The email to send from" }, { "key": "mail_to_groups_subject", "value": "Dokument till sektionsmöte den {day}/{month}", "config_type": string, "description": """ The subject for "regular" email sendout (that goes out to all active groups that have documents to turn in for the meeting). \n Description of the formatting values: \n - {group_name} = The display name of the group \n - {meeting_day} = The day of month for the meeting \n - {meeting_month} = The month (number) of the meeting \n - {deadline_time} = The deadline time (hh:mm) \n - {deadline_date} = The deadline date (dd/mm) \n - {task_list} = A list of the tasks that the group should upload \n - {frontend_url} = The url to the website \n - {group_code} = Their unique code \n - {template_url} = The document (overleaf) template url \n - {secretary_email} = The email to the secretary \n - {board_display_name} = The display name of the board \n - {board_email} = The email to the board """ }, { "key": "mail_to_groups_message", "value": "\nHej {group_name}!\n\nDen {meeting_day}/{meeting_month} är det dags för sektionsmöte och senast {deadline_time} den {deadline_date} behöver ni lämna in " "följande dokument: {task_list}\nDetta görs på sidan: {frontend_url}\nAnge koden: {group_code}\n\nMall för vissa " "dokument finns här: {template_url}\nGör en kopia av projektet (Menu -> Copy Project) och fyll i.\n\nOm ni har " "några frågor eller stöter på några problem kan kan ni kontakta mig på {secretary_email} eller hela {board_display_name} på {board_email} " ": ).", "config_type": long_string, "description": """ The body of the "regular" emails (the ones that are sent to all the active groups that should turn in documents for the meeting). \n Description of the formatting values: \n - {group_name} = The display name of the group \n - {meeting_day} = The day of month for the meeting \n - {meeting_month} = The month (number) of the meeting \n - {deadline_time} = The deadline time (hh:mm) \n - {deadline_date} = The deadline date (dd/mm) \n - {task_list} = A list of the tasks that the group should upload \n - {frontend_url} = The url to the website \n - {group_code} = Their unique code \n - {template_url} = The document (overleaf) template url \n - {secretary_email} = The email to the secretary \n - {board_display_name} = The display name of the board \n - {board_email} = The email to the board """ }, { "key": "mail_to_board_subject", "value": "Dokument för sektionsmöte {meeting_number} lp {meeting_lp}", "config_type": string, "description": """ The subject of the email that is sent to the board upon reaching the deadline. \n Description of the formatting values: \n - {board_name} = The display name of the board \n - {meeting_number} = The number of the meeting (usually 0) \n - {meeting_lp} = The study period of the meeting \n - {meeting_archive_url} = A link to the archive download \n - {secretary_email} = The email to the secretary """ }, { "key": "mail_to_board_message", "value": "\nHej {board_name}!\n\nDeadlinen för dokumentinsamling till sektionsmöte {meeting_number} i lp {meeting_lp} är nu nådd.\nFör " "nedladdning av dessa dokument klicka på denna länk: {meeting_archive_url}\n\nVid frågor, kontakta sekreteraren på {secretary_email}", "config_type": long_string, "description": """ The contents of the email that is sent out to the board upon reaching the deadline. \n Description of the formatting values: \n - {board_name} = The display name of the board \n - {meeting_number} = The number of the meeting (usually 0) \n - {meeting_lp} = The study period of the meeting \n - {meeting_archive_url} = A link to the archive download \n - {secretary_email} = The email to the secretary """ }, { "key": "mail_for_stories_subject", "value": "Dokument för sektionsmöte {meeting_number} lp {meeting_lp}", "config_type": string, "description": """ The subject of the email that is sent to the "story groups" (i.e. the groups that needs to turn in eberattelser / vberattelser. \n Description of the formatting values: \n - {group_name_year} = Display name of the group. \n - {meeting_day} = The day of month that the meeting will take place \n - {meeting_month} = The month (number) of the meeting \n - {deadline_time} = The deadline time \n - {deadline_date} = The deadline date \n - {task_list} = A list of the tasks that the group will have to turn in. \n - {frontend_url} = A url to the frontend (upload page) \n - {group_code} = Their unique code \n - {template_url} = A link the overleaf template for the documents. \n - {secretary_email} = The email to the secretary \n - {board_display_name} = The display name of the board \n - {board_email} = The email to the board \n - {meeting_number} = The number of the meeting that study period (usually 0) \n - {meeting_lp} = The study period """ }, { "key": "mail_for_stories", "value": "\nHej {group_name_year}!\n\nDen {meeting_day}/{meeting_month} är det dags för sektionsmöte och senast {deadline_time} den {deadline_date} behöver ni lämna in " "följande dokument: {task_list}\nDetta görs på sidan: {frontend_url}\nAnge koden: {group_code}\n\nMall för vissa " "dokument finns här: {template_url}\nGör en kopia av projektet (Menu -> Copy Project) och fyll i.\n " "Kontakta revisorerna på [email protected] för mer information om vad som behövs göras innan ni " "kan bli rekomenderade att bli ansvarsbefriade.\n\nOm ni har " "några frågor eller stöter på några problem kan kan ni kontakta mig på {secretary_email} eller hela {board_display_name} på {board_email} " ": ).", "config_type": long_string, "description": """ The body of the email that is sent to the "story groups" (i.e. the groups that needs to turn in eberattelser / vberattelser) \n Description of the formatting values: \n - {group_name_year} = Display name of the group. \n - {meeting_day} = The day of month that the meeting will take place \n - {meeting_month} = The month (number) of the meeting \n - {deadline_time} = The deadline time \n - {deadline_date} = The deadline date \n - {task_list} = A list of the tasks that the group will have to turn in. \n - {frontend_url} = A url to the frontend (upload page) \n - {group_code} = Their unique code \n - {template_url} = A link the overleaf template for the documents. \n - {secretary_email} = The email to the secretary \n - {board_display_name} = The display name of the board \n - {board_email} = The email to the board \n - {meeting_number} = The number of the meeting that study period (usually 0) \n - {meeting_lp} = The study period """ }, { "key": "board_display_name", "value": "styrIT", "config_type": string, "description": "The display name of the board" }, { "key": "minutes_after_deadline_to_mail", "value": "5", "config_type": number, "description": "The amount of minutes to wait extra after the deadline before sending the email to the board" }, { "key": "check_for_deadline_frequency", "value": "5", "config_type": number, "description": "The frequence (in minutes) to check if any deadlines have been reached" }, { "key": "possible_years_back_for_stories", "value": "5", "config_type": number, "description": "The number of years back that one should be able to select story groups for (usually 5 due to tax reasons)" }] for config in config_list: conf = Config.get(key=config["key"]) if conf is None: Config(key=config["key"], value=config["value"], config_type=config["config_type"], description=config["description"]) else: # Since the only way to change the description is here, # we always want the db version to be up to date with this list on application restart. conf.description = config["description"] # Setup groups and tasks groups = [{ "codeName": "armit", "displayName": "ArmIT" }, { "codeName": "digit", "displayName": "digIT" }, { "codeName": "fanbarerit", "displayName": "FanbärerIT" }, { "codeName": "fritid", "displayName": "frITid" }, { "codeName": "mrcit", "displayName": "MRCIT" }, { "codeName": "nollkit", "displayName": "NollKIT" }, { "codeName": "prit", "displayName": "P.R.I.T." }, { "codeName": "sexit", "displayName": "sexIT" }, { "codeName": "snit", "displayName": "snIT" }, { "codeName": "styrit", "displayName": "styrIT" }, { "codeName": "equalit", "displayName": "EqualIT" }, { "codeName": "flashit", "displayName": "FlashIT" }] tasks = [{ "codeName": "vplan", "displayName": "Verksamhetsplan / Operational plan" }, { "codeName": "budget", "displayName": "Budget" }, { "codeName": "vrapport", "displayName": "Verksamhetsrapport / Operational report" }, { "codeName": "vberattelse", "displayName": "Verksamhetsberättelse / Operational story" }, { "codeName": "eberattelse", "displayName": "Ekonomisk Berättelse / Economic story" }] for group in groups: if Group.get(name=group["codeName"]) is None: new_group = Group(name=group["codeName"], display_name=group["displayName"]) if GroupYear.get(group=new_group, year="active") is None: GroupYear(group=new_group, year="active", finished=False) for task in tasks: if Task.get(name=task["codeName"]) is None: Task(name=task["codeName"], display_name=task["displayName"]) commit() print("Finished loading database data from general config file.")
def groups(): return Group.select()
def create(self, name, telegram_id): m = Group(name=name, telegram_id=telegram_id) super().create(m)
def get_group_by_name(name: str) -> Optional[Group]: return Group.get(name=name)
def new_lesson(): return render_template('lessons/new.html', groups=Group.select(), lecturers=Lecturer.select(), addresses=Room.select(Room.address).group_by( Room.address))
def lessons_groups(group_id): return render_template('lessons/group.html', group=Group.get_by_id(group_id))
def insert(): rooms = [{ 'name': '1', 'address': 'address1', 'id': 1 }, { 'name': '10', 'address': 'address1', 'id': 2 }, { 'name': '20', 'address': 'address1', 'id': 3 }, { 'name': '30', 'address': 'address1', 'id': 4 }, { 'name': '40', 'address': 'address1', 'id': 5 }, { 'name': '1', 'address': 'address2', 'id': 6 }, { 'name': '5', 'address': 'address2', 'id': 7 }, { 'name': '10', 'address': 'address2', 'id': 8 }, { 'name': '15', 'address': 'address2', 'id': 9 }, { 'name': '20', 'address': 'address2', 'id': 10 }] Room.insert_many(rooms).execute() lecturers = [{ 'name': 'Lecturer One' }, { 'name': 'Lecturer One' }, { 'name': 'Lecturer Two' }, { 'name': 'Lecturer Three' }, { 'name': 'Lecturer Four' }] Lecturer.insert_many(lecturers).execute() groups = [{ 'name': 'stream1', 'id': 1 }, { 'name': 'stream2', 'id': 2 }, { 'name': 'group1', 'parentGroupId': 1, 'id': 3 }, { 'name': 'group2', 'parentGroupId': 1, 'id': 4 }, { 'name': 'group3', 'parentGroupId': 2, 'id': 5 }, { 'name': 'group4', 'parentGroupId': 2, 'id': 6 }, { 'name': 'group5', 'id': 7 }] Group.insert_many(groups).execute() students = [{'id': i, 'name': 'student ' + str(i)} for i in range(1, 41)] Student.insert_many(students).execute() stg = [{'StudentID': i, 'GroupID': 1} for i in range(1, 21)] stg += [{'StudentID': i, 'GroupID': 2} for i in range(21, 41)] stg += [{'StudentID': i, 'GroupID': 3} for i in range(1, 11)] stg += [{'StudentID': i, 'GroupID': 4} for i in range(11, 21)] stg += [{'StudentID': i, 'GroupID': 5} for i in range(21, 31)] stg += [{'StudentID': i, 'GroupID': 6} for i in range(31, 41)] stg += [{'StudentID': i, 'GroupID': 7} for i in range(1, 41, 5)] StudentToGroup.insert_many(stg).execute() dates = [ date(2020, 2, 10), date(2020, 2, 11), date(2020, 2, 12), date(2020, 2, 13) ] times = [(time(9, 30), time(11, 5)), (time(11, 15), time(12, 50)), (time(13, 40), time(15, 15))] lessons = [] for d in dates: (s, e) = times[0] #print(e) lessons.append({ 'group': 1, 'room': 1, 'lecturer': 1, 'name': 'Lecture', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 2, 'room': 2, 'lecturer': 2, 'name': 'Lecture', 'start': s, 'end': e, 'date': d }) (s, e) = times[1] lessons.append({ 'group': 3, 'room': 3, 'lecturer': 3, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 4, 'room': 4, 'lecturer': 4, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 5, 'room': 1, 'lecturer': 1, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 6, 'room': 2, 'lecturer': 2, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) (s, e) = times[2] lessons.append({ 'group': 7, 'room': 3, 'lecturer': 3, 'name': 'Elective', 'start': s, 'end': e, 'date': d }) print(lessons) Lesson.insert_many(lessons).execute()
def add_group1(self): logger.info("add_group1") group = Group(group_name="splatoon", user_name="ika") self.session.add(group)
def is_restored(): groups = Group.select()[:] if len(groups) > 0: return True return False
def main(): sys.path.append(ROOT_PATH) import db from db import Information, Category, Group, Type os.chdir(os.path.dirname(__file__)) clear_dir('locales') sessions = {} for lcid, name in LCID.items(): sessions[lcid] = db.create_session( os.path.join('locales', lcid + '.db')) categories_yaml = load_yaml(os.path.join('sde', 'fsd', 'categoryIDs.yaml')) groups_yaml = load_yaml(os.path.join('sde', 'fsd', 'groupIDs.yaml')) types_yaml = load_yaml(os.path.join('sde', 'fsd', 'typeIDs.yaml')) category_ids = [] group_ids = [] def id_(key): try: value = items[key] except KeyError: value = 0 return value def locale(key): try: value = items[key][lcid] except KeyError: value = '' return value.strip() for i, items in categories_yaml.items(): name = items['name']['en'] if name not in CATEGORY_NAMES: continue category_ids.append(i) for lcid, session in sessions.items(): session.add(Category(id=i, name=locale('name'))) for i, items in groups_yaml.items(): category_id = id_('categoryID') if category_id not in category_ids: continue group_ids.append(i) for lcid, session in sessions.items(): session.add( Group(id=i, categoryID=category_id, name=locale('name'))) for i, items in types_yaml.items(): group_id = id_('groupID') if group_id not in group_ids: continue for lcid, session in sessions.items(): session.add( Type(id=i, groupID=group_id, name=locale('name'), description=locale('description'))) for lcid, session in sessions.items(): session.add(Information(lcid=lcid, name=LCID[lcid])) session.commit()
def restore_groups(json): for group in json: group = Group(name=group["name"], display_name=group["display_name"]) GroupYear(group=group, year="active", finished=False) arr = Group.select()[:] print("===RESTORED {0} {1}===".format(len(arr), "Groups"))
from db import User, Group, init_db, destroy_db, Session from logger import Logger from logging import getLogger from sqlalchemy.orm import selectinload Logger() logger = getLogger("src." + __name__) try: init_db() user = User(name="ika", email="*****@*****.**") group = Group(group_name="splatoon", user_name="ika") Session.add_all([user, group]) Session.commit() # SELECT # users.id AS users_id, users.name AS users_name, users.email AS users_email # FROM # users # JOIN # groups ON users.name = groups.user_name # WHERE # users.name = groups.user_name logger.info("----test1----") query = Session.query(User).join(Group).filter(User.name == Group.user_name).all() logger.info(query) # [<User 'ika'>] logger.info(type(query)) # <class 'list'> # SELECT