Beispiel #1
0
def booking_view(request, date=None):
    if date is None:
        date = datetime.date.today()
    else:
        date = timezones.parse_iso_date_to_naive(date)
    def get_bookings(date):
      today_str    = timezones.as_iso_date(date)
      tomorrow_str = timezones.as_iso_date(date + datetime.timedelta(days=1))
      url = settings.BOOKING_SYSTEM_URL + "/api/entries.php?start_date={today_str}&end_date={tomorrow_str}&with_tokens=1".format(**locals())
      h = httplib2.Http()
      (resp_headers, content) = h.request(url, "GET")
      if resp_headers.status != httplib.OK:
          raise Exception("unable to fetch bookings data, status = " + str(resp_headers.status) + ", response: " +  content)
      return content
    bookings = get_bookings(date)
    context = {
        "date": date,
        "bookings": bookings,
        "booking_system_url": settings.BOOKING_SYSTEM_URL,
        "starts": range(420, 1380, 15),
        "durations": [30, 45, 60, 75, 90, 120, 180, 240]
    }
    if request.user.is_authenticated():
      player = Player.get_player_for_user(request.user)
      if player is not None:
          booking_user_id = player.booking_system_id
          context["booking_user_id"] = booking_user_id
          context["booking_user_auth_token"] = BookingSystemEvent.generate_hmac_token_raw("id:{booking_user_id}".format(**locals()))
          context["booking_user_name"] = player.user.get_full_name()

    return render(request, 'court_booking.html', context)
Beispiel #2
0
def cmdline_add_old_league(args):
  if len(args) != 2:
    sys.stderr.write("USAGE: {0} {1} <yyyy-mm-dd> <file.csv>\n".format(*sys.argv))
    sys.exit(1)
  end_date = timezones.parse_iso_date_to_naive(args[0])

  from wsrc.site.competitions.models import CompetitionGroup
  from wsrc.site.usermodel.models import Player

  def convert(s): 
    result = ''
    for c in s:
      if ord(c) < 127:
        result += chr(ord(c))
    return result.lower()

  players = Player.objects.all()
  players = dict([(convert(p.user.get_full_name()), p) for p in players])

  existing = CompetitionGroup.objects.filter(comp_type="wsrc_boxes", end_date=end_date)
  if len(existing) > 0:
    raise Exception("ERROR - league ending " + end_date.isoformat() + " already exists, delete it first!")

  fh = open(os.path.expanduser(args[1]), "r")
  reader = csv.reader(fh)

  boxes = []
  def is_blank(row):
    for item in row:
      if len(item) != 0:
        return False
    return True

  for row in reader:
    if row[0]:
      league_name = row[0]
      if league_name == '#':
        continue
      current_box = []
      boxes.append([league_name, current_box])
    elif is_blank(row):
      current_box = None
    else:
      name = convert(row[1])
      player = players.get(name)
      if player is None:
        raise Exception("ERROR - player {0} not found.".format(name))
      current_box.append((player, row[3:]))

  LOOKUP_TABLE = PointsTable()
        
  for kv in boxes: 
    [name, box] = kv
    kv.pop()
    matches, players = analyse_box(box, LOOKUP_TABLE)
    kv.extend([matches, players])

    
  add_old_league_data(boxes, end_date)
Beispiel #3
0
 def get_queryset(self):
     queryset = BookingSystemEvent.objects.order_by("start_time")
     date = self.request.query_params.get('date', None)
     if date is not None:
         date = timezones.parse_iso_date_to_naive(date)
         date = datetime.datetime.combine(date, datetime.time(0, tzinfo=timezone.get_default_timezone()))
         delta = self.request.query_params.get('day_offset', None)
         if delta is not None:
           date = date + datetime.timedelta(days=int(delta))
         tplus1 = date + datetime.timedelta(days=1)
         queryset = queryset.filter(start_time__gte=date, start_time__lt=tplus1)
     return queryset
Beispiel #4
0
 def __init__(self, *args, **kwargs):
     ctx = kwargs.get('context')
     req = ctx is not None and ctx.get('request') or None
     super(CustomBookingListSerializer, self).__init__(*args, **kwargs)
     self.date = None
     if req is not None:
         date = req.query_params.get('date', None)
         if date is not None:
             self.date = timezones.parse_iso_date_to_naive(date)
             delta = req.query_params.get('day_offset', None)
             if delta is not None:
                 self.date += datetime.timedelta(days=int(delta))
