helpers.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import datetime
  2. from .models import Participant, Date, Event
  3. def slots2string( participant : Participant, n_slots : int ) -> str :
  4. """ Convert the slots of a participant to a string. """
  5. # Get the slots of the participant
  6. byte_array = participant.slots
  7. # Convert the slots to a string
  8. string_value = bin(int.from_bytes(byte_array, byteorder='big'))[2:]
  9. # Pad the string with 0s if necessary
  10. return '0' * (n_slots - len(string_value)) + string_value
  11. def string2slots( string : str, n_slots : int ) -> bytes :
  12. """ Convert a string to a byte array. """
  13. if len(string) != n_slots:
  14. raise ValueError(f"Invalid string length: {len(string)} (expected {n_slots})")
  15. # Convert the string to a byte array
  16. return int(string, 2).to_bytes((n_slots + 7) // 8, byteorder='big')
  17. def get_slot_count( event ) -> int :
  18. """ Get the number of slots in an event. """
  19. # Get the timespan of the event
  20. start_time = datetime.datetime.combine(datetime.date.today(), event.start_time)
  21. end_time = datetime.datetime.combine(datetime.date.today(), event.end_time)
  22. if(start_time>end_time):
  23. end_time += datetime.timedelta(days=1)
  24. timespan = end_time - start_time
  25. # Get the number of slots in the event
  26. days = event.date_set.count()
  27. slots_per_day = int(timespan.total_seconds() // event.slot_interval.total_seconds())
  28. return days * slots_per_day
  29. def slots2grid( event : Event, participants : list[Participant]) -> dict :
  30. """ Convert the slots of an event to data for the grid. """
  31. # Get the number of slots in the event
  32. n_slots = get_slot_count(event)
  33. data = {
  34. 'rows': [],
  35. 'days': [],
  36. 'colors': [],
  37. 'n_days': event.date_set.count(),
  38. }
  39. # Get the timespan of the event
  40. start_time = datetime.datetime.combine(datetime.date.today(), event.start_time)
  41. end_time = datetime.datetime.combine(datetime.date.today(), event.end_time)
  42. if(start_time>end_time):
  43. end_time += datetime.timedelta(days=1)
  44. timespan = end_time - start_time
  45. # Get the slots in a day
  46. slots_per_day = int(timespan.total_seconds() // event.slot_interval.total_seconds())
  47. # Get the slots of each day
  48. participant_slot_strings = [slots2string(participant, n_slots) for participant in participants]
  49. max_occupancy = 1
  50. for n, date in enumerate(event.date_set.all()):
  51. # Get participants for each slot
  52. slot_participants = [[] for i in range(slots_per_day)]
  53. for i, participant in enumerate(participants):
  54. for j in range(slots_per_day):
  55. if participant_slot_strings[i][n*slots_per_day + j] == '1':
  56. slot_participants[j].append(participant)
  57. # Fill the slots of the day
  58. slots = []
  59. last_hour = None
  60. last_half_hour = None
  61. for j, ps in enumerate(slot_participants):
  62. slot_begin = (start_time + j * event.slot_interval).strftime('%H:%M')
  63. slot_end = (start_time + (j+1) * event.slot_interval).strftime('%H:%M')
  64. current_time = start_time + j * event.slot_interval
  65. slots.append({
  66. 'tooltip': f"{slot_begin} - {slot_end} \n{', '.join([p.user.username for p in ps])}",
  67. 'offset': n*slots_per_day + j,
  68. 'date': date.date,
  69. 'time': current_time,
  70. 'color': len(ps),
  71. 'checked': 'checked="checked"' if len(ps) > 0 else '',
  72. 'is_full_hour': current_time.hour != last_hour,
  73. 'is_half_hour': current_time.minute // 30 != last_half_hour,
  74. })
  75. max_occupancy = max(max_occupancy, len(ps))
  76. last_hour = current_time.hour
  77. last_half_hour = current_time.minute // 30
  78. day = {
  79. 'date': date.date,
  80. 'slots': slots,
  81. }
  82. data['days'].append(day)
  83. # Fill the rows of the grid
  84. last_hour = None
  85. for i in range(slots_per_day):
  86. current_time = start_time + i * event.slot_interval
  87. data['rows'].append({
  88. 'time': current_time,
  89. 'is_full_hour': current_time.hour != last_hour,
  90. })
  91. last_hour = current_time.hour
  92. data['rows'].append({
  93. 'time': end_time,
  94. 'is_full_hour': True,
  95. })
  96. data['colors'] = max_occupancy
  97. return data