sessions

package
v0.0.0-...-95891f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 38 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sessions provides the game session tracking addon for campaigns. This file embeds the plugin's SQL migration files so they are available in the compiled binary regardless of the runtime working directory.

Package sessions manages game session scheduling, linked entities, and RSVP tracking for Chronicle campaigns. Sessions bridge worldbuilding and actual play by recording when games happen, who attended, and which entities were involved.

Index

Constants

View Source
const (
	CadenceEveryWeek = 0
	CadenceWeekA     = 1
	CadenceWeekB     = 2
)

Week cadence values, stored in member_availability.week_parity.

CadenceEveryWeek is 0 so that the column's DEFAULT 0 makes every row written before this feature existed mean exactly what it meant then — every week. That is the whole reason 0 is not one of the two tracks.

View Source
const (
	AvailAvailable   = "available"
	AvailPreferred   = "preferred"
	AvailUnavailable = "unavailable"
)

Availability state constants. A recurring block is stored only when a member is available or actively prefers a time; the ABSENCE of a row means "unavailable" (the default wash in the overlay). Exceptions may carry an explicit "unavailable" to punch a hole in the recurring pattern for one date.

View Source
const (
	StatusPlanned   = "planned"
	StatusCompleted = "completed"
	StatusCancelled = "cancelled"
)

Session status constants.

View Source
const (
	RecurrenceWeekly   = "weekly"   // Every week on the same day.
	RecurrenceBiWeekly = "biweekly" // Every 2 weeks on the same day.
	RecurrenceMonthly  = "monthly"  // Same day-of-month each month.
	RecurrenceCustom   = "custom"   // Every N weeks (recurrence_interval).
)

Recurrence type constants for repeating sessions.

View Source
const (
	RSVPInvited   = "invited"
	RSVPAccepted  = "accepted"
	RSVPDeclined  = "declined"
	RSVPTentative = "tentative"
	// RSVPCarriedYes is a proposal-confirmed "yes" vote that still needs the
	// member's own explicit confirmation before it counts as Going. A member carries this status until they submit their own
	// accepted/declined/tentative answer through the normal RSVP flow, which
	// simply overwrites it — there is no separate "confirm" action.
	RSVPCarriedYes = "carried_yes"
)

Attendee RSVP status constants.

View Source
const (
	EntityRoleMentioned   = "mentioned"
	EntityRoleEncountered = "encountered"
	EntityRoleKey         = "key"
)

Session entity role constants.

View Source
const (
	NotifNightEntryReady = "game_night_entry_ready"
	NotifNightCheckIn    = "game_night_checkin"
	NotifNightShareEntry = "game_night_share_entry"
)

Bell types, also the keys notifyprefs files them under.

View Source
const (
	NightYes      = "yes"
	NightMaybe    = "maybe"
	NightNo       = "no"
	NightNoAnswer = ""
)

Game-night answers as the calendar shows them. Silence is NightNoAnswer, never a no.

View Source
const (
	ProposalOpen   = "open"
	ProposalClosed = "closed"
)

Proposal status values.

View Source
const (
	ResponseYes   = "yes"
	ResponseNo    = "no"
	ResponseMaybe = "maybe"
)

Per-option response values (mirror RSVP accepted/declined/tentative without reusing that table).

View Source
const (
	NotifProposalCreated   = "proposal_created"
	NotifProposalResponse  = "proposal_response"
	NotifProposalConfirmed = "proposal_confirmed" // winner picked, session created.
	// NotifAvailabilityNudge is the Director asking a member who has never
	// answered to set their availability. Sent only on an explicit press —
	// there is no scheduled-job runner, so a timer-fired reminder would need
	// separate consent.
	NotifAvailabilityNudge = "availability_nudge"
	// NotifAvailabilityConfirm is the Director asking everyone to confirm
	// their times are still right. The newest one is also the ask's time,
	// which a member's confirmation has to come after.
	NotifAvailabilityConfirm = "availability_confirm"

	// Game-night lifecycle notifications (issue #741). Each fires only
	// to members who had already RESPONDED before the change — an untouched
	// invite carries no expectation to notify anyone of. The event itself
	// (needs_recheck) always fires; whether a member reads it as urgent is a
	// UI concern.
	NotifSessionMoved     = "session_moved"
	NotifSessionCancelled = "session_cancelled"
	NotifSessionRestored  = "session_restored"
	// NotifSessionRescheduleSuggested tells the organizer/co-Director a
	// member proposed a different time via the emailed "suggest another
	// time" link.
	NotifSessionRescheduleSuggested = "session_reschedule_suggested"
)

Notification types.

View Source
const (
	SightingSeen    = "seen"
	SightingNotSeen = "not_seen"

	SightingSourceCheckin = "checkin"
	SightingSourceManual  = "manual"
	SightingSourceLink    = "link"
)

Sighting states and sources. A stored row is "seen" or "not_seen" and came from the after-night check-in or was added by hand; "link" marks a session_entities link merged in at read time, never stored here.

View Source
const LastSeenBlockType = "last_seen"

LastSeenBlockType is the page block's type in the block registry.

View Source
const NoRealDateWords = "No real date yet"

NoRealDateWords is how every page says a night has no real-life date. A night made from a story calendar's event has only an in-world day, and a bare "–" there reads as a bug, so the words are shared by every place that would otherwise show a blank.

View Source
const NotifNightReminder = "game_night_reminder"

NotifNightReminder asks a player to answer whether they are coming: the person running the night pressing Remind, or the bell the day before.

View Source
const NotifSessionScheduled = "session_scheduled"

NotifSessionScheduled tells members a new game night is on the calendar. It asks for an answer, so it also raises the call-to-action banner (calloutNotifTypes) until the member answers that night, when it is marked read. Without it, a campaign with no email set up told players nothing.

View Source
const PluginSlug = "sessions"

PluginSlug names this plugin in the registry and its static URL prefix.

View Source
const RSVPActionSuggest = "suggest"

RSVP-token action constants for session_rsvp_tokens.action, beyond the accept/decline/tentative actions that reuse the RSVP status constants above. RSVPActionSuggest marks an emailed "suggest another time" link, whose token does not resolve to one of those three fixed outcomes.

View Source
const SessionEventKindSlug = "session"

SessionEventKindSlug is the calendar event kind that marks a session. Kinds are the campaign's own list, so this is a convention a campaign follows by naming a kind "session"; a campaign without one simply never gets the strip.

View Source
const SessionsAddonSlug = "sessions"

SessionsAddonSlug is the Game nights switch. The slug predates the name: it was the dashboard block's addon, and keeping it means campaigns that had that block on keep game nights on.

Variables

View Source
var ErrRSVPTokenSpent = apperror.NewBadRequest("this RSVP link has already been used")

ErrRSVPTokenSpent is returned by MarkRSVPTokenUsed when the token had already been consumed — i.e. this caller LOST the race for a single-use link. It is a normal outcome, not an internal error: the winner already applied the action.

View Source
var MigrationsFS embed.FS

MigrationsFS contains the embedded SQL migration files for the sessions plugin.

View Source
var StaticAssetsFS embed.FS

StaticAssetsFS holds the Last seen block's script, served at /static/plugins/sessions/ and loaded on sight (ADR-063).

Functions

func AgoText

func AgoText(date string, now time.Time) string

AgoText says how long before now a night was. The rule is mirrored in static/js/last_seen.js (agoText) so the line reads the same after the DM changes it without a reload; both are pinned by tests with the same cases.

func CadenceLabel

func CadenceLabel(cadence int, from timeutil.CivilDate) timeutil.CivilDate

CadenceLabel names a track by a real date inside it — the Sunday that starts the first such week on or after from. The UI shows "week of 16 Aug", never "odd weeks", so the member is choosing between two weeks they can point at on a calendar instead of decoding a convention.

func ConfigureRecipientFilter

func ConfigureRecipientFilter(svc SessionService, f RecipientFilter)

ConfigureRecipientFilter wires people's notification choices into the bell writes after construction, as the app builds auth first.

func PublicTextColumns

func PublicTextColumns() []database.PublicTextColumn

PublicTextColumns lists the recap, which every member reads, for the boot-time reconciler that removes GM-only parts saved before UpdateSessionRecap stripped them.

func ReconcileAddonEnablement

func ReconcileAddonEnablement(ctx context.Context, svc SessionService, store AddonEnablementStore) (int, error)

ReconcileAddonEnablement turns the Game nights switch on for every campaign that already uses game nights but has never had the switch recorded either way, so giving game nights a switch of its own (off for new campaigns) does not take them away from anyone. A recorded row, on or off, is an owner's choice and is left alone. Idempotent; safe every boot. Returns how many campaigns it switched on.

func ReconcileWorldDateCalendars

func ReconcileWorldDateCalendars(ctx context.Context, svc SessionService, resolver DefaultCalendarResolver) (int, error)

ReconcileWorldDateCalendars gives every session that has an in-world date but no calendar the campaign's default calendar, which is the calendar the date was set against before sessions recorded one. Campaigns with no calendar are skipped and retried on the next boot. Idempotent: stamped rows are never rewritten. A failure on one campaign is logged and does not stop the rest; the first error is returned. Returns sessions stamped.

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *Handler,
	campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterRoutes sets up all session-related routes. Game nights have their own addon switch (slug "sessions") and also need the calendar addon, since nights and hours are shown in the calendar.

func ShowLastSeen

func ShowLastSeen(v LastSeenView, dm bool) bool

ShowLastSeen is whether the block draws at all. A player whose page was never seen gets nothing, not an empty block; the DM always gets the line, because it is where they add a sighting.

func StartNightBells

func StartNightBells(ctx context.Context, svc NightEntryService)

StartNightBells sends due bell items now and then every bellTick until ctx ends.

func ValidWeekCadence

func ValidWeekCadence(v int) bool

ValidWeekCadence reports whether v is a cadence the store accepts.

func WeekCadenceFor

func WeekCadenceFor(d timeutil.CivilDate) int

WeekCadenceFor returns which alternating track the real date d falls in — CadenceWeekA or CadenceWeekB. It never returns CadenceEveryWeek: "every week" is a property a BLOCK can have, not a property a date can have.

Types

type AIGameNights

type AIGameNights struct {
	// contains filtered or unexported fields
}

AIGameNights is the game nights' part of the AI engine (aiplug): the `game-night` block an AI can ask to write and the `game-nights` lookup. Matched by name, with `date` telling apart two nights of the same name; the block's body is the night's recap, which every member can read.

func NewAIGameNights

func NewAIGameNights(svc SessionService, members campaigns.MemberLister) *AIGameNights

NewAIGameNights builds the AI part over the sessions service. members lets a new night invite everyone, as the Game nights page does.

func (*AIGameNights) Answer

func (k *AIGameNights) Answer(ctx context.Context, campaignID string, a aiplug.Actor, r aiplug.Record) (string, string, error)

Answer lists the game nights. They are Director content, as the block is, so a player's view gets a refusal.

func (*AIGameNights) Apply

func (k *AIGameNights) Apply(ctx context.Context, campaignID string, a aiplug.Actor, r aiplug.Record) error

Apply writes an approved block, re-planning it first.

func (*AIGameNights) Brief

func (*AIGameNights) Brief() string

func (*AIGameNights) Doc

func (*AIGameNights) Doc() string

func (*AIGameNights) Export

func (k *AIGameNights) Export(ctx context.Context, campaignID string, a aiplug.Actor) (string, error)

Export lists every game night in the block's own format, so an AI can update or remove one by name. Recaps are left out: the export's Sessions section already carries them.

func (*AIGameNights) Label

func (*AIGameNights) Label() string

func (*AIGameNights) LookupInfo

func (*AIGameNights) LookupInfo() aiplug.LookupInfo

LookupInfo describes `what: game-nights` and its tool.

func (*AIGameNights) Name

func (*AIGameNights) Name() string

func (*AIGameNights) Pieced

func (k *AIGameNights) Pieced()

Pieced says Answer cuts its own list by `piece`, so the engine does not.

func (*AIGameNights) Plan

func (k *AIGameNights) Plan(ctx context.Context, campaignID string, a aiplug.Actor, r aiplug.Record) aiplug.Plan

Plan checks a block for the review screen. Game nights are the Director's, so only the owner or a co-DM may change them.

type AddExceptionRequest

type AddExceptionRequest struct {
	OnDate      string `json:"onDate"` // YYYY-MM-DD
	StartMinute int    `json:"startMinute"`
	EndMinute   int    `json:"endMinute"`
	State       string `json:"state"` // available | preferred | unavailable
	TZ          string `json:"tz"`
}

AddExceptionRequest adds a per-date override to the current user's pattern.

type AddonEnablementStore

type AddonEnablementStore interface {
	HasCampaignAddonRecord(ctx context.Context, campaignID string, addonSlug string) (bool, error)
	EnableForCampaignBySlug(ctx context.Context, campaignID string, addonSlug string, userID string) error
}

AddonEnablementStore is the addons-service surface the reconciler needs. Satisfied by addons.AddonService. HasCampaignAddonRecord, not IsEnabledForCampaign, because "never decided" and "switched off" must be told apart.

type Attendee

type Attendee struct {
	ID          int        `json:"id"`
	SessionID   string     `json:"session_id"`
	UserID      string     `json:"user_id"`
	Status      string     `json:"status"` // invited, accepted, declined, tentative, carried_yes
	RespondedAt *time.Time `json:"responded_at,omitempty"`
	// Note is a short player-set note on their own RSVP. Nil means none —
	// stored as SQL NULL, and an explicit empty-string write also clears it
	// (see sessionRepository.SetAttendeeNote). json:"-": nothing serializes
	// Attendee to JSON today (every read renders Templ/HTML); a future JSON
	// endpoint must opt back in deliberately rather than hand every
	// attendee's note to every viewer by default.
	Note *string `json:"-"`
	// ExcludedFromCount is the Director's own "leave myself out of the N/M
	// tally" switch (operator answer #3). Only ever true on the row of the
	// user who set it on themselves; excludes the row from both the
	// numerator and denominator of any going/total count while leaving the
	// individual answer visible to them and to the Director.
	ExcludedFromCount bool `json:"excluded_from_count"`
	// NeedsRecheck is set when the session moved or was cancelled AFTER this
	// member had already answered. The answer itself is never cleared — this
	// only flags "look again".
	NeedsRecheck bool `json:"needs_recheck"`

	// Joined data.
	DisplayName string  `json:"display_name,omitempty"`
	AvatarPath  *string `json:"avatar_path,omitempty"`
}

Attendee represents a campaign member's RSVP status for a session.

type AvailabilityAnswerStatus

type AvailabilityAnswerStatus struct {
	UserID     string `json:"userId"`
	Name       string `json:"name"`
	Answered   bool   `json:"answered"`
	AnsweredAt string `json:"answeredAt,omitempty"` // RFC3339, empty when never
}

AvailabilityAnswerStatus is one member's answered-or-not state, as the Director's roster and the nudge action both need it.

type AvailabilityBlock

type AvailabilityBlock struct {
	ID          string
	CampaignID  string
	UserID      string
	DayOfWeek   int // 0=Sun..6=Sat
	StartMinute int // minutes from local midnight
	EndMinute   int
	State       string // available | preferred
	TZ          string // IANA zone the wall-clock is in
	// WeekCadence is CadenceEveryWeek / CadenceWeekA / CadenceWeekB
	// (availability_cadence.go). Zero means every week.
	WeekCadence int
	UpdatedAt   time.Time
}

