Exemplo n.º 1
0
    def reg_activity(cls, group_id: int, act_name: str, act_info: str,
                     act_start_time: datetime, act_end_time: datetime,
                     by: User) -> Result[bool]:
        with RxTable(UserGroup) as ug_dao:
            if not ug_dao.where(UserGroup.user_cls.in_(
                [Role.leader, Role.admin]),
                                user_id=by.id,
                                group_id=group_id).first():
                return Result(False, '操作用户权限不足')

        with RxTable(Activity) as act_dao:
            if act_dao.where(name=act_name).first():
                return Result(False, '活动重复')

            act = act_dao.add(name=act_name, info=act_info)

            with RxTable(GroupActivity) as ga_dao:
                ga_dao.add(group_id=group_id,
                           activity_id=act.id,
                           start=act_start_time,
                           end=act_end_time,
                           is_active=0)

            if not act_dao.is_succeed:
                return Result(False, '创建活动失败,不再相信爱')

        return Result(True, '建立活动成功')
Exemplo n.º 2
0
    def test4_controller(self):
        from rx_sharh.rxdb import RxRecord, RxTable, RxMany, RxList
        from rx_sharh.states.database import Course, UserCourse, User, db_session, delete_user

        with RxTable(User) as user, RxTable(Course) as course, RxTable(UserCourse) as user_course:
            with open('./samples.json') as f:
                s = f.read()
                users = user_deserialize(s)
                courses = default_serialize(s, 'Course')
            users = user.add_many(users)
            courses = course.add_many(courses)
            user_course_s = [dict(course_id=each_course.id,
                                  user_id=each_user.id) for each_course in courses for each_user in users]
            user_course.add_many(user_course_s)

        from rx_sharh.service.controller import user as c_user, course as c_course

        pprint(list(c_course.Controller.get_normals_of(course.first())))
        pprint(list(c_user.Controller.get_normals_for(user.first(), Course)))

        with user:
            for each in user.rx_iter():
                each.mutate(password=lambda password: password + "233")

        print('after mutate:')
        user.foreach(lambda x: pprint(x.password))

        with user:
            users_all: List[User] = user.where().all()

            for each in RxList(users_all).where(id = lambda x: True).rx_iter():
                each.delete()

        print('after delete:')
        user.foreach(lambda x: pprint(x.password))
Exemplo n.º 3
0
    def test3_mutate_relation(self):
        from rx_sharh.rxdb import RxRecord, RxTable, RxMany
        from rx_sharh.states.database import Course, UserCourse, User, db_session
        import rx_sharh.service.controller.group as group

        with RxTable(User) as user:
            for each in user:
                print()
                print('relation:')
                relation = RxRecord(each).relation(Course)
                pprint(relation)
                relation.delete()

        print()
        print('after delete')

        with user:
            for each in user:
                pprint(each.ref_courses)

        with user, RxTable(UserCourse) as uc, RxTable(Course) as c:
            user.where().delete()
            c.where().delete()
        uc: RxTable[UserCourse]
        print(uc.where().where(user_cls=Role.normal).unbox.all())
Exemplo n.º 4
0
    def test2_multi_transaction(self):
        print("test2:")
        from rx_sharh.rxdb import RxRecord, RxTable, RxMany
        from rx_sharh.states.database import User, Course, UserCourse
        with RxTable(User) as user, RxTable(Course) as course, RxTable(UserCourse) as user_course:
            user: RxTable[User]
            with open('./samples.json') as f:
                s = f.read()
                users = user_deserialize(s)
                courses = default_serialize(s, 'Course')
            users = user.add_many(users)
            courses = course.add_many(courses)
            user_course_s = [dict(course_id=each_course.id,
                                  user_id=each_user.id) for each_course in courses for each_user in users]
            user_course.add_many(user_course_s)

            print('insert count:', User.query.count())

        print(f'users_num : {len(users)}, courses_num: {len(courses)}')
        pprint(user_course_s)
        print('user_course relation count:', UserCourse.query.count())
        print()

        print('all users')
        pprint(user.where().all())

        print('user_courses?:')
        pprint(User.query.first().ref_courses)
        print()

        print('before delete')
        for each in user:
            pprint(each.ref_courses)

        with user:
            user: RxTable[User]
            for each in user:
                print(RxRecord(each.ref_courses[0]).delete())

        print('after delete')
        for each in user:
            pprint(each.ref_courses)

        with user, user_course, course:
            user_course.where().delete()
            course.where().delete()
            user.where().delete()

            with open('./samples.json') as f:
                s = f.read()
                users = user_deserialize(s)
                courses = default_serialize(s, 'Course')
            users = user.add_many(users)
            courses = course.add_many(courses)
            user_course_s = [dict(course_id=each_course.id, user_id=each_user.id)
                             for each_course in courses for each_user in users]
            user_course.add_many(user_course_s)
