Ejemplo n.º 1
0
    def patch(self, team_id, user_id):
        """修改会员信息, 如果有分组信息变化, 需要额外处理"""
        form = self.validated_arguments
        if not form:
            raise ApiException(400, "填写需要修改的属性和值")

        team = Team.get_or_404(id=team_id)
        member = TeamMember.get_or_404(user=user_id, team=team_id)

        self.has_update_permission(member)

        group = None
        group_id = form.pop("group_id", None)
        if group_id:
            group = self.validate_group_id(team, group_id)

        with self.db.transaction():

            # 如果有分组修改, 额外处理
            if group:
                TeamMemberGroupService.add_member(group, member)
                form["group_name"] = group.name

            logging.debug(form)
            TeamMember.update(**form)\
                .where(TeamMember.id == user_id, TeamMember.team == team_id)\
                .execute()

        self.set_status(204)
Ejemplo n.º 2
0
    def get(self, team_id):
        team = Team.get_or_404(id=team_id)
        if not team.is_member(user_id=self.current_user.id):
            raise ApiException(400, "未加入俱乐部")

        team.leave(self.current_user)

        self.set_status(204)
Ejemplo n.º 3
0
 def patch(self, team_id):
     """
     修改俱乐部信息;
     俱乐部徽标额外接口修改
     """
     team = Team.get_or_404(id=team_id)
     self.has_update_permission(team)
     form = self.validated_arguments
     Team.update(**form).where(Team.id == team.id).execute()
     self.set_status(204)
Ejemplo n.º 4
0
    def get(self, team_id, user_id):
        team = Team.get_or_404(id=team_id)
        member = TeamMember.get_or_404(user=user_id, team=team_id)

        if self.current_user == member.user or self.current_user == team.owner:
            serializer = InsecureMemberSerializer
        else:
            serializer = SimpleMemberSerializer

        self.write(serializer(instance=member).data)
Ejemplo n.º 5
0
 def post(self, team_id: int):
     """
     关注俱乐部
     :param team_id:
     :return:
     """
     team = Team.get_or_404(id=team_id)  # type: Team
     if team.get_follower(user_id=self.current_user.id):
         raise ApiException(422, "您已关注俱乐部, 无须重复关注")
     team.add_follower(user_id=self.current_user.id)
     self.set_status(204, "关注成功")
Ejemplo n.º 6
0
    def _approve(self, application_id):
        application = TeamCertifyApplication.get_or_404(id=application_id)
        team = Team.get_or_404(id=application.team_id)

        with(self.db.transaction()):
            application.set_approved()
            application.save()

            team.verified = True
            team.save()

        self.write_success()
Ejemplo n.º 7
0
    def _disapprove(self, application_id, reason=""):
        application = TeamCertifyApplication.get_or_404(id=application_id)
        team = Team.get_or_404(id=application.team_id)

        with(self.db.transaction()):
            application.set_disapproved()
            application.save()

            team.verified = False
            team.verified_reason = reason
            team.save()

        self.write_success()
Ejemplo n.º 8
0
    def delete(self, team_id: int):
        """
        取消关注
        :param team_id:
        :return:
        """
        # user_id = self.get_query_argument("user_id", None)
        user_id = self.current_user.id
        team = Team.get_or_404(id=team_id)  # type: Team
        if not team.get_follower(user_id=user_id):
            raise ApiException(422, "您未关注俱乐部")

        team.delete_follower(user_id=user_id)
        self.set_status(204, "取消关注成功")
Ejemplo n.º 9
0
    def get(self, team_id):
        """
        获取俱乐部分组
        Args:
            team_id: int

        """
        team = Team.get_or_404(id=team_id)
        self.has_read_permission(team)

        query = TeamMemberGroup.select().where(TeamMemberGroup.team == team)
        page = self.paginate_query(query)
        data = self.get_paginated_data(page=page, alias="groups")
        self.write(data)
Ejemplo n.º 10
0
    def delete(self, team_id, group_id):
        """
        删除分组
        Args:
            team_id:
            group_id:

        """
        team = Team.get_or_404(id=team_id)
        group = TeamMemberGroup.get_or_404(id=group_id, team=team)

        self.has_delete_permission(team)

        self.group_allow_delete(group)

        self.set_status(204)
Ejemplo n.º 11
0
    def get(self, team_id):
        """获取俱乐部详情"""

        obj = Team.get_or_404(id=team_id)
        info = TeamSerializer(instance=obj, request=self).data

        if self.current_user and \
                TeamFollower.select().where(
                    TeamFollower.user_id == self.current_user.id,
                    TeamFollower.team_id == obj.id
                ).exists():
            info['is_following'] = True

        else:
            info['is_following'] = False

        self.write(info)