AvailabilityBlock is one stored recurring weekly block, expressed as a ZONE-LOCAL wall-clock (RC-12.5): a weekday plus a [start,end) minute range in the member's own IANA zone. Never a UTC instant.

type AvailabilityBlockDTO

type AvailabilityBlockDTO struct {
	DayOfWeek   int    `json:"dayOfWeek"`   // 0=Sun..6=Sat
	StartMinute int    `json:"startMinute"` // minutes from local midnight
	EndMinute   int    `json:"endMinute"`
	State       string `json:"state"` // available | preferred
	// WeekCadence is 0 every week / 1 week A / 2 week B. Omitted by a client
	// that predates alternating weeks, which decodes to 0 — every week — so an
	// old client keeps working and keeps meaning what it always meant.
	WeekCadence int `json:"weekCadence"`
}

AvailabilityBlockDTO is one block in a save request or a "my availability" response.

type AvailabilityException

type AvailabilityException struct {
	ID          string
	CampaignID  string
	UserID      string
	OnDate      string // YYYY-MM-DD
	StartMinute int
	EndMinute   int
	State       string // available | preferred | unavailable
	TZ          string
	UpdatedAt   time.Time
}

AvailabilityException overrides the recurring pattern for one real-world (Gregorian) date — e.g. "this week I'm away Thursday". When a member has any exception rows for a date, those rows REPLACE the recurring pattern for that date in the overlay projection.

type AvailabilityWindowDTO

type AvailabilityWindowDTO struct {
	OnDate      string `json:"onDate"` // YYYY-MM-DD
	StartMinute int    `json:"startMinute"`
	EndMinute   int    `json:"endMinute"`
}

AvailabilityWindowDTO is one TEMPORARY window a member offers for a specific real-world date — "I could actually do Tuesday 6–10pm".

Distinct from ExceptionBlockDTO, which is a composed piece of a whole-day replacement: a window is an ADDITIVE offer, and the service composes the rest of the day around it so the offer can never reduce the member's availability.

type AwayRequest

type AwayRequest struct {
	From string `json:"from"`
	To   string `json:"to"`
	TZ   string `json:"tz"`
}

AwayRequest marks (or clears) a stretch of days a member can't play, From..To inclusive, as YYYY-MM-DD dates in TZ.

type CalendarFeedToken

type CalendarFeedToken struct {
	ID         int
	CampaignID string
	UserID     string
	Token      string
	CreatedAt  time.Time
}

CalendarFeedToken is one member's private, replaceable game-night calendar feed credential (session_calendar_feed_tokens) — operator answer #1.

type Callout

type Callout struct {
	Kind CalloutKind
	// Message is the human sentence. Empty when Kind is CalloutNone.
	Message string
	// Link is where the primary action goes, for CalloutRSVP. Empty otherwise —
	// the timezone callout acts in place rather than navigating.
	Link string
	// Count is how many unanswered requests there are, for CalloutRSVP.
	Count int
	// NoAccountPage drops the timezone banner's "Choose" link, for a guest
	// whose session is fenced away from /account: the link would only bounce
	// them back to their campaign.
	NoAccountPage bool
}

Callout is what the banner should say, already decided.

func BuildCallout

func BuildCallout(unread []Notification, zoneSet bool, now time.Time) Callout

BuildCallout decides what one player should be shown, from their unread notifications and their stored account timezone.

An unanswered RSVP always outranks the timezone ask, never "most recent wins": the RSVP is time-limited (a session gets scheduled with or without that player), while a missing timezone is wrong every day but keeps until tomorrow. The two are never shown together, since stacked banners crowd the page and train a reflex dismissal that loses both.

zoneSet reports whether the account carries an IANA zone. It is passed rather than read here so this stays pure and so the caller owns the auth seam.

type CalloutKind

type CalloutKind string

CalloutKind names what the banner is asking for. The zero value is "nothing", so a caller that ignores the error still shows nothing rather than something wrong.

const (
	// CalloutNone is "say nothing". It is the zero value on purpose.
	CalloutNone CalloutKind = ""
	// CalloutRSVP is an unanswered scheduling or RSVP request.
	CalloutRSVP CalloutKind = "rsvp"
	// CalloutTimezone is "we do not know your timezone and are about to guess".
	CalloutTimezone CalloutKind = "timezone"
)

type CampaignReader

type CampaignReader interface {
	GetByID(ctx context.Context, id string) (*campaigns.Campaign, error)
}

CampaignReader is the ONE campaign read the overlay's role column needs: the campaign row, whose parsed settings carry the co-DM grant list.

It is deliberately GetByID and not IsUserDmGranted(campaign, user): campaigns' IsUserDmGranted re-reads the campaign row per call, so asking it once per member would turn a roster render into an N+1. One read, one grant set, every member labelled from it.

type CheckInPerson

type CheckInPerson struct {
	EntityID  string `json:"entityId"`
	Name      string `json:"name"`
	Answer    string `json:"answer,omitempty"`
	NoteID    string `json:"noteId,omitempty"`
	NoteTitle string `json:"noteTitle,omitempty"`
	MoreNotes int    `json:"moreNotes,omitempty"`
	Line      string `json:"line,omitempty"`
}

CheckInPerson is one page the check-in asks about. NoteID is the first entry naming it, with MoreNotes counting the others; a page only linked to the night as mentioned has no entry. Answer is "" until the DM answers.

type CreateProposalRequest

type CreateProposalRequest struct {
	Title   string                `json:"title"`
	Note    string                `json:"note"`
	TZ      string                `json:"tz"` // IANA zone the wall-clocks are in
	Options []ProposalOptionInput `json:"options"`
}

CreateProposalRequest is the DM slot-builder submission: a title/note plus 1..5 candidate slots, submitted as viewer-zone wall-clocks (date + minute range in TZ). The service resolves them to UTC instants via timeutil for DST correctness. Storage is UTC; only the API input is wall-clock.

type CreateSessionInput

type CreateSessionInput struct {
	Name          string
	Summary       *string
	ScheduledDate *string
	ScheduledTime *string
	// ScheduledTZ is the organizer's IANA zone ScheduledTime was set in (see
	// Session.ScheduledTZ). Nil for a manual session whose creator's zone
	// wasn't captured.
	ScheduledTZ         *string
	CalendarYear        *int
	CalendarMonth       *int
	CalendarDay         *int
	IsRecurring         bool
	RecurrenceType      *string
	RecurrenceInterval  int
	RecurrenceDayOfWeek *int
	RecurrenceEndDate   *string
	CreatedBy           string
	// CalendarEventID links the new night to the calendar event it was made
	// from. Only the make-from-event path sets it.
	CalendarEventID *string
}

CreateSessionInput is the validated input for creating a session.

type DefaultCalendarResolver

type DefaultCalendarResolver interface {
	DefaultCalendarID(ctx context.Context, campaignID string) (string, error)
}

DefaultCalendarResolver names a campaign's default calendar, or "" when it has none. Implemented in internal/app over the calendar service, so this plugin never imports the calendar plugin.

type EntityCampaignChecker

type EntityCampaignChecker interface {
	EntityBelongsToCampaign(ctx context.Context, entityID, campaignID string) (bool, error)
}

EntityCampaignChecker verifies that an entity belongs to a given campaign. Used to prevent cross-campaign entity linking (IDOR prevention).

type EntityVisibilityFilter

type EntityVisibilityFilter interface {
	FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
}

EntityVisibilityFilter resolves which of a set of entity IDs a viewer (role + userID) may see, applying the entities plugin's own visibility policy (default is_private, custom per-subject grants, tag grants). Wraps entities.EntityService.FilterViewableEntityIDs — the SAME method the relations widget uses to hide private-entity targets — so the sessions plugin never imports the entities repository (rule 8) while still deferring to a single real policy. Keeps a session's linked-entity list from naming a private entity to a viewer who could not otherwise see it (ADR-055 rule 3).

type ExceptionBlockDTO

type ExceptionBlockDTO struct {
	StartMinute int    `json:"startMinute"`
	EndMinute   int    `json:"endMinute"`
	State       string `json:"state"` // available | preferred | unavailable
}

ExceptionBlockDTO is one composed block within a day-replace request.

type GameNight

type GameNight struct {
	SessionID      string `json:"sessionId"`
	Name           string `json:"name"`
	Summary        string `json:"summary,omitempty"`
	Date           string `json:"date"`
	Time           string `json:"time,omitempty"`
	TZ             string `json:"tz,omitempty"`
	Recurring      bool   `json:"recurring"`
	RecurrenceType string `json:"recurrenceType,omitempty"`
	// The series as stored, so the calendar's editor can show and change it:
	// the first night, every-N-weeks for a custom repeat, and the last date.
	SeriesDate         string        `json:"seriesDate,omitempty"`
	RecurrenceInterval int           `json:"recurrenceInterval,omitempty"`
	RecurrenceEndDate  string        `json:"recurrenceEndDate,omitempty"`
	OrganizerID        string        `json:"organizerId"`
	OrganizerName      string        `json:"organizerName,omitempty"`
	Past               bool          `json:"past"`
	Tally              NightTally    `json:"tally"`
	Roster             []NightAnswer `json:"roster"`
	// Viewer-specific: filled by ForViewer, never by the service.
	Mine       *NightAnswer `json:"mine"`
	CanExclude bool         `json:"canExclude"`
}

GameNight is one night of a session, for the calendar's day card and event page. A repeating session yields one GameNight per night, each with its own answers.

func (*GameNight) ForViewer

func (n *GameNight) ForViewer(userID string, isCampaignOwner bool)

ForViewer fills the fields that depend on who is looking: their own answer, and whether they may switch themselves out of the count (the organizer or the campaign owner, the rule SetExcludedFromCount enforces).

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler processes HTTP requests for the sessions plugin.

func NewHandler

func NewHandler(svc SessionService) *Handler

NewHandler creates a new sessions Handler.

func (*Handler) AddExceptionAPI

func (h *Handler) AddExceptionAPI(c *echo.Context) error

AddExceptionAPI adds a per-date override for the current user. POST /campaigns/:id/availability/exceptions

func (*Handler) AllGameNightsAPI

func (h *Handler) AllGameNightsAPI(c *echo.Context) error

AllGameNightsAPI is every game night in the campaign, grouped as Upcoming, Played, Completed and Cancelled, for the calendar's Game nights panel. Members only, like the rest of the game-night answers. GET /campaigns/:id/sessions/all

func (*Handler) ApplyProposalToken

func (h *Handler) ApplyProposalToken(c *echo.Context) error

ApplyProposalToken records a one-click response and consumes the token. POST /proposals/respond/:token — the state-changing half of the flow. Re-runs the open-proposal (service) and current-membership checks before applying.

func (*Handler) ApplyRSVPToken

func (h *Handler) ApplyRSVPToken(c *echo.Context) error

ApplyRSVPToken applies a one-click RSVP and consumes the token. POST /rsvp/:token — the state-changing half of the token flow.

func (*Handler) ApplySuggestToken

func (h *Handler) ApplySuggestToken(c *echo.Context) error

ApplySuggestToken records the suggestion — see SessionService.ValidateAndRecordSuggestion for the validate-before-consume ordering — and tells the organizer. POST /rsvp/:token/suggest

func (*Handler) AvailabilityAnswersAPI

func (h *Handler) AvailabilityAnswersAPI(c *echo.Context) error

AvailabilityAnswersAPI lists who has answered and who has not. GET /campaigns/:id/availability/answers

Party-visible, for the same reason RosterEntry.HasAnswered is: it says who has spoken, never what they said.

func (*Handler) CalloutAPI

func (h *Handler) CalloutAPI(c *echo.Context) error

CalloutAPI renders the player's one outstanding call-to-action, or nothing. GET /notifications/call-to-action

An empty body means an empty banner, matching NotificationBadgeAPI's contract: the caller is an HTMX poll swapping innerHTML.

Every error path returns empty HTML with 200 rather than failing the poll: a banner that cannot be built should read the same as one with nothing to say, not as a page-wide error toast.

func (*Handler) CalloutHTML

func (h *Handler) CalloutHTML(c *echo.Context) (body string, ok bool)

CalloutHTML is the banner the endpoint answers. The page draws it into the strip itself on a full load, so the strip has its height from the first paint instead of pushing the page down when a poll fills it. ok is false when the banner could not be built; the strip then asks for itself as before.

func (*Handler) CampaignRoster

func (h *Handler) CampaignRoster(ctx context.Context, campaignID string) []RosterEntry

CampaignRoster returns the overlay roster in its stable render order, with roles, co-DM grants and zones resolved from their truth sources. Availability is deliberately not included — see RosterEntry.

func (*Handler) CampaignWeekOverlay

func (h *Handler) CampaignWeekOverlay(ctx context.Context, campaignID, weekStart, viewerTZ string,
	includeDetail bool) (*WeekOverlay, error)

CampaignWeekOverlay builds the campaign's availability overlay for the week containing weekStart, projected into viewerTZ.

includeDetail IS THE PERMISSION and it is the caller's to decide, from role, never from the route. When false, BuildOverlay omits Members and every *IDs array wholesale: a non-entitled viewer's payload does not contain another member's lane data at all, hidden or otherwise.

func (*Handler) ClearAwayAPI

func (h *Handler) ClearAwayAPI(c *echo.Context) error

ClearAwayAPI takes the away mark off a stretch of days. POST /campaigns/:id/availability/away/clear

func (*Handler) ClearSightingAPI

func (h *Handler) ClearSightingAPI(c *echo.Context) error

ClearSightingAPI removes one night's answer for one page: DELETE /campaigns/:id/sessions/:sid/sightings?entity=ID&date=YYYY-MM-DD.

func (*Handler) ConfirmMyAvailabilityAPI

func (h *Handler) ConfirmMyAvailabilityAPI(c *echo.Context) error

ConfirmMyAvailabilityAPI records that the caller's saved times are still right, answering a confirm ask without changing them. POST /campaigns/:id/availability/confirm

func (*Handler) ConfirmProposalAPI

func (h *Handler) ConfirmProposalAPI(c *echo.Context) error

ConfirmProposalAPI is the DM/Scribe confirm-winner action: pick a winning option, which closes the proposal and creates a planned session from that slot's UTC instant. Members are auto-invited to the new session and every responder is notified — both off the request path, mirroring create. POST /campaigns/:id/proposals/:pid/confirm

func (*Handler) CreateProposalAPI

func (h *Handler) CreateProposalAPI(c *echo.Context) error

CreateProposalAPI creates a proposal from the DM slot builder, then fans out notifications + email invites to members. POST /campaigns/:id/proposals

func (*Handler) CreateSession

func (h *Handler) CreateSession(c *echo.Context) error

CreateSession creates a new session. POST /campaigns/:id/sessions

func (*Handler) DeleteExceptionAPI

func (h *Handler) DeleteExceptionAPI(c *echo.Context) error

DeleteExceptionAPI removes one of the current user's own exceptions. DELETE /campaigns/:id/availability/exceptions/:eid

func (*Handler) DeleteSessionAPI

func (h *Handler) DeleteSessionAPI(c *echo.Context) error