Exemplo n.º 5
0
    def test2_relation_add(self):
        from rx_sharh.rxdb import RxTable, RxRecord
        from rx_sharh.states.database import User, UserStudent, Permission, Student
        with RxTable(User) as c, RxTable(Student) as s:
            for each in c.where(permission=Permission.student).rx_iter():
                print(each)
                each: RxRecord[User]
                r = each.relation(to=Student)
                e = s.where(id=each.unbox.id).first()
                if e:
                    each.add_relation_between(e)

        for each in c.where(permission=Permission.student).rx_iter():
            print(each.unbox.ref_students)
Exemplo n.º 6
0
def stop_sign(sign_name):
    sign_dao = RxTable(db.Sign)
    sign = sign_dao.where(name=sign_name).first()
    if not sign:
        flash("实例不存在!")
        Config.app.logger.warning('{}'.format(sign_name))
        return redirect(url_for('attendance.stop', sign_name=sign_name, status=1, qrcode=0))

    with RxRecord(sign) as sign_rx:
        sign_rx.mutate(end=SyncCurrent.get_date(), is_active=0)

    flash('停止签到')

    return redirect(url_for('attendance.stop', sign_name=sign_name, status=0, qrcode=0))
Exemplo n.º 7
0
def signin():
    # if g.user is not None and g.user.is_authenticated:
    #     return redirect(url_for('index'))
    if request.method == 'POST':
        form = request.form
        try:
            with RxTable(db.User) as user_table:
                account = form['account']
                if user_table.where(account=account).first():
                    raise Exception
                user = user_table.add(account=form['account'],
                                      password=form['password'],
                                      permission=Permission(
                                          form['permission']),
                                      status=db.Status.ready)

            flash("注册成功!")
            login_user(user)
            if g.user.is_authenticated:
                return redirect_with_302(location='index')
            else:
                return redirect_with_302(location='authentication.signin')
        except Exception as e:
            flash("账号已存在")
            app.logger.warning(str(f'{e}|{user_table.msg}'))
            return redirect_with_302(location='authentication.signin')

    return render_template('authentication/signin.html', title='注册')
Exemplo n.º 8
0
def change_info():
    """昵称
       性别
       生日
    """

    if request.method != 'POST':
        return render_template('profile/info.html', user=g.user, title="更改信息")

    form = request.form
    user = g.user

    with RxTable(db.User) as user_dao:
        suc = user_dao.where(id=user.id).mutate(nickname=form['nickname'],
                                                birthday=form['birthday'],
                                                sex=Sex(form['sex']),
                                                email=form['email'])

    if suc and user_dao.is_succeed:
        flash('更新成功')
        return redirect_with_302('profile.profile')

    else:
        flash('更新失败')
        app.logger.warning(user_dao.msg)
        return redirect_with_302('profile.change_info')
