def get(self): """获取俱乐部列表""" keyword = self.get_argument("kw", "") state = intval(self.get_argument("state", -1)) sort = intval(self.get_argument("sort", 0)) query = Team.select() # 这里限制的需要是 俱乐部创建者所在的位置进行过滤 而不是俱乐部本身的位置 is_restrict_by_areas = self.current_user.is_restrict_by_areas() if is_restrict_by_areas: query = query.join( User, on=(User.id == Team.owner_id) ).where( User.province << self.current_user.valid_manage_provinces ) if state in (0, 1): query = query.where(Team.state == state) if keyword: query = query.where(Team.name.contains(keyword)) query = query.order_by(Team.id.desc()) teams = self.paginate_query(query) self.render("team/list.html", teams=teams, )
def post(self): action = self.get_argument("action") if action == "delete_round": round_id = intval(self.get_argument("id", "")) self._delete_round(round_id) elif action == "settlement_application": match_id = intval(self.get_argument("id")) self._settlement_application(match_id) else: self.logger.error("用户在赛程详情页面尝试调用不存在的操作: %s" % action)
def post(self): username = self.validated_arguments['username'].lower() password = self.validated_arguments['password'] if len(username) == 0 or len(password) == 0: raise ApiException(400, "用户名和密码不能为空") fail_times_key = "yiyun:user:%s:login_fail_times" % username if intval(self.redis.get(fail_times_key)) >= 5: raise ApiException(403, "密码错误次数太多,请休息10分钟再试") if is_mobile(username): user = User.get_or_none(mobile=username) elif username.find('@') > 0: user = User.get_or_none(email=username) else: raise ApiException(400, "用户名格式不正确,请填写手机号或电子邮箱") if not password or not user \ or not User.check_password(user.password, password): fail_times = intval(self.redis.incr(fail_times_key)) if fail_times == 1: self.redis.expire(fail_times_key, 600) raise ApiException(403, "密码有误,如果没有设置密码请使用手机号找回密码") # 重试次数归零 self.redis.delete(fail_times_key) if not user.is_active(): raise ApiException(403, "你的账户不可用,无法登录") update = {"last_login": datetime.now()} if self.device_id > 0: update["last_device_id"] = self.device_id User.update(**update).where(User.id == user.id).execute() if user and self.device_id: Device.update(owner_id=user.id).where( Device.id == self.device_id).execute() self.write(self.create_session(user))
def get(self): state = intval(self.get_argument("state", 100)) start = self.get_argument("start", "") end = self.get_argument("end", "") query = TeamCashLog.select().where( TeamCashLog.team_id == self.current_team.id ).order_by( TeamCashLog.created.desc() ) if start: query = query.where(TeamCashLog.created >= start) if end: query = query.where(TeamCashLog.created <= end) if state != 100: query = query.where(TeamCashLog.state == TeamCashLog.TeamCashState(state)) cash_logs = self.paginate_query(query) self.render("orders/cash_logs.html", cash_logs=cash_logs, states=TeamCashLog.STATE_NAMES )
def parse_custom_options(self): """ 解析自定义选项 """ options = {} for key in self.request.arguments: if key.startswith("custom_option"): value = self.get_argument(key) parts = key.split("-") idx = int(parts[-1]) if idx not in options: options[idx] = { "id": 0, "title": "", "field_type": "text", "required": 0, "choices": "" } if parts[1] in ("required", "id"): value = intval(value) options[idx][parts[1]] = value options = [options[idx] for idx in options if options[idx]['title']] for idx in range(0, len(options)): option = options[idx] if option['field_type'] not in ("multichoice", "choice"): option['choices'] = "" options[idx] = option return options
def get(self): """ 获取用户列表 """ keyword = self.get_argument("kw", "") sort = intval(self.get_argument("sort", 0)) query = User.select() if keyword: query = query.where((User.name.contains(keyword)) | (User.mobile == keyword)) if sort == 2: query = query.order_by(User.name.desc()) else: query = query.order_by(User.id.desc()) users = self.paginate_query(query) self.render( "user/list.html", users=users, )
def _handler(self): action = self.get_argument("action", "") if action == "config": self.write(tornado.escape.json_encode(self._config)) elif action in ["uploadvideo", "uploadimage", "uploadfile"]: team_id = intval(self.get_argument("team_id", "")) upfile = self.request.files.get("upfile", []) if upfile: file_key = ArticleHelper.get_upload_file_key( self.current_user.id) file_bucket = self.settings["qiniu_attach_bucket"] qiniu_file_key = ArticleHelper.upload_image(image_file=upfile, image_name="文章封面", file_key=file_key, file_bucket=file_bucket) self.write({ "state": "SUCCESS", "url": Article.get_attach_urls(qiniu_file_key)["large"] }) elif action == "listimage": # TODO 列出已经上传的图片 pass elif action == "catchimage": source = self.arguments["source[]"] images = [] if len(source) > 0: file_bucket = self.settings["qiniu_attach_bucket"] for file_url in source: try: http_client = tornado.httpclient.HTTPClient() response = http_client.fetch( file_url, headers={"User-Agent": "Mozilla/5.0"}) # FIXME 文件类型转换 file_key = ArticleHelper.get_upload_file_key( self.current_user.id) qiniu_file_key = ArticleHelper.upload_to_qiniu(file_bucket=file_bucket, file_key=file_key, image_data=response.body, mime_type="image/jpeg") images.append({"url": Article.get_cover_urls(qiniu_file_key)["large"], "source": file_url, "state": "SUCCESS"}) except Exception as e: self.logger.error("抓取远程图片失败: %s" % e) images.append({"url": "", "source": file_url, "state": "FAIL"}) self.write({"state": "SUCCESS", "list": images})
def post(self): action = self.get_argument("action", "") application_id = intval(self.get_argument("id", "")) if action == "approve": self.approve(application_id) elif action == "disapprove": self.disapprove(application_id) else: self.logger.error("用户在结算申请列表尝试不存在的操作:%s" % action)
def post(self): action = self.get_argument("action", "") status_id = intval(self.get_argument("id", "")) if action == "delete": self._delete(status_id) else: self.logger.warning("用户在赛事动态列表中尝试调用不存在的操作: %s", action) self.write_success()
def get(self): """获取活动列表""" keyword = self.get_argument("kw", "") state = intval(self.get_argument("state", -1)) sort = intval(self.get_argument("sort", 0)) query = Activity.select( Activity, Team, ).join(Team, on=(Team.id == Activity.team).alias("team")) is_restrict_by_areas = self.current_user.is_restrict_by_areas() if is_restrict_by_areas: query = query.join(User, on=(User.id == Team.owner_id)).where( User.province << self.current_user.valid_manage_provinces) if state == 0: query = query.where( Activity.state == Activity.ActivityState.cancelled) elif state == 1: query = query.where( Activity.state == Activity.ActivityState.opening) elif state == 2: query = query.where( Activity.state == Activity.ActivityState.finished) if keyword: query = query.where(Activity.title.contains(keyword)) if sort == 2: query = query.order_by(Activity.start_time.desc()) else: query = query.order_by(Activity.id.desc()) activities = self.paginate_query(query) self.render( "activity/list.html", activities=activities, )
def post(self, service): access_token = self.validated_arguments['access_token'] expires_in = self.validated_arguments['expires_in'] openid = self.validated_arguments['openid'] platform = self.validated_arguments['platform'] if platform == "web": client_id = self.settings.get("qq_web_apiid") elif platform == "android": client_id = self.settings.get("qq_android_apiid") else: client_id = self.settings['qq_apiid'] response = yield self.qq_request("/user/get_user_info", access_token=access_token, openid=openid, client_id=client_id, format='json') if not response or intval(response.get('ret', 0)) != 0: raise ApiException(403, "QQ绑定失败,请重试") if response.get("figureurl_qq_2", None) \ and response.get("figureurl_qq_2", "").find("942FEA70050EEAFBD4DCE2C1FC775E56") == -1: head_url = response.get("figureurl_qq_2", None) elif response.get("figureurl_qq_1", None) \ and response.get("figureurl_qq_1", "").find("942FEA70050EEAFBD4DCE2C1FC775E56") == -1: head_url = response.get("figureurl_qq_1", None) else: head_url = None gender = 'n' if response.get("gender", False) == '男': gender = 'm' elif response.get("gender", False) == '女': gender = 'f' auth_data = { "openid": openid, "nickname": response.get("nickname", ""), "access_token": access_token, "session_expires": expires_in } self.register_or_login("qq", openid=openid, access_token=access_token, expires_in=expires_in, nickname=response.get("nickname", ""), gender=gender, head_url=head_url, auth_data=auth_data)
def get(self): keyword = self.get_argument("kw", "") filter_state = intval(self.get_argument("state", -1)) sort = intval(self.get_argument("sort", 0)) query = Match.select() # 这里是根据 match.user_id 指向用户的区域进行的过滤 is_restrict_by_areas = self.current_user.is_restrict_by_areas() if is_restrict_by_areas: query = query.join(User, on=(User.id == Match.user_id)).where( User.province << self.current_user.valid_manage_provinces) # 已取消 if filter_state == 0: query = query.where(Match.state == Match.MatchState.cancelled) # 等待审核 elif filter_state == 1: query = query.where(Match.state == Match.MatchState.wait_review) # 进行中 elif filter_state == 2: query = query.where(Match.state == Match.MatchState.opening) # 已结束 elif filter_state == 3: query = query.where(Match.state == Match.MatchState.finished) if keyword: query = query.where(Match.title.contains(keyword)) if sort == 2: query = query.order_by(Match.start_time.desc()) else: query = query.order_by(Match.id.desc()) matches = self.paginate_query(query) self.render( "match/list.html", matches=matches, )
def validate_groups(self, form, groups): group_type = intval(self.get_argument("group_type")) if group_type == 1: if len(groups) == 0: form.groups.errors = [ValidationError("至少需要添加一个分组")] return False else: for group in groups: if intval(group['max']) <= 0: form.groups.errors = [ValidationError("人数限制不能为零")] return False else: max_members = intval(self.get_argument("max_members")) if max_members <= 0: form.max_members.errors = [ValidationError("不能为零")] return False return True
def get(self): parteam = Parteam(self.settings["parteam_api_url"]) state = intval(self.get_argument("state", 100)) start = self.get_argument("start", "") end = self.get_argument("end", "") orders = TeamOrder.select( TeamOrder, MatchMember ).join( MatchMember, on=(TeamOrder.id == MatchMember.order_id).alias("match_member") ).where( TeamOrder.team == self.current_team ).order_by( TeamOrder.id.desc() ) if start: start = "%s 00:00:00" % start orders = orders.where(TeamOrder.created >= start) if end: end = "%s 23:59:59" % end orders = orders.where(TeamOrder.created <= end) if state != 100: orders = orders.where(TeamOrder.state == TeamOrder.OrderState(state)) query = self.paginate_query(orders) orders = [] for item in query: orders.append(dict(item.info, order_type_name=item.order_type_name, state_name=item.state_name, payment_method_name=item.payment_method_name, match_member=item.match_member.info)) user_ids = [order["match_member"]["user_id"] for order in orders if order["match_member"]["user_id"]] if user_ids: user_infos = parteam.parteam_user(user_ids) for order in orders: order["user_info"] =\ user_infos.get(order["match_member"]["user_id"]) self.render("orders/orders.html", states=TeamOrder.ORDER_STATES, orders=orders, pagination=query.pagination )
def validate_is_super(self, form, action, admin): if action == "add": return True if admin.id == self.current_user.id \ and intval(self.get_argument("state", 0)) != 1: form.state.errors = [ValidationError("不能禁用自己"), ] return False return True
def get(self): """订单列表""" state = intval(self.get_argument("state", 100)) start = self.get_argument("start", "") end = self.get_argument("end", "") query = TeamOrder.select( TeamOrder, Team, Activity, ).join( Team, on=(Team.id == TeamOrder.team).alias("team") ).switch( TeamOrder ).join( Activity, join_type=JOIN.LEFT_OUTER, on=(Activity.id == TeamOrder.activity_id).alias("activity") ) is_restrict_by_areas = self.current_user.is_restrict_by_areas() if is_restrict_by_areas: query = query.join( User, on=(User.id == Team.owner_id) ).where( User.province << self.current_user.valid_manage_provinces ) kw = self.get_argument("kw", "") if kw: query = query.where(TeamOrder.title ** ("%%%s%%" % kw)) if start: start = "%s 00:00:00" % start query = query.where(TeamOrder.created >= start) if end: end = "%s 23:59:59" % end query = query.where(TeamOrder.created <= end) if state != 100: query = query.where(TeamOrder.state == TeamOrder.OrderState(state)) query = query.order_by(TeamOrder.id.desc()) orders = self.paginate_query(query) self.render("order/orders.html", states=TeamOrder.ORDER_STATES, orders=orders, )
def get(self): """提现申请""" team_id = intval(self.get_argument("team_id", 0)) keyword = self.get_argument("kw", "") state = intval(self.get_argument("state", 0)) sort = intval(self.get_argument("sort", 0)) query = TeamCashLog.select( TeamCashLog, Team ).join( Team, on=(Team.id == TeamCashLog.team_id).alias("team") ) is_restrict_by_areas = self.current_user.is_restrict_by_areas() if is_restrict_by_areas: query = query.where(Team.province << self.current_user.valid_manage_provinces) if state >= 0: query = query.where(TeamCashLog.state == state) if keyword: query = query.where(Team.name.contains(keyword)) if team_id > 0: query = query.where(Team.team_id == team_id) if state == 0: query = query.order_by(TeamCashLog.id.asc()) else: query = query.order_by(TeamCashLog.id.desc()) cash_logs = self.paginate_query(query) self.render("order/cash_logs.html", cash_logs=cash_logs, )
def get(self): keyword = self.get_argument("kw", "") filter_state = intval(self.get_argument("state", -1)) sort = intval(self.get_argument("sort", 0)) query = Activity.select( Activity, User ).join( User, on=(Activity.leader == User.id).alias("leader") ).where( Activity.team == self.current_team ) if filter_state == 0: query = query.where(Activity.state == Activity.ActivityState.cancelled) elif filter_state == 1: query = query.where(Activity.state == Activity.ActivityState.opening) elif filter_state == 2: query = query.where(Activity.state == Activity.ActivityState.finished) if keyword: query = query.where(Activity.title.contains(keyword)) if sort == 2: query = query.order_by(Activity.start_time.desc()) else: query = query.order_by(Activity.id.desc()) activities = self.paginate_query(query) self.render("activity/list.html", activities=activities, )
def get(self): keyword = self.get_argument("kw", "") filter_state = intval(self.get_argument("state", -1)) sort = intval(self.get_argument("sort", 0)) query = Match.select( Match, ).where(Match.team_id == self.current_team.id) # 已取消 if filter_state == 0: query = query.where(Match.state == Match.MatchState.cancelled) # 等待审核 elif filter_state == 1: query = query.where(Match.state == Match.MatchState.wait_review) # 进行中 elif filter_state == 2: query = query.where(Match.state == Match.MatchState.opening) # 已结束 elif filter_state == 3: query = query.where(Match.state == Match.MatchState.finished) if keyword: query = query.where(Match.title.contains(keyword)) if sort == 2: query = query.order_by(Match.start_time.desc()) else: query = query.order_by(Match.id.desc()) matches = self.paginate_query(query) self.render( "match/list.html", matches=matches, )
def post(self): member_id = intval(self.get_argument("id", "")) action = self.get_argument("action", "") if action == "ban": self._ban(member_id) elif action == "unban": self._unban(member_id) elif action == "approve": self._approve(member_id) elif action == "reject": self._reject(member_id) elif action == "request_for_improved": self._request_for_improved(member_id) else: self.logger.debug("用户在赛事成员列表尝试进行不存在的操作: %s" % action)
def post(self, service): access_token = self.validated_arguments['access_token'] expires_in = self.validated_arguments['expires_in'] uid = self.validated_arguments['uid'] response = yield self.weibo_request("/users/show.json", access_token=access_token, uid=uid) if not response or response.get("id", None) != intval(uid): raise ApiException(403, "新浪微博认证失败,请重试") # 头像 if response.get("avatar_hd", None): head_url = response['avatar_hd'] elif response.get("avatar_large", None): head_url = response['avatar_large'] else: head_url = response.get("profile_image_url", None) gender = 'n' if response.get("gender", None) in ( 'm', 'f', ): gender = response['gender'] auth_data = { "uid": uid, "domain": response.get("domain", ""), "screen_name": response.get("screen_name", ""), "access_token": access_token, "session_expires": expires_in } self.register_or_login("weibo", openid=uid, access_token=access_token, expires_in=expires_in, nickname=response.get("screen_name", ""), gender=gender, head_url=head_url, auth_data=auth_data)
def paginate_query(self, query, gen_pagination=True, per_page=20): """ 对 Query 进行分页处理 """ page = max(1, intval(self.get_argument('page', 1))) total_count = query.count() pages_count = int(math.ceil(total_count / per_page)) # page = min(pages_count, page) query = query.paginate(page, per_page) if gen_pagination: query.pagination = Pagination(page, per_page, total_count) return query
def get(self, key): content = urlsafe_b64decode(key) attname = self.get_argument("attname", "") size = intval(self.get_argument("size", 512)) qr = qrcode.QRCode( version=2, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=30, border=1, ) qr.add_data(content) img = qr.make_image() if size > 1280: size = 1280 elif size < 16: size = 16 img.thumbnail((size, size)) fp = BytesIO() img.save(fp) fp.seek(0, os.SEEK_END) if attname: self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Disposition', 'attachment; filename=%s' % attname) self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Pragma', 'public') self.set_header('Content-Length', fp.tell()) self.set_header('Expires', '0') self.set_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') self.set_header('Content-Type', 'image/png') self.write(fp.getvalue())
def parse_groups(self): groups = {} for key in self.request.arguments: if key.startswith("group") and key not in ("group_type", ): value = self.get_argument(key) parts = key.split("_", 3) idx = int(parts[2]) if idx not in groups: groups[idx] = {"id": 0, "name": "", "price": 0, "max": 0} if parts[1] in ("max", "id"): value = intval(value) elif parts[1] in ('price', ): value = decimalval(value) groups[idx][parts[1]] = value return [groups[idx] for idx in groups if groups[idx]['name']]
def get(self): """ 获取赛事列表 """ team_id = self.get_argument("team_id", None) keyword = self.get_argument("keyword", None) sport = self.get_argument("sport", None) province = self.get_argument("province", None) city = self.get_argument("city", None) sort = self.get_argument("sort", 'newest') query = Match.select( Match, Team, ).join( Team, on=(Team.id == Match.team_id).alias("team")).where(Match.state << ( Match.MatchState.opening, Match.MatchState.finished)) if team_id: query = query.where(Match.team_id == team_id) if keyword: query = query.where(Match.title.contains(keyword)) if sport: sport = sport.split(",") query = query.where(Match.sport_id << sport) if province: province = province.split(",") query = query.where(Match.province << province) if city: city = city.split(",") query = query.where(Match.city << city) if sort == 'newest': # 未结束的 query = query.where(Match.end_time >= datetime.now()) # 按开始时间排序 query = query.order_by("start_time") elif sort == 'hottest': # 未结束的 query = query.where(Match.end_time >= datetime.now()) # 按报名要数排序 query = query.order_by("-members_count") elif sort == 'colsest': # 已结束的 query = query.where(Match.end_time <= datetime.now()) # 按结束时间倒序 query = query.order_by("-end_time") if sort == "distance": lat = self.get_query_argument("lat", None) lon = self.get_query_argument("lng", None) distance = intval(self.get_query_argument("distance", 10)) if distance > 100: distance = 100 if distance < 1: distance = 1 if not (lat and lon): raise ApiException(400, "按距离排序需要提供经纬值") lat, lon = float(lat), float(lon) min_lat, min_lon, max_lat, max_lon = \ self.calculate_range(distance, lat, lon) tmp_query = query.where(Match.lat.between(min_lat, max_lat), Match.lng.between(min_lon, max_lon)) sorted_matches = self.sorting_by_distance(tmp_query, lat, lon) data = self.render_page_info(self.paginate_query(tmp_query)) paged = self.paged_data(sorted_matches) data["matches"] = [ SimpleMatchSerializer(row).data for row in paged ] else: page = self.paginate_query(query) data = self.get_paginated_data(page=page, alias='matches', serializer=SimpleMatchSerializer) self.write(data)
def post(self): mobile = self.validated_arguments['mobile'] action = self.validated_arguments['action'] sent_times_key = "yiyun:mobile:%s:code_sent_times" % mobile if intval(self.redis.get(sent_times_key)) >= 5: raise ApiException(400, "你已重发5次,请稍后再试") # 有效期内发送相同的验证码 verify_code = random.randint(1000, 9999) logging.debug('verify code for mobile[{0}]: {1}'.format( mobile, verify_code)) is_registered = User.select().where(User.mobile == mobile).exists() if action == "register" and is_registered: raise ApiException(1020, "手机号码已注册", status_code=400) if action in ('register_or_login', 'register', 'login'): # 保存验证码 self.save_verify_code(mobile, verify_code) # 发短信 if not self.settings["debug"]: tasks.message.send_sms_verifycode(mobile, verify_code) self.write_success(is_registered=is_registered) elif action == "forgot": if not is_registered: raise ApiException(400, "手机号码没有注册") # 保存验证码 self.save_verify_code(mobile, verify_code) # 发短信 tasks.message.send_sms_verifycode(mobile, verify_code) self.write_success() elif action == "update_mobile": if not self.current_user: raise ApiException(403, "登录后才能修改手机号") if is_registered: raise ApiException(403, "该号码已经使用,请更换") if self.current_user.password and \ not User.check_password(self.current_user.password, self.validated_arguments["password"]): raise ApiException(403, "密码不正确,不能修改手机号") # 保存验证码 self.save_verify_code(mobile, verify_code) # 发短信 tasks.message.send_sms_verifycode(mobile, verify_code) # 关联验证码与当前用户 self.redis.set( "yiyun:update_mobile:%s:verify_code:%s" % (mobile, verify_code), self.current_user.id) # 30分钟内有效 self.redis.expire( "yiyun:update_mobile:%s:verify_code:%s" % (mobile, verify_code), 1800) self.write_success() # 30分钟内最多发送5次验证码 sent_times = intval(self.redis.incr(sent_times_key)) if sent_times == 1: self.redis.expire(sent_times_key, 1800)
def post(self): mobile = self.get_argument("mobile") action = self.get_argument("action") if not is_mobile(mobile): raise ArgumentError(400, "手机号码格式不正确") sent_times_key = "yiyun:mobile:%s:code_sent_times" % mobile if intval(self.redis.get(sent_times_key)) >= 5: raise ArgumentError(400, "你已重发5次,请稍后再试") # 有效期内发送相同的验证码 verify_code = random.randint(1000, 9999) is_registered = User.select().where(User.mobile == mobile).exists() self.logger.debug("send: %s to %s" % (verify_code, mobile)) if action == "register" and is_registered: raise ArgumentError(1020, "手机号码已注册", status_code=400) if action in ('register_or_login', 'register', 'login'): # 保存验证码 self.save_verify_code(mobile, verify_code) # 发短信 tasks.message.send_sms_verifycode(mobile, verify_code) self.write_success(is_registered=is_registered) elif action == "forgot": if not is_registered: raise ArgumentError(400, "手机号码没有注册") # 保存验证码 self.save_verify_code(mobile, verify_code) # 发短信 tasks.message.send_sms_verifycode(mobile, verify_code) self.write_success() elif action == "update_mobile": if not self.current_user: raise ArgumentError(403, "登录后才能修改手机号") if is_registered: raise ArgumentError(403, "该号码已经使用,请更换") # 保存验证码 self.save_verify_code(mobile, verify_code) # 发短信 tasks.message.send_sms_verifycode(mobile, verify_code) # 关联验证码与当前用户 self.redis.set( "ihealth:update_mobile:%s:verify_code:%s" % (mobile, verify_code), self.current_user.id) # 30分钟内有效 self.redis.expire( "ihealth:update_mobile:%s:verify_code:%s" % (mobile, verify_code), 1800) self.write_success() # 30分钟内最多发送5次验证码 sent_times = int(self.redis.incr(sent_times_key)) if sent_times == 1: self.redis.expire(sent_times_key, 1800)
def post(self): action = self.get_argument("action") user_id = self.get_argument("user_id") if action == "change_group": group_name = self.get_argument("group_name") member = Team.get_member(self.current_team.id, user_id) TeamMember.update(group_name=group_name).where( TeamMember.team == self.current_team, TeamMember.user == user_id).execute() # 计算新分组成员数量 TeamMemberGroup.update_members_count(self.current_team.id, group_name) # 计算旧分组成员数量 TeamMemberGroup.update_members_count(self.current_team.id, member.group_name) elif action == "apply": user = User.get_or_404(id=user_id) self.current_team.apply(user) elif action == "remove_member": member = Team.get_member(self.current_team.id, user_id) if member: if not member.can_leave(): raise HttpForbiddenError("该会员有财务没有结清,不能踢出") user = User.get_or_404(id=user_id) self.current_team.leave(user) TeamMemberGroup.update_members_count(self.current_team.id, member.group_name) elif action == "recharge": amount = intval(self.get_argument("amount")) freetimes = intval(self.get_argument("freetimes")) remark = self.get_argument("remark") member = Team.get_member(self.current_team.id, user_id) if member: TeamMember.change_credit( self.current_team.id, user_id=user_id, change_type=1, # 充值类型为后台操作 change_amount=amount, free_times=freetimes, operator_id=self.current_user.id, note=remark) elif action == "deduction": amount = intval(self.get_argument("amount")) freetimes = intval(self.get_argument("freetimes")) remark = self.get_argument("remark") member = Team.get_member(self.current_team.id, user_id) if member: TeamMember.change_credit( self.current_team.id, user_id=user_id, change_type=1, # 充值类型为后台操作 change_amount=0 - amount, free_times=0 - freetimes, operator_id=self.current_user.id, note=remark) self.write_success()
def post(self, round_id): match_round = MatchRound.get_or_404(id=round_id) match = Match.get_or_404(id=match_round.match_id) againsts = {} for key in self.request.arguments: if key.startswith("ag-"): value = self.get_argument(key) parts = key.split("-") idx = int(parts[-1]) if idx not in againsts: againsts[idx] = { "left": 0, "right": 0, "address": "", "start_time": "", "left_score": 0, "right_score": 0 } if parts[1] in ("left", "right", "left_score", "right_score"): value = intval(value) elif parts[1] in ("start_time", ) and value == "": raise ArgumentError(400, "请填写对战时间") elif parts[1] in ("address", ) and value == "": raise ArgumentError(400, "请填写对战地址") againsts[idx][parts[1]] = value # 清除旧的 MatchAgainst.delete().where( MatchAgainst.round_id == match_round.id).execute() againsts = [againsts[idx] for idx in againsts if againsts[idx]['left']] start_time = None end_time = None for against in againsts: if against['left_score'] > against['left_score']: win_member_id = against['left'] elif against['left_score'] < against['left_score']: win_member_id = against['right'] elif against['left_score'] == against['left_score']: win_member_id = 0 MatchAgainst.create(match_id=match.id, round_id=match_round.id, left_member_id=intval(against['left']), right_member_id=intval(against['right']), address=against['address'], left_score=intval(against['left_score']) or "0", right_score=intval(against['right_score']) or "0", win_member_id=win_member_id, start_time=against['start_time'] if against['start_time'] else None) if not start_time or against['start_time'] < start_time: start_time = against['start_time'] if not end_time or against['start_time'] > end_time: end_time = against['start_time'] if match.type == 0: MatchRound.update(start_time=start_time, end_time=end_time).where( MatchRound.id == match_round.id).execute() self.write_success()
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)