DeleteSessionAPI soft-deletes a session (co-Director/Owner — see routes.go) and, per the operator's "moving or deleting an event that collects RSVPs notifies the people who answered" rule, tells everyone who had already responded. Their answer is kept, not cleared — RestoreSessionAPI below puts it back exactly as it was. DELETE /campaigns/:id/sessions/:sid

func (*Handler) DismissEventAPI

func (h *Handler) DismissEventAPI(c *echo.Context) error

DismissEventAPI is "Not this one": the event stops being offered on the strip for everyone in the campaign. The event is read again from the calendar, so only a Session event this viewer may see can be stored, never an arbitrary id. A second press changes nothing. PUT /campaigns/:id/sessions/event-dismissals/:eid

func (*Handler) EmailBackOn

func (h *Handler) EmailBackOn(ctx context.Context, campaignID string, s *Session)

EmailBackOn sends the back-on email for a game night restored from the campaign Trash, where no request carries the campaign or who restored it.

func (*Handler) EmbedSessions

func (h *Handler) EmbedSessions(c *echo.Context) error

EmbedSessions returns an HTMX fragment for the dashboard session tracker block. Shows upcoming planned sessions with RSVP counts in a compact format. GET /campaigns/:id/sessions/embed

func (*Handler) EventsWithoutNightAPI

func (h *Handler) EventsWithoutNightAPI(c *echo.Context) error

EventsWithoutNightAPI lists Session-kind calendar events that have no game night and were not set aside with "Not this one", for the strip at the top of the calendar's Game nights panel. GET /campaigns/:id/sessions/event-candidates

func (*Handler) GameNightFeedICS

func (h *Handler) GameNightFeedICS(c *echo.Context) error

GameNightFeedICS serves one member's private game-night feed as an ICS subscription. Public — the token IS the credential, mirroring /rsvp/:token — so an unknown token and a campaign-disabled feed both answer a plain 404 rather than distinguishing "wrong token" from "turned off" to a stranger. GET /sessions/feed/:token(.ics)

func (h *Handler) GameNightsLink(c *echo.Context) error

GameNightsLink sends the sidebar's "Game nights" link, the RSVP card's links, the dashboard's game night list and the retired Game nights page's address to the calendar, where members see and answer them. Game nights are members' business, so anyone else goes to the campaign. GET /campaigns/:id/game-nights[?session=ID&date=YYYY-MM-DD] GET /campaigns/:id/sessions

func (*Handler) GetFeedSettingsAPI

func (h *Handler) GetFeedSettingsAPI(c *echo.Context) error

GetFeedSettingsAPI reports whether this campaign's calendar feed is on. GET /campaigns/:id/sessions/feed-settings

func (*Handler) GetFeedTokenAPI

func (h *Handler) GetFeedTokenAPI(c *echo.Context) error

GetFeedTokenAPI returns (creating on first call) the caller's own private feed URL. POST /campaigns/:id/sessions/feed/token

func (*Handler) GetMyAvailabilityAPI

func (h *Handler) GetMyAvailabilityAPI(c *echo.Context) error

GetMyAvailabilityAPI returns the current user's own recurring pattern to seed the paint grid. GET /campaigns/:id/availability/mine

func (*Handler) GetOverlayAPI

func (h *Handler) GetOverlayAPI(c *echo.Context) error

GetOverlayAPI returns the DM heatmap payload for a week. All members receive the anonymous density; per-member identity is included only for the owner / DM-granted (enforced here by role, not by route — design §5 / Q1). GET /campaigns/:id/availability/overlay?week=YYYY-MM-DD&tz=IANA

func (*Handler) GetRecapAPI

func (h *Handler) GetRecapAPI(c *echo.Context) error

GetRecapAPI returns the recap in the page editor's load contract. GET /campaigns/:id/sessions/:sid/recap

func (*Handler) GettingStartedBlock

func (h *Handler) GettingStartedBlock(c *echo.Context) error

GettingStartedBlock draws the block, or an empty answer that removes the placeholder when there is nothing left to do. GET /campaigns/:id/getting-started

func (*Handler) LastTimeBlock

func (h *Handler) LastTimeBlock(c *echo.Context) error

LastTimeBlock draws the latest night's recap as the viewer may read it, or an empty answer that removes the placeholder when no recap was written. GET /campaigns/:id/last-time

func (*Handler) LinkEntityAPI

func (h *Handler) LinkEntityAPI(c *echo.Context) error

LinkEntityAPI links an entity to a session. POST /campaigns/:id/sessions/:sid/entities

func (*Handler) ListGameNightsAPI

func (h *Handler) ListGameNightsAPI(c *echo.Context) error

ListGameNightsAPI returns the game nights in a date window, each with the whole table's answers, for the calendar's day card and event page. GET /campaigns/:id/sessions/nights?from=YYYY-MM-DD&to=YYYY-MM-DD

func (*Handler) ListMyExceptionsAPI

func (h *Handler) ListMyExceptionsAPI(c *echo.Context) error

ListMyExceptionsAPI returns the current user's per-date overrides. GET /campaigns/:id/availability/exceptions

func (*Handler) ListNotificationsAPI

func (h *Handler) ListNotificationsAPI(c *echo.Context) error

ListNotificationsAPI returns the current user's recent notifications as JSON (the bell dropdown renders them client-side). GET /notifications

func (*Handler) ListProposals

func (h *Handler) ListProposals(c *echo.Context) error

ListProposals renders the proposals list for a campaign. GET /campaigns/:id/proposals

func (*Handler) MakeNightFromEventAPI

func (h *Handler) MakeNightFromEventAPI(c *echo.Context) error

MakeNightFromEventAPI makes the game night for one Session-kind event. The request names only the event: its name, date and page are read again here, so a request cannot make a night with words the event does not have. POST /campaigns/:id/sessions/from-event {"eventId": "..."}

func (*Handler) MarkAllNotificationsReadAPI

func (h *Handler) MarkAllNotificationsReadAPI(c *echo.Context) error

MarkAllNotificationsReadAPI marks all of the current user's notifications read. POST /notifications/read-all

func (*Handler) MarkAwayAPI

func (h *Handler) MarkAwayAPI(c *echo.Context) error

MarkAwayAPI marks a stretch of days the caller can't play. PUT /campaigns/:id/availability/away

func (*Handler) MarkNotificationReadAPI

func (h *Handler) MarkNotificationReadAPI(c *echo.Context) error

MarkNotificationReadAPI marks one of the current user's notifications read. POST /notifications/:nid/read

func (*Handler) NextGameBlock

func (h *Handler) NextGameBlock(c *echo.Context) error

NextGameBlock draws the block, or an empty answer that removes the placeholder when the nights cannot be read. A guest of a public campaign gets it only where the owner placed the block on the Guests home. GET /campaigns/:id/next-game

func (*Handler) NightPageAPI

func (h *Handler) NightPageAPI(c *echo.Context) error

NightPageAPI returns a game night's recap and linked pages for its page in the calendar. Linked pages go through the same visibility filter as a night's own page (ADR-055 rule 3): a page the viewer can't open is absent, not named. With ?date= (one of the session's nights) it adds the night's Journal entries the viewer can read and, for the DM, the check-in. GET /campaigns/:id/sessions/:sid/page[?date=YYYY-MM-DD]

func (*Handler) NotificationBadgeAPI

func (h *Handler) NotificationBadgeAPI(c *echo.Context) error

NotificationBadgeAPI returns the unread-count badge as an HTML fragment for the topbar bell's HTMX poll. Empty output means zero unread (nothing shown). GET /notifications/badge

func (*Handler) NudgeAvailabilityAPI

func (h *Handler) NudgeAvailabilityAPI(c *echo.Context) error

NudgeAvailabilityAPI asks every member who has never answered to set their availability, via the bell in the top-right. POST /campaigns/:id/availability/nudge

OWNER / CO-DM ONLY, enforced here by role rather than by route: this is the one availability action that writes into other people's notification lists, so an ungated version would be a campaign-wide broadcast handed to anybody who could reach the URL.

An optional JSON body widens the ask: {"userId": "..."} reminds that one member whatever their state, and {"ask": "confirm"} asks everyone to confirm their times, on the site and by email.

func (*Handler) OpenPollsAPI

func (h *Handler) OpenPollsAPI(c *echo.Context) error

OpenPollsAPI returns the open date polls for the calendar, dates in the zone the calendar asks for (?tz=, else the viewer's own). GET /campaigns/:id/proposals/open

func (*Handler) RSVPSession

func (h *Handler) RSVPSession(c *echo.Context) error

RSVPSession updates the current user's attendance status. POST /campaigns/:id/sessions/:sid/rsvp

func (*Handler) RecordSightingAPI

func (h *Handler) RecordSightingAPI(c *echo.Context) error

RecordSightingAPI answers one night for one page: PUT /campaigns/:id/sessions/:sid/sightings {entityId, date, state, source}.

func (*Handler) RedeemProposalToken

func (h *Handler) RedeemProposalToken(c *echo.Context) error

RedeemProposalToken renders the confirm interstitial for a one-click response token. GET /proposals/respond/:token — no auth, the token is the credential. GET is a pure read: it validates the token, rechecks the proposal is still open (in the service) and the user is still a member (below), then shows a POST form. ApplyProposalToken records the response, so a mail prefetcher's GET never writes.

func (*Handler) RedeemRSVPToken

func (h *Handler) RedeemRSVPToken(c *echo.Context) error

RedeemRSVPToken renders the confirm interstitial for a one-click RSVP token. GET /rsvp/:token — no auth required, token is the credential. GET is a pure read: it validates the token and shows a POST form; ApplyRSVPToken records the RSVP, so a mail scanner prefetching the link can't auto-RSVP.

func (*Handler) RedeemSuggestToken

func (h *Handler) RedeemSuggestToken(c *echo.Context) error

RedeemSuggestToken shows the suggest-a-time form for an emailed "Suggest another time" link. Read-only — nothing is written until the form is submitted, matching every other token route's GET-confirm/POST-apply split (a mail scanner's background GET must never act). GET /rsvp/:token/suggest

func (*Handler) RemindNightAPI

func (h *Handler) RemindNightAPI(c *echo.Context) error

RemindNightAPI asks players to answer one game night, on the site and by email. Only the night's organiser, the campaign owner or a co-Director may. POST /campaigns/:id/sessions/:sid/remind {"date": "YYYY-MM-DD", "userId": optional}

func (*Handler) ReplaceDayExceptionsAPI

func (h *Handler) ReplaceDayExceptionsAPI(c *echo.Context) error

ReplaceDayExceptionsAPI atomically replaces the current user's overrides for one date with a composed set — the backend for the "compose the day" editor. An empty blocks array clears the day. PUT /campaigns/:id/availability/exceptions

func (*Handler) ReplaceFeedTokenAPI

func (h *Handler) ReplaceFeedTokenAPI(c *echo.Context) error

ReplaceFeedTokenAPI mints a new token and drops the old one at once — "if it gets out, replace it: the old link stops working immediately." POST /campaigns/:id/sessions/feed/token/replace

func (*Handler) RespondOptionAPI

func (h *Handler) RespondOptionAPI(c *echo.Context) error

RespondOptionAPI records a member's response to one option, then notifies the proposer. Returns the refreshed detail fragment so the card re-renders in place. POST /campaigns/:id/proposals/:pid/options/:oid/respond

func (*Handler) RestoreEventAPI

func (h *Handler) RestoreEventAPI(c *echo.Context) error

RestoreEventAPI is the Undo of "Not this one": the event is offered on the strip again. It never reads the calendar: an event that was deleted has no dismissal left to remove, and removing nothing is still a success. DELETE /campaigns/:id/sessions/event-dismissals/:eid

func (*Handler) RestoreSessionAPI

func (h *Handler) RestoreSessionAPI(c *echo.Context) error

RestoreSessionAPI undoes a soft delete (co-Director/Owner — see routes.go) and tells everyone who had answered before it was cancelled that it's back on. The campaign Trash restores through the same service call. POST /campaigns/:id/sessions/:sid/restore

func (*Handler) SaveMyAvailabilityAPI

func (h *Handler) SaveMyAvailabilityAPI(c *echo.Context) error

SaveMyAvailabilityAPI replaces the current user's recurring pattern. PUT /campaigns/:id/availability/mine

func (*Handler) SetCalendarFinder

func (h *Handler) SetCalendarFinder(f RealWorldCalendarFinder)

SetCalendarFinder wires the lookup GameNightsLink uses. Without it every game-night link falls back to the Calendar app.

func (*Handler) SetCampaignReader

func (h *Handler) SetCampaignReader(cr CampaignReader)

SetCampaignReader wires the campaign read used for co-DM labelling. Nil-safe: with no reader the roster still labels roles correctly, it just cannot mark the co-DM grant — which is a degradation, not a leak, because the grant only ever ADDS a marker.

func (*Handler) SetFeedSettingsAPI

func (h *Handler) SetFeedSettingsAPI(c *echo.Context) error

SetFeedSettingsAPI is the owner's campaign-wide kill switch. PUT /campaigns/:id/sessions/feed-settings

func (*Handler) SetHeroChecker

func (h *Handler) SetHeroChecker(c HeroChecker)

SetHeroChecker wires the check behind the Getting started block's hero step. Without it the step is left out.

func (*Handler) SetMailSender

func (h *Handler) SetMailSender(ms MailSender, baseURL string)

SetMailSender wires the SMTP mail sender for RSVP email notifications.

func (*Handler) SetMemberLister

func (h *Handler) SetMemberLister(ml campaigns.MemberLister)

SetMemberLister wires a campaign member lister for RSVP invite-all.

func (*Handler) SetMentionHider

func (h *Handler) SetMentionHider(m sanitize.MentionHider)

SetMentionHider injects the check that hides mentions of pages a reader can't open. Unset, every mention in a served recap is hidden.

func (*Handler) SetNightEntryService

func (h *Handler) SetNightEntryService(s NightEntryService)

SetNightEntryService wires the night's Journal entries and the check-in. Without it a night's page shows neither.

func (*Handler) SetPlacementChecker

func (h *Handler) SetPlacementChecker(p campaigns.BlockPlacementChecker)

SetPlacementChecker wires the check a guest-facing block asks for a page placement.

func (*Handler) SetRSVPExcludedAPI

func (h *Handler) SetRSVPExcludedAPI(c *echo.Context) error

SetRSVPExcludedAPI is the Director's own "leave myself out of the tally" switch (operator answer #3: the Director counts like any member, with a switch to leave themselves out). Self-only and organizer/owner-only — the service enforces that, this handler just passes the caller's own id and campaign role through. PUT /campaigns/:id/sessions/:sid/rsvp-exclude

func (*Handler) SetRecipientFilter

func (h *Handler) SetRecipientFilter(f RecipientFilter)

SetRecipientFilter wires people's notification choices into the emails.

func (*Handler) SetSessionEventSource

func (h *Handler) SetSessionEventSource(s SessionEventSource)

SetSessionEventSource wires the lookup behind the Game nights strip. Without it the strip is empty and making a night from an event is refused.

func (*Handler) SetSightingService

func (h *Handler) SetSightingService(s SightingService)

SetSightingService wires per-night sightings. Without it the sightings routes answer 404.

func (*Handler) SetUserDirectory

func (h *Handler) SetUserDirectory(ud UserDirectory)