Exemplo n.º 9
0
def validate_phone():
    user: db.User = g.user
    form = request.form
    # sms_response = session['sms_response']
    name = form['name']
    new_password = form['newPassword']

    if user.permission == db.Permission.student:
        us = user.ref_students.first()
        if us and us.student.name != name:
            flash('信息错误,无法通过')
            return redirect_with_302('profile.bind_phone')

    elif user.permission == db.Permission.teacher:
        ut = user.ref_teachers.first()
        if ut and ut.teacher.name != name:
            flash("信息错误,无法通过")
            return redirect_with_302('profile.bind_phone')

    # if sms_response['Phone'] != form['phoneNumber'] and sms_response['Code'] != form['code']:
    #     flash("绑定失败!")
    #     return redirect_with_302('profile.bind_phone')
    # else:
    with RxTable(db.User) as user_dao:
        user_dao.where(id=user.id).mutate(status=Status.active,
                                          password=new_password)
    flash("修改成功!")
    return redirect_with_302('index')
Exemplo n.º 10
0
    def clear(cls, group_id: {'all', 'int'}, channels):
        """
        >>> from rx_sharh.states.message.ref import Group
        >>> Group.clear(group_id=1, channels=Group.Channel.Public)
        >>> Group.clear(group_id=1, channels=(Group.Channel.ApplyIn, Group.Channel.Public))
        >>> Group.clear(group_id=all, channels=all)
        """
        if channels is all:
            channels = tuple(cls.Channel)
        elif isinstance(channels, cls.Channel):
            channels = (channels, )

        def for_each_group(each_group_id: int):
            for channel in channels:
                length_key = name_pattern(group=cls.Group,
                                          field=cls.Field.Length,
                                          index=each_group_id,
                                          channel=channel.value)

                cache_storage.set(length_key, 0)

                for field in cls.Field.except_length():
                    cache_storage.delete(
                        name_pattern(cls.Group, field, each_group_id, channel))

        if group_id is not all:
            return for_each_group(group_id)

        from rx_sharh.rxdb import RxTable
        from rx_sharh.states.database import Group
        RxTable(Group).foreach(lambda x: for_each_group(x.id))
Exemplo n.º 11
0
    def modify_info(cls, group_id: int, group_spec: dict,
                    by: User) -> Result[bool]:
        checked = check_group_spec(group_spec)
        if not checked.Object:
            return Result(False, "群信息不合法")

        with RxTable(Group) as group_dao:
            ug = RxTable(UserGroup).where(user_id=by.id,
                                          group_id=group_id).first()
            if not ug:
                return Result(False, '群里没这个人')
            if ug.user_cls not in (Role.leader, Role.admin):
                return Result(False, '操作用户权限不足')

            group_dao.where(id=group_id).mutate(**checked.Object)

        return Result(group_dao.is_succeed, group_dao.msg)
Exemplo n.º 12
0
    def test1_where(self):
        from rx_sharh.rxdb import RxTable
        from rx_sharh.states.database import User
        from rx_sharh.components.date import SyncCurrent, timedelta

        with RxTable(User) as c:
            (c.where(id=lambda id: id > 100).where(
                User.birthday > SyncCurrent.get_date() -
                timedelta(minutes=100)).limit(10).foreach(print))
Exemplo n.º 13
0
    def search_by_class(cls,
                        visible_group_classes: List[GroupClass],
                        start_from: datetime = None) -> RxManyRef[Group]:
        current = SyncCurrent.get_date()
        if start_from is None:
            start_from = current - timedelta(days=30)

        return RxTable(Group).where(Group.cls.in_(visible_group_classes),
                                    Group.start > start_from)
Exemplo n.º 14
0
def login():
    # if g.user is not None and g.user.is_authenticated:
    #     return redirect(url_for('index'))

    if request.method == 'POST':
        form = request.form
        account: str = form['account']

        if len(account) < 9 and account.strip().isdigit():
            account = account[-5:]

        user: db.User = RxTable(db.User).where(account=account).first()

        if not user:
            flash("账号不存在", '错误')
            user = FakeUser
            return redirect_with_302(location='authentication.login')
        elif user.password != form['password']:
            flash("密码错误", '错误')
            return redirect_with_302(location='authentication.login')
        else:
            if "unionid" in session:
                user_dao = RxTable(db.User)
                with user_dao:
                    is_mutate = RxRecord(user).mutate(
                        openid=session["unionid"],
                        avatar=session["headimgurl"])
                if is_mutate:
                    flash("绑定成功,现在即可通过微信扫一扫参与签到")
                    login_user(user)
                    return redirect_with_302(location='index')
                else:
                    flash("绑定失败", '错误')
                    return redirect_with_302(location='authentication.login')
            else:
                flash('登录成功')

                login_user(user)

                next_page = request.args.get('next')

                return redirect_with_302(location=next_page or 'index')

    return render_template('authentication/login.html', title='登录')
