Coverage for app/backend/src/couchers/models/events.py: 100%
128 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-19 15:47 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-19 15:47 +0000
1import enum
2from datetime import datetime
3from typing import TYPE_CHECKING, cast
5from geoalchemy2 import Geometry
6from psycopg.types.range import TimestamptzRange
7from sqlalchemy import (
8 BigInteger,
9 Boolean,
10 CheckConstraint,
11 DateTime,
12 Enum,
13 ForeignKey,
14 Index,
15 String,
16 UniqueConstraint,
17 and_,
18 func,
19)
20from sqlalchemy.dialects.postgresql import TSTZRANGE, ExcludeConstraint
21from sqlalchemy.ext.hybrid import hybrid_property
22from sqlalchemy.orm import DynamicMapped, Mapped, backref, column_property, mapped_column, relationship
23from sqlalchemy.sql import expression
24from sqlalchemy.sql.elements import ColumnElement
26from couchers.models.base import Base, Geom, communities_seq
27from couchers.models.moderation import ModerationObjectType
28from couchers.utils import get_coordinates
30if TYPE_CHECKING:
31 from couchers.models import Cluster, Node, Thread, Upload, User
32 from couchers.models.moderation import ModerationState
35class ClusterEventAssociation(Base, kw_only=True):
36 """
37 events related to clusters
38 """
40 __tablename__ = "cluster_event_associations"
41 __table_args__ = (UniqueConstraint("event_id", "cluster_id"),)
43 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
45 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
46 cluster_id: Mapped[int] = mapped_column(ForeignKey("clusters.id"), index=True)
48 event: Mapped[Event] = relationship(init=False, backref="cluster_event_associations")
49 cluster: Mapped[Cluster] = relationship(init=False, backref="cluster_event_associations")
52class Event(Base, kw_only=True):
53 """
54 An event is composed of two parts:
56 * An event template (Event)
57 * An occurrence (EventOccurrence)
59 One-off events will have one of each; repeating events will have one Event,
60 multiple EventOccurrences, one for each time the event happens.
61 """
63 __tablename__ = "events"
65 id: Mapped[int] = mapped_column(
66 BigInteger, communities_seq, primary_key=True, server_default=communities_seq.next_value(), init=False
67 )
68 parent_node_id: Mapped[int] = mapped_column(ForeignKey("nodes.id"), index=True)
70 title: Mapped[str] = mapped_column(String)
72 slug: Mapped[str] = column_property(func.slugify(title))
74 creator_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
75 created: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
76 owner_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), index=True, default=None)
77 owner_cluster_id: Mapped[int | None] = mapped_column(ForeignKey("clusters.id"), index=True, default=None)
79 parent_node: Mapped[Node] = relationship(
80 init=False, backref="child_events", remote_side="Node.id", foreign_keys="Event.parent_node_id"
81 )
82 subscribers: DynamicMapped[User] = relationship(
83 init=False, backref="subscribed_events", secondary="event_subscriptions", lazy="dynamic", viewonly=True
84 )
85 organizers: DynamicMapped[User] = relationship(
86 init=False, backref="organized_events", secondary="event_organizers", lazy="dynamic", viewonly=True
87 )
88 creator_user: Mapped[User] = relationship(
89 init=False, backref="created_events", foreign_keys="Event.creator_user_id"
90 )
91 owner_user: Mapped[User | None] = relationship(
92 init=False, backref="owned_events", foreign_keys="Event.owner_user_id"
93 )
94 owner_cluster: Mapped[Cluster | None] = relationship(
95 init=False,
96 backref=backref("owned_events", lazy="dynamic"),
97 uselist=False,
98 foreign_keys="Event.owner_cluster_id",
99 )
100 occurrences: DynamicMapped[EventOccurrence] = relationship(init=False, lazy="dynamic")
102 __table_args__ = (
103 # Only one of owner_user and owner_cluster should be set
104 CheckConstraint(
105 "(owner_user_id IS NULL) <> (owner_cluster_id IS NULL)",
106 name="one_owner",
107 ),
108 )
111class EventOccurrence(Base, kw_only=True):
112 __tablename__ = "event_occurrences"
113 __moderation_author_column__ = "creator_user_id"
114 __moderation_object_type__ = ModerationObjectType.event_occurrence
115 __moderation_has_own_visibility_mechanism__ = False
117 id: Mapped[int] = mapped_column(
118 BigInteger, communities_seq, primary_key=True, server_default=communities_seq.next_value(), init=False
119 )
120 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
121 moderation_state_id: Mapped[int] = mapped_column(ForeignKey("moderation_states.id"), index=True)
122 thread_id: Mapped[int] = mapped_column(ForeignKey("threads.id"), unique=True)
124 # the user that created this particular occurrence of a repeating event (same as event.creator_user_id if single event)
125 creator_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
126 content: Mapped[str] = mapped_column(String) # CommonMark without images
127 photo_key: Mapped[str | None] = mapped_column(ForeignKey("uploads.key"), default=None)
129 is_cancelled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=expression.false())
130 is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, server_default=expression.false())
132 # The GPS coordinates of the event location
133 geom: Mapped[Geom] = mapped_column(Geometry(geometry_type="POINT", srid=4326))
134 # The physical address string. Legacy online events have been migrated to put the link in here.
135 address: Mapped[str] = mapped_column(String)
137 # IANA timezone identifier of the event
138 timezone: Mapped[str] = mapped_column(String)
140 # time during which the event takes place; this is a range type (instead of separate start+end times) which
141 # simplifies database constraints, etc
142 during: Mapped[TimestamptzRange] = mapped_column(TSTZRANGE)
144 created: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
145 last_edited: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
147 creator_user: Mapped[User] = relationship(
148 init=False, backref="created_event_occurrences", foreign_keys="EventOccurrence.creator_user_id"
149 )
150 thread: Mapped[Thread] = relationship(init=False, backref="event_occurrence", uselist=False)
151 event: Mapped[Event] = relationship(
152 init=False,
153 back_populates="occurrences",
154 remote_side="Event.id",
155 foreign_keys="EventOccurrence.event_id",
156 )
158 photo: Mapped[Upload | None] = relationship(init=False)
159 attendances: DynamicMapped[EventOccurrenceAttendee] = relationship(
160 init=False, back_populates="occurrence", lazy="dynamic"
161 )
162 community_invite_requests: DynamicMapped[EventCommunityInviteRequest] = relationship(
163 init=False, back_populates="occurrence", lazy="dynamic"
164 )
165 moderation_state: Mapped[ModerationState] = relationship(init=False)
167 __table_args__ = (
168 # Can't have overlapping occurrences in the same Event
169 ExcludeConstraint(("event_id", "="), ("during", "&&"), name="event_occurrences_event_id_during_excl"),
170 )
172 @property
173 def coordinates(self) -> tuple[float, float]:
174 # returns (lat, lng) or None
175 return get_coordinates(self.geom)
177 @hybrid_property
178 def start_time(self) -> datetime:
179 return cast(datetime, self.during.lower)
181 @start_time.inplace.expression
182 @classmethod
183 def _start_time_expression(cls) -> ColumnElement[datetime]:
184 return cast(ColumnElement[datetime], func.lower(cls.during))
186 @hybrid_property
187 def end_time(self) -> datetime:
188 return cast(datetime, self.during.upper)
190 @end_time.inplace.expression
191 @classmethod
192 def _end_time_expression(cls) -> ColumnElement[datetime]:
193 return cast(ColumnElement[datetime], func.upper(cls.during))
196class EventSubscription(Base, kw_only=True):
197 """
198 Users' subscriptions to events
199 """
201 __tablename__ = "event_subscriptions"
202 __table_args__ = (UniqueConstraint("event_id", "user_id"),)
204 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
206 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
207 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
208 joined: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
210 user: Mapped[User] = relationship(init=False)
211 event: Mapped[Event] = relationship(init=False)
214class EventOrganizer(Base, kw_only=True):
215 """
216 Organizers for events
217 """
219 __tablename__ = "event_organizers"
220 __table_args__ = (UniqueConstraint("event_id", "user_id"),)
222 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
224 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
225 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
226 joined: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
228 user: Mapped[User] = relationship(init=False)
229 event: Mapped[Event] = relationship(init=False)
232class AttendeeStatus(enum.Enum):
233 going = enum.auto()
236class EventOccurrenceAttendee(Base, kw_only=True):
237 """
238 Attendees for events
239 """
241 __tablename__ = "event_occurrence_attendees"
242 __table_args__ = (UniqueConstraint("occurrence_id", "user_id"),)
244 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
246 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
247 occurrence_id: Mapped[int] = mapped_column(ForeignKey("event_occurrences.id"), index=True)
248 responded: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
249 attendee_status: Mapped[AttendeeStatus] = mapped_column(Enum(AttendeeStatus))
251 user: Mapped[User] = relationship(init=False)
252 occurrence: Mapped[EventOccurrence] = relationship(init=False, back_populates="attendances")
254 reminder_sent: Mapped[bool] = mapped_column(Boolean, default=False, server_default=expression.false())
257class EventCommunityInviteRequest(Base, kw_only=True):
258 """
259 Requests to send out invitation notifications/emails to the community for a given event occurrence
260 """
262 __tablename__ = "event_community_invite_requests"
264 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
266 occurrence_id: Mapped[int] = mapped_column(ForeignKey("event_occurrences.id"), index=True)
267 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
269 created: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
271 decided: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), default=None)
272 decided_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), default=None)
273 approved: Mapped[bool | None] = mapped_column(Boolean, default=None)
275 occurrence: Mapped[EventOccurrence] = relationship(init=False, back_populates="community_invite_requests")
276 user: Mapped[User] = relationship(init=False, foreign_keys="EventCommunityInviteRequest.user_id")
278 __table_args__ = (
279 # each user can only request once
280 UniqueConstraint("occurrence_id", "user_id"),
281 # each event can only have one notification sent out
282 Index(
283 "ix_event_community_invite_requests_unique",
284 occurrence_id,
285 unique=True,
286 postgresql_where=and_(approved.is_not(None), approved == True),
287 ),
288 # decided and approved ought to be null simultaneously
289 CheckConstraint(
290 "((decided IS NULL) AND (decided_by_user_id IS NULL) AND (approved IS NULL)) OR \
291 ((decided IS NOT NULL) AND (decided_by_user_id IS NOT NULL) AND (approved IS NOT NULL))",
292 name="decided_approved",
293 ),
294 )