Ejemplo n.º 12
0
    def post(self, team_id):
        """
        新建俱乐部分组
        Args:
            team_id:

        Returns:

        """
        team = Team.get_or_404(id=team_id)
        self.has_read_permission(team)
        form = self.validated_arguments

        group = TeamMemberGroup.create(team=team, **form)

        self.set_status(201)
        self.write(group.info)
Ejemplo n.º 13
0
    def get(self, match_id):
        """获取赛事信息

        :match_id: 赛事ID
        :returns: 赛事信息

        """

        preview = self.get_query_argument("preview", False)
        match = self.get_object(match_id, preview)
        match.team = Team.get_or_404(id=match.team_id)

        serializer = MatchSerializer(instance=match)

        info = serializer.data

        # 获取赛事分组信息
        query = MatchGroup.select().where(
            MatchGroup.match_id == match.id, ).order_by(
                MatchGroup.sort_num.desc())

        groups = []
        for group in query:
            groups.append(group.info)

        info['groups'] = groups

        # 获取赛事海报列表
        query = MatchCover.select().where(
            MatchCover.match_id == match.id).order_by(MatchCover.id.desc())

        covers = []
        for cover in query:
            covers.append(cover.info)

        info['covers'] = covers

        if self.current_user:
            member = MatchMember.get_or_none(match_id=match_id,
                                             user_id=self.current_user.id)

            if member:
                info['my_state'] = member.mini_info

        self.write(info)
Ejemplo n.º 14
0
    def patch(self, team_id, group_id):
        """
        修改分组
        Args:
            team_id:
            group_id:

        Returns:

        """
        team = Team.get_or_404(id=team_id)
        TeamMemberGroup.get_or_404(id=group_id, team=team)

        self.has_read_permission(team)

        TeamMemberGroup\
            .update(**self.validated_arguments)\
            .where(TeamMemberGroup.team == team, TeamMemberGroup.id == group_id)\
            .execute()

        self.set_status(204)
Ejemplo n.º 15
0
    def post(self, team_id):
        form = self.validated_arguments
        team = Team.get_or_404(id=team_id)

        if team.is_member(user_id=self.current_user.id):
            raise ApiException(422, "你已是俱乐部会员, 不用重复加入")

        if team.open_type == 0:
            state = TeamMember.TeamMemberState.normal.value
            msg = "正常"
        elif team.open_type == 1:
            state = TeamMember.TeamMemberState.pending.value
            msg = "待审核"
        else:
            raise ApiException(422, "俱乐部拒绝加入")

        team.add_member(user_id=self.current_user.id,
                        role=Team.TeamRole.member,
                        state=state,
                        **form)
        self.write_success(msg=msg)
Ejemplo n.º 16
0
    def put(self, team_id):
        team = Team.get_or_404(id=team_id)
        self.has_update_permission(team)

        if "icon" not in self.request.files:
            raise ApiException(400, "请选择文件")

        to_bucket = self.settings['qiniu_avatar_bucket']
        to_key = "team:%s%s" % (self.current_user.id, time.time())
        to_key = hashlib.md5(to_key.encode()).hexdigest()

        icon_key = self.upload_file(
            "icon",
            to_bucket=to_bucket,
            to_key=to_key,
        )
        team.icon_key = icon_key
        team.save()

        updated = Team.get(id=team.id)
        self.write(updated.icon)
Ejemplo n.º 17
0
    def get(self, match_id):

        match = Match.get_or_404(id=match_id)
        match.sport_id = Sport.get_or_none(id=match.sport_id)

        match.group_type = str(match.group_type)
        team = Team.get_or_404(id=match.team_id)
        form = EditMatchFrom(obj=match, team=team)

        # 获取赛事分组信息
        query = MatchGroup.select().where(
            MatchGroup.match_id == match.id).order_by(
                MatchGroup.sort_num.desc())

        groups = []
        for group in query:
            group = group.info
            group['max'] = group['max_members']
            groups.append(group)

        # 获取报名表自定义选项
        query = MatchOption.select().where(
            MatchOption.match_id == match.id).order_by(
                MatchOption.sort_num.desc())

        custom_options = []
        for option in query:
            option = option.info
            if 'choices' in option:
                option['choices'] = "|".join(option['choices'])
            custom_options.append(option)

        self.render("match/edit.html",
                    form=form,
                    match=match,
                    cities=ChinaCity.get_cities(),
                    group_type=match.group_type,
                    groups=groups,
                    custom_options=custom_options,
                    options=match.fields)