Exemplo n.º 15
0
    def delete(cls, group_id: int, by: User) -> Result[bool]:
        with RxTable(UserGroup) as ug_dao:
            ug = ug_dao.where(group_id=group_id, user_id=by.id).first()

            if not ug:
                return Result(False, '当前组已不存在')

            if ug.user_cls != Role.leader:
                return Result(False, '请技术宅不要作弊,诅咒你补给全保底,副本零掉落:)')
            before_delete(group_id, trigger_user=by)
            db.delete_group(ug.group)
        return Result(ug_dao.is_succeed, ug_dao.msg)
Exemplo n.º 16
0
def resign(sign_name):
    """补签"""

    if request.method == 'POST':
        return render_template('attendance/resign.html',
                               title="补签",
                               sign_name=sign_name)

    sign_dao = RxTable(db.Sign)
    user_dao = RxTable(db.User)
    form = request.form

    sign = sign_dao.where(name=sign_name).first()

    user = user_dao.where(account=form['account'])

    if not sign:
        flash("实例不存在!")
        Config.app.logger.warning('{} {}'.format(sign_name, form))
        return redirect(url_for('attendance.center'))

    if not user:
        flash("用户不存在!")
        return render_template('attendance/resign.html', sign_name=sign_name, form=form)

    with user_dao:
        r = RxRecord(user).add_relation_between(sign)

    if not user_dao.is_succeed:
        flash("补签失败!")
        return redirect(url_for('attendance.resign', sign_name=sign_name))

    flash("补签成功!")
    return redirect(url_for('attendance.resign', sign_name=sign_name))
Exemplo n.º 17
0
    def change_role(cls, group_id: int, other_user_id: int, new_role: Role,
                    by: User) -> Result[bool]:
        """加减管理员"""
        with RxTable(UserGroup) as ug_dao:
            ug = ug_dao.where(group_id=group_id, user_id=by.id).first()
            if ug.user_cls != Role.leader:
                return Result(False, "操作用户权限不足")

            before_change_role(group_id, trigger_user=by)
            suc = ug_dao.where(group_id=group_id,
                               user_id=other_user_id).mutate(user_cls=new_role)

        return Result(ug_dao.is_succeed and suc, ug_dao.msg)
Exemplo n.º 18
0
    def leave_group(cls, group_id: int, target_id: int,
                    by: User) -> Result[bool]:
        """退群"""
        with RxTable(UserGroup) as ug_dao:
            ug = ug_dao.where(user_id=target_id, group_id=group_id).first()
            if not ug:
                return Result(False, f'{by.nickname}不在此群')
            if ug.user_cls == Role.leader:
                before_delete(group_id, trigger_user=by)
                db.delete_group(ug.group)
            RxRecord(ug).delete()

        return Result(ug_dao.is_succeed, ug_dao.msg)
Exemplo n.º 19
0
def validate(sign_name):
    """验证签到"""
    user = g.user
    form = request.form

    sign = RxTable(db.Sign).where(name=sign_name).first()

    if not sign:
        flash('实例不存在!')
        Config.app.logger.warning('{}: {}'.format(sign_name, repr(sign)))
        return redirect_with_302('attendance.center')

    if not sign.is_active:
        flash('签到已结束')

    elif form['sign_code'] == sign.sign_code:
        with RxTable(db.UserSign) as us_dao:

            us_dao.where(user_id=user.id, sign_id=sign.id).mutate(is_sign=1)
            flash('签到成功!')
    else:
        flash('签到码错误')

    return redirect_with_302('attendance.center')