SetUserDirectory wires the auth service for viewer-zone resolution. Called from RegisterRoutes with the auth service already passed in, so no extra app-wiring is required.

func (*Handler) SetWorldDateWorder

func (h *Handler) SetWorldDateWorder(w WorldDateWorder)

SetWorldDateWorder wires the wording of a date-less night's in-world day.

func (*Handler) ShowAvailability

func (h *Handler) ShowAvailability(c *echo.Context) error

ShowAvailability renders the availability page shell (paint grid + DM overlay). The interactive grid/heatmap is rendered client-side from the JSON APIs below, matching the signed mockup encoding. GET /campaigns/:id/availability

func (*Handler) ShowProposal

func (h *Handler) ShowProposal(c *echo.Context) error

ShowProposal renders one proposal's detail: options in the viewer's zone, the viewer's own responses, tallies, and (owner only) the per-responder breakdown. GET /campaigns/:id/proposals/:pid

func (*Handler) ShowSession

func (h *Handler) ShowSession(c *echo.Context) error

ShowSession renders a session detail page. GET /campaigns/:id/sessions/:sid

func (*Handler) SightingNightsAPI

func (h *Handler) SightingNightsAPI(c *echo.Context) error

SightingNightsAPI returns the played game nights, for a page's Last seen to draw every night and let the DM answer one: GET /campaigns/:id/sessions/sightings/nights.

func (*Handler) SightingsAPI

func (h *Handler) SightingsAPI(c *echo.Context) error

SightingsAPI returns when the party saw one page: GET /campaigns/:id/sessions/sightings?entity=ID.

func (*Handler) UnlinkEntityAPI

func (h *Handler) UnlinkEntityAPI(c *echo.Context) error

UnlinkEntityAPI removes an entity link from a session. DELETE /campaigns/:id/sessions/:sid/entities/:eid

func (*Handler) UpdateRecapAPI

func (h *Handler) UpdateRecapAPI(c *echo.Context) error

UpdateRecapAPI saves the session recap (post-session write-up visible to all members). The page editor sends entry/entry_html; the calendar's plain box sends recap/recap_html. A body with both uses the editor's. PUT /campaigns/:id/sessions/:sid/recap

func (*Handler) UpdateSessionAPI

func (h *Handler) UpdateSessionAPI(c *echo.Context) error

UpdateSessionAPI updates a session. PUT /campaigns/:id/sessions/:sid

func (*Handler) WhenWeCouldPlayBlock

func (h *Handler) WhenWeCouldPlayBlock(c *echo.Context) error

WhenWeCouldPlayBlock draws the block, or an empty answer that removes the placeholder when a source cannot be read. Members see their own answers and the table's usual free times; a guest of a public campaign (only when the owner placed the block on the Guests home) sees set nights as date and time. GET /campaigns/:id/when-we-could-play

func (*Handler) WhenWePlayBlock

func (h *Handler) WhenWePlayBlock(c *echo.Context) error

WhenWePlayBlock draws the windows most of the table is free, or an empty answer that removes the placeholder when nobody has said enough yet. GET /campaigns/:id/when-we-play

type HeroChecker

type HeroChecker interface {
	// PlayingHero reports whether heroes are claimed in this campaign at all
	// (tracked) and whether userID plays one (has).
	PlayingHero(ctx context.Context, campaignID, userID string) (tracked, has bool, err error)
}

HeroChecker says whether a member plays a hero. Implemented in internal/app over the entities service, so this plugin reads no pages.

type LaneSegment

type LaneSegment struct {
	DayIndex    int    `json:"day"`   // 0..6 (column offset from WeekStart)
	StartMinute int    `json:"start"` // viewer-zone minute-of-day
	EndMinute   int    `json:"end"`
	State       string `json:"state"` // available | preferred
}

LaneSegment is one contiguous availability run for a member on one column, already converted to the viewer's zone.

type LastSeenView

type LastSeenView struct {
	// Seen is how many nights count, the "N nights" at the line's end.
	Seen int
	// What is the newest sighting's name; "Not seen yet" when there is none.
	What string
	// When is how long ago that was; empty when there is no dated sighting.
	When string
	// Review is how many nights are suggested to the DM; always 0 for a player.
	Review int
}

LastSeenView is what the block's server-rendered line says for one viewer. It is built from SightingsFor's answer for that viewer, so it holds nothing the viewer could not already fetch from the sightings route.

func BuildLastSeenView

func BuildLastSeenView(s *Sightings, now time.Time) LastSeenView

BuildLastSeenView turns a viewer's sightings into the block's line. The newest sighting leads (the service sorts undated series last, so a dated night always outranks a series-wide link).

type LocalSlot

type LocalSlot struct {
	StartsAtUTC string `json:"startsAtUtc"` // RFC-3339 UTC (stable key)
	EndsAtUTC   string `json:"endsAtUtc"`
	Date        string `json:"date"`      // YYYY-MM-DD the slot starts on, in the viewer zone
	DateLabel   string `json:"dateLabel"` // e.g. "Sat, Jul 18"
	TimeLabel   string `json:"timeLabel"` // e.g. "7:00 PM – 11:00 PM"
	TZLabel     string `json:"tzLabel"`   // the viewer zone the labels are in
}

LocalSlot is a UTC option range projected into a viewer zone for display.

type MailSender

type MailSender interface {
	SendHTMLMail(ctx context.Context, to []string, subject, plainBody, htmlBody string) error
	IsConfigured(ctx context.Context) bool
}

MailSender sends email notifications. Wraps the SMTP service interface.

type MemberAvailabilityStatus

type MemberAvailabilityStatus struct {
	CampaignID string
	UserID     string
	AnsweredAt time.Time
	TZ         string
}

MemberAvailabilityStatus records that a member ANSWERED the availability question for a campaign — not what they answered.

It exists because absence of AvailabilityBlock rows means "unavailable", so without this a member who never opened the page and a member who is genuinely never free are the same row-count: zero. They are not the same fact, and the difference is the one the Director actually needs when a week looks empty. Answering with an EMPTY grid writes a row here, which is why this cannot be derived from the block tables.

type MyAvailabilityResponse

type MyAvailabilityResponse struct {
	TZ     string                 `json:"tz"`
	Blocks []AvailabilityBlockDTO `json:"blocks"`
	// Answered is false until the member has saved once. The grid uses it to
	// tell "you have not answered yet" apart from "you answered: never free",
	// which look identical in Blocks (both empty).
	Answered bool `json:"answered"`
	// AnsweredAt is when they last saved or confirmed (RFC3339), so a
	// "confirm your times" ask can tell whether they have answered it.
	AnsweredAt string `json:"answeredAt,omitempty"`
	// WeekALabel/WeekBLabel are the YYYY-MM-DD Sundays that start the next week
	// of each alternating track, so the picker can offer two dates the member
	// can find on a calendar instead of the words "odd" and "even".
	WeekALabel string `json:"weekALabel"`
	WeekBLabel string `json:"weekBLabel"`
}

MyAvailabilityResponse is the current user's own recurring pattern, returned to seed the paint grid.

type NextNight

type NextNight struct {
	SessionID string
	Name      string
	// Date is YYYY-MM-DD and Time is "HH:MM" ("" when the night has no start
	// time), both on the wall clock of TZ.
	Date string
	Time string
	// TZ is the IANA zone the night was scheduled in; "" means UTC.
	TZ string
	// At is the night's start instant (end of day when no time is set), so a
	// caller can say "in 3 days" without redoing the zone arithmetic.
	At time.Time
}

NextNight is the soonest game night still ahead, with no roster: the header widget needs only a name and a moment, and building a roster costs a read per member per night on every page load.

type NightAnswer

type NightAnswer struct {
	UserID string `json:"userId"`
	Name   string `json:"name"`
	Answer string `json:"answer"`
	Note   string `json:"note,omitempty"`
	// Excluded is the organizer's own "leave me out of the count" switch.
	Excluded bool `json:"excluded"`
	// Recheck: the night moved after this member answered.
	Recheck bool `json:"recheck"`
	// Carried: a yes to a proposed time, not yet confirmed as Going.
	Carried bool `json:"carried"`
}

NightAnswer is one member's answer to one game night.

type NightAudience

type NightAudience struct {
	// UserIDs said Going or Maybe to a night that has not happened yet.
	UserIDs []string
	// Night is the session as the notice should describe it: a repeating
	// series carries its next upcoming date instead of the series' first.
	Night *Session
}

NightAudience is who hears about a change to a game night and which night the notice names.

type NightBellCampaigns

type NightBellCampaigns interface {
	// GameNightsOn reports whether the campaign has Game nights turned on.
	GameNightsOn(ctx context.Context, campaignID string) (bool, error)
	// BellMembers lists the campaign's members.
	BellMembers(ctx context.Context, campaignID string) ([]NightBellMember, error)
}

NightBellCampaigns is the campaign side of the bells, implemented by an adapter over the campaigns and addons services.

type NightBellMember

type NightBellMember struct {
	UserID string
	Role   int
}

NightBellMember is one campaign member as the bells need them. Role is the visibility role: a co-DM counts as Owner.

type NightBellNotifier

type NightBellNotifier interface {
	NotifyUsersWithDetail(ctx context.Context, userIDs []string, campaignID, ntype, message, detail, link string) error
}

NightBellNotifier writes bell items, honouring people's choices.

type NightBellRoster

type NightBellRoster interface {
	ListGameNights(ctx context.Context, campaignID, from, to, today string, members []NightMember) ([]GameNight, error)
}

NightBellRoster reads who has answered a night, the same list the calendar shows.

type NightBellSessions

type NightBellSessions interface {
	GetSession(ctx context.Context, id string) (*Session, error)
}

NightBellSessions loads a session with its linked pages, which the check-in needs.

type NightDateNote

type NightDateNote struct {
	NoRealDate bool
	// Words is "No real date yet · 14 Hammer, 1492" when NoRealDate.
	Words string
	// EventName and EventHref name and open the linked calendar event, empty
	// when the night has none or the viewer may not see that event.
	EventName string
	EventHref string
}

NightDateNote is what a night's page says about its date when the date is not a plain real one: that there is none yet (with the in-world day), and the calendar event the night was made from.

type NightEntryNight

type NightEntryNight struct {
	NightEntryRow
	Name string
	Time string
	TZ   string
}

NightEntryNight is an entry with the night it belongs to.

type NightEntryRepository

type NightEntryRepository interface {
	// InsertNightEntry records an entry; one already recorded for that
	// night and member is left as it is.
	InsertNightEntry(ctx context.Context, row NightEntryRow) error
	// ListNightEntries returns every entry recorded for one night.
	ListNightEntries(ctx context.Context, sessionID, occurrenceDate string) ([]NightEntryRow, error)
	// ListUserNightEntries returns userID's entries on the given sessions.
	ListUserNightEntries(ctx context.Context, userID string, sessionIDs []string) ([]NightEntryRow, error)
	// ListNightEntriesByNote returns the entries among noteIDs that belong
	// to a live game night of the campaign, with the night's name and time.
	ListNightEntriesByNote(ctx context.Context, campaignID string, noteIDs []string) ([]NightEntryNight, error)
	// ListBellNights returns, across every campaign, the sessions that are
	// planned or completed and may have a night in [from, to].
	ListBellNights(ctx context.Context, from, to string) ([]Session, error)
	// ClaimNightBell records that one bell item goes to userID for one night;
	// false means it was already claimed and must not be sent again.
	ClaimNightBell(ctx context.Context, sessionID, date, userID, kind string) (bool, error)
}

NightEntryRepository stores which Journal note is whose entry for which game night (session_night_entries).

func NewNightEntryRepository

func NewNightEntryRepository(db *sql.DB) NightEntryRepository

NewNightEntryRepository creates the night entries repository.

type NightEntryRow

type NightEntryRow struct {
	SessionID string
	Date      string
	UserID    string
	NoteID    string
}

NightEntryRow is one recorded entry.

type NightEntryService

type NightEntryService interface {
	// ForNight returns the entries v can read for one night of sess (date is
	// one of its occurrences) and, for the DM, the check-in. sess must carry
	// its linked pages. The viewer's own entry is made first when it is due.
	ForNight(ctx context.Context, sess *Session, date string, v permissions.Viewer, now time.Time) (*NightNotes, error)
	// EnsureEntries makes v's entries for every night that is due and has
	// none yet. An entry its writer deleted is not made again.
	EnsureEntries(ctx context.Context, campaignID string, v permissions.Viewer, now time.Time) error
	// Tags returns, for those of noteIDs that are game-night entries in the
	// campaign, the night each belongs to.
	Tags(ctx context.Context, campaignID string, noteIDs []string, now time.Time) (map[string]NightTag, error)
	// SetBells wires the game-night bell items; see night_bells.go.
	SetBells(campaigns NightBellCampaigns, sessions NightBellSessions, notify NightBellNotifier)
	// SetBellRoster adds the day-before nudge to members who haven't said
	// whether they are coming; see night_bells.go.
	SetBellRoster(roster NightBellRoster)
	// SendBells sends the bell items due at now that haven't gone out.
	SendBells(ctx context.Context, now time.Time) error
}

NightEntryService gives members their game-night entries and reads them.

func NewNightEntryService

func NewNightEntryService(sessions nightSessionLister, entries NightEntryRepository, journal NightJournal, pages NightPageNamer, sightings SightingRepository) NightEntryService

NewNightEntryService creates the service. All five are required.

type NightEntryView

type NightEntryView struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	AuthorID string `json:"authorId"`
	// AuthorName is filled by the handler from the member list.
	AuthorName string `json:"authorName,omitempty"`
	Audience   string `json:"audience"`
}

NightEntryView is one entry in "Entries for this night".

type NightJournal

type NightJournal interface {
	// CreateEntry makes v's entry with this id and title, in their Game
	// nights folder. An entry that already exists is not an error.
	CreateEntry(ctx context.Context, campaignID string, v permissions.Viewer, id, title string) error
	// ReadableEntries returns the notes among ids that v can read, in the
	// order given; the rest are left out.
	ReadableEntries(ctx context.Context, campaignID string, v permissions.Viewer, ids []string) ([]NightNote, error)
}

NightJournal is the notes side of game-night entries, implemented by an adapter over the notes widget so every read applies the notes' own visibility rule.

type NightMember

type NightMember struct {
	UserID string
	Name   string
}

NightMember is one campaign member a game night's roster lists, whether or not they have answered.

type NightNote

type NightNote struct {
	ID        string
	Title     string
	AuthorID  string
	UpdatedAt time.Time
	// Audience is the note's visibility: private, gm, party or custom.
	Audience string
	// PageIDs are the pages the note links, in order.
	PageIDs []string
	// Lines holds, per linked page, the line of the note that names it.
	Lines map[string]string
}

NightNote is one game-night entry as the night's page needs it. The notes widget fills it through NightJournal; PageIDs and Lines come from the page links in its body.

type NightNotes

type NightNotes struct {
	Entries []NightEntryView `json:"entries"`
	// CheckIn is set only for a viewer who sees DM-only content, once the
	// night has started.
	CheckIn []CheckInPerson `json:"checkIn,omitempty"`
}

NightNotes is what a night's page shows from the entries: the ones the viewer can read, and for the DM the after-night check-in.

type NightPageNamer

type NightPageNamer interface {
	PageNames(ctx context.Context, campaignID string, v permissions.Viewer, ids []string) (map[string]string, error)
}

