Exemplo n.º 1
0
async def register_students(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        payload = hyperjson.loads(ans.object.object.message.payload)
        data = []
        raw_html = requests.get(payload["students"])
        soup = BeautifulSoup(raw_html.text, "html.parser")
        students_ids = list(map(int, soup.find_all("pre")[1].text.split(",")))
        students = await api.users.get(user_ids=students_ids)
        student_last_id = Student.select().order_by(Student.id.desc()).get().id
        for student in students.response:
            student_last_id += 1
            data.append(
                {
                    "id": student_last_id,
                    "first_name": student.first_name,
                    "second_name": student.last_name,
                    "vk_id": student.id,
                    "group_id": payload["group"],
                    "academic_status": 1,
                },
            )
        query = Student.insert_many(data).execute()

        await ans.answer(
            f"{len(query)} студент(ов) зарегистрировано",
            keyboard=kbs.preferences.configure_chat(payload["chat_id"]),
        )
Exemplo n.º 2
0
def get_student_by_id(student_id):
    """
    Get (read), update or delete a student

    Args:
        student_id (Object id): The student Id of the student record that nees to be modified.

    Returns:
        dict: The dictionary with output values
        int : The status code
    """

    if request.method == 'GET':
        # get studeny by id worked---------------

        student = Student.objects.get(id=student_id)
        if student:
            # Update Code here
            researchgroup_ids = [str(tmp.id) for tmp in student.researchGroups]
            response = {
                'name': str(student.name),
                'studentNumber': str(student.studentNumber),
                'researchGroups': researchgroup_ids
            }
            response = jsonify(response)
            return response, 200
            # output = {'name': "", 'studentNumber': "", 'researchGroups': ""}
        else:
            # Update Code here
            response = {'message': 'Not Found'}
            return response, 404
    elif request.method == 'PUT':
        # put worked-----------------------
        body = request.get_json()
        if body:
            # Update Code here
            if 'researchGroups' in body:
                researchgroup_ids = [
                    ObjectId(tmp) for tmp in body['researchGroups']
                ]
                body['researchGroups'] = researchgroup_ids

            Student.objects(id=student_id).update(**body)
            response = {
                'message': 'Student successfully updated',
                'id': str(student_id)
            }
            return response, 200
        else:
            # Update Code here
            response = {'message': 'No Content'}
            return response, 204
    elif request.method == 'DELETE':
        # delete worked-----------------
        Student.objects.get_or_404(id=student_id).delete()
        response = {
            'message': 'Student successfully deleted',
            'id': str(student_id)
        }
        return response, 200
Exemplo n.º 3
0
 def __init__(self):
     # Seed data for test database
     self.seeds = [
         Student(name="James Dean",
                 email="*****@*****.**",
                 phone="123-456-7890"),
         Student(name="Jimmy Dean",
                 email="*****@*****.**",
                 phone="123-456-7890"),
         Student(name="Howard Dean",
                 email="*****@*****.**",
                 phone="123-456-7890"),
         Student(name="Brenda Dean",
                 email="*****@*****.**",
                 phone="123-456-7890"),
         Student(name="Felicity Dean",
                 email="*****@*****.**",
                 phone="123-456-7890")
     ]
     # Data for test cases.
     self.data = SimpleNamespace(add_student={
         "name": "John Cleese",
         "email": "*****@*****.**",
         "phone": "123-456-7890"
     },
                                 edit_student={"phone": "098-765-4321"},
                                 missing_key={
                                     "name": "John Cleese",
                                     "email": "*****@*****.**"
                                 },
                                 bad_key={
                                     "name":
                                     "John Cleese",
                                     "email":
                                     "*****@*****.**",
                                     "phone":
                                     "123-456-7890",
                                     "something_bad":
                                     "You don't want this in your data."
                                 },
                                 bad_phone={
                                     "name": "John Cleese",
                                     "email": "*****@*****.**",
                                     "phone": "123-456-789098765"
                                 },
                                 bad_email={
                                     "name": "John Cleese",
                                     "email": "john@[email protected]",
                                     "phone": "123-456-7890"
                                 },
                                 not_unique_email={
                                     "name": "James Dean",
                                     "email": "*****@*****.**",
                                     "phone": "123-456-7890"
                                 },
                                 patch_not_unique_email={
                                     "name": "James R. Dean",
                                     "email": "*****@*****.**"
                                 })
Exemplo n.º 4
0
 def update(self):
     student = Student()
     group_number: str = self.group_number
     ls_all: list = student.show_all(self.session, group_number)
     ls_all: np.ndarray = np.array(ls_all)
     self.tableWidget = set_items_to_table(self.tableWidget, ls_all)
     self.tableWidget.resizeColumnsToContents()
     self.label.setText("Список группы: №" + str(group_number))
     self.group_number = str(group_number)
Exemplo n.º 5
0
    def delete(self):
        items = self.tableWidget.selectedItems()
        for i in items:
            row = self.tableWidget.row(i)
            number = self.tableWidget.item(row, 1).text()

            student = Student()
            student.delete(self.session, number)

            self.tableWidget.removeRow(row)
Exemplo n.º 6
0
 def show_student_list_window(self):
     student = Student()
     group_number: str = self.comboBox.currentText()
     ls_all: list = student.show_all(self.session, group_number)
     ls_all: np.ndarray = np.array(ls_all)
     self.student_list_ui.tableWidget = set_items_to_table(
         self.student_list_ui.tableWidget, ls_all)
     self.student_list_ui.tableWidget.resizeColumnsToContents()
     self.student_list_ui.label.setText("Список группы: №" +
                                        str(group_number))
     self.student_list_ui.group_number = str(group_number)
     self.student_list_window.show()
Exemplo n.º 7
0
    def update(self):
        note = self.textEdit.toPlainText()
        number = self.lineEdit_2.text()
        fio = self.lineEdit.text()

        student = Student()
        student.update(self.session, self.update_value, fio, number, note)

        self.table.setItem(self.row, 0, QtWidgets.QTableWidgetItem(fio))
        self.table.setItem(self.row, 1, QtWidgets.QTableWidgetItem(number))
        self.table.setItem(self.row, 2, QtWidgets.QTableWidgetItem(note))
        self.table.resizeColumnsToContents()

        self.update_student_window.close()
def add_student():

    body = request.get_json()
    if (request.args.get('researchGroups')):
        rg = (body['researchGroups'])
        rg = [ObjectId(rg_id) for rg_id in rg]
        body['researchGroups'] = rg
    student = Student(**body)
    print(body)
    # print(body['researchGroups'])
    student.save()
    id = student.id
    output = {'message': "Student successfully created", 'id': str(id)}
    return (output), 201
Exemplo n.º 9
0
def get_group_by_id(group_id):
    if request.method == "GET":
        group = json.loads(
            ResearchGroup.objects(id=group_id).get_or_404().to_json())
        output = {
            'id': str(group_id),
            'name': str(group['name']),
            'founder': str(group['founder']['$oid'])
        }
        return jsonify(output), 200
    elif request.method == "PUT":
        body = request.get_json()
        keys = body.keys()
        if body and keys:
            if 'name' in keys:
                ResearchGroup.objects(id=group_id).update(
                    set__name=body['name'])
            if 'founder' in keys:
                prof_ids = [prof.id for prof in Professor.objects()]
                if ObjectId(body['founder']) in prof_ids:
                    ResearchGroup.objects(id=group_id).update(
                        set__founder=ObjectId(body['founder']))
                    Professor.objects(id=body['founder']).update(
                        push__researchGroups=ObjectId(group_id))
                else:
                    output = {'message': 'Invalid founder ID'}
                    return output, 404
            if 'description' in keys:
                ResearchGroup.objects(id=group_id).update(
                    set__description=body['description'])
            output = {
                'message': 'Group successfully updated',
                'id': str(group_id)
            }
        else:
            output = {'message': 'Message body is empty'}
        return output, 200
    elif request.method == "DELETE":
        ResearchGroup.objects().get(id=group_id).delete()
        founder = Professor.objects(researchGroups=group_id)
        if founder:
            Professor.objects(researchGroups=group_id).update(
                pull__researchGroups=ObjectId(group_id))
        student = Student.objects(researchGroups=group_id)
        if student:
            Student.objects(researchGroups=group_id).update(
                pull__researchGroups=ObjectId(group_id))
        output = {'message': 'Group successfully deleted', 'id': str(group_id)}
        return output, 200
Exemplo n.º 10
0
def All_students():

    collection = db.Student
    # students =[doc for doc in Student.objects().all()]


    data = []
    for i in Student.objects().all():
     dataJson = i.to_json()
     res = json.loads(dataJson)
     data.append(res)

   
    cur = collection.find()
    if cur.count()==0: 
        # no data exist
        return jsonify({
                    "success": False ,            
        },404)
      
    else:
        return jsonify({
                    "success": True ,
                    "data": data   
        })
Exemplo n.º 11
0
def get_all_student():
    keys = [key for key in request.args.keys()]
    if keys:
        if keys[0] == 'groupName':
            value = request.args.get(keys[0])
            if value:
                groups = ResearchGroup.objects(name=value)
                if groups:
                    group_id = [group.id for group in groups]
                    students = Student.objects(
                        researchGroups=group_id[0]).to_json()
                    all_students = json.loads(students)
                    output = [{
                        'name': str(p['name']),
                        'studentNumber': str(p['studentNumber'])
                    } for p in all_students]
                    return jsonify(output), 200
                else:
                    output = {'message': 'Invalid groupName'}
                    return output, 200
            else:
                output = {'message': 'Params value empty'}
                return output, 200
        else:
            output = {'message': 'Incorrect search key'}
            return output, 200
Exemplo n.º 12
0
def generate_debtors_call(admin_id: int) -> t.List[str]:
    """
    Генерирует сообщение призыва должников.

    Args:
        admin_id: идентификатор администратора

    Returns:
        List[str]: сообщение(я) призыва должников
    """
    store = db.admin.get_admin_storage(admin_id)
    debtors = db.finances.get_debtors(store.category_id)
    category = FinancialCategory.get_by_id(store.category_id)
    messages = [
        f"Вы не сдали на {category.name} сумму, указанную напротив вашего имени\n",
    ]
    for debtor_id in debtors:
        if donate := FinancialDonate.get_or_none(
            category=category.id,
            student=debtor_id,
        ):
            summ = category.summ - donate.summ
        else:
            summ = category.summ
        student = Student.get_by_id(debtor_id)
        tmp = (
            f"@id{student.vk_id} ({student.first_name} {student.second_name}) - "
            f"{summ} руб.\n"
        )
        if len(messages[-1]) < 2000:
            messages[-1] += tmp
        else:
            messages.append("")
Exemplo n.º 13
0
def add_student(name, email, cohort):
    '''
    '''
    new_student = Student(name=name, email=email, cohort_id=cohort)
    db.session.add(new_student)
    db.session.commit()
    print('Student added')
def get_all_students():
    """
    This function lists all students
    """
    try:
        gname = request.args.get('groupName')

        if gname:
            logging.error(gname)
            grp = ResearchGroup.objects.get(name=gname)
            students = Student.objects(researchGroups=grp)
            output = []
            for st in students:
                output.append({
                    'name': st.name,
                    'studentNumber': st.studentNumber
                })
        else:
            output = {'message': 'Empty or Invalid body'}

        return Response(json.dumps(output),
                        mimetype='application/json',
                        status=200)
    except Exception as e:
        logging.exception(e)
        output = {'message': 'Server Error'}
        return output, 500
Exemplo n.º 15
0
    def import_csv(self):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        try:
            path, _ = QtWidgets.QFileDialog.getOpenFileName(
                self.student_list_window, "Open Image", ".",
                "Image Files (*.csv)")

            with open(path, "r") as f_obj:
                reader = csv.reader(f_obj)
                student = Student()
                students = student.show_name(self.session, self.group_number)

                for row in reader:
                    fio = row[0]
                    number = row[1]
                    note = row[2]
                    flag_s = 0
                    for s in students:
                        if fio == s:
                            flag_s = 1
                            break

                    if flag_s == 0:
                        student.add(self.session, fio, number, note,
                                    self.group_number)
                        number_row = self.tableWidget.rowCount()
                        self.tableWidget.setRowCount(number_row + 1)
                        self.tableWidget.setItem(
                            number_row, 0, QtWidgets.QTableWidgetItem(fio))
                        self.tableWidget.setItem(
                            number_row, 1,
                            QtWidgets.QTableWidgetItem(str(number)))
                        self.tableWidget.setItem(
                            number_row, 2,
                            QtWidgets.QTableWidgetItem(str(note)))
                        self.tableWidget.resizeColumnsToContents()

            msg.setText("Импорт выполнен")
            msg.setInformativeText('Импорт данных из CSV выполнен.')
            msg.setWindowTitle("Импорт выполнен")

        except:
            msg.setText("Импорт не выполнен")
            msg.setInformativeText('Импорт данных из CSV не выполнен.')
            msg.setWindowTitle("Импорт не выполнен")
        msg.exec_()
Exemplo n.º 16
0
    def add(self):
        fio = self.lineEdit.text()
        number = self.lineEdit_2.text()
        note = self.textEdit.toPlainText()

        student = Student()
        student.add(self.session, fio, number, note, self.group_number)

        row = self.table.rowCount()

        self.table.setRowCount(row + 1)
        self.table.setItem(row, 0, QtWidgets.QTableWidgetItem(fio))
        self.table.setItem(row, 1, QtWidgets.QTableWidgetItem(number))
        self.table.setItem(row, 2, QtWidgets.QTableWidgetItem(note))
        self.table.resizeColumnsToContents()

        self.add_student_window.close()
Exemplo n.º 17
0
async def register_chat(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        store = db.admin.get_admin_storage(
            db.students.get_system_id_of_student(ans.object.object.message.from_id),
        )
        if (
            store.confirm_message in ans.object.object.message.text
            and ans.object.object.message.from_id == Student.get_by_id(store.id).vk_id
        ):
            db.shortcuts.clear_admin_storage(
                db.students.get_system_id_of_student(ans.object.object.message.from_id),
            )

            group = db.admin.get_active_group(
                db.students.get_system_id_of_student(
                    ans.object.object.message.from_id,
                ),
            )
            if db.chats.is_chat_registered(
                ans.object.object.message.peer_id,
                group,
            ):
                await api.messages.send(
                    message="Чат уже зарегистрирован в этой группе",
                    peer_id=ans.object.object.message.from_id,
                    random_id=0,
                    keyboard=await kbs.preferences.connected_chats(
                        db.students.get_system_id_of_student(
                            ans.object.object.message.from_id,
                        ),
                    ),
                )
            else:
                chat = db.chats.register_chat(ans.object.object.message.peer_id, group)
                db.shortcuts.update_admin_storage(
                    db.students.get_system_id_of_student(
                        ans.object.object.message.from_id,
                    ),
                    current_chat_id=chat.id,
                )
                try:
                    chat_object = await api.messages.get_conversations_by_id(
                        peer_ids=ans.object.object.message.peer_id,
                    )
                    chat_name = chat_object.response.items[0].chat_settings.title
                except IndexError:
                    chat_name = "???"
                await api.messages.send(
                    message=f'Чат "{chat_name}" зарегистрирован',
                    peer_id=ans.object.object.message.from_id,
                    random_id=0,
                    keyboard=await kbs.preferences.connected_chats(
                        db.students.get_system_id_of_student(
                            ans.object.object.message.from_id,
                        ),
                    ),
                )
                await ans.answer("Привет!")
def add_student():

    # Update the code here.
    body = request.get_json()
    student = Student(**body).save()
    output = {'message': "Student successfully created", 'id': str(student.id)}
    # Update the status code
    status_code = 201
    return output, status_code
Exemplo n.º 19
0
def add_student():
    body = request.get_json()
    student = Student(**body).save()
    student_id = student.id
    output = {'message': 'Student successfully created', 'id': str(student_id)}
    return output, 201


#app.run() # FLASK_APP=app.py FLASK_ENV=development flask run
Exemplo n.º 20
0
    def show_add_safety_student_window(self):
        student = Student()
        s_name = student.show_name(self.session, self.group_number)
        self.add_safety_student_ui.comboBox.clear()
        self.add_safety_student_ui.comboBox.addItems(s_name)

        safety = Safety()
        safe_name = safety.all_name(self.session, self.discipline_name,
                                    self.group_number)
        self.add_safety_student_ui.comboBox_2.clear()
        self.add_safety_student_ui.comboBox_2.addItems(safe_name)

        date_now = self.add_safety_student_ui.dateEdit.date().currentDate()
        self.add_safety_student_ui.dateEdit.setDate(date_now)

        self.add_safety_student_ui.group_number = self.group_number
        self.add_safety_student_ui.discipline_name = self.discipline_name
        self.add_safety_student_window.show()
Exemplo n.º 21
0
    def test_get_list_of_students_by_letter(self):

        test_letter = "Б"
        test_user_id = 1
        test_student = Student.get_by_id(4)

        st = students.get_list_of_students_by_letter(test_user_id, test_letter)

        it(st).should.be_equal([test_student])
Exemplo n.º 22
0
def get_students_by_property():
    groupName = request.args.get('groupName')
    research_group = ResearchGroup.objects.get(name=groupName)
    students = Student.objects(researchGroups=research_group)
    output = [{
        'name': student.name,
        'studentNumber': student.studentNumber
    } for student in students]
    return jsonify(output), 200
Exemplo n.º 23
0
async def delete_students(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        payload = hyperjson.loads(ans.object.object.message.payload)
        query = 0
        raw_html = requests.get(payload["students"])
        soup = BeautifulSoup(raw_html.text, "html.parser")
        students_ids = list(map(int, soup.find_all("pre")[1].text.split(",")))
        for st in students_ids:
            query += Student.delete().where(Student.vk_id == st).execute()
        await ans.answer(
            f"{query} студент(ов) удалено",
            keyboard=kbs.preferences.configure_chat(payload["chat_id"]),
        )
Exemplo n.º 24
0
def get_unique_second_name_letters_in_a_group(group_id: int) -> list:
    """
    Возвращает список первых букв фамилий в активной группе.

    Args:
        group_id: Идентификатор группы

    Returns:
        list: список первых букв фамилий
    """
    query = (Student.select(Student.second_name).where(
        Student.group_id == group_id).order_by(Student.second_name).distinct())
    snd_names = [name.second_name[0] for name in query]
    if snd_names:
        return list(dict.fromkeys(snd_names))
Exemplo n.º 25
0
def sort_student():
    

    # Order by ascending data
    data = []
    sorted_data = Student.objects().order_by('name') 

    for i in sorted_data:
     dataJson = i.to_json()
     res = json.loads(dataJson)
     data.append(res)
       # equivalent to .order_by('+date')
    return jsonify({
                "success": True ,
                "message":data 
      }) 
Exemplo n.º 26
0
def get_student_by_groupname():
    # get students by groupname worked-----------
    groupname = request.args.get('groupName')
    if groupname:
        group = ResearchGroup.objects.get(name=groupname)
        student_list = Student.objects(researchGroups=group)
        response = [{
            'name': student.name,
            'studentNumber': student.studentNumber
        } for student in student_list]

        response = jsonify(response)
        return response, 200

    else:
        response = {'message': 'Not Found'}
        return response, 404
Exemplo n.º 27
0
def get_list_of_students_by_letter(admin_id: int,
                                   letter: str) -> t.List[Student]:
    """
    Возвращает объекты студентов активной группы, фамилии которых начинаются на letter.

    Args:
        admin_id: идентификатор пользователся
        letter: первая буква фамилий

    Returns:
        list[Student]: список студентов
    """
    active_group = admin.get_active_group(admin_id)
    query = (Student.select().where(
        (Student.second_name.startswith(letter))
        & (Student.group_id == active_group), ).order_by(
            Student.second_name.asc()))
    return shortcuts.generate_list(query)
Exemplo n.º 28
0
def generate_mentions(names_usage: bool, students: str) -> str:
    """
    Генерирует призыв студентов.

    Args:
        names_usage: Использование имен студентов
        students: Список идентификаторов призываемых студентов

    Returns:
        str: Призыв студентов
    """
    mentions = []
    sep = ", " if names_usage else ""
    for student in students.split(","):
        if student:
            st = Student.get(id=int(student))
            hint = st.first_name if names_usage else "!"
            mentions.append(f"@id{st.vk_id} ({hint})")
    return sep.join(mentions)
Exemplo n.º 29
0
def update_students(student_id):

    body = request.get_json()
    student = Student.objects(id=student_id)
    try:
        rg = body["researchGroups"]
        rg = [ObjectId(rg_id) for rg_id in rg]
        print(rg)

        body['researchGroups'] = rg
    except KeyError:
        pass
    finally:
        student.update(**body)
        output = {
            'message': "Student successfully updated",
            'id': str(student_id)
        }
        return output, 200
Exemplo n.º 30
0
def get_system_id_of_student(vk_id: int) -> int:
    """
    Возвращает идентификатор студента в системе.

    Args:
        vk_id: идентификатор студента в ВКонтакте

    Returns:
        int: идентификатор студента в системе

    Raises:
        StudentNotFound: когда студент с указанным идентификатором ВК не найден в
        системе
    """
    student = Student.get_or_none(vk_id=vk_id)
    if student is not None:
        return student.id
    raise StudentNotFound(
        f"Студента с id ВКонтакте {vk_id} не существует в системе")