Exemplo n.º 20
0
    def apply_for_join_in(cls, group_id: int, apply_info: str,
                          by: User) -> Result[bool]:
        """
        申请加群
        """
        with RxTable(UserGroup) as ug_dao:
            if ug_dao.where(user_id=by.id, group_id=group_id).first():
                return Result(False, '请勿重复加群')

        rx_msg.Group.push_msg_list(group_id,
                                   title=f'{by.nickname}的申请加群',
                                   content=apply_info,
                                   operating_user_id=by.id,
                                   operating_username=by.nickname,
                                   channel_branch=rx_msg.Group.Channel.ApplyIn)

        return Result(True, '加群成功')
Exemplo n.º 21
0
    def invite_member(cls, group_id: int, invited_user_id: int,
                      by: User) -> Result[bool]:
        """
        邀请用户加群
        """
        with RxTable(UserGroup) as ug_dao:
            if not ug_dao.where(UserGroup.user_cls.in_(
                [Role.leader, Role.admin]),
                                user_id=by.id,
                                group_id=group_id).first():
                return Result(False, '操作用户权限不足')

            if ug_dao.where(user_id=invited_user_id,
                            group_id=group_id).first():
                return Result(True, "已加群")

            ug_dao.add(group_id=group_id, user_id=invited_user_id)

        return Result(ug_dao.is_succeed, ug_dao.msg)
Exemplo n.º 22
0
def all_sign_stats(inst_id):
    user: db.User = g.user
    if user.nickname != '贪玩':
        Dangerous.add(100)
        return '您即将贪玩...'

    course = RxTable(db.Course).where(id=inst_id).first()
    if not course:
        return "贪玩不了"
    user_course = RxList(
        course.ref_users).where(user_cls=db.Role.leader).first()

    res = render_course_sign_stats(user_course)
    return inc.Html(
        inc.Head(
            inc.Tag("style", TableStyle),
            '<link rel="shortcut icon" href="/static/favicon.ico">',
        ),
        inc.Container(*res).append(
            inc.Align.center).set_indent(1)).__str__() if isinstance(
                res, tuple) else inc.Page(
                    inc.Container(res).set_indent(1)).__str__()
Exemplo n.º 23
0
def profile():
    """账号|昵称|性别|生日
       学号|姓名|学院|专业|班级 / 工号|姓名|隶属部门|直属部门
       介绍(可变大小)
    """
    user = g.user

    if request.method != 'POST':
        return render_template('profile/center.html',
                               user=g.user,
                               title="个人中心")

    form = request.form

    with RxTable(db.User) as user_dao:
        suc = user_dao.where(id=user.id).mutate(**form)

    if suc and user_dao.is_succeed:
        flash('修改成功')
    else:
        flash('修改失败')

    return redirect_with_302('profile.profile')
Exemplo n.º 24
0
def stop(sign_name, qrcode, status):
    """开始签到跳转, 停止签到"""

    sign = RxTable(db.Sign).where(name=sign_name).first()

    if not sign:
        flash("实例不存在!")
        Config.app.logger.warning('{}'.format(sign_name))
        return redirect(url_for('attendance.center'))

    if not status:
        need_sign_num, actual_sign_num, sign_users, not_sign_users = sign_helper.Controller.statistics(sign)
        # 将签到信息记录置于redis中缓存
        if sign.cls == db.SignClass.course:
            cls = 'c'

            @curry
            def make_student_info(user: db.User, is_sign: int):
                stu = user.ref_students.first().student
                return dict(name=stu.name,
                            number=stu.number,
                            is_sign=is_sign)

            inst_id = sign.inst_id

            cache_storage.set(
                name_pattern(cls, inst_id, None, "week"),
                SyncCurrent.to_week_index()
            )

            cache_storage.hset(
                name_pattern(cls, inst_id, None, "values"),
                SyncCurrent.to_week_index(),
                json.dumps(dict(
                    应到=need_sign_num,
                    实到=actual_sign_num,
                    人员=[*RxList(sign_users)
                        .map(make_student_info(is_sign=1)),
                        *RxList(not_sign_users)
                        .map(make_student_info(is_sign=0))]
                ))
            )

        return render_template('attendance/stop.html',
                               sign_name=sign_name,
                               sign_code=sign.sign_code,
                               status=status,
                               need_sign_num=need_sign_num,  # 应到人数, int
                               actual_sign_num=actual_sign_num,  # 实到人数,int
                               sign_users=map(get_name_id, sign_users),  # 签到的用户, List[User]
                               not_sign_users=map(get_name_id, not_sign_users))  # 未签到的用户, List[User]

    if qrcode:
        return render_template('attendance/qrcode.html',
                               title="签到管理",
                               sign_name=sign_name,
                               status=status)

    return render_template('attendance/stop.html',
                           title="签到管理",
                           sign_name=sign_name,
                           sign_code=sign.sign_code,
                           status=status)