Ejemplo n.º 18
0
    def get(self, team_id: int):
        """俱乐部粉丝列表"""
        team = Team.get_or_404(id=team_id)
        query = TeamService.followers(team=team)
        page = self.paginate_query(query)

        data = self.render_page_info(page)
        data["followers"] = []
        uids = set()

        def merge_followers(ids, parteam_users):
            for uid in ids:
                user = parteam_users[uid]
                data.setdefault("followers", []).append(user.secure_info)

        for row in page:
            uids.add(row.user_id)
        if uids:
            pt = Parteam(self.settings["parteam_api_url"])
            pt_users = pt.parteam_user(list(uids))
            merge_followers(uids, pt_users)

        self.write(data)
Ejemplo n.º 19
0
    def post(self, match_id):
        """ 报名赛事

        :match_id: 赛事ID
        :returns:

        """

        match = Match.get_or_404(id=match_id)

        # 检查赛事是否可以报名
        result = match.can_join()
        self.has_joined(match, user_id=self.current_user.id)

        if not result['can']:
            raise ApiException(403,
                               result['reason'],
                               log_message="报名失败:{0}, {1}".format(
                                   match_id, result['reason']))

        team = Team.get_or_404(id=match.team_id)

        # 分组比赛模式
        group = None
        if match.group_type == 1:
            group_id = self.get_argument("group_id")
            group = MatchGroup.get_or_none(id=group_id, match_id=match_id)
            if group is None:
                raise ApiException(404, "赛事分组不存在")

            # 分组是否已报满
            if group.max_members <= group.members_count:
                raise ApiException(403, "赛事分组已报满")

            total_fee = group.price

        else:
            total_fee = match.price

        name = self.get_argument("name")
        mobile = self.get_argument("mobile")

        if not name:
            raise ApiException(400, "请填写名称")

        if not mobile:
            raise ApiException(400, "请填写手机号码")

        elif not is_mobile(mobile):
            raise ApiException(400, "手机号码格式有误")

        # TODO: 上线前移除
        # member = MatchMember.get_or_none(match_id=match.id,
        #                                  user_id=self.current_user.id)
        # if member is not None:
        #     raise ApiException(403, "你已报名此赛事,无需重复报名")

        extra_attrs = self.parse_options(match_id)

        with self.db.transaction() as txn:

            # 零元赛事无需支付不生成订单
            order = None
            if total_fee > 0:
                order = TeamOrder.create(
                    order_no=TeamOrder.get_new_order_no(),
                    team=team,
                    user=team.owner_id,
                    title=match.title,
                    order_type=TeamOrder.OrderType.MATCH,
                    payment_fee=total_fee,
                    total_fee=total_fee,
                    activity_id=match.id,
                    state=TeamOrder.OrderState.WAIT_BUYER_PAY)

            other_attrs = {}
            if "avatar" in match.fields:
                other_attrs['avatar_key'] = self.upload_photo("avatar", "头像")

            if "idcard_photo" in match.fields:
                other_attrs['idcard_front'] = self.upload_photo(
                    "idcard_front", "证件照片正面")
                other_attrs['idcard_back'] = self.upload_photo(
                    "idcard_back", "证件照片背面")

            gender = self.get_argument("gender", "")
            if gender in ("0", "1"):
                gender = ("f", "m")[int(gender)]
            else:
                gender = "n"

            if order and order.state == TeamOrder.OrderState.WAIT_BUYER_PAY:
                member_state = MatchMember.MatchMemberState.wait_pay
            else:
                member_state = MatchMember.MatchMemberState.normal

            team.add_member(self.current_user.id,
                            nick=name,
                            state=TeamMember.TeamMemberState.normal)
            member = MatchMember.create(
                match_id=match.id,
                group_id=group.id if group else 0,
                member_type=match.join_type,
                user_id=self.current_user.id,
                name=name,
                mobile=mobile,
                gender=gender,
                age=self.get_argument("age", "0"),
                is_leader=self.get_argument("is_leader", False),
                realname=self.get_argument("realname", ""),
                idcard_number=self.get_argument("idcard_number", ""),
                extra_attrs=extra_attrs,
                order_id=order.id if order else 0,
                total_fee=total_fee,
                state=member_state,
                **other_attrs)

            # 如果需要付费则生成支付订单
            if total_fee > 0:

                if match.refund_expire:
                    refund_expire = match.refund_expire.strftime(
                        "%Y%m%d%H%M%S")
                else:
                    refund_expire = datetime.now().strftime("%Y%m%d%H%M%S")

                resp = self.parteam_request(
                    "/match/openapi/createOrderInfo.do",
                    post_args={
                        "orderValue":
                        match.id,
                        "eachFee":
                        int(total_fee * 100),
                        "num":
                        1,
                        "totalFee":
                        int(total_fee * 100),
                        "subject":
                        match.title,
                        "userId":
                        self.current_user.id,
                        "notifyUrl":
                        urljoin(
                            self.request.full_url(),
                            self.reverse_url('rest_match_join_notify',
                                             match.id)),
                        "version":
                        1,
                        "expDatetime":
                        refund_expire,
                        "tradeType":
                        "APP" if self.device_type.lower() in ("ios", "android")
                        else "WEB",
                    })

                if "orderNo" not in resp:
                    txn.rollback()
                    raise ApiException(
                        400,
                        "创建订单失败",
                        log_message="match order fail:{0}".format(resp))

                MatchMember.update(pt_order_no=resp['orderNo']).where(
                    MatchMember.id == member.id).execute()

            # 统计赛事人数
            Match.update_members_count(match.id)
            if group:
                MatchGroup.update_members_count(group.id)

            member = MatchMember.get_or_404(id=member.id)

        member_info = member.info
        member_info['order'] = {
            "orderNo": member.pt_order_no,
            "orderValue": match.id,
            "eachFee": int(total_fee * 100),
            "num": 1,
            "totalFee": int(total_fee * 100),
            "subject": match.title,
            "userId": self.current_user.id,
        }

        self.write(member_info)
