def get_context(self): context = super().get_context() competitors = Competitor.objects.filter( competition_id=self.competition.id) results = app.models.Result.objects.filter( competition_id=self.competition.id) rounds = Round.objects.filter(competition_id=self.competition.id) for result in results: result.format_values = format_values(result) results = sorted(results, key=lambda x: x.rank) rounds = sorted(rounds, key=lambda x: x.type, reverse=True) competition_rounds = {} for round in rounds: if round.event_id in competition_rounds: competition_rounds[round.event_id].append( round.get_type_display()) else: competition_rounds[round.event_id] = [round.get_type_display()] events = list({ "event_id": k, "event_name": v } for k, v in Event.get_events(self.competition.event_ids).items()) competitor_names = {} for competitor in competitors: competitor_names[ competitor.person.id] = competitor.person.get_full_name() competitor_wca_names = {} for competitor in competitors: competitor_wca_names[ competitor.person.id] = competitor.person.wca_name competitor_prefectures = {} for competitor in competitors: competitor_prefectures[ competitor.person. id] = competitor.person.get_prefecture_id_display() context["competitor_names"] = competitor_names context["competitor_wca_names"] = competitor_wca_names context["competitor_prefectures"] = competitor_prefectures context["events"] = events context["rounds"] = competition_rounds context["results"] = results context["best_only_event_ids"] = Event.get_best_only_values() return context
def check_round(line, data, event_ids): errors = [] if int(data["event_id"]) != 0: if not Event.get_name(int(data["event_id"])): errors.append("event_idが規定外です。" + line + "行目 event_id: " + data["event_id"]) if not RoundType.get_name(int(data["type"])): errors.append("round_typeが規定外です。" + line + "行目 type: " + data["type"]) if not Format.get_name(int(data["format_id"])): errors.append("format_idが規定外です。" + line + "行目 format_id: " + data["format_id"]) if int(data["limit_type"]) != 0 and not RoundLimitType.get_name( int(data["limit_type"])): errors.append("limit_typeが規定外です。" + line + "行目 limit_type: " + data["limit_type"]) if not int(data["event_id"]) in event_ids: errors.append("event_idがcompetition.event_idsに含まれていません。" + line + "行目") if int(data["event_id"]) == 0 and ( int(data["attempt_count"]) != 0 or int(data["type"]) != 0 or int(data["format_id"]) != 0 or int(data["limit_type"]) != 0 or int(data["limit_time"]) != 0 or int(data["cutoff_attempt_count"]) != 0 or int(data["cutoff_time"]) != 0 or int(data["proceed_count"]) != 0): errors.append( "event_idが0のときはevent_name、room_name、begin_at, end_atが0でなければなりません。" + line + "行目") return errors
class Scramble(models.Model): competition_id = models.IntegerField("大会ID") event_id = models.SmallIntegerField("イベントID", choices=Event.choices()) round_id = models.IntegerField("ラウンドID") group_id = models.CharField("グループID", max_length=4) scramble = models.TextField("スクランブル")
class Result(models.Model): competition_id = models.IntegerField("大会ID") event_id = models.SmallIntegerField("イベントID", choices=Event.choices()) person_id = models.IntegerField("競技者ID") round = models.ForeignKey(Round, on_delete=models.CASCADE) rank = models.SmallIntegerField("順位") best = models.FloatField("Best") average = models.FloatField("Average") value1 = models.FloatField("値1") value2 = models.FloatField("値2") value3 = models.FloatField("値3") value4 = models.FloatField("値4") value5 = models.FloatField("値5") format_values = [] class Meta: indexes = [ models.Index(name="idx_competition_id", fields=["competition_id"]) ] def __str__(self): return (str(self.competition_id) + "_" + str(self.event_id) + "_" + str(self.round_id) + "_" + str(self.person_id))
class BestRank(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, default=None) event_id = models.SmallIntegerField("イベントID", choices=Event.choices()) competition_id = models.IntegerField("大会ID") competition_name_id = models.CharField("大会名ID", max_length=64, default="") competition_name = models.CharField("大会名", max_length=64, default="") year = models.SmallIntegerField("年", default=0) best = models.FloatField("ベスト") gender = models.SmallIntegerField("性別", default=0, choices=Gender.choices()) generation = models.SmallIntegerField("世代", default=0) prefecture_id = models.SmallIntegerField( "都道府県ID", default=0, choices=PrefectureAndOversea.choices()) rank = models.IntegerField("ランク", default=0) gender_rank = models.IntegerField("性別ランク", default=0) generation_rank = models.IntegerField("世代ランク", default=0) prefecture_rank = models.IntegerField("県ランク", default=0) class Meta: indexes = [models.Index(name="idx_person", fields=["person"])] def __str__(self): return str(self.person_id)
def check_feeperevent(line, data, event_ids): errors = [] if int(data["event_id"]) != 0 and not Event.get_name(int( data["event_id"])): errors.append("event_idが規定外です。" + line + "行目 event_id: " + data["event_id"]) return errors
def create_form(self): guests = [] for guest_count in range(self.competition.guest_limit + 1): guests.append((int(guest_count), str(guest_count) + "人")) self.form.fields["guest_count"].choices = guests events = [] for event_id in self.competition.event_ids: if event_id in dict(Event.choices()): events.append((str(event_id), Event.get_name(event_id))) self.form.fields["event_ids"].choices = events if self.competitor is not None: self.form.fields["event_ids"].initial = self.competitor.event_ids self.form.fields["guest_count"].initial = self.competitor.guest_count self.form.fields["comment"].initial = self.competitor.comment if self.competitor.status == CompetitorStatus.REGISTRATION.value: self.form.fields["event_ids"].widget.attrs["disabled"] = "disabled" self.form.fields["guest_count"].widget.attrs["disabled"] = "disabled" self.form.fields["comment"].widget.attrs["disabled"] = "disabled"
def check_competition(data, type): errors = [] if not data["name"]: errors.append("nemaは必須です。") if not data["name_id"]: errors.append("nema_idは必須です。") if not CompetitionType.has(int(data["type"])): errors.append("typeに規定外の値が設定されています。") if len(data["name"]) > 64: errors.append("nameが64文字を超えて設定されています。") if type == "create" and Competition.objects.filter( name=data["name"]).exists(): errors.append("nameがすでに存在しています。") if len(data["name_id"]) > 64: errors.append("name_idが64文字を超えて設定されています。") if (type == "create" and Competition.objects.filter(name_id=data["name_id"]).exists()): errors.append("name_idがすでに存在しています。") if not check_date(str(data["open_at"]), "%Y-%m-%d"): errors.append("open_atのformatが規定外です。YYYY-MM-DD で記述してください。") if not check_date(str(data["close_at"]), "%Y-%m-%d"): errors.append("close_atのformatが規定外です。YYYY-MM-DD で記述してください。") if not check_date(data["registration_open_at"], "%Y-%m-%dT%H:%M:%S"): errors.append( "registration_open_atのformatが規定外です。YYYY-MM-DD HH:MM:SS で記述してください。") if not check_date(data["registration_close_at"], "%Y-%m-%dT%H:%M:%S"): errors.append( "registration_close_atのformatが規定外です。YYYY-MM-DD HH:MM:SS で記述してください。" ) if (int(data["stripe_user_person_id"]) > 0 and not Person.objects.filter( id=data["stripe_user_person_id"]).exists()): errors.append("stripe_user_person_idが存在しないIDです。") event_ids = set(json.loads(data["event_ids"])) if not Event.has(event_ids): errors.append("event_idsに規定外の値が設定されています。") if not Prefecture.has(int(data["prefecture_id"])): errors.append("prefecutre_idに規定外の値が設定されています。") organizer_person_ids = set(json.loads(data["organizer_person_ids"])) if (len(organizer_person_ids) != Person.objects.filter(id__in=organizer_person_ids).count()): errors.append("organizer_person_idsに規定外の値が設定されています。") if not FeePayType.has(int(data["fee_pay_type"])): errors.append("fee_pay_typeに規定外の値が設定されています。") if not FeeCalcType.has(int(data["fee_calc_type"])): errors.append("fee_calc_typeに規定外の値が設定されています。") return errors
def get_context(self): is_prepaid = False if self.target_competitor: is_prepaid = StripeProgress.objects.filter( competitor_id=self.target_competitor.id ).exists() context = super().get_context() context["events"] = Event.get_events(self.competition.event_ids) context["competitor"] = self.target_competitor context["guest_counts"] = range(self.competition.guest_limit + 1) context["is_prepaid"] = is_prepaid context["admin_errors"] = self.admin_errors return context
class FeePerEvent(models.Model): competition_id = models.IntegerField("大会ID") event_id = models.SmallIntegerField("イベントID", choices=Event.choices()) price = models.IntegerField("料金") prepaid_price = models.IntegerField("事前決済料金", default=0) def delete(competition_id): FeePerEvent.objects.filter(competition_id=competition_id).delete() def create(self, feeperevent, competition_id): self.competition_id = competition_id self.event_id = feeperevent["event_id"] self.price = feeperevent["price"] self.prepaid_price = feeperevent["prepaid_price"] self.save()
def event_id_name(event_id): return Event.get_id_name(event_id)
def post(self, request, **kwargs): if "name_id" not in kwargs: return redirect("competition_index") name_id = kwargs.get("name_id") competition = Competition.objects.filter(name_id=name_id) if not competition.exists(): return redirect("competition_index") competition = competition.first() if competition.type != CompetitionType.WCA.value: return redirect("competition_index") if not competition.is_superuser(request.user): return redirect("competition_index") competitors = Competitor.objects.filter( competition_id=competition.id).order_by("created_at") now = datetime.datetime.now(tz=datetime.timezone.utc) now_str = localtime(now).strftime("%Y%m%d%H%M%S") response = HttpResponse(content_type="text/csv; charset=UTF-8") filename = urllib.parse.quote( (name_id + "_registration_" + now_str + ".csv").encode("utf8")) response[ "Content-Disposition"] = "attachment; filename*=UTF-8''{}".format( filename) writer = csv.writer(response) event_name_dict = {} event_id_names = Event.get_event_id_names() for event_id in competition.event_ids: event_name_dict[event_id] = event_id_names[event_id] country_names = dict(Country.choices()) gender = dict(GenderEn.choices()) event_name_id_list = [] for event_id, event_id_name in event_name_dict.items(): if event_id in competition.event_ids: event_name_id_list.append(event_id_name) columns = [ "Status", "Name", "Country", "WCA ID", "Birth Date", "Gender", "Email", ] columns.extend(list(event_name_dict.values())) writer.writerow(columns) for competitor in competitors: if request.POST.get("competitor_id_" + str(competitor.id)): status = "null" if competitor.status == CompetitorStatus.REGISTRATION.value: status = "a" elif competitor.status == CompetitorStatus.CANCEL.value: status = "d" event_join_list = [] for event_id in event_name_dict.keys(): if event_id in competitor.event_ids: event_join_list.append(1) else: event_join_list.append(0) row = [ status, competitor.person.wca_name, country_names[competitor.person.wca_country_iso2], competitor.person.wca_id, competitor.person.birth_at, gender[competitor.person.gender], competitor.person.wca_email, ] row.extend(event_join_list) writer.writerow(row) return response
def get_context(self): context = super().get_context() event_id = 0 if self.event_name != "list": event_id = Event.get_value(self.event_name) if event_id: competitors = app.models.Competitor.objects.filter( competition_id=self.competition.id, event_ids__contains=event_id) else: competitors = app.models.Competitor.objects.filter( competition_id=self.competition.id) if self.competition.is_display_pending_competitor: competitors = competitors.exclude( status=CompetitorStatus.CANCEL.value).order_by("created_at") else: competitors = competitors.filter( status=CompetitorStatus.REGISTRATION.value).order_by( "created_at") bests = {} averages = {} if event_id: if self.competition.type == CompetitionType.SCJ.value: person_ids = [] for competitor in competitors: person_ids.append(competitor.person.id) best_ranks = BestRank.objects.filter(event_id=event_id, person_id__in=person_ids) for best_rank in best_ranks: bests[best_rank.person.id] = best_rank.best average_ranks = AverageRank.objects.filter( event_id=event_id, person_id__in=person_ids) for average_rank in average_ranks: averages[average_rank.person.id] = average_rank.best elif self.competition.type == CompetitionType.WCA.value: wca_ids = [] for competitor in competitors: wca_ids.append(competitor.person.wca_id) competitor_list = [] name = "" country = "" prefecture = "" for competitor in competitors: if self.competition.type == CompetitionType.SCJ.value: name = competitor.person.get_full_name() prefecture = competitor.person.get_prefecture_id_display() best = (bests[competitor.person.id] if competitor.person.id in bests else OUTLIERS) average = (averages[competitor.person.id] if competitor.person.id in averages else OUTLIERS) elif self.competition.type == CompetitionType.WCA.value: name = competitor.person.wca_name country_names = dict(Country.choices()) country = country_names[competitor.person.wca_country_iso2] best = (bests[competitor.person.wca_id] if competitor.person.wca_id in bests else OUTLIERS) average = (averages[competitor.person.wca_id] if competitor.person.wca_id in averages else OUTLIERS) competitor_list.append({ "status": competitor.status, "name": name, "country": country, "prefecture": prefecture, "best": best, "average": average, "person": competitor.person, }) competitor_list = sorted(competitor_list, key=lambda x: x["average"]) event_names = Event.get_names(self.competition.event_ids) context["competitors"] = competitor_list context["event_id"] = event_id context["event_name"] = self.event_name context["event_names"] = event_names return context
def get(self, request): type = int(self.request.GET.get(key="type", default=0)) event_id = int(self.request.GET.get(key="event_id", default=0)) year = int(self.request.GET.get(key="year", default=0)) prefecture_id = int(self.request.GET.get(key="prefecture_id", default=0)) form = CompetitionForm( initial={ "type": type, "event_id": event_id, "year": year, "prefecture_id": prefecture_id, } ) competition_types = [(0, "全種別")] competition_types += list( map(lambda x: (x[0], str(x[1]) + "大会"), CompetitionType.choices()) ) form.fields["type"].choices = competition_types events = [(0, "全種目")] events += Event.choices() form.fields["event_id"].choices = tuple(events) years = [(0, "最新")] current_year = datetime.date.today().year years += list( map( lambda x: (x, str(x) + "年"), reversed(range(SCJ_COMPETITON_FIRST_YEAR, current_year + 1)), ) ) form.fields["year"].choices = tuple(years) prefectures = [(0, "全都道府県")] prefectures += list(map(lambda x: (x.value, x.name), Prefecture)) form.fields["prefecture_id"].choices = tuple(prefectures) competitions = ( Competition.objects.filter(is_display=True, is_private=False) .order_by("open_at") .reverse() ) if type != 0: competitions = competitions.filter(type=type) if event_id != 0: competitions = competitions.filter(event_ids__contains=[event_id]) if year != 0: competitions = competitions.filter(open_at__year=year) if prefecture_id != 0: competitions = competitions.filter(prefecture_id=prefecture_id) competition_list = [] finish_competition_list = [] for competition in competitions: if competition.is_open() or not competition.is_finish(): competition_list.append(competition) else: finish_competition_list.append(competition) context = { "form": form, "competitions": competition_list, "finish_competitions": finish_competition_list, } return render(request, "app/competition/index.html", context)
def post(self, request, **kwargs): if "name_id" not in kwargs: return redirect("competition_index") name_id = kwargs.get("name_id") competition = Competition.objects.filter(name_id=name_id) if not competition.exists(): return redirect("competition_index") competition = competition.first() if not competition.is_superuser(request.user): return redirect("competition_index") competitors = Competitor.objects.filter( competition_id=competition.id).order_by("created_at") stripe_progresses = StripeProgress.objects.filter( competition_id=competition.id, refund_price=0) for competitor in competitors: for stripe_progress in stripe_progresses: if competitor.id == stripe_progress.competitor_id: competitor.set_stripe_progress(stripe_progress) now = datetime.datetime.now(tz=datetime.timezone.utc) now_str = localtime(now).strftime("%Y%m%d%H%M%S") response = HttpResponse(content_type="text/csv; charset=UTF-8") filename = urllib.parse.quote( (name_id + "_competitor_" + now_str + ".csv").encode("utf8")) response[ "Content-Disposition"] = "attachment; filename*=UTF-8''{}".format( filename) writer = csv.writer(response) event_name_dict = {} event_id_names = Event.get_event_id_names() for event_id in competition.event_ids: event_name_dict[event_id] = event_id_names[event_id] if competition.type == CompetitionType.WCA.value: row = [ "id", "scj_id", "wca_id", "wca_user_id", "name", "full_name_kana", "email", "birth_at", ] elif competition.type == CompetitionType.SCJ.value: row = [ "id", "scj_id", "full_name", "full_name_kana", "full_name_rome", "email", "birth_at", ] row.extend(list(event_name_dict.values())) row.extend([ "guest_count", "pay_price", "stripe_charge_id", "comment", "pay_at", "created_at", ]) writer.writerow(row) for index, competitor in enumerate(competitors): if request.POST.get("competitor_id_" + str(competitor.id)): event_join_list = [] for event_id in event_name_dict.keys(): if event_id in competitor.event_ids: event_join_list.append(1) else: event_join_list.append(0) if competition.type == CompetitionType.WCA.value: row = [ index + 1, competitor.person.id, competitor.person.wca_id, competitor.person.wca_user_id, competitor.person.wca_name, competitor.person.get_full_name_kana(), competitor.person.wca_email, competitor.person.wca_birth_at, ] elif competition.type == CompetitionType.SCJ.value: row = [ index + 1, competitor.person.id, competitor.person.get_full_name(), competitor.person.get_full_name_kana(), competitor.person.get_full_name_roma(), competitor.person.user.email, competitor.person.birth_at, ] row.extend(event_join_list) row.extend([ competitor.guest_count, competitor.stripe_progress.pay_price if competitor.stripe_progress is not None else 0, competitor.stripe_progress.charge_id if competitor.stripe_progress is not None else "", competitor.comment.replace("\r\n", ""), localtime(competitor.stripe_progress.pay_at) if competitor.stripe_progress is not None else "", localtime(competitor.created_at), ]) writer.writerow(row) return response