Exemplo n.º 25
0
def render_course_sign_stats(
    user_course: db.UserCourse
) -> Union[Tuple[inc.Table, ...], inc.IconTextBlock]:
    course = user_course.course
    inst_id = course.id
    teacher = user_course.user.ref_teachers.first().teacher

    # 当前周数
    week_index = cache_storage.get(
        name_pattern('c', str(inst_id), None, "week"))

    if not week_index:
        return inc.IconTextBlock("blue", f"{course.name}", "暂无记录",
                                 inc.Icon("edit"))

    count = int(week_index)
    src_rows = defaultdict(dict)
    course = RxTable(db.Course).where(id=inst_id).first()

    上课周 = [
        i + 1
        for i, test in enumerate(map(lambda _: _ is '1', course.week[2:count]))
        if test
    ]

    total_count = len(course.week) - 2

    上课周 = tuple(map(lambda _: "-".join(map(str, _)), to_interval(上课周)))

    if not week_index:
        return inc.IconTextBlock("blue", f"{course.name}", "无签到记录",
                                 inc.Icon("edit"))

    上课时间 = f'第{",".join(上课周)}周'
    上课地点 = course.location
    学期 = course.term

    stats = []

    for week_index in range(1, count + 1):
        src = cache_storage.hget(
            name_pattern('c', str(inst_id), None, "values"), week_index)
        if src:
            src = json.loads(src)
            应到 = src['应到']
            实到 = src['实到']
            到勤率 = 实到 / 应到
            stats.append((应到, 实到, 到勤率))

            for each in src['人员']:
                src_rows[each['name'],
                         each['number']][week_index] = each['is_sign']

    上课周数 = len(stats)
    stats = tuple(zip(*stats))
    应到平均 = round(sum(stats[0]) / 上课周数, 2)
    实到平均 = round(sum(stats[1]) / 上课周数, 2)
    到勤率平均 = f"{round(100 * sum(stats[2]) / 上课周数, 2)}%"

    src_rows = dict(src_rows)

    签到总览 = [[
        姓名, 学号, *('+' if _2.get(i, 0) else '&nbsp;'
                  for i in range(1, total_count + 1)),
        f"{round(100 * sum(_2.values()) / 上课周数, 2)}%"
    ] for (姓名, 学号), _2 in sorted((_1 for _1 in src_rows.items()),
                                 key=lambda _: _[0][1])]

    table1 = inc.Table(
        data_source=[[
            course.name, teacher.name, 上课时间, 上课地点, 学期, 应到平均, 实到平均, 到勤率平均
        ]],
        columns=['课程名', '任课老师', "上课时间", "上课地点", "学期", "平均应到", "平均实到", "平均到勤率"])

    table2 = inc.Table(data_source=签到总览,
                       columns=['姓名', '学号', *range(1, total_count + 1), '平时分'])
    return table1 << inc.Attr("id", "stats"), table2 << inc.Attr(
        "id", "details")