NightPageNamer names the pages a viewer may see; any other id is absent from the result.

type NightReminder

type NightReminder struct {
	Result  NudgeResult
	UserIDs []string
	Night   GameNight
}

NightReminder is who RemindNight reached: their names for the page, and their ids so the handler can email the same people.

type NightTag

type NightTag struct {
	SessionID string
	Date      string
	Name      string
	Time      string
	// Started is whether the night has begun, so the entry is being read.
	Started bool
}

NightTag is the night a Journal entry belongs to, for the Journal's tag.

type NightTally

type NightTally struct {
	Going    int `json:"going"`
	Maybe    int `json:"maybe"`
	Cant     int `json:"cant"`
	NoAnswer int `json:"noAnswer"`
}

NightTally counts a night's answers. Excluded members count nowhere.

type Notification

type Notification struct {
	ID         string
	UserID     string
	CampaignID *string
	Type       string
	Payload    *string // JSON blob (render context)
	Link       *string
	ReadAt     *time.Time
	CreatedAt  time.Time
}

Notification is one in-app notification row. Generic and removable (T-B2); the scheduler is its only writer.

type NudgeResult

type NudgeResult struct {
	Notified []string `json:"notified"` // display names, in roster order
	Skipped  int      `json:"skipped"`  // members who had already answered
}

NudgeResult reports what a nudge actually did — how many members were asked, and who. Returned so the Director sees the outcome rather than a silent success that may have notified nobody.

type OccurrenceRSVP

type OccurrenceRSVP struct {
	ID                int
	SessionID         string
	UserID            string
	OccurrenceDate    string // YYYY-MM-DD
	Status            string
	Note              *string
	ExcludedFromCount bool
	NeedsRecheck      bool
	RespondedAt       *time.Time

	// Joined data, populated by ListOccurrenceRSVPs for rendering a roster.
	DisplayName string
	AvatarPath  *string
}

OccurrenceRSVP is one member's answer to a SPECIFIC night of a repeating session — the per-occurrence twin of Attendee. See session_occurrence_rsvps.

type OverlayDay

type OverlayDay struct {
	Date    string        `json:"date"`    // YYYY-MM-DD
	Weekday int           `json:"weekday"` // 0=Sun..6=Sat
	Hours   []OverlayHour `json:"hours"`   // 24 entries; index == hour 0..23
}

OverlayDay is one column: a real date and its 24 per-hour aggregate cells.

type OverlayHour

type OverlayHour struct {
	Free      int      `json:"free"`
	Prefer    int      `json:"prefer"`
	FreeIDs   []string `json:"freeIds,omitempty"`   // detail only
	PreferIDs []string `json:"preferIds,omitempty"` // detail only
}

OverlayHour is the aggregate for one hour cell in the viewer's zone. Free counts members available (preferred implies available); Prefer is the subset who actively prefer it. The client derives the ★ full-house-and-keen marker from Free==TotalMembers && Prefer==TotalMembers.

type OverlayMember

type OverlayMember struct {
	UserID string  `json:"userId"`
	Name   string  `json:"name"`
	Color  string  `json:"color"`
	Avatar *string `json:"avatar,omitempty"`
	Role   string  `json:"role"` // campaigns.Role.DisplayName(): Owner | Scribe | Player
	// IsCoDM is the DM grant (campaigns.CampaignContext.CanControlWorldState's
	// second clause). A co-DM is not a role — it is a capability laid over one —
	// so it rides beside Role rather than replacing it.
	IsCoDM bool `json:"isCoDm,omitempty"`
	// TZ is the member's stored IANA zone, EMPTY when they have not set one.
	// Empty is a first-class state and must stay one: users.timezone is
	// NULLABLE, and a clock rendered for a zone-less member as a UTC guess
	// would be a guess presented as fact. Consumers print a "zone not set"
	// repair and no clock.
	//
	// It is a DTO field and deliberately NOT a campaign_members column: zone
	// is a user-account fact, campaign-independent, and duplicating it per
	// membership would create a second copy that can go stale.
	TZ    string        `json:"tz,omitempty"`
	Lanes []LaneSegment `json:"lanes,omitempty"`
	// HasAnswered separates "answered: never free" from "has not answered" —
	// both of which render as empty Lanes and must not be presented as the
	// same fact.
	HasAnswered bool `json:"hasAnswered"`
	// OffDays are the columns (0..6) the member marked as a day they can't
	// play although their usual hours would have had them free, so the DM
	// can tell a change from a member who is never free that day.
	OffDays []int `json:"offDays,omitempty"`
}

OverlayMember is one member's roster entry: a stable color for their lane plus, for the DM, their projected per-day availability lanes.

Role carries campaigns.Role.DisplayName() (Owner / Scribe / Player), resolved by the handler from the campaign roster, never derived here from IsOwner alone — that would mislabel a co-DM as "player" on the one surface whose subject is who-may-see-what. IsCoDM carries the DM grant separately so a consumer can mark it without the role string encoding two facts.

type ProposalOptionInput

type ProposalOptionInput struct {
	Date        string `json:"date"` // YYYY-MM-DD (wall-clock date in the request's TZ)
	StartMinute int    `json:"startMinute"`
	EndMinute   int    `json:"endMinute"`
}

ProposalOptionInput is one candidate slot as a viewer-zone wall-clock: a date (YYYY-MM-DD in TZ) plus a [start,end) minute range from local midnight.

type ProposalOptionView

type ProposalOptionView struct {
	Option     SlotProposalOption
	Local      LocalSlot
	YesCount   int
	NoCount    int
	MaybeCount int
	MyResponse string                  // "", yes, no, maybe
	Responders []ProposalResponderView // detail only (owner)
}

ProposalOptionView is one option with its response tally + the viewer's own choice, plus (detail only) the per-responder breakdown.

type ProposalResponderView

type ProposalResponderView struct {
	UserID   string
	Name     string
	Response string
}

ProposalResponderView is one member's response, shown to the owner only.

type ProposalSummary

type ProposalSummary struct {
	Proposal    SlotProposal
	OptionCount int
	ResponderN  int  // distinct members who responded to any option
	MyResponded bool // whether the viewer has responded to any option
}

ProposalSummary is one row in the proposals list.

type ProposalTokenContext

type ProposalTokenContext struct {
	Token    *SlotProposalToken
	Proposal *SlotProposal
	Option   *SlotProposalOption
}

ProposalTokenContext is the resolved state behind a one-click response token: the token itself, its proposal (for the campaign + open/closed check + confirm page), and the option (for the slot label). Returned by ValidateProposalToken.

type ProposalView

type ProposalView struct {
	Proposal      SlotProposal
	ViewerTZ      string
	IncludeDetail bool
	Options       []ProposalOptionView
}

ProposalView is the full proposal detail for one viewer: options with tallies, the viewer's own response per option, and — for the owner (includeDetail) — who responded what.

type RSVPToken

type RSVPToken struct {
	ID        int        `json:"id"`
	Token     string     `json:"token"`
	SessionID string     `json:"session_id"`
	UserID    string     `json:"user_id"`
	Action    string     `json:"action"` // accepted, declined, tentative
	UsedAt    *time.Time `json:"used_at,omitempty"`
	ExpiresAt time.Time  `json:"expires_at"`
	CreatedAt time.Time  `json:"created_at"`
}

RSVPToken holds a one-time-use RSVP token for email-based responses.

type RSVPTokens

type RSVPTokens struct {
	Accept  string
	Maybe   string
	Decline string
	Suggest string
}

RSVPTokens are one member's single-use answer links for one game night.

type RealWorldCalendarFinder

type RealWorldCalendarFinder interface {
	RealWorldCalendarID(ctx context.Context, campaignID string, role int, userID string) (string, error)
}

RealWorldCalendarFinder names the calendar game nights are answered in: the campaign's real-world (wall-clock) calendar that this viewer may see, or "" when there is none. Implemented in internal/app over the calendar service, so this plugin never imports the calendar plugin.

type RecapView

type RecapView struct {
	// Open shows the recap card (members only; see recapOpen).
	Open bool
	// StartWriting opens the recap editor ready to type.
	StartWriting bool
	// Played marks a planned night already behind the viewer (isPlayed).
	Played bool
}

RecapView says how a night's page shows its recap.

type RecipientFilter

type RecipientFilter interface {
	AllowedRecipients(ctx context.Context, ids []string, category string, ch notifyprefs.Channel) []string
}

RecipientFilter narrows recipients to those whose notification choices allow this category on this channel, keeping their order. Implemented by the auth service.

type RecordSightingInput

type RecordSightingInput struct {
	SessionID string `json:"-"`
	Date      string `json:"date"`
	EntityID  string `json:"entityId"`
	State     string `json:"state"`
	Source    string `json:"source"`
}

RecordSightingInput is one answer for one night and page.

type ReplaceDayExceptionsRequest

type ReplaceDayExceptionsRequest struct {
	OnDate string              `json:"onDate"` // YYYY-MM-DD
	TZ     string              `json:"tz"`
	Blocks []ExceptionBlockDTO `json:"blocks"`
}

ReplaceDayExceptionsRequest replaces ALL of a member's overrides for one date in a single atomic call — the storage side of the "compose the day" editor. The client pre-fills the editor with the effective day (recurring pattern) and sends the whole composed set back, so marking one hour busy re-sends the rest rather than erasing it. An empty Blocks reverts the day to the recurring pattern.

type RescheduleSuggestion

type RescheduleSuggestion struct {
	ID             int
	SessionID      string
	UserID         string
	OccurrenceDate *string // set only when suggesting against one night of a series
	SuggestedDate  string
	SuggestedTime  *string
	Note           *string
	CreatedAt      time.Time
}

RescheduleSuggestion is a member's "suggest another time" reply, recorded from the emailed suggest-token flow (session_reschedule_suggestions).

type RespondRequest

type RespondRequest struct {
	Response string `json:"response" form:"response"` // yes | no | maybe
}

RespondRequest records a member's response to a single option. Bound from either a JSON body or an HTMX form post (hx-vals), so it carries both tags.

type RosterEntry

type RosterEntry struct {
	UserID string
	Name   string
	// Role is campaigns.Role.DisplayName(): Owner | Scribe | Player.
	Role string
	// IsOwner is the ordering key (owners first), not the label.
	IsOwner bool
	// IsCoDM is the campaign's DM grant — a capability over a role, not a role.
	IsCoDM bool
	// TZ is the stored IANA zone, EMPTY when unset. Empty is a state, not a
	// default: see OverlayMember.TZ.
	TZ string
	// HasAnswered is whether this member has ever saved an availability
	// pattern. Party-visible by the same rule as name/role/zone: knowing that
	// somebody has not answered yet says nothing about WHEN they are free,
	// which is the fact the lanes gate protects.
	HasAnswered bool
}

RosterEntry is one member of the overlay roster with NO availability attached — the PARTY-VISIBLE half of the roster.

A member's name, role, zone and answer are visible to the whole party, while their availability LANES are owner / co-DM only. WeekOverlay.Members carries both fused together and is populated only under includeDetail, so a player-facing surface that needs the names cannot use it; this type is what a player is entitled to, and nothing on it is gated.

The ORDER is the identity key: hue and pattern are taken from the index, so the order must not depend on availability, tally or answer.

type SaveAvailabilityRequest

type SaveAvailabilityRequest struct {
	TZ     string                 `json:"tz"`
	Blocks []AvailabilityBlockDTO `json:"blocks"`
}

SaveAvailabilityRequest is the bulk save of a member's recurring pattern. The whole pattern is replaced atomically (replace-all), so the client always sends the complete current grid.

type Session