Ejemplo n.º 20
0
    def post(self, match_id):
        match = Match.get_or_404(id=match_id)
        team = Team.get_or_404(id=match.team_id)
        form = EditMatchFrom(self.arguments, team=team)

        groups = self.parse_groups()
        options = self.parse_options()
        custom_options = self.parse_custom_options()

        # 验证分组设置
        groups_validated = self.validate_groups(form, groups)

        if form.validate() and groups_validated:
            with (self.db.transaction()):
                form.populate_obj(match)

                # 计算赛事总人数限制
                if intval(match.group_type) == 1:
                    match.price = min(map(lambda x: float(x['price']),
                                          groups)) if groups else 0
                    match.max_members = reduce(lambda x, y: x + y,
                                               map(lambda x: x['max'],
                                                   groups)) if groups else 0

                if "coverfile" in self.request.files:
                    to_bucket = self.settings['qiniu_avatar_bucket']
                    to_key = "match:%s%s" % (self.current_user.id, time.time())
                    to_key = hashlib.md5(to_key.encode()).hexdigest()

                    cover_key = self.upload_file(
                        "coverfile",
                        to_bucket=to_bucket,
                        to_key=to_key,
                    )

                    match.cover_key = cover_key

                match.user_id = self.current_user.id
                match.fields = options

                if not match.join_end:
                    match.join_end = match.start_time

                match.save()

                if intval(match_id) > 0:
                    group_ids = [
                        group['id'] for group in groups if group['id'] > 0
                    ]

                    if len(group_ids) > 0:
                        MatchGroup.delete().where(
                            MatchGroup.match_id == intval(match_id),
                            MatchGroup.id.not_in(group_ids)).execute()

                    else:
                        MatchGroup.delete().where(
                            MatchGroup.match_id == intval(match_id)).execute()

                # 保存分组
                for group in groups:
                    if group['id'] > 0:
                        MatchGroup.update(
                            name=group['name'],
                            price=group['price'],
                            max_members=group['max']).where(
                                MatchGroup.id == group['id']).execute()

                    else:
                        MatchGroup.create(match_id=match.id,
                                          name=group['name'],
                                          price=group['price'],
                                          max_members=group['max'])

                if intval(match_id) > 0:
                    custom_option_ids = [
                        custom_option['id'] for custom_option in custom_options
                        if custom_option['id'] > 0
                    ]

                    if len(custom_option_ids) > 0:
                        MatchOption.delete().where(
                            MatchOption.match_id == intval(match_id),
                            MatchOption.id.not_in(
                                custom_option_ids)).execute()

                    else:
                        MatchOption.delete().where(MatchOption.match_id ==
                                                   intval(match_id)).execute()

                # 保存自定义选项
                for custom_option in custom_options:
                    if custom_option['id'] > 0:
                        MatchOption.update(
                            title=custom_option['title'],
                            field_type=custom_option['field_type'],
                            required=custom_option['required'],
                            choices=custom_option['choices'],
                        ).where(
                            MatchOption.id == custom_option['id']).execute()
                    else:
                        MatchOption.create(
                            match_id=match.id,
                            title=custom_option['title'],
                            field_type=custom_option['field_type'],
                            required=custom_option['required'],
                            choices=custom_option['choices'],
                        )

            # MatchService.add_match_start_notify(match)
            self.redirect(self.reverse_url("admin_match_detail", match.id))
            return

        province = self.get_argument("province", None)
        if province:
            form.city.choices = ChinaCity.get_cities(province)

        self.validate_groups(form, groups)

        self.render("match/edit.html",
                    form=form,
                    match=match,
                    cities=ChinaCity.get_cities(),
                    groups=groups,
                    group_type=self.get_argument("group_type", "0"),
                    options=options,
                    custom_options=custom_options)