Exemplo n.º 26
0
    def for_activity():
        nonlocal sign

        act_dao = RxTable(db.Activity)
        act: db.Activity = act_dao.where(id=instance_id).first()

        if not act:
            flash("实例不存在!")
            Config.app.logger.warning('{}: {}'.format(instance_id, repr(form)))
            return failed()

        group_id = act.ref_groups.first().group_id
        ug: db.UserGroup = RxList(user.ref_groups).where(group_id=group_id).first()
        if not ug or ug.user_cls == db.Role.normal:
            flash("权限不足")
            return failed()
        if not sign:

            # 建立签到
            with sign_dao:
                # 二维码
                if qrcode:
                    sign = sign_dao.add(inst_id=instance_id,
                                        name=make_sign_name(act),
                                        sign_code="with_qrcode",
                                        start=date.SyncCurrent.get_date(),
                                        cls=db.SignClass.course,
                                        is_active=1)
                # 非二维码
                else:
                    sign = sign_dao.add(inst_id=instance_id,
                                        name=make_sign_name(act),
                                        sign_code=form['sign_code'],
                                        start=date.SyncCurrent.get_date(),
                                        cls=db.SignClass.course,
                                        is_active=1)

            if not sign_dao.is_succeed:
                flash('新建失败!')
                Config.app.logger.warning(sign_dao.msg)
                return failed()

        else:
            # 修改
            with sign_dao:
                sign.is_active = 1
                with sign_dao:
                    if len(form) != 0:
                        sign.sign_code = form['sign_code']
                    else:
                        sign.sign_code = 'with_qrcode'

            if not sign_dao.is_succeed:
                flash('修改失败!')
                Config.app.logger.warning(sign_dao.msg)
                return failed()

            flash('修改成功!')

        # 更新群员的签到信息
        with sign_dao:
            for each in act.ref_groups.first().group.ref_users:
                if not RxTable(db.UserSign).where(user_id=each.user_id, sign_id=sign.id).first():
                    RxRecord(each.user).add_relation_between(sign, user_cls=each.user_cls)

        if qrcode:
            return succeed(1)

        flash('开始签到!')
        return succeed(0)