Beispiel #5
0
def boxes_view(request, end_date=None, template_name="boxes.html", check_permissions=False, comp_type="boxes", name=None, year=None):
    """Return a view of the Leagues for ending on END_DATE. If
    END_DATE is  negative, the current league is shown"""

    if check_permissions:
        if (request.user.groups.filter(name="Competition Editor").count() == 0 and not request.user.is_superuser):
            raise PermissionDenied()

    queryset = CompetitionGroup.objects.filter(comp_type="wsrc_" + comp_type)
    if end_date is None:
        if year is not None:
            name = "{comp_type} - {name} {year}".format(**locals())
            group = get_object_or_404(queryset, end_date__year=year, name__iexact=name)

        groups = queryset.exclude(competition__state="not_started").order_by('-end_date')
        group = groups[0]
    else:
        end_date = parse_iso_date_to_naive(end_date)
        group = get_object_or_404(queryset, end_date=end_date)

    box_data = JSON_RENDERER.render(CompetitionGroupSerializer(group, context={"request": FAKE_REQUEST_CONTEXT}).data)
    competition_groups = JSON_RENDERER.render(CompetitionGroupSerializer(queryset, many=True).data)
    is_editor = request.user.has_perm("competitions.change_match")

    def create_box_config(previous_comp, competition, ctx):
        is_second = False
        ctx["maxplayers"] = max(ctx["maxplayers"], len(competition.entrant_set.all()))
        if previous_comp is not None:
            if previous_comp["name"][:-1] == competition.name[:-1]: # e.g. "League 1A" vs "League 1B"
                is_second = True
                previous_comp["colspec"] = 'double'
                previous_comp["nthcol"] = 'first'
        entrants = [p for p in competition.entrant_set.all().order_by("ordering")]
        def this_user():
            for e in entrants:
                if e.player1.user.id == request.user.id:
                    return True
            return False
        can_edit = competition.state == "active" and (is_editor or this_user())
        return {"colspec": is_second and "double" or "single",
                "nthcol": is_second and 'second' or 'first',
                "name": competition.name,
                "id": competition.id,
                "entrants": entrants,
                "can_edit": can_edit,
                }

    def create_new_box_config(idx):
        result = {"id": None, "players": None}
        if idx == 0:
            result["colspec"] = "single"
            result["name"] = "Premier"
            result["nthcol"] = "first"
        else:
            result["colspec"] = "double"
            suffix = (idx % 2 == 1) and "A" or "B"
            number = (idx+1)/2
            result["name"] = "League %(number)d%(suffix)s" % locals()
            result["nthcol"] = suffix == "A" and "first" or "second"
        return result


    class NP(dict):
        def get_players_as_string(self): return ""
    nullplayer = NP({"name": "", "id": ""})
    last = None
    boxes = []
    comp_meta = {"maxplayers": 0, "name": group.name, "id": group.id}
    for league in group.competition_set.all():
        cfg = create_box_config(last, league, comp_meta)
        boxes.append(cfg)
        last = cfg
        if cfg["nthcol"] == "second":
          last = None
    for box in boxes:
        while len(box["entrants"]) < comp_meta["maxplayers"]:
            box["entrants"].append(nullplayer)

    if request.GET.get('format') == 'xlsx':
        payload = create_spreadsheet(comp_meta, boxes)
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        response = HttpResponse(payload, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename="boxes_{date:%Y-%m-%d}.xlsx"'.format(date=group.end_date)
        return response

    ctx = {"competition": comp_meta}
    options = set_view_options(request, ctx)
    new_boxes = [create_new_box_config(i) for i in range(0,21)]
    ctx["boxes"] = boxes
    ctx["new_boxes"] = new_boxes
    ctx["is_editor"] = is_editor
    ctx["competition_groups"] = competition_groups
    ctx["selector"] = comp_type == "boxes" and get_boxes_links(options, group) or get_tournament_links(options, group)
    ctx["box_data"] = box_data
    ctx['players'] = Player.objects.all() # TODO - filter to players in comp group
    return TemplateResponse(request, template_name, ctx)