Coverage for app/backend/src/couchers/models/events.py: 100%
127 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-23 04:10 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-23 04:10 +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)
78 thread_id: Mapped[int] = mapped_column(ForeignKey("threads.id"), unique=True)
80 parent_node: Mapped[Node] = relationship(
81 init=False, backref="child_events", remote_side="Node.id", foreign_keys="Event.parent_node_id"
82 )
83 thread: Mapped[Thread] = relationship(init=False, backref="event", uselist=False)
84 subscribers: DynamicMapped[User] = relationship(
85 init=False, backref="subscribed_events", secondary="event_subscriptions", lazy="dynamic", viewonly=True
86 )
87 organizers: DynamicMapped[User] = relationship(
88 init=False, backref="organized_events", secondary="event_organizers", lazy="dynamic", viewonly=True
89 )
90 creator_user: Mapped[User] = relationship(
91 init=False, backref="created_events", foreign_keys="Event.creator_user_id"
92 )
93 owner_user: Mapped[User | None] = relationship(
94 init=False, backref="owned_events", foreign_keys="Event.owner_user_id"
95 )
96 owner_cluster: Mapped[Cluster | None] = relationship(
97 init=False,
98 backref=backref("owned_events", lazy="dynamic"),
99 uselist=False,
100 foreign_keys="Event.owner_cluster_id",
101 )
102 occurrences: DynamicMapped[EventOccurrence] = relationship(init=False, lazy="dynamic")
104 __table_args__ = (
105 # Only one of owner_user and owner_cluster should be set
106 CheckConstraint(
107 "(owner_user_id IS NULL) <> (owner_cluster_id IS NULL)",
108 name="one_owner",
109 ),
110 )
113class EventOccurrence(Base, kw_only=True):
114 __tablename__ = "event_occurrences"
115 __moderation_author_column__ = "creator_user_id"
116 __moderation_object_type__ = ModerationObjectType.event_occurrence
118 id: Mapped[int] = mapped_column(
119 BigInteger, communities_seq, primary_key=True, server_default=communities_seq.next_value(), init=False
120 )
121 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
122 moderation_state_id: Mapped[int] = mapped_column(ForeignKey("moderation_states.id"), index=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 timezone = "Etc/UTC"
139 # time during which the event takes place; this is a range type (instead of separate start+end times) which
140 # simplifies database constraints, etc
141 during: Mapped[TimestamptzRange] = mapped_column(TSTZRANGE)
143 created: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
144 last_edited: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
146 creator_user: Mapped[User] = relationship(
147 init=False, backref="created_event_occurrences", foreign_keys="EventOccurrence.creator_user_id"
148 )
149 event: Mapped[Event] = relationship(
150 init=False,
151 back_populates="occurrences",
152 remote_side="Event.id",
153 foreign_keys="EventOccurrence.event_id",
154 )
156 photo: Mapped[Upload | None] = relationship(init=False)
157 attendances: DynamicMapped[EventOccurrenceAttendee] = relationship(
158 init=False, back_populates="occurrence", lazy="dynamic"
159 )
160 community_invite_requests: DynamicMapped[EventCommunityInviteRequest] = relationship(
161 init=False, back_populates="occurrence", lazy="dynamic"
162 )
163 moderation_state: Mapped[ModerationState] = relationship(init=False)
165 __table_args__ = (
166 # Can't have overlapping occurrences in the same Event
167 ExcludeConstraint(("event_id", "="), ("during", "&&"), name="event_occurrences_event_id_during_excl"),
168 )
170 @property
171 def coordinates(self) -> tuple[float, float]:
172 # returns (lat, lng) or None
173 return get_coordinates(self.geom)
175 @hybrid_property
176 def start_time(self) -> datetime:
177 return cast(datetime, self.during.lower)
179 @start_time.inplace.expression
180 @classmethod
181 def _start_time_expression(cls) -> ColumnElement[datetime]:
182 return cast(ColumnElement[datetime], func.lower(cls.during))
184 @hybrid_property
185 def end_time(self) -> datetime:
186 return cast(datetime, self.during.upper)
188 @end_time.inplace.expression
189 @classmethod
190 def _end_time_expression(cls) -> ColumnElement[datetime]:
191 return cast(ColumnElement[datetime], func.upper(cls.during))
194class EventSubscription(Base, kw_only=True):
195 """
196 Users' subscriptions to events
197 """
199 __tablename__ = "event_subscriptions"
200 __table_args__ = (UniqueConstraint("event_id", "user_id"),)
202 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
204 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
205 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
206 joined: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
208 user: Mapped[User] = relationship(init=False)
209 event: Mapped[Event] = relationship(init=False)
212class EventOrganizer(Base, kw_only=True):
213 """
214 Organizers for events
215 """
217 __tablename__ = "event_organizers"
218 __table_args__ = (UniqueConstraint("event_id", "user_id"),)
220 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
222 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
223 event_id: Mapped[int] = mapped_column(ForeignKey("events.id"), index=True)
224 joined: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
226 user: Mapped[User] = relationship(init=False)
227 event: Mapped[Event] = relationship(init=False)
230class AttendeeStatus(enum.Enum):
231 going = enum.auto()
234class EventOccurrenceAttendee(Base, kw_only=True):
235 """
236 Attendees for events
237 """
239 __tablename__ = "event_occurrence_attendees"
240 __table_args__ = (UniqueConstraint("occurrence_id", "user_id"),)
242 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
244 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
245 occurrence_id: Mapped[int] = mapped_column(ForeignKey("event_occurrences.id"), index=True)
246 responded: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
247 attendee_status: Mapped[AttendeeStatus] = mapped_column(Enum(AttendeeStatus))
249 user: Mapped[User] = relationship(init=False)
250 occurrence: Mapped[EventOccurrence] = relationship(init=False, back_populates="attendances")
252 reminder_sent: Mapped[bool] = mapped_column(Boolean, default=False, server_default=expression.false())
255class EventCommunityInviteRequest(Base, kw_only=True):
256 """
257 Requests to send out invitation notifications/emails to the community for a given event occurrence
258 """
260 __tablename__ = "event_community_invite_requests"
262 id: Mapped[int] = mapped_column(BigInteger, primary_key=True, init=False)
264 occurrence_id: Mapped[int] = mapped_column(ForeignKey("event_occurrences.id"), index=True)
265 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
267 created: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), init=False)
269 decided: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), default=None)
270 decided_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), default=None)
271 approved: Mapped[bool | None] = mapped_column(Boolean, default=None)
273 occurrence: Mapped[EventOccurrence] = relationship(init=False, back_populates="community_invite_requests")
274 user: Mapped[User] = relationship(init=False, foreign_keys="EventCommunityInviteRequest.user_id")
276 __table_args__ = (
277 # each user can only request once
278 UniqueConstraint("occurrence_id", "user_id"),
279 # each event can only have one notification sent out
280 Index(
281 "ix_event_community_invite_requests_unique",
282 occurrence_id,
283 unique=True,
284 postgresql_where=and_(approved.is_not(None), approved == True),
285 ),
286 # decided and approved ought to be null simultaneously
287 CheckConstraint(
288 "((decided IS NULL) AND (decided_by_user_id IS NULL) AND (approved IS NULL)) OR \
289 ((decided IS NOT NULL) AND (decided_by_user_id IS NOT NULL) AND (approved IS NOT NULL))",
290 name="decided_approved",
291 ),
292 )