Exemplo n.º 27
0
def register(cls, instance_id, qrcode):
    """注册或修改签到"""

    succeed = lambda flag: redirect_with_302('attendance.stop',
                                             sign_name=sign.name,
                                             qrcode=flag,
                                             status=1) if not flag else redirect(url_for('attendance.stop',
                                                                                         sign_name=sign.name,
                                                                                         qrcode=flag,
                                                                                         status=1))

    failed = lambda: redirect_with_302('attendance.center')

    user: db.User = g.user
    if request.method == 'POST':
        form = request.form
        sign_dao = RxTable(db.Sign)
    else:
        form = {}
        sign_dao = RxTable(db.Sign)

    sign: db.Sign = sign_dao.where(inst_id=instance_id).first()

    def for_course():
        nonlocal sign
        course_dao = RxTable(db.Course)

        course: db.Course = course_dao.where(id=instance_id).first()
        if not course:
            flash("实例不存在!")
            Config.app.logger.warning('{}: {}'.format(instance_id, repr(form)))
            return failed()

        uc: db.UserCourse = RxList(user.ref_courses).where(course_id=instance_id).first()
        if not uc or uc.user_cls == db.Role.normal:
            flash("权限不足")
            return failed()

        if not sign:

            # 建立签到
            with sign_dao:
                # 二维码
                if qrcode:
                    sign = sign_dao.add(inst_id=instance_id,
                                        name=make_sign_name(course),
                                        sign_code="with_qrcode",
                                        start=date.SyncCurrent.get_date(),
                                        cls=db.SignClass.course,
                                        is_active=1)
                # 非二维码
                else:
                    sign = sign_dao.add(inst_id=instance_id,
                                        name=make_sign_name(course),
                                        sign_code=form['sign_code'],
                                        start=date.SyncCurrent.get_date(),
                                        cls=db.SignClass.course,
                                        is_active=1)

            if not sign_dao.is_succeed:
                flash('新建失败!')
                Config.app.logger.warning(sign_dao.msg)
                return failed()

        else:
            # 修改
            with sign_dao:
                sign.is_active = 1
                with sign_dao:
                    if len(form) != 0:
                        sign.sign_code = form['sign_code']
                    else:
                        sign.sign_code = 'with_qrcode'

            if not sign_dao.is_succeed:
                flash('修改失败!')
                Config.app.logger.warning(sign_dao.msg)
                return failed()

            flash('修改成功!')

        # 更新群员的签到信息
        with sign_dao:
            for each in course.ref_users:
                if not RxTable(db.UserSign).where(user_id=each.user_id, sign_id=sign.id).first():
                    RxRecord(each.user).add_relation_between(sign, user_cls=each.user_cls)

        if qrcode:
            return succeed(1)

        flash('开始签到!')
        return succeed(0)

        # 修改

    def for_activity():
        nonlocal sign

        act_dao = RxTable(db.Activity)
        act: db.Activity = act_dao.where(id=instance_id).first()

        if not act:
            flash("实例不存在!")
            Config.app.logger.warning('{}: {}'.format(instance_id, repr(form)))
            return failed()

        group_id = act.ref_groups.first().group_id
        ug: db.UserGroup = RxList(user.ref_groups).where(group_id=group_id).first()
        if not ug or ug.user_cls == db.Role.normal:
            flash("权限不足")
            return failed()
        if not sign:

            # 建立签到
            with sign_dao:
                # 二维码
                if qrcode:
                    sign = sign_dao.add(inst_id=instance_id,
                                        name=make_sign_name(act),
                                        sign_code="with_qrcode",
                                        start=date.SyncCurrent.get_date(),
                                        cls=db.SignClass.course,
                                        is_active=1)
                # 非二维码
                else:
                    sign = sign_dao.add(inst_id=instance_id,
                                        name=make_sign_name(act),
                                        sign_code=form['sign_code'],
                                        start=date.SyncCurrent.get_date(),
                                        cls=db.SignClass.course,
                                        is_active=1)

            if not sign_dao.is_succeed:
                flash('新建失败!')
                Config.app.logger.warning(sign_dao.msg)
                return failed()

        else:
            # 修改
            with sign_dao:
                sign.is_active = 1
                with sign_dao:
                    if len(form) != 0:
                        sign.sign_code = form['sign_code']
                    else:
                        sign.sign_code = 'with_qrcode'

            if not sign_dao.is_succeed:
                flash('修改失败!')
                Config.app.logger.warning(sign_dao.msg)
                return failed()

            flash('修改成功!')

        # 更新群员的签到信息
        with sign_dao:
            for each in act.ref_groups.first().group.ref_users:
                if not RxTable(db.UserSign).where(user_id=each.user_id, sign_id=sign.id).first():
                    RxRecord(each.user).add_relation_between(sign, user_cls=each.user_cls)

        if qrcode:
            return succeed(1)

        flash('开始签到!')
        return succeed(0)

    return {'a': for_activity,
            'c': for_course}[cls]()
Exemplo n.º 28
0
 def accurate_search_by_keywords(cls, **spec) -> RxManyRef[Group]:
     return RxTable(Group).where(**spec)
Exemplo n.º 29
0
            "8:50", "9:40", "10:25", "11:30", "12:15", "14:50", "15:35",
            "16:40", "17:30", "18:15", "19:50", "20:40", "21:25"
        ])))

if debug:
    conf_spec['debug'] = True
    conf_spec[
        'database_url'] = 'mysql+pymysql://root:12345@localhost/dev2?charset=utf8'
for k, v in conf_spec.items():
    setattr(Config, k, v)

from rx_sharh.states.database import init_db
init_db()
from rx_sharh.states.database import *

with open('../rx_sharh/states/database/spec.test_samples.py', 'r') as f:
    exec(f.read())

from rx_sharh.rxdb import RxTable

RxTable(User).add_many(UserList)
RxTable(Course).add_many(CourseList)
RxTable(Group).add_many(GroupList)
RxTable(Sign).add_many(SignList)
RxTable(StudentList).add_many(StudentList[:-10])
RxTable(TeacherList).add_many(TeacherList[-10:])
RxTable(Activity).add_many(ActivityList)

with RxTable(User):
    pass