type Session struct {
	ID            string  `json:"id"`
	CampaignID    string  `json:"campaign_id"`
	Name          string  `json:"name"`
	Summary       *string `json:"summary,omitempty"`
	Notes         *string `json:"-"`                        // ProseMirror JSON, GM-only.
	NotesHTML     *string `json:"notes_html,omitempty"`     // Pre-rendered HTML.
	Recap         *string `json:"-"`                        // ProseMirror JSON, visible to all members.
	RecapHTML     *string `json:"recap_html,omitempty"`     // Pre-rendered HTML.
	ScheduledDate *string `json:"scheduled_date,omitempty"` // YYYY-MM-DD format.
	// ScheduledTime is the wall-clock start time as "HH:MM" (24-hour), zone-less
	// like ScheduledDate. Set from a confirmed proposal's winning UTC instant
	// (converted to the confirmer's zone) or the create/edit modal. nil means
	// no time set.
	ScheduledTime *string `json:"scheduled_time,omitempty"`
	// ScheduledTZ is the IANA zone ScheduledTime was set in — the organizer's
	// zone at confirm/create time (game-night server change #1). Nil for
	// every row that predates it and for a manual session whose creator's
	// zone was never captured; a viewer with no zone of their own falls back
	// to THIS zone for display, never UTC and never a calendar's own zone
	// (a session is not necessarily tied to one calendar row).
	ScheduledTZ   *string `json:"scheduled_tz,omitempty"`
	CalendarYear  *int    `json:"calendar_year,omitempty"`
	CalendarMonth *int    `json:"calendar_month,omitempty"`
	CalendarDay   *int    `json:"calendar_day,omitempty"`
	// CalendarID names the calendar the in-world date above is a position
	// in. Month and day are positions, so without it the same numbers mean
	// different dates in a campaign with more than one calendar. The service
	// stamps it whenever a complete in-world date is saved and clears it
	// when the date is cleared; no request body carries it. Only FindByID
	// loads it (the load-merge-write path needs it); list queries leave it nil.
	CalendarID *string `json:"calendar_id,omitempty"`
	// CalendarEventID is the calendar Session event this night was made from,
	// nil for any other night. Set at creation only and never by a request
	// body, so an update cannot move or clear it; the unique index behind it
	// is what keeps one event to one night.
	CalendarEventID *string `json:"calendar_event_id,omitempty"`
	Status          string  `json:"status"`

	// Recurrence fields for repeating sessions (e.g. "every other Saturday").
	IsRecurring         bool    `json:"is_recurring"`
	RecurrenceType      *string `json:"recurrence_type,omitempty"`        // weekly, biweekly, monthly, custom
	RecurrenceInterval  int     `json:"recurrence_interval,omitempty"`    // N for "every N weeks" (custom type)
	RecurrenceDayOfWeek *int    `json:"recurrence_day_of_week,omitempty"` // 0=Sun, 1=Mon, ..., 6=Sat
	RecurrenceEndDate   *string `json:"recurrence_end_date,omitempty"`    // YYYY-MM-DD when recurrence stops

	SortOrder int       `json:"sort_order"`
	CreatedBy string    `json:"created_by"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	// DeletedAt marks a soft-deleted (cancelled/removed) session, restorable
	// by a co-Director/Owner. Nil means live. Every repository read filters
	// deleted_at IS NULL except the restore path.
	DeletedAt *time.Time `json:"-"`

	// Joined data (not always populated).
	Attendees   []Attendee      `json:"attendees,omitempty"`
	Entities    []SessionEntity `json:"entities,omitempty"`
	CreatorName string          `json:"creator_name,omitempty"`
}

Session represents a game session for a campaign.

func (*Session) AcceptsRSVP

func (s *Session) AcceptsRSVP() bool

AcceptsRSVP reports whether members may still answer this session. A completed or cancelled night is a record of who came, not a question, so answering it would count a player at a game they never played.

func (*Session) FormatScheduledDate

func (s *Session) FormatScheduledDate() string

FormatScheduledDate returns a human-readable date string like "Sat, Mar 8, 2028" from the YYYY-MM-DD scheduled_date field, with the wall-clock time appended ("Sat, Mar 8, 2028 · 7:00 PM") when scheduled_time is set. Returns empty string if no date is set.

func (*Session) FormatScheduledFor

func (s *Session) FormatScheduledFor(viewerTZ string) string

FormatScheduledFor is how a page shows a game night's date and time to one viewer. With the viewer's zone and the organizer's both known, the moment is converted to the viewer's clock and labelled ("Tue, Oct 27, 2026 · 6:00 PM CDT"); otherwise it is the organizer's clock with the organizer's zone (FormatScheduledWhen), so a page never shows a bare time that a reader in another zone could take for their own.

func (*Session) FormatScheduledTime

func (s *Session) FormatScheduledTime() string

FormatScheduledTime renders the "HH:MM" (24-hour) scheduled_time as a friendly 12-hour clock ("7:00 PM"), or "" if unset/unparseable. Zone-less, matching the zone-less scheduled_date (the confirmed slot's wall-clock for the group).

func (*Session) FormatScheduledWhen

func (s *Session) FormatScheduledWhen() string

FormatScheduledWhen is FormatScheduledDate plus the zone the time was set in ("Sat, Oct 10, 2026 · 7:00 PM CDT"), for places like the invite email that a reader sees outside Chronicle, with no page converting the time to theirs. Without a stored zone or time it is FormatScheduledDate unchanged.

func (*Session) GetCampaignID

func (s *Session) GetCampaignID() string

GetCampaignID returns the campaign this session belongs to. Implements middleware.CampaignScoped for generic IDOR protection.

func (*Session) HasCalendarDate

func (s *Session) HasCalendarDate() bool

HasCalendarDate returns true if the session has an in-game date set.

func (*Session) IsPlanned

func (s *Session) IsPlanned() bool

IsPlanned returns true if the session hasn't happened yet.

func (*Session) RecurrenceLabel

func (s *Session) RecurrenceLabel() string

RecurrenceLabel returns a human-readable label for the recurrence pattern. e.g. "Every week", "Every 2 weeks", "Monthly".

type SessionEntity

type SessionEntity struct {
	ID        int    `json:"id"`
	SessionID string `json:"session_id"`
	EntityID  string `json:"entity_id"`
	Role      string `json:"role"` // mentioned, encountered, key

	// Joined data.
	EntityName string `json:"entity_name,omitempty"`
	EntitySlug string `json:"entity_slug,omitempty"`
}

SessionEntity represents an entity linked to a session.

type SessionEvent

type SessionEvent struct {
	ID         string
	Name       string
	CalendarID string
	Year       int
	Month      int
	Day        int
	// When is the date in the calendar's own words ("14 Hammer, 1492"),
	// worded by the calendar since month names are its.
	When string
	// RealDate is YYYY-MM-DD when the event sits on a real-life calendar, so
	// its date is a real one and can be the night's date. Empty for a story
	// calendar, whose date is not a real day.
	RealDate string
	// EntityID and EntityName are the page the event is linked to, "" if none.
	EntityID   string
	EntityName string
}

SessionEvent is a calendar event of the Session kind, as the sessions plugin needs it. The calendar's event is a day in the story; a game night is a real evening players answer, so the two are separate records and this is only what is carried across.

type SessionEventSource

type SessionEventSource interface {
	SessionEvents(ctx context.Context, campaignID string, role int) ([]SessionEvent, error)
}

SessionEventSource lists the campaign's Session-kind events. Implemented in internal/app over the calendar service, so this plugin never imports the calendar plugin. role is the viewer's, so an event they cannot see is never offered.

type SessionGroup

type SessionGroup struct {
	Key      string // "upcoming", "played", "completed", "cancelled"
	Label    string
	Sessions []Session
}

SessionGroup is one heading on the Sessions list and the nights under it.

type SessionListData

type SessionListData struct {
	Sessions []Session
	Campaign interface{} // *campaigns.Campaign, avoid import cycle.
}

SessionListData holds data for the session list page.

type SessionRepository

type SessionRepository interface {
	Create(ctx context.Context, campaignID string, s *Session) error
	FindByID(ctx context.Context, id string) (*Session, error)
	// FindByIDIncludingDeleted is FindByID without the deleted_at filter —
	// used only to confirm a soft-deleted session's campaign before
	// restoring it.
	FindByIDIncludingDeleted(ctx context.Context, id string) (*Session, error)
	ListByCampaign(ctx context.Context, campaignID string) ([]Session, error)
	// ListLinkedEventIDs is every calendar event that has a night in the
	// campaign, a night in the Trash included: its link outlives deleting it,
	// so the event is not offered for a second night.
	ListLinkedEventIDs(ctx context.Context, campaignID string) ([]string, error)
	// ListDismissedEventIDs is the events whose "Not this one" was pressed.
	ListDismissedEventIDs(ctx context.Context, campaignID string) ([]string, error)
	// DismissEvent records "Not this one" for an event. Idempotent.
	DismissEvent(ctx context.Context, campaignID, eventID, userID string) error
	// RestoreEvent undoes "Not this one". Idempotent, scoped to the campaign.
	RestoreEvent(ctx context.Context, campaignID, eventID string) error
	ListByDateRange(ctx context.Context, campaignID, startDate, endDate string) ([]Session, error)
	// ListPlannedByWorldDateRange returns planned sessions whose in-world
	// date (calendar_year/month/day) lies in [from, to] inclusive, soonest
	// first, up to limit rows (limit<=0: no cap). Only ID, CampaignID, Name
	// and the Calendar* fields are populated.
	// A non-empty calendarID restricts the result to sessions whose date is on
	// that calendar; "" means every calendar.
	ListPlannedByWorldDateRange(ctx context.Context, campaignID, calendarID string, from, to WorldDate, limit int) ([]Session, error)
	// ListCampaignIDsWithUnstampedWorldDates is every campaign holding a
	// session with a complete in-world date but no calendar id. Backs the
	// boot reconciler.
	ListCampaignIDsWithUnstampedWorldDates(ctx context.Context) ([]string, error)
	// StampWorldDateCalendar sets calendar_id on a campaign's sessions that
	// have a complete in-world date and no calendar id, returning how many.
	// Rows already stamped are never touched, so it is safe to repeat.
	StampWorldDateCalendar(ctx context.Context, campaignID, calendarID string) (int64, error)
	// RemapMonthPositions rewrites calendar_month on the campaign's sessions
	// dated on calendarID, old position -> new, in one statement so a swap
	// reads every old value before any is replaced. Returns rows changed.
	RemapMonthPositions(ctx context.Context, campaignID, calendarID string, remap map[int]int) (int64, error)
	SearchByCampaign(ctx context.Context, campaignID, query string) ([]Session, error)
	Update(ctx context.Context, s *Session) error
	UpdateRecap(ctx context.Context, id string, recap, recapHTML *string) error
	Delete(ctx context.Context, id string) error

	// Attendee management.
	AddAttendee(ctx context.Context, sessionID, userID, status string) error
	UpdateAttendeeStatus(ctx context.Context, sessionID, userID, status string) error
	RemoveAttendee(ctx context.Context, sessionID, userID string) error
	ListAttendees(ctx context.Context, sessionID string) ([]Attendee, error)
	// SetAttendeeNote sets or clears a single attendee's note. Only ever
	// called when the caller means to touch the note (the service simply
	// skips the call otherwise), so there is no "leave alone" state here.
	SetAttendeeNote(ctx context.Context, sessionID, userID string, note *string) error
	// SetAttendeeExcluded is the Director's own "leave myself out of the
	// tally" switch for a non-recurring session's single attendee row.
	SetAttendeeExcluded(ctx context.Context, sessionID, userID string, excluded bool) error
	// MarkSeriesNeedsRecheck bulk-flags every ANSWERED (non-invited)
	// session_attendees row for a moved/cancelled non-recurring session.
	MarkSeriesNeedsRecheck(ctx context.Context, sessionID string) error
	// ListRespondedUserIDs returns user ids with a non-"invited" answer on a
	// non-recurring session — who to notify on a move/cancel/restore.
	ListRespondedUserIDs(ctx context.Context, sessionID string) ([]string, error)

	// Soft delete. A soft-deleted session is excluded from every other read
	// in this file (FindByID, the list/search/date-range queries); both
	// methods are idempotent no-ops when the row is already in the target
	// state, matching this file's existing same-state-resubmit convention.
	SoftDeleteSession(ctx context.Context, id string) error
	// RestoreSession reports whether it brought the session back, so of two
	// restores racing for the same night only one announces it.
	RestoreSession(ctx context.Context, id string) (bool, error)
	// ListDeleted lists a campaign's soft-deleted sessions, newest first,
	// for the campaign Trash.
	ListDeleted(ctx context.Context, campaignID string) ([]TrashedSession, error)
	// PurgeDeletedBefore hard-deletes sessions soft-deleted before cutoff.
	PurgeDeletedBefore(ctx context.Context, cutoff time.Time) (int, error)

	// Per-occurrence RSVPs for a RECURRING session (session_occurrence_rsvps).
	// See occurrence_rsvp_repository.go.
	UpsertOccurrenceRSVP(ctx context.Context, sessionID, userID, occurrenceDate, status string, note *string) error
	ListOccurrenceRSVPs(ctx context.Context, sessionID, occurrenceDate string) ([]OccurrenceRSVP, error)
	SetOccurrenceExcluded(ctx context.Context, sessionID, userID, occurrenceDate string, excluded bool) error
	// MarkOccurrenceNeedsRecheck bulk-flags every answered row for ONE night.
	MarkOccurrenceNeedsRecheck(ctx context.Context, sessionID, occurrenceDate string) error
	ListOccurrenceRespondedUserIDs(ctx context.Context, sessionID, occurrenceDate string) ([]string, error)
	// MarkAllOccurrencesNeedsRecheck / ListAllOccurrenceRespondedUserIDs are
	// the whole-series equivalents of the two methods above, needed when a
	// RECURRING session itself (not one specific night) is moved, cancelled
	// or restored — every night's answer is flagged, not just one.
	MarkAllOccurrencesNeedsRecheck(ctx context.Context, sessionID string) error
	ListAllOccurrenceRespondedUserIDs(ctx context.Context, sessionID string) ([]string, error)
	// ListGoingOrMaybeUserIDs returns who answered Going or Maybe to the
	// session or to a night on or after fromDate (YYYY-MM-DD): who a cancel,
	// move or back-on email goes to. Answers to nights already played are
	// left out. Deleted sessions included, since a cancel reads it after.
	ListGoingOrMaybeUserIDs(ctx context.Context, sessionID, fromDate string) ([]string, error)

	// "Suggest another time" (session_reschedule_suggestions).
	CreateRescheduleSuggestion(ctx context.Context, s *RescheduleSuggestion) error

	// Calendar feed credentials + the campaign-wide kill switch (see
	// feed_repository.go).
	GetOrCreateFeedToken(ctx context.Context, campaignID, userID string) (*CalendarFeedToken, error)
	ReplaceFeedToken(ctx context.Context, campaignID, userID string) (*CalendarFeedToken, error)
	FindFeedToken(ctx context.Context, token string) (*CalendarFeedToken, error)
	IsCalendarFeedEnabled(ctx context.Context, campaignID string) (bool, error)
	SetCalendarFeedEnabled(ctx context.Context, campaignID string, enabled bool) error

	// Entity linking.
	LinkEntity(ctx context.Context, sessionID, entityID, role string) error
	UnlinkEntity(ctx context.Context, sessionID, entityID string) error
	ListSessionEntities(ctx context.Context, sessionID string) ([]SessionEntity, error)

	// RSVP tokens for email-based responses.
	CreateRSVPToken(ctx context.Context, token *RSVPToken) error
	FindRSVPToken(ctx context.Context, tokenStr string) (*RSVPToken, error)
	MarkRSVPTokenUsed(ctx context.Context, tokenStr string) error

	// Availability scheduler. Recurring per-member blocks + per-date
	// exceptions live in their own tables (member_availability,
	// availability_exceptions) — see availability_repository.go.
	ListUserAvailability(ctx context.Context, campaignID, userID string) ([]AvailabilityBlock, error)
	ListCampaignAvailability(ctx context.Context, campaignID string) ([]AvailabilityBlock, error)
	ReplaceUserAvailability(ctx context.Context, campaignID, userID, tz string, blocks []AvailabilityBlock) error
	// ListAnsweredUserIDs is the answered-or-not store: who has saved a
	// pattern at all, keyed by user id. Absence of blocks means
	// "unavailable", so without this the roster cannot tell silence from a "no".
	ListAnsweredUserIDs(ctx context.Context, campaignID string) (map[string]time.Time, error)
	// TouchAvailabilityAnswered moves a member's answered stamp to at
	// without touching their hours; false when they never answered.
	TouchAvailabilityAnswered(ctx context.Context, campaignID, userID string, at time.Time) (bool, error)
	ListUserExceptions(ctx context.Context, campaignID, userID string) ([]AvailabilityException, error)
	ListCampaignExceptionsInRange(ctx context.Context, campaignID, startDate, endDate string) ([]AvailabilityException, error)
	AddException(ctx context.Context, e *AvailabilityException) error
	CountUserExceptions(ctx context.Context, campaignID, userID string) (int, error)
	ReplaceDayExceptions(ctx context.Context, campaignID, userID, onDate string, excs []AvailabilityException) error
	DeleteException(ctx context.Context, campaignID, userID, exceptionID string) error

	// Slot proposals + responses + tokens. Own tables (slot_proposals,
	// slot_proposal_options, slot_proposal_responses, slot_proposal_tokens) —
	// never session_attendees — see proposals_repository.go.
	CreateProposal(ctx context.Context, p *SlotProposal, options []SlotProposalOption) error
	GetProposal(ctx context.Context, campaignID, proposalID string) (*SlotProposal, []SlotProposalOption, error)
	// FindProposalByID loads a proposal by id alone (no campaign scope) for the
	// emailed-token redeem path; SetProposalWinnerAndClose marks the winner +
	// closes the proposal atomically.
	FindProposalByID(ctx context.Context, proposalID string) (*SlotProposal, error)
	SetProposalWinnerAndClose(ctx context.Context, proposalID, winningOptionID string) error
	ListProposals(ctx context.Context, campaignID string) ([]SlotProposal, error)
	ListProposalOptions(ctx context.Context, proposalID string) ([]SlotProposalOption, error)
	FindOption(ctx context.Context, optionID string) (*SlotProposalOption, error)
	UpsertProposalResponse(ctx context.Context, r *SlotProposalResponse) error
	ListProposalResponses(ctx context.Context, proposalID string) ([]SlotProposalResponse, error)
	CreateProposalToken(ctx context.Context, token *SlotProposalToken) error
	FindProposalToken(ctx context.Context, tokenStr string) (*SlotProposalToken, error)
	MarkProposalTokenUsed(ctx context.Context, tokenStr string) error

	// Scheduler-scoped notifications. Own table (notifications); see
	// notifications_repository.go.
	CreateNotification(ctx context.Context, n *Notification) error
	MergeUnreadNotification(ctx context.Context, n *Notification) error
	// FindUnreadNotification is the user's newest unread notification of the
	// type and link; nil when there is none.
	FindUnreadNotification(ctx context.Context, userID, ntype, link string) (*Notification, error)
	// RewriteUnreadNotification replaces a row's payload and time while it is
	// still unread and still holds payload was; false when it no longer does.
	RewriteUnreadNotification(ctx context.Context, id string, was, payload *string, at time.Time) (bool, error)
	// LatestCampaignNotificationAt is when the campaign last sent a
	// notification of ntype to anyone; the zero time when never.
	LatestCampaignNotificationAt(ctx context.Context, campaignID, ntype string) (time.Time, error)
	ListNotifications(ctx context.Context, userID string, limit int) ([]Notification, error)
	// ListUnreadNotificationsOfType returns the user's unread notifications
	// of one type, newest first, capped at limit.
	ListUnreadNotificationsOfType(ctx context.Context, userID, ntype string, limit int) ([]Notification, error)

	// ListCampaignIDsUsingGameNights is every campaign that has planned a
	// session, painted hours or opened a proposal.
	ListCampaignIDsUsingGameNights(ctx context.Context) ([]string, error)
	CountUnreadNotifications(ctx context.Context, userID string) (int, error)
	MarkNotificationRead(ctx context.Context, userID, notificationID string) error
	MarkAllNotificationsRead(ctx context.Context, userID string) error
	// MarkNotificationsReadForLink marks the user's unread notifications of
	// one type that point at link read.
	MarkNotificationsReadForLink(ctx context.Context, userID, ntype, link string) error
}

SessionRepository defines the data access contract for session operations.

func NewSessionRepository

func NewSessionRepository(db *sql.DB) SessionRepository

NewSessionRepository creates a new session repository.

type SessionService

type SessionService interface {
	CreateSession(ctx context.Context, campaignID string, input CreateSessionInput) (*Session, error)
	GetSession(ctx context.Context, id string) (*Session, error)
	// GetSessionIncludingDeleted is GetSession for a soft-deleted session —
	// used only to confirm which campaign a session to be RESTORED belongs
	// to (IDOR scoping) before restoring it; GetSession itself must keep
	// answering not-found for a soft-deleted session everywhere else.
	GetSessionIncludingDeleted(ctx context.Context, id string) (*Session, error)
	ListSessions(ctx context.Context, campaignID string) ([]Session, error)
	// ListLinkedEventIDs, ListDismissedEventIDs and DismissEvent back the
	// Game nights strip of calendar Session events: which events already have
	// a night (in the Trash too), and which were set aside with "Not this one".
	ListLinkedEventIDs(ctx context.Context, campaignID string) ([]string, error)
	ListDismissedEventIDs(ctx context.Context, campaignID string) ([]string, error)
	DismissEvent(ctx context.Context, campaignID, eventID, userID string) error
	// RestoreEvent puts a dismissed event back on the strip. Idempotent.
	RestoreEvent(ctx context.Context, campaignID, eventID string) error
	// ListPlannedSessions returns only planned (upcoming) sessions for a campaign.
	ListPlannedSessions(ctx context.Context, campaignID string) ([]Session, error)
	ListSessionsForDateRange(ctx context.Context, campaignID, startDate, endDate string) ([]Session, error)
	// ListPlannedSessionsInWorldDateRange returns planned sessions whose
	// in-world date on calendarID ( = any calendar) falls in [from, to]
	// inclusive, soonest first, capped at limit (<=0: no cap). Lets the calendar name the sessions an anchor
	// move would re-date. Only identity, name and in-world date are filled.
	ListPlannedSessionsInWorldDateRange(ctx context.Context, campaignID, calendarID string, from, to WorldDate, limit int) ([]Session, error)
	// ListCampaignIDsWithUnstampedWorldDates and StampWorldDateCalendar back
	// ReconcileWorldDateCalendars: campaigns holding a session with an
	// in-world date but no calendar, and the stamp for one campaign.
	ListCampaignIDsWithUnstampedWorldDates(ctx context.Context) ([]string, error)
	StampWorldDateCalendar(ctx context.Context, campaignID, calendarID string) (int64, error)
	// RemapMonthPositions moves the in-world month of the sessions dated on
	// calendarID (old 1-based position -> new) when a calendar structure
	// edit reorders its months, so game nights follow their month. Returns
	// how many sessions changed.
	RemapMonthPositions(ctx context.Context, campaignID, calendarID string, remap map[int]int) (int, error)
	// UpdateSession validates and updates a session. If a recurring session is
	// completed, auto-generates the next occurrence and returns it. Returns nil
	// if no new session was created.
	UpdateSession(ctx context.Context, id string, input UpdateSessionInput) (*Session, error)
	// MoveSession is UpdateSession's entrypoint for the PUT session route: same
	// partial update, plus — when the stored schedule actually changed on a
	// session that already has RSVP responses — those responses are flagged
	// "needs to check again" (never cleared) and the affected user ids are
	// returned so the handler can notify them.
	MoveSession(ctx context.Context, id string, input UpdateSessionInput) (*Session, []string, error)
	// DeleteSession soft-deletes (never hard-deletes — a co-Director/Owner can
	// restore). Returns the user ids who had already RESPONDED, to notify.
	DeleteSession(ctx context.Context, id string) ([]string, error)
	// RestoreSession undoes a soft delete, returning the restored session and
	// the same "who had responded" list DeleteSession returned, for a
	// symmetrical re-notify.
	// changed is false when the session was not deleted (a restore that lost
	// a race), in which case nothing should be announced.
	RestoreSession(ctx context.Context, id string) (sess *Session, responded []string, changed bool, err error)
	// RestoreAndAnnounce restores a deleted session of this campaign and
	// tells everyone who had answered that it is back on. A session of
	// another campaign, or one not deleted, is not found.
	RestoreAndAnnounce(ctx context.Context, campaignID, id string) (*Session, error)
	// NightChangeAudience says who hears by email that the night changed:
	// those who answered Going or Maybe to it or, for a repeating series, to
	// a night still to come, with the night to name. Nil when every night is
	// already over. The session may be deleted.
	NightChangeAudience(ctx context.Context, s *Session) (*NightAudience, error)
	// ListTrashedSessions lists the campaign's deleted sessions for the Trash.
	ListTrashedSessions(ctx context.Context, campaignID string) ([]TrashedSession, error)
	// PurgeTrashedSessions removes for good sessions deleted before cutoff.
	PurgeTrashedSessions(ctx context.Context, cutoff time.Time) (int, error)
	UpdateSessionRecap(ctx context.Context, id string, recap, recapHTML *string) error
	// LastNightToWriteUp is the latest one-off night of the past week that
	// has no recap, for home's "Last night: write it up"; nil when none.
	LastNightToWriteUp(ctx context.Context, campaignID, today string) (*Session, error)
	// LastGameNight is the latest planned night dated before today, recap or
	// not, for the campaign home's "At a glance"; nil when there is none.
	LastGameNight(ctx context.Context, campaignID, today string) (*Session, error)
	SearchSessions(ctx context.Context, campaignID, query string) ([]map[string]string, error)

	// Attendees / RSVP.
	InviteAll(ctx context.Context, sessionID string, userIDs []string) error
	// InviteAllWithStatus is InviteAll generalized to any status — used to
	// carry a proposal's winning-option yes-voters in as "carried_yes" rather
	// than plain "invited" (see ConfirmProposalWinner).
	InviteAllWithStatus(ctx context.Context, sessionID string, userIDs []string, status string) error
	UpdateRSVP(ctx context.Context, sessionID, userID, status string) error
	// UpdateRSVPDetailed is UpdateRSVP extended for game nights: an optional
	// occurrenceDate routes a RECURRING session's answer to its own night
	// (session_occurrence_rsvps) instead of the whole-series row, defaulting
	// to the next upcoming night when omitted; note is a patch.Field so
	// "clear my note" (explicit null) is distinguishable from "don't touch
	// it" (absent) at this boundary. UpdateRSVP itself is unchanged and keeps
	// its exact prior behavior — this is an addition, not a replacement.
	UpdateRSVPDetailed(ctx context.Context, sessionID, userID, status string, occurrenceDate *string, note patch.Field[string]) error
	// RespondRSVP is a member answering a session they can see: it refuses a
	// session that no longer AcceptsRSVP, then records the answer through
	// UpdateRSVPDetailed when a note or night is given, else UpdateRSVP. The
	// two underlying calls stay unguarded because an import restores the
	// attendance of nights that are already over.
	RespondRSVP(ctx context.Context, session *Session, userID, status string, occurrenceDate *string, note patch.Field[string]) error
	// NotifySessionScheduled tells every member but the scheduler that a new
	// night is on the calendar and asks if they're coming.
	NotifySessionScheduled(ctx context.Context, session *Session, schedulerID, schedulerName string, memberIDs []string) error
	// SetExcludedFromCount is the Director's own "leave myself out of the
	// tally" switch (operator answer #3). Only the session's organizer or the
	// campaign owner may call it, and only ever on their OWN userID —
	// isCampaignOwner is the handler's campaign-role check, passed in because
	// this service never imports the campaigns package.
	SetExcludedFromCount(ctx context.Context, sessionID, userID string, isCampaignOwner, excluded bool, occurrenceDate *string) error
	ListAttendees(ctx context.Context, sessionID string) ([]Attendee, error)
	// ListOccurrenceAttendees is ListAttendees' per-occurrence twin for a
	// recurring session's one specific night.
	ListOccurrenceAttendees(ctx context.Context, sessionID, occurrenceDate string) ([]OccurrenceRSVP, error)
	// ListGameNights lists every planned night in [from, to] with each
	// member's answer, for the calendar's day card.
	ListGameNights(ctx context.Context, campaignID, from, to, today string, members []NightMember) ([]GameNight, error)
	// NextGameNight is the soonest planned night not yet started, without a
	// roster, for the header's countdown; nil when none is scheduled.
	NextGameNight(ctx context.Context, campaignID string, now time.Time) (*NextNight, error)

	// "Suggest another time" (see ValidateAndRecordSuggestion's doc comment
	// for the validate-before-consume ordering this fixes).
	ValidateAndRecordSuggestion(ctx context.Context, tokenStr, suggestedDate string, suggestedTime, note *string) (*RescheduleSuggestion, error)

	// Calendar feed (operator answer #1): a private, replaceable per-member
	// feed link, campaign-wide-enabled by default.
	GetOrCreateFeedToken(ctx context.Context, campaignID, userID string) (*CalendarFeedToken, error)
	ReplaceFeedToken(ctx context.Context, campaignID, userID string) (*CalendarFeedToken, error)
	IsCalendarFeedEnabled(ctx context.Context, campaignID string) (bool, error)
	SetCalendarFeedEnabled(ctx context.Context, campaignID string, enabled bool) error
	// ResolveFeedToken validates a feed token (checking the campaign-wide
	// switch) and returns its campaignID/userID, WITHOUT touching any
	// session data. The caller MUST re-check that userID is still a
	// campaign member before calling ListFeedSessions — this token has no
	// expiry, unlike a session RSVP token.
	ResolveFeedToken(ctx context.Context, tokenStr string) (campaignID, userID string, err error)
	// ListFeedSessions returns campaignID's upcoming sessions for the ICS
	// feed. Call only after ResolveFeedToken succeeds and membership is
	// re-checked — see ResolveFeedToken's doc comment.
	ListFeedSessions(ctx context.Context, campaignID string) ([]Session, error)
	BuildFeedICS(sessions []Session) string

	// RSVP tokens for email-based responses. Redeem is split into a read-only
	// validate (GET confirm page) + a state-changing apply (POST) so a mail
	// prefetcher's GET never records an RSVP.
	CreateRSVPTokens(ctx context.Context, sessionID, userID string) (RSVPTokens, error)
	ValidateRSVPToken(ctx context.Context, tokenStr string) (*RSVPToken, error)
	ApplyRSVPToken(ctx context.Context, tokenStr string) (*RSVPToken, error)

	// Entity linking. campaignID is used to verify the entity belongs to the
	// same campaign as the session, preventing cross-campaign IDOR attacks.
	LinkEntity(ctx context.Context, sessionID, entityID, role, campaignID string) error
	UnlinkEntity(ctx context.Context, sessionID, entityID string) error
	ListSessionEntities(ctx context.Context, sessionID string) ([]SessionEntity, error)
	// FilterEntitiesForViewer removes session-linked entities a given viewer
	// may not see. The owner and Co-DMs (role >= 3) see the list unchanged; a
	// Scribe, Player or anonymous viewer is narrowed via
	// EntityVisibilityFilter. Hidden content is ABSENT from the returned
	// slice, never a placeholder or a count (ADR-055 rule 3). Fails CLOSED
	// (returns nothing) if no filter is wired, rather than risk showing a
	// name it cannot check.
	FilterEntitiesForViewer(ctx context.Context, campaignID string, ents []SessionEntity, role int, userID string) ([]SessionEntity, error)

	// Availability scheduler. See availability_service.go.
	GetMyAvailability(ctx context.Context, campaignID, userID string) (*MyAvailabilityResponse, error)
	SaveMyAvailability(ctx context.Context, campaignID, userID string, req SaveAvailabilityRequest) error
	ListMyExceptions(ctx context.Context, campaignID, userID string) ([]AvailabilityException, error)
	AddMyException(ctx context.Context, campaignID, userID string, req AddExceptionRequest) error
	ReplaceMyDayExceptions(ctx context.Context, campaignID, userID string, req ReplaceDayExceptionsRequest) error
	// AddMyAvailableWindows records temporary offered availability for specific
	// dates, composing each day so the offer never erases the member's usual
	// hours.
	AddMyAvailableWindows(ctx context.Context, campaignID, userID, tz string, windows []AvailabilityWindowDTO) error
	DeleteMyException(ctx context.Context, campaignID, userID, exceptionID string) error
	// CampaignMemberZones returns the zone each member set on the availability
	// page (member_availability.tz), keyed by user id. Absent = not set there.
	CampaignMemberZones(ctx context.Context, campaignID string) (map[string]string, error)
	BuildOverlay(ctx context.Context, campaignID string, members []overlayMemberInput, weekStart, viewerTZ string, includeDetail bool) (*WeekOverlay, error)
	// AvailabilityAnswerStatuses / NudgeUnansweredAvailability are the
	// answered-or-not pair: zero availability rows always means "unavailable",
	// so these two distinguish a member who never opened the page from one who
	// is genuinely never free, and let the Director ask the silent ones on an
	// explicit press (there is no scheduled-job runner in this product).
	AvailabilityAnswerStatuses(ctx context.Context, campaignID string, members []overlayMemberInput) ([]AvailabilityAnswerStatus, error)
	NudgeUnansweredAvailability(ctx context.Context, campaignID, link string, members []overlayMemberInput) (*NudgeResult, error)
	// The Director's further asks and a member's away dates; see
	// availability_asks.go.
	PingMemberAvailability(ctx context.Context, campaignID, askerID, askerName, targetID, link string, members []overlayMemberInput) (*NudgeResult, error)
	AskAllToConfirm(ctx context.Context, campaignID, askerID, askerName, link string, members []overlayMemberInput) (*NudgeResult, []string, error)
	LastConfirmAsk(ctx context.Context, campaignID string) (time.Time, error)
	// RemindNight asks one player, or everyone who hasn't answered, to say
	// whether they're coming to one night; see night_reminders.go.
	RemindNight(ctx context.Context, campaignID, sessionID, date, askerID, askerName, targetID, today string, members []NightMember) (*NightReminder, error)
	// ListCampaignIDsUsingGameNights is every campaign with game-night data,
	// for the addon reconciler.
	ListCampaignIDsUsingGameNights(ctx context.Context) ([]string, error)
	ConfirmMyAvailability(ctx context.Context, campaignID, userID string) error
	MarkMeAway(ctx context.Context, campaignID, userID string, req AwayRequest) error
	ClearMeAway(ctx context.Context, campaignID, userID string, req AwayRequest) error

	// Slot proposals + responses. See proposals_service.go.
	CreateProposal(ctx context.Context, campaignID, createdBy string, req CreateProposalRequest) (*SlotProposal, error)
	GetProposalView(ctx context.Context, campaignID, proposalID, viewerID, viewerTZ string, includeDetail bool) (*ProposalView, error)
	ListProposalSummaries(ctx context.Context, campaignID, viewerID string) ([]ProposalSummary, error)
	ListOpenProposalViews(ctx context.Context, campaignID, viewerID, viewerTZ string) ([]ProposalView, error)
	RespondToOption(ctx context.Context, campaignID, proposalID, optionID, userID, response string) error
	CreateProposalTokens(ctx context.Context, optionID, userID string) (map[string]string, error)
	// Emailed-token redeem is split into a read-only validate (used by the GET
	// confirm page) and a state-changing apply (POST only), so a mail prefetcher's
	// GET never records a response; validate also enforces the proposal is
	// still open.
	ValidateProposalToken(ctx context.Context, tokenStr string) (*ProposalTokenContext, error)
	ApplyProposalToken(ctx context.Context, tokenStr string) (*ProposalTokenContext, error)
	// ConfirmProposalWinner (Scribe+ or co-Director) marks the winning option, closes the
	// proposal, and creates a planned session from the winning UTC instant.
	// Also returns the user ids who voted "yes" on the WINNING option — see
	// its own doc comment for why the handler, not this method, decides
	// every attendee's starting status.
	ConfirmProposalWinner(ctx context.Context, campaignID, proposalID, optionID, confirmedBy, confirmerTZ string) (*Session, []string, error)

	// Scheduler-scoped notifications. Writes are driven by the handler (which
	// enumerates members / resolves names); the service owns the
	// payload/link/message construction. See notifications_service.go.
	NotifyProposalCreated(ctx context.Context, campaignID, proposalID, title string, recipientIDs []string) error
	NotifyProposalResponse(ctx context.Context, campaignID, proposalID, responderID, responderName string) error
	// NotifyUsers is the generic fan-in the notifications store supports, so a
	// feature outside the scheduler can write a bell notification without the
	// scheduler growing a method per feature and without that feature
	// reaching the repository.
	NotifyUsers(ctx context.Context, userIDs []string, campaignID, ntype, message, link string) error
	// NotifyUsersWithDetail is NotifyUsers with a short second line the bell
	// shows under the message, before the time ("On Bren").
	NotifyUsersWithDetail(ctx context.Context, userIDs []string, campaignID, ntype, message, detail, link string) error
	// NotifyUsersWithAction adds a label for the link, shown under the detail.
	NotifyUsersWithAction(ctx context.Context, userIDs []string, campaignID, ntype, message, detail, action, link string) error
	// FoldUnreadNotification keeps one unread row of a type and link per
	// recipient: a write while the row is unread rewrites it from the state it
	// kept; a read row starts a fresh one. See notifications_service.go.
	FoldUnreadNotification(ctx context.Context, userIDs []string, campaignID, ntype, link string, fold func(kept string) (message, detail, state string)) error
	// NotifyProposalConfirmed tells everyone who responded that the winning
	// slot was picked, linking to the new session.
	NotifyProposalConfirmed(ctx context.Context, campaignID, proposalID, sessionID string) error
	ListMyNotifications(ctx context.Context, userID string, limit int) ([]Notification, error)
	// OpenAsks drops the scheduled-night asks whose night is over (played,
	// completed, cancelled or removed), for the call-to-action banner and
	// the bell. today is the reader's own date for a campaign's nights; nil
	// means the day where the date ends last, so no night is closed early.
	OpenAsks(ctx context.Context, notes []Notification, today func(campaignID string) string) []Notification
	// ListMyUnreadAsks returns the member's unread "are you coming?" asks.
	ListMyUnreadAsks(ctx context.Context, userID string) ([]Notification, error)
	CountMyUnreadNotifications(ctx context.Context, userID string) (int, error)
	MarkNotificationRead(ctx context.Context, userID, notificationID string) error
	MarkAllNotificationsRead(ctx context.Context, userID string) error
}

SessionService defines the business logic contract for sessions.

func NewSessionService

NewSessionService creates a new session service. The EntityCampaignChecker is used to verify entities belong to the correct campaign when linking, preventing cross-campaign IDOR attacks. The EntityVisibilityFilter is used to keep a session's linked-entity list from naming an entity a Player could not otherwise see (ADR-055 rule 3); both may be nil in tests that never touch entity linking or the session detail page.

type Sighting

type Sighting struct {
	SessionID   string `json:"sessionId"`
	SessionName string `json:"sessionName"`
	Date        string `json:"date,omitempty"`
	Source      string `json:"source"`
	// Role is the session_entities role, set only when Source is "link".
	Role string `json:"role,omitempty"`
	// AddedBy is who recorded a stored row; only the DM is told.
	AddedBy string `json:"addedBy,omitempty"`
}

Sighting is one night in a page's Last seen. Date is the night's occurrence date; it is empty only for a link on a repeating series, which names the series but no single night.

type SightingLink struct {
	SessionID     string
	SessionName   string
	Role          string
	ScheduledDate string
	IsRecurring   bool
}

SightingLink is one session_entities link on a live session.

type SightingNight

type SightingNight struct {
	SessionID   string `json:"sessionId"`
	SessionName string `json:"sessionName"`
	Date        string `json:"date"`
	Recurring   bool   `json:"recurring"`
}

SightingNight is one played game night: the session and the night's date.

type SightingNights

type SightingNights struct {
	Nights    []SightingNight `json:"nights"`
	Truncated bool            `json:"truncated"`
}

SightingNights is the played nights, newest first. Truncated says older nights were left off at the bound.

type SightingRepository

type SightingRepository interface {
	// UpsertSighting writes one night's answer for one page; the key is
	// (session, occurrence date, entity), so answering again replaces it.
	UpsertSighting(ctx context.Context, s SightingRow) error
	DeleteSighting(ctx context.Context, sessionID, occurrenceDate, entityID string) error
	// ListSightingsForEntity returns the page's rows on live sessions of the
	// campaign.
	ListSightingsForEntity(ctx context.Context, campaignID, entityID string) ([]SightingRow, error)
	// ListLinksForEntity returns the page's session_entities links on live
	// sessions of the campaign, with each session's date and recurrence.
	ListLinksForEntity(ctx context.Context, campaignID, entityID string) ([]SightingLink, error)
	// ListSightingsForNight returns every answer stored for one night, as
	// entity id to state.
	ListSightingsForNight(ctx context.Context, sessionID, occurrenceDate string) (map[string]string, error)
}

SightingRepository stores per-night sightings (session_night_sightings) and reads the session links a page's Last seen merges with them.

func NewSightingRepository

func NewSightingRepository(db *sql.DB) SightingRepository

NewSightingRepository creates the sightings repository.

type SightingRow

type SightingRow struct {
	SessionID      string
	SessionName    string
	OccurrenceDate string
	EntityID       string
	State          string
	Source         string
	AddedBy        string
}

SightingRow is one stored answer, with its session's name.

type SightingService

type SightingService interface {
	// SightingsFor merges stored rows with the page's encountered/key links,
	// newest night first, and adds unanswered "mentioned" nights as
	// suggestions for a DM viewer. A viewer who cannot see the page gets
	// nothing.
	SightingsFor(ctx context.Context, campaignID, entityID string, v permissions.Viewer) (*Sightings, error)
	// RecordSighting writes one answer. DM only.
	RecordSighting(ctx context.Context, campaignID string, in RecordSightingInput, v permissions.Viewer) error
	// ClearSighting removes one answer, so the night is unanswered again. DM only.
	ClearSighting(ctx context.Context, campaignID, sessionID, date, entityID string, v permissions.Viewer) error
	// NightsFor lists the campaign's game nights that have already been
	// played, newest first, so a page's Last seen can draw every night and
	// let the DM answer one. Any member may read it.
	NightsFor(ctx context.Context, campaignID, today string) (*SightingNights, error)
}

SightingService is the one place sightings are read and written, so the check-in and a page's Last seen share them.

func NewSightingService

NewSightingService creates the sightings service. The entity checker and visibility filter are the same adapters the session service uses; with no visibility filter every read fails closed.

type Sightings

type Sightings struct {
	Seen        []Sighting `json:"seen"`
	Suggestions []Sighting `json:"suggestions,omitempty"`
	NotSeen     []Sighting `json:"notSeen,omitempty"`
}

Sightings is everything a viewer may know about when the party saw a page. Suggestions and NotSeen are filled only for a viewer who sees DM-only content: they are nights the page came up but nobody has said it was seen.

type SinceItem

type SinceItem struct {
	ID   string
	Name string
	Date string
	At   time.Time
}

SinceItem is one night or poll after the cut-off. Date is a night's own YYYY-MM-DD ("" for the others).

type SinceReader

type SinceReader struct {
	// contains filtered or unexported fields
}

SinceReader reads game-night news.

func NewSinceReader

func NewSinceReader(db *sql.DB) *SinceReader

NewSinceReader creates the reader.

func (*SinceReader) NightsSince

func (r *SinceReader) NightsSince(ctx context.Context, campaignID string, since time.Time, today string) ([]SinceItem, error)

NightsSince lists the planned nights set after since that have not happened yet (today is the reader's own YYYY-MM-DD), newest first. A night in the past is not news.

func (*SinceReader) PollsSince

func (r *SinceReader) PollsSince(ctx context.Context, campaignID string, since time.Time) ([]SinceItem, error)

PollsSince lists the date polls opened after since that are still open, newest first. Any member may see a poll, so there is no per-reader filter.

func (*SinceReader) RecapsSince

func (r *SinceReader) RecapsSince(ctx context.Context, campaignID string, since time.Time, v SinceViewer) ([]SinceItem, error)

RecapsSince lists the nights whose recap was posted after since and that this reader can read, newest first. A night with no readable text is left out.

type SinceViewer

type SinceViewer struct {
	DMTeam bool
}

SinceViewer says who is reading. DMTeam is the owner or a Co-DM, and is false for an owner previewing as a player, so that reader gets the recap a player gets.

type SlotProposal

type SlotProposal struct {
	ID         string
	CampaignID string
	CreatedBy  string
	Title      string
	Note       *string
	Status     string // open | closed
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

SlotProposal is a DM's scheduling proposal header.

type SlotProposalOption

type SlotProposalOption struct {
	ID          string
	ProposalID  string
	StartsAtUTC time.Time
	EndsAtUTC   time.Time
	Ordinal     int
	IsWinner    bool
}

SlotProposalOption is one candidate slot, stored as a UTC instant range.

type SlotProposalResponse

type SlotProposalResponse struct {
	ID        string
	OptionID  string
	UserID    string
	Response  string // yes | no | maybe
	UpdatedAt time.Time
}

SlotProposalResponse is a member's response to one option. One row per (option, user); re-responding upserts.

type SlotProposalToken

type SlotProposalToken struct {
	ID        int
	Token     string
	OptionID  string
	UserID    string
	Response  string
	UsedAt    *time.Time
	ExpiresAt time.Time
	CreatedAt time.Time
}

SlotProposalToken is a one-click email response token (option + user + response). Single-use, expiring. Mirrors RSVPToken as a pattern.

type TrashedSession

type TrashedSession struct {
	ID        string
	Name      string
	DeletedAt time.Time
}

TrashedSession is a deleted game night as the campaign Trash lists it.

type UpdateSessionInput

type UpdateSessionInput struct {
	Name                patch.Field[string]
	Summary             patch.Field[string]
	ScheduledDate       patch.Field[string]
	ScheduledTime       patch.Field[string]
	CalendarYear        patch.Field[int]
	CalendarMonth       patch.Field[int]
	CalendarDay         patch.Field[int]
	Status              patch.Field[string]
	IsRecurring         patch.Field[bool]
	RecurrenceType      patch.Field[string]
	RecurrenceInterval  patch.Field[int]
	RecurrenceDayOfWeek patch.Field[int]
	RecurrenceEndDate   patch.Field[string]
	// ScheduledTZ is the IANA zone a changed ScheduledTime is in; a value
	// that is not a real zone is refused.
	ScheduledTZ patch.Field[string]
}

UpdateSessionInput is the validated input for updating a session.

Every field is a patch.Field: this is a PARTIAL update — an absent key preserves the stored value, an explicit null clears it, a present value replaces it. Do not re-introduce a value-typed field here; partial_update_test.go reddens if you do.

type UserDirectory

type UserDirectory interface {
	GetUser(ctx context.Context, userID string) (*auth.User, error)
	// GetTimezonesByIDs answers many members' account zones in one read so a
	// roster render is not one lookup per member.
	GetTimezonesByIDs(ctx context.Context, userIDs []string) (map[string]string, error)
}

UserDirectory is the narrow slice of the auth service the availability overlay needs: resolve a user's stored IANA timezone so the heatmap renders in the DM's own zone. Kept minimal to preserve plugin isolation.

type WeekOverlay

type WeekOverlay struct {
	WeekStart     string          `json:"weekStart"` // YYYY-MM-DD, first column (viewer zone)
	ViewerTZ      string          `json:"viewerTz"`  // IANA label rendered on the grid
	TotalMembers  int             `json:"totalMembers"`
	IncludeDetail bool            `json:"includeDetail"`
	Days          []OverlayDay    `json:"days"`    // exactly 7 columns
	Members       []OverlayMember `json:"members"` // roster (colors/names) — detail only
}

WeekOverlay is the heatmap payload for one week, already projected into the viewer's zone. Per-hour density (Free/Prefer counts) is visible to ALL members; per-member identity (Members[].Lanes and OverlayHour.FreeIDs/ PreferIDs) is populated ONLY when IncludeDetail is true — owner / DM-granted (design §5 / Q1: members see the anonymous aggregate, the DM sees who).

type WorldDate

type WorldDate struct {
	Year, Month, Day int
}

WorldDate is an in-world calendar date as stored on a session. It carries no calendar id: a session's date is a bare year/month/day triple.

type WorldDateWorder

type WorldDateWorder interface {
	WorldDateWordsFor(ctx context.Context, campaignID string) func(calendarID string, year, month, day int) string
}

WorldDateWorder words an in-world date in its calendar's own months ("14 Hammer, 1492"). Implemented in internal/app over the calendar service, so this plugin never imports the calendar plugin. It answers "" when the date cannot be worded, and the page then says only that there is no real date.

WorldDateWordsFor reads the campaign's calendars once and returns the wording function for that read, so a list of date-less nights costs one calendar read rather than one per row.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL