calendar

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: 46 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 calendar - backup.go reads and restores the calendar data a campaign backup carries beyond the calendar's own row and sub-resources: each day's weather, a hand-set moon's mode and marks, and event rolls with their stored nights. Only a viewer who sees everything (the backup's system viewer, or the Director) may call it, since all three hold Director-only state.

Package calendar is, for now, a migrations-and-identity carrier.

CALV5-PLACEHOLDER: the plugin was deleted for a ground-up rebuild (V5, issue #741); only migrations, MigrationsFS, PluginSlug and the widget type constants remain, kept so applied migrations stay immutable, the plugin stays registered, and existing addon/widget-binding rows don't orphan.

TODO(#778): this doc has been stale since service.go/handler.go/routes.go landed; rewrite it once V5 is complete instead of patching it slice by slice.

Registers "calendar" and "worldstate" with the widget-binding framework (see internal/plugins/timeline/timeline_widget_type.go for the pattern this mirrors). Both bind a campaign's calendar as their instance — the entity-page "calendar" block and the "worldstate" sky/hourglass embed are two independently bindable slots that happen to point at the same kind of thing, so they share calendarInstanceBase and differ only in Slug and RenderBlock.

Package calendar — entity_ties.go holds the optional many-to-many ties between entities and calendar events/eras: an entity can be, but does not have to be, tied to either. Both directions carry a participation role; event ties always have one (an event tie is always "someone's involvement in something"), era ties are coarser and may carry none.

Package calendar - entity_ties_repository.go: MariaDB reads/writes for the entity<->event / entity<->era link tables. Hand-written SQL per the project conventions. Cascade-on-delete is DB-enforced via the ON DELETE CASCADE FKs, so there is no unlink-all-for-entity method here.

Package calendar - era_look_view.go builds the config the structure editor's Era look part hands to calendar_era_look.js.

Package calendar — era_version_repository.go: MariaDB reads and writes for entity_era_versions. Hand-written SQL per the project conventions; page and era deletes cascade in the database.

Package calendar — era_versions.go: a page's version for one era of the campaign's main calendar. A version holds only what it changes (name, picture, text, field values); everything else is the usual page. The main calendar's current date picks the era every page is shown in.

The entities plugin owns how a page is drawn and edited; this file owns which era applies and what each version stores, reached through EraVersionService.

Package calendar - event_batch.go saves a whole year-track draft (or undoes one) in one request and one database transaction: the events to create, the repeating events to change, the events to delete and the weather days to write or clear. Every item is judged by the same rules as its single route, and one refusal refuses the whole batch, so Keep means all of it or none.

Package calendar - event_batch_handler.go serves the year track's batch save. The rules are in event_batch.go; this only binds, calls and answers.

Package calendar - event_kind_repository.go persists the campaign's event kinds (calendar_event_kinds): one shared list per campaign, referenced by events across every calendar in it (see model.go's EventKind doc).

Package calendar - event_outcome.go is what became of an event: its status (planned, happened, moved, called off), the Director's line on what happened, the day a moved event was planned for, and the list of events whose day the Director has just moved today past, which the calendar asks about. The calendar asks when the day passes and stores these four words, so the page, the campaign AI and Foundry say the same thing.

Package calendar - event_outcome_handler.go serves what became of events: the list the calendar asks about once today moves past them, and the Calendar settings switch that turns the question off. An event's status and line themselves travel on PUT .../events/:eid and the batch route.

Package calendar - event_pages.go links pages to an event through entity_event_links, for the event page's "Linked pages" list. A link made here always carries the "involved" role; nothing yet asks for a finer one.

Package calendar - event_repository.go persists calendar events: the events themselves, their date-range/search/upcoming reads, and (in entity_ties_repository.go, same aggregate) their optional ties to entities and eras.

Package calendar - event_roll_repository.go persists event rolls: each event's roll settings (calendar_event_rolls) and each night's stored result (calendar_event_roll_nights). Who may see which night is a service rule; this file only reads and writes the stored state.

Package calendar - event_rolls.go is a roll on an event: dice or a rolling table, rolled for each night the event lands on (the Bloodnight on every full moon), with result bands saying what players and the Director see. This file holds the shapes and the pure parts: reading a dice expression, checking a roll's settings, picking a band and shaping a night for a viewer. Storage is event_roll_repository.go, the rules event_rolls_service.go.

Package calendar - event_rolls_handler.go serves event rolls over JSON: reading a roll and its nights, and the Director's writes. The rules are in event_rolls_service.go; these only bind, call and answer.

Package calendar - event_rolls_service.go is the rules for event rolls: who sees which night, rolling ahead (one night or a whole year), rolling a night that arrived unrolled, locks and telling players.

A player learns nothing about a roll until a night they were told about arrives, and then only that night's player text. Every write is the Director's (owner or granted co-DM), checked here as well as on the route.

Package calendar — export.go provides JSON export of calendar configurations. Exports include all sub-resources (months, weekdays, moons, seasons, eras, cycles, festivals, weather) in Chronicle's native format. Events are optionally included in the export and read back on import (#779, see ImportResult.Events and parseChronicle in import.go) — a Chronicle export/import round-trip covers events as well as calendar structure.

Package calendar - handler.go binds HTTP requests to explicit input structs, calls the service, and renders the response. No business logic lives here — see routes.go for the route table and service.go for the rules each route ultimately enforces.

Package calendar — import.go imports calendars from three formats, auto-detected from the JSON shape:

  • Chronicle native (chronicle-calendar-v1): round-trips perfectly.
  • Simple Calendar (Foundry VTT): top-level "calendar" key with months/weekdays/time/leapYear; numberOfDays/numberOfLeapYearDays, hoursInDay/minutesInHour, startingMonth/startingDay, cycleLength/cycleDayAdjust.
  • Calendaria (Foundry VTT): top-level "months" as an object, or "days.hoursPerDay" present; days/leapDays, cycleLength/referenceDate, eras and festivals.

Calendaria seasons appear in two shapes (day-of-year span, or a month range with 0- or 1-based indices), and which shape/base a file uses is detected per file in calendariaSeasonMonthBase — do not replace that detection with a constant, real exports disagree.

Package calendar — list_handler.go serves the campaign calendars list page. Thin handlers only: bind, call the service, render — see CLAUDE.md's layering rule.

Package calendar provides a custom fantasy calendar system for campaigns. Supports non-Gregorian months, named weekdays, moons with phase tracking, named seasons, and events linked to entities. Each campaign can have multiple calendars (one marked as default); the addon must be enabled per-campaign.

Package calendar - moon_lore.go answers the entity page's question "which moons is this page the lore of, and what do they look like tonight?". A moon's lore page is the one link between a moon and an entity; this is the read from the entity's side, so the page can show a chip without the entities plugin ever touching a calendar table.

Package calendar - moon_marks.go is a moon the Director sets by hand (Umbra): it has no cycle, and holds the state of its latest mark until the next one. This file holds the states, the marks and the pure rules: which mark a day falls under, the words for each state, and what a player may see. Storage is moon_mark_repository.go, the rules moon_marks_service.go.

Package calendar - moon_marks_handler.go serves the Director's writes to a hand-set moon over JSON. The rules are in moon_marks_service.go; these only bind, call and answer with the moon as the Director now sees it.

Package calendar — moon_silhouette.go computes the lit-crescent SVG path for the v5 moon-silhouette mark (the .sil/.db/.dl classes in static/css/calendar_v5.css). This is a direct, small port of the signed mockup's litPath(p, r) — the photorealistic canvas-rendered moon engine the mockup also carries (MOONR) is a separate, larger rendering system, so every place a moon appears here uses this simple silhouette instead.

Package calendar - occurrences.go works out the dates a repeating event lands on within a range: weekly/monthly/yearly events through Event.OccursOn, rule events through their RecurrenceRule, and both with their "this one only" skips and moves applied.

Every day is read on the calendar's own day counter (absDayIndex, the one the grid, weekdays and moon phases use) and walked month by month through MonthDays, so leap days, intercalary months and Each-month-starts-a-new- week all come from the same place the grid gets them, and a rule can never drift from what the grid shows.

Package calendar - page_timeline.go answers the time line block's question "which dated events belong to this page, and where do they sit between the first of them and the campaign's today, or the subject's death?". It reads one calendar, the one the campaign uses, so every bead is placed on the same day counter.

Package calendar - place_backup.go reads and restores the weather stored for each place and the party's moves, for a campaign backup. Like backup.go, only a viewer who sees everything may call it: a hidden place's weather and the party's whole route are Director-only.

Package calendar - place_weather.go gives each place with a climate of its own its own weather, and keeps where the party is.

A place's climate is a field on its page, owned by the entities plugin; a page with none takes its nearest parent's, and a page with no climate above it keeps the calendar's world climate. The page that holds the climate is the place's region, and weather is stored per region (calendar_place_weather_days). The calendar's own day weather stays the weather everywhere else.

The party's marks say where the party is from a day on. A player sees one weather a day: the weather of the region the party was in that day, never another place's, and only for today and earlier, as before. A region with a climate but no reading that day shows nothing rather than the world's weather, which would be the wrong climate.

Package calendar - place_weather_handler.go is the JSON API for each place's weather and the party's marks. Every route here is the Director's (CanAuthorDmOnly in routes.go): players read the party's weather through the ordinary day-weather route, which the service already narrows.

Package calendar - place_weather_repository.go persists the weather of each place that has a climate of its own (calendar_place_weather_days) and the days the party arrived somewhere (calendar_party_places). Like weather_repository.go it only reads and writes stored state; who may see which place is the service's decision.

reallife.go builds the wizard's "Real-world calendar" tile: a fixed Gregorian ImportResult (real months, real weekdays, and — because it can be aligned to real new moons, see below — the real Moon). It is deliberately NOT one of the shipped presets.go/presets/*.json entries: a fantasy preset is a starting point the owner is expected to rename and reshape, while the Gregorian structure must stay exactly the real-world calendar (WeekdayIndex/MonthDays only compute correctly for a TracksRealTime calendar when the stored months/weekdays actually ARE January..December and Monday..Sunday — see model.go's MonthDays/ WeekdayIndex doc comments), so it is never offered next to Harptos or Dwarven in the preset picker.

Package calendar - recurrence_rule.go defines the rule a RecurrenceByRule event repeats by ("every full moon of Luna", "the 3rd Kingsday of each month", "2 days after the Festival of Masks") and its strict parsing.

A rule is a list of conditions a day must ALL meet, so a "custom" rule is just more conditions, never a new kind. Parsing here checks shape only; what a rule may reference in its calendar (a moon, a season, another event) is the service's check, because it needs the calendar and the author.

Package calendar - repository.go is the calendar aggregate's persistence: the calendar row itself and its structural sub-resources (months, weekdays, moons, seasons, eras, cycles, festivals). Hand-written SQL, one repository per aggregate root, per the project convention. Events, event kinds and weather are separate aggregate roots with their own files.

roll_table_when.go decides which lines of a saved rolling table can come up on a given night. A line may carry day conditions ("when"); the rolling tables plugin validates them and the browser's Roll one reads them with the generator engine. The server reads the same shape here, from the facts the calendar already holds (moons, seasons, weekdays, months, the night's stored weather and the calendar's climate), so a nightly event roll obeys a table exactly as Roll one does.

Package calendar - service.go holds the calendar plugin's business logic over the repositories (CalendarRepository, EventRepository, EventKindRepository, WeatherRepository). It never imports Echo — the handler binds requests and the service decides what happens.

Every read that a Player, Scribe or public visitor can reach goes through a permissions.Viewer (ADR-049): an anonymous request can never be mistaken for a trusted system caller, and dm_only content / hidden moons / per-user visibility_rules are resolved the same way for every viewer weaker than Owner. Structural resources (event kinds, eras, the moon hidden flag) are authorized entirely at the route — listing event kinds Owner only, every other write CanAuthorDmOnly (Owner or a granted co-Director) — so they carry no viewer parameter at all.

Package calendar - service_recurrence.go holds the service side of events that repeat by a rule and of "this one only" skips and moves: checking a rule against its calendar, expanding a month's repeating events into dates, keeping what a rule refers to from players who may not see it, the override writes, and the editor's "next few dates" preview.

Visibility, in one place:

  • A rule may only name a moon or an anchor event its author can see; a hidden one answers as unknown, so a rule cannot probe for it.
  • A viewer who can see a rule event sees its dates, even when they are worked out from an anchor that viewer cannot see. The anchor itself is never revealed: a non-author gets the rule stripped from the event whenever it names a hidden moon or an anchor that viewer cannot see.
  • Skipped occurrences (and a moved one's original date) go only to a viewer who may edit the event; players never learn of them.

Package calendar - structure_edit.go is the owner's whole-structure save for an EXISTING calendar: months, weekdays, the leap rule, moons and seasons in one go. It previews before it writes, because a structure change re-dates things the owner may not have thought about.

The rules it keeps:

  • Events are warned about, never refused and never silently rewritten. The one rewrite it makes is shown in the preview first: an event in a month that keeps its name follows that month to its new place.
  • Months are matched by name where the name is unchanged; a month whose name changed but whose place did not is treated as renamed.
  • The current date is never reset. It follows its month like an event, and is clamped (and the preview says so) only when its day is gone.
  • Moons and seasons keep their ids where the editor sent them back, so anything keyed to a moon's id (its hidden flag, its phases) survives. A moon's lore page changes only when the editor says so (LoreSet).

Package calendar - structure_editor_state.go builds the Alpine state of the structure editor that both the new-calendar wizard's "Build your own" step and an existing calendar's "Edit structure" page render: the wizard starts it from defaults, the edit page from the calendar itself.

Package calendar - structure_handler.go serves an existing calendar's "Edit structure" page and its preview and save. Owner only (routes.go), like the wizard and PUT /calendars/:calid. Thin: bind, call the service, render.

Package calendar - structure_repeats.go plans what a structure save does to repeat-by-rule events and their one-off overrides. Both name months by position (a rule's month/months conditions, an override's occurrence and new month), so they have to follow their month the way events do, or "every Fireday in Harvestide" would quietly point at another month after a reorder.

Package calendar - structure_repository.go is CalendarRepository's structure save: everything an owner's structure edit writes, in one transaction, so a failure part-way leaves the calendar exactly as it was.

view.go — the calendar's own page (V5 part A, #741): GET /campaigns/:id/calendars/:calid/view. The handler is thin (bind, call service, render); the month grid, day/era cards, event details and moons are all rendered client-side by the calendar_view widget from the JSON this handler ferries down on first paint (see view.templ's config div).

Package calendar — view_helpers.go holds small, pure presentation-shaping helpers shared by the calendars list (and its cards' month peeks) and the new-calendar wizard Templ pages. None of these decide authorization or business rules (that stays in service.go) — they only reshape already-authorized data for rendering.

Package calendar - weather_climates.go lists the climates a calendar can pick for its world. The ids and names mirror the weather generator in static/js/widgets/chronicle_gen.js (a JS test pins the two together), so the weather calendar can start from the stored id without a lookup table.

Package calendar - weather_forecast.go builds the forecast players are shown in place of the real weather: the stored reading for a coming day, blurred more the further ahead it looks. It is a port of forecastWeather in static/js/widgets/chronicle_gen.js, simplified so it needs no climate model and is deterministic under the server's forecast key: the same calendar, day and lead always give the same entry, so a player cannot refresh their way to the truth and a forecast does not change under them between page loads. The key keeps the draws secret: with only public inputs in the seed, a player could replay it and strip the blur.

A forecast entry is built only from a coarse category and numbers. It never carries the reading's preset id, label, colour, description or wind, since those would leak a day the owner has kept hidden (an own kind such as "Fire rain" names itself).

Package calendar - weather_kinds.go validates the owner's own kinds of weather (calendar_weather_settings.kinds). The rules mirror validateWeatherKind in static/js/widgets/chronicle_gen.js, which is the generator that consumes these kinds, so a kind saved here is one the generator accepts. A JS test pins weatherPresets and weatherEffects to the generator's tables; keep each entry on its own line in that exact form.

Package calendar - weather_kinds_editor.go builds the Alpine state of the "Your own weather" editor in Calendar settings. The state lives in a nested x-data inside the Weather section and is written Go-side, not as a script helper, because the page can arrive by an htmx swap where a sibling script element is not reliably run.

Package calendar - weather_repository.go persists a calendar's weather: the single current reading (calendar_weather) and one reading per day (calendar_weather_days). Player visibility of this data is a caller decision, not a repository one: this file only reads and writes the stored state.

Package calendar — wizard_generate_handler.go serves the "Generate one" step: a client-side recipe sheet that drives the generator engine (static/js/widgets/chronicle_gen.js, loaded on demand only for this step — see wizardGenerateBody's own doc comment for why) so the owner can reach the wizard's shared Review step from a fresh, complete calendar without typing anything.

The server never runs the generator itself — generation is pure client- side JavaScript, deterministic by seed, with nothing for Go to compute or import Echo-free business logic over. This file's only job is what every other wizard step's Preview handler already does: re-validate whatever the browser produced before the Review step ever renders it. A generated preset gets exactly the same treatment an uploaded file gets — the same Chronicle-format parser, the same clampCalendarStructure/ checkCalendarImportLimits bounds (parseGeneratedCalendarJSON, reusing CalendarService.PreviewImport rather than a bespoke check) — because it says "chronicle-calendar-v1" no more trustworthy than an upload claiming the same thing.

Package calendar — wizard_handler.go serves the new-calendar wizard's steps: Start, the preset picker + review, the import drop zone + review, the real-world calendar's own review, and the "Build your own" structure editor + review. Every route is Owner only (routes.go), matching the rest of this plugin's calendar-structure mutation routes.

There is no server-side draft session for the wizard: a preset's step-to-step state is just re-fetched each time (PreviewPreset is a pure, deterministic read), the real-world calendar's structure is rebuilt fresh server-side every time too (GregorianImportResult), and an uploaded import's or a hand-built calendar's parsed *ImportResult is round-tripped through a hidden form field between its preview and review/create steps, since the browser already holds the original file (or Alpine state) and re-sending it a second time would need larger form plumbing for no benefit. Because that field is client-submitted, WizardCreate re-validates it (parseWizardImportJSON) rather than trusting it outright — see that function's own doc comment.

Index

Constants

View Source
const (
	WidgetTypeCalendar   = "calendar"
	WidgetTypeWorldstate = "worldstate"
)

WidgetTypeCalendar and WidgetTypeWorldstate are the widgetbindings widget types a GM's saved entity bindings point at. calendarWidgetType and worldstateWidgetType (calendar_widget_type.go) implement widgetbindings.WidgetType for them; internal/app/routes.go registers both.

View Source
const (
	DayPartDawn  = "dawn"
	DayPartDay   = "day"
	DayPartDusk  = "dusk"
	DayPartNight = "night"
)

Parts of the day, by how high the calendar's sun stands.

View Source
const (
	EventStatusPlanned   = "planned"
	EventStatusHappened  = "happened"
	EventStatusMoved     = "moved"
	EventStatusCalledOff = "called_off"
)

The four things an event can have become. Planned is every event's start and stays until someone answers; once its day has passed, an unanswered event reads as happened.

View Source
const (
	PubEventCreated        = "event.created"
	PubEventUpdated        = "event.updated"
	PubEventDeleted        = "event.deleted"
	PubDateAdvanced        = "date.advanced"
	PubWeatherChanged      = "calendar.weather.changed"
	PubStructureUpdated    = "calendar.structure.updated"
	PubSeasonChanged       = "calendar.season.changed"
	PubEraChanged          = "calendar.era.changed"
	PubMoonPhaseChanged    = "calendar.moon.phase_changed"
	PubCycleChanged        = "calendar.cycle.changed"
	PubFestivalChanged     = "calendar.festival.changed"
	PubWorldStateChanged   = "calendar.worldstate.changed"
	PubWeatherZonesChanged = "calendar.weather.zones.changed"
)

Calendar change events the service hands to a CalendarEventPublisher. The calendar package knows nothing of WebSockets: internal/app maps these names to wire message types, so a service never imports a transport.

View Source
const (
	RollSourceDice  = "dice"
	RollSourceTable = "table"
)

Where a roll's result comes from.

View Source
const (
	RollNightAhead  = "ahead"
	RollNightOnDay  = "night"
	RollNightManual = "manual"
)

How a night's result was stored: rolled ahead (one night or the whole year), rolled when the night arrived, or typed by the Director.

View Source
const (
	// ModeFantasy indicates a fully custom fantasy calendar.
	ModeFantasy = "fantasy"
	// ModeRealLife indicates a Gregorian calendar synced to real-world time.
	ModeRealLife = "reallife"
)

Calendar mode constants.

View Source
const (
	RecurrenceWeekly   = "weekly"   // every week, on the base date's weekday
	RecurrenceBiWeekly = "biweekly" // every 2 weeks
	RecurrenceMonthly  = "monthly"  // same day-of-month each month
	RecurrenceCustom   = "custom"   // every N weeks (RecurrenceInterval)
	RecurrenceYearly   = "yearly"   // same month + day-of-month each year
	RecurrenceByRule   = "rule"     // every day the event's RecurrenceRule matches
)

Recurrence type constants. The first five mirror the sessions plugin's vocabulary (internal/plugins/sessions/model.go) so the two share semantics; RecurrenceByRule is the calendar's own. Any other or empty recurrence_type renders once at its stored date.

This block is the accepted set, stated exactly once. CreateEventAPI / UpdateEventAPI validate an inbound recurrence_type against these constants plus the empty string and reject anything else with a 400. Adding a member here widens what the API accepts, so a new constant is a wire-contract change, not a rename.

View Source
const (
	EraStyleGas = "gas"
	EraStyleInk = "ink"

	EraFeelStill  = "still"
	EraFeelSubtle = "subtle"
	EraFeelLively = "lively"
	EraFeelCustom = "custom"
)

Era styles and feels. A feel names an intensity and speed pair; "custom" is only ever the calendar's own feel, when the owner fine-tuned it.

View Source
const (
	AnnouncedAhead = "ahead"
	AnnouncedOnDay = "on_day"
)

Announced setting constants: separate from Visibility (who can ever see an event) and from an event's date (when it happens). AnnouncedAhead means players may know about an event before it happens (a festival's date is common knowledge); AnnouncedOnDay means it only becomes knowable on the day itself.

View Source
const (
	HemisphereNorth = "north"
	HemisphereSouth = "south"
)

Hemisphere constants for Calendar.Hemisphere.

View Source
const (
	MoonNightBlood       = "blood"
	MoonNightMagic       = "magic"
	MoonNightConjunction = "conjunction"
	MoonNightEclipse     = "eclipse"
	MoonNightHarvest     = "harvest"
)

Moon night payload: the "type" a calendar_events.payload JSON blob carries for a moon-themed night, e.g. `{"type":"blood","moons":[3]}`. moons holds the ids of the calendar_moons rows the night applies to.

View Source
const (
	WeatherSourceManual    = "manual"
	WeatherSourceGenerated = "generated"
)

Weather sources: who wrote a day's reading. A generated write never replaces a manual one, so regenerating a range keeps what was painted.

View Source
const (
	MoonCycle  = "cycle"
	MoonManual = "manual"
)

How a moon moves.

View Source
const (
	MoonFull     = "full"
	MoonHalf     = "half"
	MoonCrescent = "crescent"
	MoonDark     = "dark"
	MoonVanished = "vanished"
)

A manual moon's states, brightest first.

View Source
const (
	OverrideSkip = "skip"
	OverrideMove = "move"
)

Override actions for one occurrence of a repeating event.

View Source
const (
	RuleMoonPhase  = "moon_phase"   // the day a moon reaches a phase
	RuleWeekday    = "weekday"      // any of the listed weekdays (0-based)
	RuleNthWeekday = "nth_weekday"  // the nth (or last) of a weekday in its month
	RuleDayOfMonth = "day_of_month" // a day of the month (or the last)
	RuleMonths     = "months"       // any of the listed months (1-based)
	RuleSeason     = "season"       // any day inside a season
	RuleAfterEvent = "after_event"  // N days after (negative: before) each occurrence of another event
	// RuleMonth, RuleSeasonStart and RuleRelativeToEvent are the single-value
	// forms the editor offers: one month, a season's first day, and the
	// anchor event's own dates (after_event with zero days; the rule's
	// offset_days then reads "2 days after").
	RuleMonth           = "month"
	RuleSeasonStart     = "season_start"
	RuleRelativeToEvent = "relative_to_event"
)

Rule condition kinds. The set is closed: an unknown kind is a 400, never a condition that silently matches nothing.

View Source
const (
	SunKindRed    = "red"
	SunKindOrange = "orange"
	SunKindYellow = "yellow"
	SunKindWhite  = "white"
	SunKindBlue   = "blue"
)

The kinds of star a calendar's sun can be. The sky draws each in its own colour and warms or cools the daylight and the sun's glow to match; yellow draws the sun exactly as it was before suns had a kind.

View Source
const (
	// DefaultWeatherClimate and DefaultWeatherContinuity are what a calendar
	// with no stored setting reports.
	DefaultWeatherClimate    = "temperate"
	DefaultWeatherContinuity = 0.55
	// DefaultForecastDays and MaxForecastDays bound how far ahead a player's
	// forecast reaches: past ten days a guess carries no information.
	DefaultForecastDays = 5
	MaxForecastDays     = 10
)
View Source
const DefaultMoonStrength = 0.4

DefaultMoonStrength is how strongly the sky shows a moon's colour when the moon has no strength of its own (sky_moon.js specFor).

View Source
const MaxEraVersionName = 200

MaxEraVersionName bounds a version's name like a page name.

View Source
const MaxMonthDays = maxCalendarMonthDays

MaxMonthDays is the longest month a calendar can hold.

View Source
const (
	// MaxMoonStateWord is the longest word a Director may give a state.
	MaxMoonStateWord = 40
)

Limits keep a manual moon small.

View Source
const MaxOutcomeChars = 1000

MaxOutcomeChars caps the line on what happened. It is a line, not the event's notes, which keep their own much larger limit.

View Source
const PluginSlug = "calendar"

PluginSlug is the addon slug the calendar plugin gates on.

calendar/routes.go's own RegisterRoutes gates directly on it via addons.RequireAddon. The entity_calendar/entity_worldstate/skybox/ upcoming_events dashboard blocks (internal/app/routes.go) do not call RequireAddon themselves — they register with entities.BlockRegistry, passing this slug as their BlockMeta.Addon, and BlockRegistry.Render is what checks it before rendering each block.

View Source
const RollTableDMOnly = "dm_only"

RollTableDMOnly is a table's Visibility for results only the Director sees.

Variables

View Source
var AnnouncedValues = []string{AnnouncedAhead, AnnouncedOnDay}

AnnouncedValues is the accepted set, for input validation — mirrors the RecurrenceTypes pattern above.

EventStatuses is the accepted set, in the order the event card offers it.

View Source
var MigrationsFS embed.FS

MigrationsFS contains the embedded SQL migration files for the calendar plugin, registered by cmd/server/main.go with the startup migration runner.

MoonStates lists the states in the order the editor offers them.

ParticipationRoles is the ordered, canonical set — the single source of truth a future validator and role picker both read from.

RecurrenceTypes is the accepted set as data, for the handlers' input validation. It is derived from the constants above rather than re-typed, so the handler stays the one validator for one set.

SunKinds lists the kinds in order, coolest-burning first.

View Source
var WeatherClimates = []WeatherClimate{
	{ID: "temperate", Name: "Temperate"},
	{ID: "cold-coast", Name: "Cold coast"},
	{ID: "desert", Name: "Desert"},
	{ID: "tropical", Name: "Tropical"},
	{ID: "highland", Name: "Highland"},
	{ID: "mediterranean", Name: "Warm coast"},
	{ID: "tundra", Name: "Tundra"},
	{ID: "steppe", Name: "Steppe"},
	{ID: "rainforest", Name: "Rainforest"},
	{ID: "savanna", Name: "Savanna"},
	{ID: "taiga", Name: "Taiga"},
	{ID: "storm-isles", Name: "Storm isles"},
	{ID: "bayou", Name: "Bayou"},
	{ID: "fey-wilds", Name: "Fey wilds", Magic: true},
	{ID: "ashlands", Name: "Ashlands", Magic: true},
	{ID: "gloomfen", Name: "Gloomfen", Magic: true},
	{ID: "frostfell", Name: "Frostfell", Magic: true},
	{ID: "leylands", Name: "Leylands", Magic: true},
	{ID: "duskmarch", Name: "Duskmarch", Magic: true},
	{ID: "blightlands", Name: "Blightlands", Magic: true},
}

WeatherClimates is the ordered list the settings form renders.

Functions

func AllPublishedEventTypes

func AllPublishedEventTypes() []string

AllPublishedEventTypes lists every event type a publisher can be handed. The app-layer adapter test walks it so an event type added here without a wire mapping fails the build instead of publishing into nothing.

func EraFeelNumbers

func EraFeelNumbers(feel string) (intensity, speed float64, ok bool)

EraFeelNumbers is the intensity and speed a preset feel stands for, so a caller that picks a feel by name stores the same numbers the era look screen does; ok is false for "custom" and anything unknown.

func EraIndexAt

func EraIndexAt(sorted []Era, y, m, d int) int

EraIndexAt returns the index in sorted (oldest first) of the era a day belongs to, or -1: the latest-starting era that has begun and has not explicitly ended, the rule the calendar page draws by (EraMath.at), so an era with no end gives way to the next one.

func IsEventStatus

func IsEventStatus(s string) bool

IsEventStatus reports whether s is one of EventStatuses.

func IsMoonNightType

func IsMoonNightType(t string) bool

IsMoonNightType reports whether t is one of the five recognized moon-night types.

func IsSunKind

func IsSunKind(k string) bool

IsSunKind reports whether k is one of SunKinds.

func IsSupportedAnnounced

func IsSupportedAnnounced(a string) bool

IsSupportedAnnounced reports whether a is a recognized Announced value.

func IsSupportedRecurrenceType

func IsSupportedRecurrenceType(t string) bool

IsSupportedRecurrenceType reports whether t is a recurrence_type the engine actually expands. The empty string is accepted and means "not recurring".

The comparison is exact and case-sensitive by design: a case-different "WEEKLY" from an integration is rejected loudly rather than coerced, since coercion would turn an undocumented spelling into a supported one.

func MoonLitPath

func MoonLitPath(phase, r float64) string

MoonLitPath returns the SVG path "d" attribute describing the lit portion of a moon's disc at the given phase (0 = new, 0.5 = full, wrapping back to 1 = new), for a disc of radius r centered at the origin. Returns "" within 0.004 of new — no sliver worth drawing — matching the mockup exactly.

func MoonStrength

func MoonStrength(tint *string) (v float64, ok bool)

MoonStrength reads a moon's stored tint as its colour strength, 0 to 1. ok is false when none is set (or what is stored is not a number, which the sky also ignores), and the sky then draws DefaultMoonStrength.

func MoonStrengthTint

func MoonStrengthTint(v float64) (string, error)

MoonStrengthTint is the stored form of a colour strength, refusing one outside 0 to 1.

func NewCalendarWidgetType

func NewCalendarWidgetType(svc CalendarService) widgetbindings.WidgetType

NewCalendarWidgetType builds the "calendar" WidgetType for registration into the widget-binding registry at app startup.

func NewWorldstateWidgetType

func NewWorldstateWidgetType(svc CalendarService) widgetbindings.WidgetType

NewWorldstateWidgetType builds the "worldstate" WidgetType for registration into the widget-binding registry at app startup.

func PrepareImport

func PrepareImport(ir *ImportResult) error

PrepareImport holds an ImportResult built in process (AI Import's calendar block) to the same limits and clamps as an uploaded file, so a calendar made that way can store nothing an upload could not.

func PresetNames

func PresetNames() ([]string, error)

PresetNames returns the available preset ids, sorted for determinism (see import_order_determinism_test.go).

func PublicTextColumns

func PublicTextColumns() []database.PublicTextColumn

PublicTextColumns lists this plugin's stored rich text that is served as stored to everyone who can see its event, for the boot-time reconciler that removes GM-only parts. An event's own visibility is what hides it.

func ReconcileDefaultCalendars

func ReconcileDefaultCalendars(ctx context.Context, store DefaultCalendarStore) (int, error)

ReconcileDefaultCalendars marks the first calendar (by sort order) default in every campaign that has calendars but no default. Calendars made before a campaign's first calendar became its default never got the mark, and the readers that follow "the campaign's calendar" (the Calendar menu link, the header clock, Coming up) showed nothing for them. Idempotent: a campaign with a default is never touched. One campaign's failure is logged and skipped; the count is campaigns repaired.

func ReconcileHarptosSeasons

func ReconcileHarptosSeasons(ctx context.Context, store HarptosSeasonStore) (int, error)

ReconcileHarptosSeasons rewrites the seasons of calendars created from the Harptos preset before its season numbering was fixed, and only those: a calendar qualifies when it has the preset's month layout and its seasons still exactly equal the old preset's (no edited bound, color, description or weather effect, none added or removed). Anything an owner touched is left alone, and a repaired calendar no longer matches, so a second run changes nothing. An idempotent boot reconciler rather than a migration: whether a row is "still the old preset" is a data judgement SQL schema files must not make. Returns the number of calendars repaired; a failure on one calendar is logged and skipped so the rest still get repaired, and the first such error is returned for the caller to log.

func RegisterAppRoutes

func RegisterAppRoutes(g *echo.Group, h *Handler, addonSvc addons.AddonService)

RegisterAppRoutes mounts the calendar on the routes of an app a member allowed (the Foundry calendar window): the calendar page's JSON routes and the fragment the window mounts. g must already authenticate the grant and check campaign access, as the notes grant group does.

func RegisterRoutes

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

RegisterRoutes sets up all calendar-related routes. Calendar routes are scoped to a campaign, gated on the "calendar" addon, and require membership. Shape mirrors internal/plugins/maps/routes.go.

Permissions (.ai/conventions.md):

  • Calendar: view Player, create/edit/delete Owner.
  • Calendar events: view Player (visibility-filtered), create/edit Scribe, delete Owner, the dm_only toggle gated on CanAuthorDmOnly (the Owner or a granted co-DM, never a plain Scribe).
  • Event kinds, eras and the moon hidden flag are calendar STRUCTURE (no Player read route for any of the three; eras reach a player only inside the calendar read, filtered). Listing event kinds stays Owner only; creating/editing/deleting an event kind or an era, and the moon hidden flag, are gated CanAuthorDmOnly like the event visibility toggle above — the Owner or a granted co-Director, never a plain Scribe.

func ValidMoonState

func ValidMoonState(s string) bool

ValidMoonState reports whether s is one of the states.

func ValidateEraLook

func ValidateEraLook(l EraLook) error

ValidateEraLook is the check SaveEraLook runs, for a caller that must refuse a bad look before it saves one.

Types

type AffectedSession

type AffectedSession struct {
	Name                                     string
	OldWorldYear, OldWorldMonth, OldWorldDay int
}

AffectedSession is one session/game-night SessionsInWorldDateRange returns: its display name and its in-world date under the OLD anchor mapping.

type AffectedSessionPreview

type AffectedSessionPreview struct {
	Name     string `json:"name"`
	OldYear  int    `json:"old_year"`
	OldMonth int    `json:"old_month"`
	OldDay   int    `json:"old_day"`
	NewYear  int    `json:"new_year"`
	NewMonth int    `json:"new_month"`
	NewDay   int    `json:"new_day"`
}

AffectedSessionPreview is one session's date under the current anchor and what it would become under the proposed one.

type AnchorMovePreview

type AnchorMovePreview struct {
	// DeltaDays is positive when the move is later, negative when earlier.
	// Zero for a calendar's first-time anchor set (see PreviewAnchorMove's
	// doc comment) — there is no prior mapping to shift away from.
	DeltaDays int `json:"delta_days"`
	// FirstTimeSet is true when the calendar has no anchor yet: there is
	// nothing to warn about moving, since nothing was ever mapped before.
	// Affected is always empty in this case.
	FirstTimeSet bool                     `json:"first_time_set"`
	Affected     []AffectedSessionPreview `json:"affected,omitempty"`
}

AnchorMovePreview is PreviewAnchorMove's read-only result: how many days later/earlier the proposed anchor move shifts every in-world date, plus up to maxAnchorMovePreviewAffected sessions/game-nights it would re-date, so a future UI can render the operator's warning box before the real anchor write is submitted.

type BackupService

type BackupService interface {
	// DayWeatherForBackup returns every stored day reading, lock included.
	DayWeatherForBackup(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) ([]DayWeather, error)
	// RestoreDayWeather stores readings as they were, source and lock
	// included. A reading for a day the calendar does not have, or one that
	// fails the usual checks, is skipped and counted.
	RestoreDayWeather(ctx context.Context, calendarID, campaignID string, days []DayWeather, v permissions.Viewer) (skipped int, err error)
	// RestoreMoonHand puts a moon back to being set by hand, with its words
	// and marks. Marks on days the calendar does not have are skipped and
	// counted.
	RestoreMoonHand(ctx context.Context, calendarID, campaignID string, moonID int, hand MoonHand, v permissions.Viewer) (skipped int, err error)
	// EventRollsForBackup returns, by event id, the roll and stored nights of
	// every event in the calendar that has one; none where rolls are not
	// wired.
	EventRollsForBackup(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (map[string]EventRollBackup, error)
	// RestoreEventRoll sets an event's roll and its stored nights. A table
	// roll is matched to this campaign's table by name; with no such table
	// the roll is left off and dropped is true.
	RestoreEventRoll(ctx context.Context, eventID, calendarID, campaignID string, roll EventRollBackup, v permissions.Viewer) (dropped bool, err error)
}

BackupService is reached by a type assertion on CalendarService, the way MoonMarkService and EventRollService are, so callers that don't back up calendars never see it.

type BatchActor

type BatchActor struct {
	Viewer permissions.Viewer
	UserID string
	// CanDelete is the Owner's right, the same gate as the single delete route.
	CanDelete bool
}

BatchActor is who sends a batch and what the campaign lets them do. The handler fills it from the request; the service never sees Echo.

type Calendar

type Calendar struct {
	ID               string  `json:"id"`
	CampaignID       string  `json:"campaign_id"`
	Mode             string  `json:"mode"` // "fantasy" or "reallife"
	Name             string  `json:"name"`
	Description      *string `json:"description,omitempty"`
	EpochName        *string `json:"epoch_name,omitempty"`
	CurrentYear      int     `json:"current_year"`
	CurrentMonth     int     `json:"current_month"`
	CurrentDay       int     `json:"current_day"`
	HoursPerDay      int     `json:"hours_per_day"`
	MinutesPerHour   int     `json:"minutes_per_hour"`
	SecondsPerMinute int     `json:"seconds_per_minute"`
	CurrentHour      int     `json:"current_hour"`
	CurrentMinute    int     `json:"current_minute"`
	LeapYearEvery    int     `json:"leap_year_every"`
	LeapYearOffset   int     `json:"leap_year_offset"`
	SortOrder        int     `json:"sort_order"`
	IsDefault        bool    `json:"is_default"`
	// Hemisphere flips how a real-world calendar's seasons read (winter in
	// the north is summer in the south); nil means unset (every fantasy
	// calendar, and a real-world one whose owner hasn't chosen yet).
	Hemisphere *string `json:"hemisphere,omitempty"`
	// ForecastsEnabled gates the one exception to "players never learn a
	// future day's weather before it happens": off by default, and even on,
	// a forecast only ever describes days ahead of the current one.
	ForecastsEnabled bool `json:"forecasts_enabled"`
	// MonthStartsNewWeek makes day 1 of every month the first weekday, with
	// intercalary festival days belonging to no week, so a festival never
	// shifts the weekdays that follow it (a Harptos-style calendar: ten-day
	// "tendays" that reset every month, with 1-day festivals between months
	// belonging to no week at all). WeekdayIndex is the single reader of this
	// switch — every weekday placement (recurrence display, a future grid
	// column) goes through it, so the two can never disagree.
	MonthStartsNewWeek bool `json:"month_starts_new_week"`
	// AskWhenDayPasses opens the sheet that asks what became of the events
	// on the days the Director moves today past (event_outcome.go). On by
	// default; the owner turns it off in Calendar settings.
	AskWhenDayPasses bool `json:"ask_when_day_passes"`
	// Per-calendar visibility, mirroring the event model: Visibility is
	// "everyone" | "dm_only"; VisibilityRules is the optional
	// {allowed_users,denied_users} JSON allow/deny override. Resolved by
	// canUserView / filterCalendarsByUser.
	Visibility      string  `json:"visibility"`
	VisibilityRules *string `json:"visibility_rules,omitempty"`
	// Real-time (wall-clock) mode: a flag on `reallife` mode, not a separate
	// mode. TracksRealTime=1 makes the loader compute Current* from the wall
	// clock in RealTimeZone and the date-writers reject manual changes; =0 is
	// stored-not-computed. RealTimeZone is the IANA anchor, required at enable.
	// TracksRealTime is wire-exposed (UsesRealTime gates MonthDays/absDayIndex/
	// WeekdayIndex on it, not on Mode alone, so the browser's CalDate/SkyWorld
	// mirrors need it to pick the same branch). RealTimeZone stays off the
	// wire; the calendar page hands it to members alone, for game-night
	// times (CalendarViewData.Zone).
	TracksRealTime bool    `json:"tracks_real_time"`
	RealTimeZone   *string `json:"-"`
	// The real-date anchor: one in-world date and the Gregorian date it
	// equals, from which every other day follows by AbsoluteDay arithmetic.
	//
	// All four or none — a partial anchor maps nothing, so HasRealAnchor()
	// requires the set and the service refuses to write a subset.
	//
	// Serialized, unlike the real-time pair above: the Foundry module and the
	// export both need to know which real date a session lands on. It carries
	// no zone and no time.
	AnchorYear     *int       `json:"anchor_year,omitempty"`
	AnchorMonth    *int       `json:"anchor_month,omitempty"`
	AnchorDay      *int       `json:"anchor_day,omitempty"`
	AnchorRealDate *time.Time `json:"anchor_real_date,omitempty"`
	CreatedAt      time.Time  `json:"created_at"`
	UpdatedAt      time.Time  `json:"updated_at"`

	// EraLook is how the eras look behind the month (migration 024).
	EraLook EraLook `json:"era_look"`

	// Sun is the kind of star the sky draws (migration 030).
	Sun SunLook `json:"sun"`

	// Eager-loaded sub-resources (populated by service, not by every query).
	Months   []Month   `json:"months,omitempty"`
	Weekdays []Weekday `json:"weekdays,omitempty"`
	Moons    []Moon    `json:"moons,omitempty"`
	Seasons  []Season  `json:"seasons,omitempty"`
	Eras     []Era     `json:"eras,omitempty"`
	// EventKinds is the campaign's shared kind list (see EventKind), not this
	// calendar's own — every calendar in a campaign sees the same kinds.
	EventKinds []EventKind `json:"event_kinds,omitempty"`
	Cycles     []Cycle     `json:"cycles,omitempty"`
	Festivals  []Festival  `json:"festivals,omitempty"`
	// Weather is nil when no row exists in calendar_weather for this
	// calendar, so the settings page can render current state without a
	// second handler-side fetch.
	Weather *Weather `json:"weather,omitempty"`
}

Calendar is the top-level calendar definition for a campaign.

func (*Calendar) AbsoluteDay

func (c *Calendar) AbsoluteDay(year, month, day int) int

AbsoluteDay returns the total number of days from year 0 day 0 to the given date (year, month 1-indexed, day). Used for moon phase calculation.

The year term MUST stay closed-form: `year` reaches this from unauthenticated query strings on public seed routes, and a per-year summation loop is an O(year) denial-of-service (TestAbsoluteDayClosedFormIsNotLinear). Do not reintroduce a bound on the input instead — a fantasy calendar's year number is authored data, so the fix belongs in the algorithm.

The arithmetic is exactly the loop's, term for term, so no stored date moves:

Σ_{y=0}^{year-1} YearLengthForYear(y)
  = Σ (YearLength() + leapExtraDays if IsLeapYear(y))
  = year·YearLength() + leapExtraDays·|{y ∈ [0,year) : IsLeapYear(y)}|

and leapYearsBefore counts that set in O(1). Year 0 contributes nothing. A negative year counts backwards the same way, subtracting the years in [year, 0), so dates keep their order through year 0 and before it:

-Σ_{y=year}^{-1} YearLengthForYear(y)
  = year·YearLength() - leapExtraDays·|{y ∈ [year,0) : IsLeapYear(y)}|

func (*Calendar) AddDays

func (c *Calendar) AddDays(d DayDate, n int) (DayDate, bool)

AddDays steps a date n days forward (n >= 0) through the calendar's own months and leap rule; false when the calendar has no day to land on.

func (*Calendar) CurrentAbsoluteDay

func (c *Calendar) CurrentAbsoluteDay() int

CurrentAbsoluteDay returns AbsoluteDay for the current date.

func (*Calendar) CurrentDayIndex

func (c *Calendar) CurrentDayIndex() int

CurrentDayIndex is today on the day counter weekdays use (absDayIndex). Moon phases read this one: a real-time calendar's real Moon is anchored to the Julian Day Number, which AbsoluteDay drifts from by a day each leap year.

func (*Calendar) CurrentEra

func (c *Calendar) CurrentEra() *Era

CurrentEra returns the era containing the current date, or nil if none match. Day-granular (EraForDate), since the current date is always known to full precision.

func (*Calendar) CurrentMonthName

func (c *Calendar) CurrentMonthName() string

CurrentMonthName is MonthName for the calendar's own current month.

func (*Calendar) CurrentSeason

func (c *Calendar) CurrentSeason() *Season

CurrentSeason returns the season for the current date, or nil if none match.

func (*Calendar) DateLabel

func (c *Calendar) DateLabel(year, month, day int) string

DateLabel formats a date the way FullDateLabel formats today.

func (*Calendar) DayNumber

func (c *Calendar) DayNumber(year, month, day int) int

DayNumber is a date on the day counter weekdays and moons use, so the days between two dates are the difference of their numbers.

func (*Calendar) DayPart

func (c *Calendar) DayPart(year, month, day, hour, minute int) string

DayPart names the time of day at the calendar's own hour and minute on a date, from the sun the sky draws (sky_world.js makeSkym.sun): the same latitude, solstice on the year's first day, and an hour rescaled to a 24-hour face. Dawn is the morning's twilight, dusk the evening's.

func (*Calendar) EraForDate

func (c *Calendar) EraForDate(year, month, day int) *Era

EraForDate returns the era containing the given date, or nil if none match. Comparisons are lexicographic over (year, month, day) so an era's start/end day within its boundary years is honoured, not just the year.

func (*Calendar) EraForYear

func (c *Calendar) EraForYear(year int) *Era

EraForYear returns the era containing the given year, or nil if none match, ignoring month/day — for callers that only have a year (e.g. legacy data with no finer precision). An era with nil EndYear is ongoing (matches every year >= StartYear). Prefer EraForDate when month/day are known: a year-only check can misplace a date that falls before an era's start day or after its end day within the boundary years.

func (*Calendar) EraIsSecret

func (c *Calendar) EraIsSecret(e *Era) bool

EraIsSecret reports whether e is hidden from players right now: flagged HiddenUntilBegins and starting after the calendar's current date. Every player-facing read asks this one question (finishCalendarForViewer, dropSecretEraEvents, the AI export's Safe mode).

func (*Calendar) FormatCurrentTime

func (c *Calendar) FormatCurrentTime() string

FormatCurrentTime returns the current time formatted as "HH:MM". Pads hours/minutes with leading zeros based on the max values (e.g. a 24-hour system uses 2 digits, a 100-hour system uses 3).

func (*Calendar) FullDateLabel

func (c *Calendar) FullDateLabel() string

FullDateLabel formats the calendar's current date as "<Month> <Day>, <Year>" (e.g. "Deepwinter 12, 1024") — the calendars list card and preview panel's one-line "world date".

func (*Calendar) GetCampaignID

func (c *Calendar) GetCampaignID() string

GetCampaignID returns the campaign ID this calendar belongs to. Implements middleware.CampaignScoped for IDOR protection.

func (*Calendar) GridFirstWeekday

func (c *Calendar) GridFirstWeekday(weekLen int) int

GridFirstWeekday is the weekday index a month grid starts each row on. A real-world calendar keeps its weekdays Monday to Sunday (WeekdayIndex's real-time branch depends on that order), but its grid starts on Sunday like a wall calendar. Every other calendar starts on its own first weekday. Only the grid layout reads this; weekday rules and recurrences keep the stored order.

func (*Calendar) HandStateOn

func (c *Calendar) HandStateOn(m *Moon, year, month, day int) string

HandStateOn is a manual moon's state on a date, "" before its first mark. m must be one of c's moons, with its marks indexed.

func (*Calendar) HasRealAnchor

func (c *Calendar) HasRealAnchor() bool

HasRealAnchor reports whether this calendar's real-date anchor is fully set — see AnchorYear's doc comment for why it is all four fields or none.

func (*Calendar) InSecretEra

func (c *Calendar) InSecretEra(year, month, day int) bool

InSecretEra reports whether a date falls inside an era that is still secret (EraIsSecret). Needs c.Eras loaded, unfiltered.

func (*Calendar) IsLeapYear

func (c *Calendar) IsLeapYear(year int) bool

IsLeapYear returns true if the given year is a leap year according to the calendar's leap year configuration. LeapYearEvery=0 means no leap years.

func (*Calendar) IsRealLife

func (c *Calendar) IsRealLife() bool

IsRealLife returns true if this calendar syncs to real-world time.

func (*Calendar) MonthDays

func (c *Calendar) MonthDays(monthIdx int, year int) int

MonthDays returns the number of days in a month for a given year, accounting for leap year extra days.

Real-time calendars (UsesRealTime) derive month length from the proleptic Gregorian stdlib (daysInGregorianMonth — correct 4/100/400 leap rule) instead of the configurable LeapYearEvery/IsLeapYear fields, which cannot express Gregorian (with LeapYearEvery=4 they render Feb 2100 as 29). Only flagged real-time calendars take this branch — fantasy and reallife-but-manual calendars keep their configured geometry unchanged.

func (*Calendar) MonthName

func (c *Calendar) MonthName(month int) string

MonthName returns the name of the given 1-based month, or a numeric fallback ("Month N") when Months isn't loaded far enough (a list read that didn't eager-load sub-resources, or a month index outside the calendar's own range).

func (*Calendar) SeasonForDate

func (c *Calendar) SeasonForDate(month, day int) *Season

SeasonForDate returns the season containing the given month+day, or nil.

func (*Calendar) UsesRealTime

func (c *Calendar) UsesRealTime() bool

UsesRealTime reports whether this calendar computes its current date from the wall clock (and rejects manual date changes). It is the single predicate gating the real-time seam, the manual-date-write guard, and the stdlib month geometry, so all three agree. Keyed on the flag, not just the mode, so a `reallife`-but-manual calendar (TracksRealTime=0) behaves exactly as before real-time support existed. A nil/blank RealTimeZone is handled by the loader's fail-safe (serve the stored date, never 500).

func (*Calendar) ValidDate

func (c *Calendar) ValidDate(year, month, day int) bool

ValidDate reports whether the calendar has that day: a month it has and a day that month has in that year, leap days included.

func (*Calendar) WeekLength

func (c *Calendar) WeekLength() int

WeekLength returns the number of days in a week (number of weekdays).

func (*Calendar) WeekdayIndex

func (c *Calendar) WeekdayIndex(year, month, day int) int

WeekdayIndex returns the 0-based index into c.Weekdays that (year, month, day) falls on. It is the single function any weekday renderer (grid column, list badge) calls to place a day in its week — never absDayIndex's modulo directly, so MonthStartsNewWeek's reset/no-week rules apply everywhere or nowhere.

OccursOn's week-based recurrence (weekly/biweekly/custom) reads the same switch through weekRowIndex, so a repeating event keeps its column in the month grid.

Real-time calendars ignore MonthStartsNewWeek entirely: Gregorian weeks are always continuous, matching this method's own MonthStartsNewWeek=false branch below.

When MonthStartsNewWeek is true, day 1 of every month is always the week's first day (a month never inherits a stray offset from the one before it), and a day inside an INTERCALARY month belongs to no week at all — it is a festival day outside the weekday cycle, so a caller must render it in its own between-week band rather than a weekday column. -1 signals that case.

When MonthStartsNewWeek is false (the default), weeks run continuously across month boundaries via the reconciled absDayIndex, guarded against a negative modulo for a year before the calendar's epoch.

func (*Calendar) YearLength

func (c *Calendar) YearLength() int

YearLength returns the total number of days in a year by summing all month lengths. Does not account for leap year — use YearLengthForYear for that.

func (*Calendar) YearLengthForYear

func (c *Calendar) YearLengthForYear(year int) int

YearLengthForYear returns the total days in a specific year, including leap year extra days if applicable.

type CalendarEventDate

type CalendarEventDate struct {
	CalendarID string
	Year       int
	Month      int
	Day        int
	Name       string
}

CalendarEventDate is a lightweight (calendar, date, name) tuple from the batch upcoming read — kept minimal so the cross-calendar query stays cheap.

type CalendarEventPublisher

type CalendarEventPublisher interface {
	PublishCalendarEvent(eventType, campaignID, calendarID string, payload any)
}

CalendarEventPublisher is the seam through which calendar writes reach live subscribers (the Foundry module). payload may be nil.

The service publishes the stored, unfiltered row: it has no recipient. The implementation must therefore deliver only to DM-equivalent recipients, or filter per recipient; it must never broadcast the payload to players.

type CalendarRepository

type CalendarRepository interface {
	// Calendar CRUD.
	Create(ctx context.Context, cal *Calendar) error
	GetByID(ctx context.Context, id string) (*Calendar, error)
	GetDefaultByCampaignID(ctx context.Context, campaignID string) (*Calendar, error)
	ListByCampaignID(ctx context.Context, campaignID string) ([]Calendar, error)
	SetDefault(ctx context.Context, campaignID, calendarID string) error
	Update(ctx context.Context, cal *Calendar) error
	Delete(ctx context.Context, id string) error
	// UpdateVisibility sets the per-calendar visibility + rules, the
	// calendar-level mirror of EventRepository.UpdateEventVisibility.
	UpdateVisibility(ctx context.Context, calendarID string, visibility string, visRules *string) error

	// Months.
	SetMonths(ctx context.Context, calendarID string, months []MonthInput) error
	GetMonths(ctx context.Context, calendarID string) ([]Month, error)

	// Weekdays.
	SetWeekdays(ctx context.Context, calendarID string, weekdays []WeekdayInput) error
	GetWeekdays(ctx context.Context, calendarID string) ([]Weekday, error)

	// Moons.
	SetMoons(ctx context.Context, calendarID string, moons []MoonInput) error
	GetMoons(ctx context.Context, calendarID string) ([]Moon, error)
	// SetMoonHidden toggles one moon's HiddenFromPlayers flag without
	// disturbing the rest of the moon set (a bulk SetMoons replace-all would
	// otherwise force every caller to resend the whole list for a one-flag
	// change). Scoped to calendarID so a moon id from another calendar can't
	// be toggled; returns apperror.NewNotFound when no row matches both ids.
	SetMoonHidden(ctx context.Context, calendarID string, moonID int, hidden bool) error
	// SetMoonTint writes one moon's colour strength (nil for the sky's
	// default), scoped like SetMoonHidden.
	SetMoonTint(ctx context.Context, calendarID string, moonID int, tint *string) error
	// SetMoonLook writes one moon's colour and colour strength together,
	// scoped like SetMoonHidden.
	SetMoonLook(ctx context.Context, calendarID string, moonID int, color string, tint *string) error
	// SetMoonPhase writes one moon's phase offset and colour, scoped like
	// SetMoonHidden.
	SetMoonPhase(ctx context.Context, calendarID string, moonID int, offset float64, color string) error

	// Seasons.
	SetSeasons(ctx context.Context, calendarID string, seasons []Season) error
	GetSeasons(ctx context.Context, calendarID string) ([]Season, error)

	// Eras (day-granular start/end; see Era's doc comment).
	SetEras(ctx context.Context, calendarID string, eras []EraInput) error
	CreateEra(ctx context.Context, calendarID string, input EraInput) (*Era, error)
	// UpdateEra and DeleteEra are scoped to calendarID so an era id can't be
	// reached through the wrong calendar.
	UpdateEra(ctx context.Context, calendarID string, eraID int, input EraInput) error
	DeleteEra(ctx context.Context, calendarID string, eraID int) error
	GetEraByID(ctx context.Context, eraID int) (*Era, error)
	GetEras(ctx context.Context, calendarID string) ([]Era, error)
	// SaveEraLook writes the calendar's era look and the listed eras' look
	// fields together; see its doc comment.
	SaveEraLook(ctx context.Context, calendarID string, look EraLook, eras []EraLookWrite) error
	// SaveSunLook writes the calendar's sun.
	SaveSunLook(ctx context.Context, calendarID string, look SunLook) error
	// SetAskWhenDayPasses writes the calendar's switch for the sheet that
	// asks what became of passed events.
	SetAskWhenDayPasses(ctx context.Context, calendarID string, ask bool) error

	// Cycles (with their entries).
	SetCycles(ctx context.Context, calendarID string, cycles []CycleInput) error
	GetCycles(ctx context.Context, calendarID string) ([]Cycle, error)

	// Festivals.
	SetFestivals(ctx context.Context, calendarID string, festivals []FestivalInput) error
	GetFestivals(ctx context.Context, calendarID string) ([]Festival, error)

	// ApplyImport runs the calendar-import write workflow (calendar fields +
	// months/weekdays/moons/seasons/eras) in one transaction, so a partial
	// failure can't leave a calendar in a mixed state. The caller validates
	// inputs before calling this; validation after BeginTx defeats the point
	// of validating upfront. Cycles are not part of ImportResult (no import
	// format supplies them). Calendaria festivals are parsed and then
	// dropped rather than carried into the result: TODO(#771) add a
	// Festivals field to ImportResult and write it here via SetFestivals.
	// result.Events (#779) is deliberately NOT written by this method: an
	// event's kind slug must be resolved against the target campaign's
	// calendar_event_kinds, which is a cross-aggregate lookup this
	// single-aggregate repository has no business making — see
	// CalendarService.CreateCalendarFromImport, which calls this first and
	// then recreates the events itself via EventRepository.
	ApplyImport(ctx context.Context, cal *Calendar, result *ImportResult) error

	// GetStructureState reads everything a structure save is planned from
	// (structure_edit.go): the calendar row with its months, weekdays,
	// moons, seasons and eras, every event's dates and every day-weather
	// reading's date.
	GetStructureState(ctx context.Context, calendarID string) (*StructureState, error)
	// ApplyStructure is the owner's structure save in one transaction. It
	// locks the calendar row, reads the same state GetStructureState does
	// through the transaction, and hands it to plan; an error from plan
	// rolls back with nothing written and is returned as is. Otherwise it
	// writes plan's StructureWrite: see structure_repository.go for exactly
	// which columns an existing moon or season keeps.
	ApplyStructure(ctx context.Context, calendarID string, plan func(*StructureState) (*StructureWrite, error)) error
}

CalendarRepository defines persistence for calendars and their structure.

func NewCalendarRepository

func NewCalendarRepository(db *sql.DB) CalendarRepository

NewCalendarRepository creates a new MariaDB-backed calendar repository.

type CalendarService

type CalendarService interface {
	// Calendars.
	CreateCalendar(ctx context.Context, campaignID string, input CreateCalendarInput) (*Calendar, error)
	// GetCalendarForViewer returns a calendar only if it belongs to
	// campaignID and v may see it (ADR-049); both failure modes collapse to
	// the same NotFound. Eager-loads every sub-resource; Eras and
	// EventKinds are stripped and Moons are filtered for a viewer that does
	// not skip the per-user layer.
	GetCalendarForViewer(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (*Calendar, error)
	// GetDefaultCalendarForViewer returns the campaign's default calendar
	// (Calendar.IsDefault), gated exactly like GetCalendarForViewer, for
	// callers that want "the campaign's calendar" without already knowing its
	// id — e.g. the skybox dashboard/template block, which is campaign-level
	// and binds to no specific calendar. Returns apperror.NotFound both when
	// the campaign has no default calendar and when it has one the viewer may
	// not see, the same collapse GetCalendarForViewer uses.
	GetDefaultCalendarForViewer(ctx context.Context, campaignID string, v permissions.Viewer) (*Calendar, error)
	// ListCalendars returns a campaign's calendars, role- and per-user
	// visibility-filtered. No sub-resources are eager-loaded (list view).
	ListCalendars(ctx context.Context, campaignID string, v permissions.Viewer) ([]Calendar, error)
	UpdateCalendar(ctx context.Context, calendarID, campaignID string, input UpdateCalendarInput) error
	// SetCurrentDate moves calendarID's current date and time, for a caller
	// that only knows the date (the Foundry sync). A real-time calendar's date
	// follows the wall clock, so it refuses with a validation error (422); a
	// date or time outside the calendar's own months, days, hours or minutes
	// is a bad request (400), so a caller can tell the two apart.
	SetCurrentDate(ctx context.Context, calendarID, campaignID string, year, month, day, hour, minute int) error
	// AdvanceCurrent steps the current date and time forward by hours and
	// whole days of the calendar's own length (advance.go). Same refusals as
	// SetCurrentDate; the caller decides who may.
	AdvanceCurrent(ctx context.Context, calendarID, campaignID string, hours, days int) error
	DeleteCalendar(ctx context.Context, calendarID, campaignID string) error
	SetDefaultCalendar(ctx context.Context, campaignID, calendarID string) error

	// Import / presets (the calendar-creation wizard, #741). PreviewImport
	// and PreviewPreset are pure parses — no DB write — so the wizard's
	// Review step can show what a file/preset contains before anything is
	// created. CreateCalendarFromImport does the actual write: see its own
	// doc comment for the current-date and event-kind-slug rules.
	PreviewImport(ctx context.Context, data []byte) (*ImportResult, error)
	PreviewPreset(ctx context.Context, name string) (*ImportResult, error)
	// PreviewRealWorld is the real-world calendar's fixed structure for the
	// wizard; it is built here, never taken from the browser.
	PreviewRealWorld(ctx context.Context) (*ImportResult, error)
	// TodayInZone is today's date on the wall clock of an IANA zone, for a
	// real-world calendar whose date follows the real one.
	TodayInZone(zone string) (year, month, day int, err error)
	CreateCalendarFromImport(ctx context.Context, campaignID string, ir *ImportResult, opts CreateCalendarFromImportOptions) (*Calendar, error)
	// GetPrimaryCalendarForViewer is "the campaign's calendar" for a caller
	// that can only follow one: the default, or when no calendar is marked
	// default, the first by sort order. Gated like GetCalendarForViewer, and
	// NotFound when the campaign has none or the viewer may not see it. The
	// fallback never picks a different calendar for a viewer who can't see
	// the default.
	GetPrimaryCalendarForViewer(ctx context.Context, campaignID string, v permissions.Viewer) (*Calendar, error)

	// Events. CreateEvent has no stored row to weigh a viewer against, so it
	// takes no Viewer: authorization for its one viewer-dependent decision
	// (may this caller author dm_only content) travels pre-resolved on
	// CreateEventInput.CanAuthorDmOnly, set by the handler from the request
	// viewer — see that field's doc comment. Every method below THIS point
	// takes a permissions.Viewer: an event on a calendar the viewer cannot
	// see, or an event the viewer cannot see itself, must answer identically
	// to one that doesn't exist — a write is not an exception to that (a
	// caller who cannot GET an event must not be able to PUT it either).
	// Visibility writes are further gated by who may AUTHOR dm_only content:
	// v.SkipsPerUserRules() is exactly campaigns.CanAuthorDmOnly()'s
	// condition when the caller's Viewer was built from cc.VisibilityRole()
	// (see handler.go's viewerFrom) — an Owner or a granted co-DM, never a
	// plain Scribe. visibility_rules carries no such gate (canChangeVisibility's
	// doc comment says why).
	CreateEvent(ctx context.Context, calendarID, campaignID string, input CreateEventInput) (*Event, error)
	// GetEventForViewer is GetEvent's viewer-aware sibling: it returns
	// NotFound (never the event) unless the event belongs to calendarID,
	// calendarID belongs to campaignID AND is itself visible to v, AND the
	// event is visible to v. Like ListEventsForMonth, a future event not yet
	// announced (dropUnannouncedFutureEvents) is not found for a player.
	GetEventForViewer(ctx context.Context, eventID, calendarID, campaignID string, v permissions.Viewer) (*Event, error)
	// EventPages lists the pages tied to an event (entity_event_links) that v
	// may see, by name. The event must pass GetEventForViewer's gates or this
	// answers NotFound; a page v may not see is left out.
	EventPages(ctx context.Context, eventID, calendarID, campaignID string, v permissions.Viewer) ([]EntityTieRef, error)
	// LinkEventPage ties a page of the same campaign to an event, and
	// UnlinkEventPage removes the tie (a no-op when there is none). Both are
	// gated like UpdateEvent: the calendar and the event must be visible to v.
	LinkEventPage(ctx context.Context, eventID, calendarID, campaignID, entityID string, v permissions.Viewer) error
	UnlinkEventPage(ctx context.Context, eventID, calendarID, campaignID, entityID string, v permissions.Viewer) error
	// ListEventsByIDsForViewer is GetEventForViewer for many ids in one
	// round of queries: the same calendar gate, event visibility, unannounced
	// and linked-entity redaction rules, with an event the viewer may not
	// see (or an unknown id, or one on another calendar) simply absent.
	// Results follow the order of eventIDs, duplicates collapsed. An
	// unreadable calendar is NotFound, as for the single read.
	ListEventsByIDsForViewer(ctx context.Context, calendarID, campaignID string, eventIDs []string, v permissions.Viewer) ([]Event, error)
	// GetCalendarNameForViewer returns just the calendar's name, gated like
	// GetCalendarForViewer but without eager-loading its sub-resources, for
	// display-only callers.
	GetCalendarNameForViewer(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (string, error)
	// ListEventsForMonth applies the same player filtering as
	// ListUpcomingEvents, including dropping future events not yet announced.
	ListEventsForMonth(ctx context.Context, calendarID, campaignID string, year, month int, v permissions.Viewer) ([]Event, error)
	// ListEraEventsForViewer returns the events dated within one era, as the
	// viewer may see that era (its end may be cleared, or the era withheld
	// entirely, by erasForPlayer) and filtered like ListEventsForMonth.
	// Oldest first, at most maxEraEvents; total counts every match.
	ListEraEventsForViewer(ctx context.Context, eraID int, calendarID, campaignID string, v permissions.Viewer) (events []Event, total int, err error)
	// ListEventIndexForViewer returns a compact calendar-wide event list
	// (id, name, date) for pickers that need events outside the loaded
	// months. It is filtered exactly like ListEraEventsForViewer: role and
	// per-user rules, unannounced future events and secret-era events are
	// dropped for a non-author. q narrows by case-insensitive name match;
	// the list is date-ordered and capped at maxEventIndex, truncated says
	// whether matches were left out.
	ListEventIndexForViewer(ctx context.Context, calendarID, campaignID, q string, v permissions.Viewer) (entries []EventIndexEntry, truncated bool, err error)
	// ListUpcomingEvents returns up to limit events on or after the
	// calendar's current date, chronological, viewer-filtered exactly like
	// ListEventsForMonth (SQL role filter + per-user visibility_rules +
	// hidden-entity-link redaction). Powers the "what's coming up" dashboard
	// and category-dashboard preview blocks (campaigns.dashCalendarPreview/
	// dashCalendarFull, entities.catCalendarPreview) and the calendar
	// preview's "Coming up" list — none of them are scoped to a single
	// month, unlike ListEventsForMonth. Does not expand
	// recurrence beyond each event's own stored date (the repository read
	// this wraps is a literal date-range scan); a recurring event only
	// appears here on its next literal occurrence row, not a virtual one.
	ListUpcomingEvents(ctx context.Context, calendarID, campaignID string, limit int, v permissions.Viewer) ([]Event, error)
	UpdateEvent(ctx context.Context, eventID, calendarID, campaignID string, input UpdateEventInput, v permissions.Viewer) error
	DeleteEvent(ctx context.Context, eventID, calendarID, campaignID string, v permissions.Viewer) error
	// SetEventVisibility is the dm_only toggle's dedicated action endpoint;
	// its route already requires campaigns.CanAuthorDmOnly, but the check
	// is repeated here (v.SkipsPerUserRules()) rather than trusted blindly.
	SetEventVisibility(ctx context.Context, eventID, calendarID, campaignID string, input UpdateEventVisibilityInput, v permissions.Viewer) error
	// ListPassedEvents lists what the calendar asks about when today moves
	// from from to to (event_outcome.go), filtered for v like a month read.
	ListPassedEvents(ctx context.Context, calendarID, campaignID string, from, to DayDate, v permissions.Viewer) (*PassedEvents, error)
	// SetAskWhenDayPasses turns that question on or off for the calendar.
	SetAskWhenDayPasses(ctx context.Context, calendarID, campaignID string, ask bool) error

	// Repeat rules and "this one only" (service_recurrence.go). The override
	// writes are gated like editing the event (Scribe+ at the route, the
	// event visible to v); the preview is gated like a read and writes
	// nothing. ListOccurrenceOverrides is system-only, for the export.
	SetOccurrenceOverride(ctx context.Context, eventID, calendarID, campaignID string, occ DayDate, input OccurrenceOverrideInput, v permissions.Viewer) (*OccurrenceOverride, error)
	DeleteOccurrenceOverride(ctx context.Context, eventID, calendarID, campaignID string, occ DayDate, v permissions.Viewer) error
	PreviewRecurrence(ctx context.Context, calendarID, campaignID string, input RecurrencePreviewInput, v permissions.Viewer) (*RecurrencePreview, error)
	ListOccurrenceOverrides(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (map[string][]OccurrenceOverride, error)

	// Event kinds. Campaign-scoped (shared by every calendar in the
	// campaign, see EventKind's doc comment) — calendar structure, not
	// content a Player ever reads directly. Listing is Owner only end to
	// end; creating, editing and deleting are CanAuthorDmOnly (Owner or a
	// granted co-Director), gated at the route (routes.go).
	ListEventKinds(ctx context.Context, campaignID string) ([]EventKind, error)
	CreateEventKind(ctx context.Context, campaignID string, input EventKindInput) (*EventKind, error)
	UpdateEventKind(ctx context.Context, kindID int, campaignID string, input UpdateEventKindInput) error
	DeleteEventKind(ctx context.Context, kindID int, campaignID string) error

	// Eras. Calendar structure, gated CanAuthorDmOnly (Owner or a granted
	// co-Director) at the route (routes.go), resolved through the calendar
	// the caller reached (GetEraByID itself is not calendar-scoped; this
	// service never calls it with an untrusted id without also checking the
	// result's CalendarID — see eraInCalendar).
	CreateEra(ctx context.Context, calendarID, campaignID string, input EraInput) (*Era, error)
	UpdateEra(ctx context.Context, eraID int, calendarID, campaignID string, input UpdateEraInput) error
	DeleteEra(ctx context.Context, eraID int, calendarID, campaignID string) error
	// SaveEraLook writes the calendar's era look and its eras' colours,
	// styles and feels at once (the Era look part of the calendar settings).
	// Owner only at the route, like the rest of the calendar settings.
	SaveEraLook(ctx context.Context, calendarID, campaignID string, look EraLook, eras []EraLookEra) error
	// SaveSunLook writes the calendar's sun: its kind of star and an
	// optional exact colour. Owner only, like the rest of the settings.
	SaveSunLook(ctx context.Context, calendarID, campaignID string, look SunLook) error

	// Moon. Calendar structure; the hidden flag is gated CanAuthorDmOnly
	// (Owner or a granted co-Director) at the route (routes.go).
	SetMoonHidden(ctx context.Context, moonID int, calendarID, campaignID string, hidden bool) error
	// SetMoonStrength sets how strongly the sky shows a moon's colour, 0 to
	// 1; nil returns it to the sky's default.
	SetMoonStrength(ctx context.Context, moonID int, calendarID, campaignID string, strength *float64) error
	// SetMoonLook sets a moon's colour and how strongly the sky shows it, as
	// the sky's hand controls save them. Owner only at the route, like the
	// sun's look.
	SetMoonLook(ctx context.Context, moonID int, calendarID, campaignID, color string, strength *float64) error
	// SetMoonPhase sets an existing moon's phase offset and colour, the two
	// a structure save leaves as stored. A real-time calendar's moons follow
	// the real sky, so they are refused.
	SetMoonPhase(ctx context.Context, moonID int, calendarID, campaignID string, offset float64, color string) error
	// MoonsForEntity lists the moons whose lore page is entityID, in every
	// calendar v may open and, for anyone who does not skip the per-user
	// layer, without hidden moons, each with tonight's phase name on its
	// calendar's current date. It does not judge whether v may see the
	// entity itself; the entity page asking has already shown it to them.
	MoonsForEntity(ctx context.Context, campaignID, entityID string, v permissions.Viewer) ([]EntityMoonRef, error)
	// PageTimeline lays the events that belong to entityID (its linked
	// events and its ties) on the campaign's calendar: the default one, else
	// the first. Each event passes every filter a month read applies for v,
	// so a player's line never holds what their calendar would not show;
	// hideDMOnly also drops Director-only events for everyone (the block's
	// own setting). NotFound when the campaign has no calendar v may open.
	// Like MoonsForEntity it does not judge whether v may see the page.
	PageTimeline(ctx context.Context, campaignID, entityID string, hideDMOnly bool, v permissions.Viewer) (*PageTimeline, error)

	// PreviewAnchorMove is a READ-ONLY preview of moving a real-anchored
	// calendar's anchor: it computes the day shift and up to three affected
	// sessions but writes nothing. Owner-only (see routes.go); the real
	// anchor write this previews is a separate, not-yet-built endpoint.
	PreviewAnchorMove(ctx context.Context, calendarID, campaignID string, newAnchorYear, newAnchorMonth, newAnchorDay int, newRealDate time.Time) (*AnchorMovePreview, error)

	// PreviewStructureEdit and ApplyStructureEdit are the owner's structure
	// editor for an existing calendar (structure_edit.go): months, weekdays,
	// the leap rule, moons and seasons. Preview writes nothing; Apply
	// recomputes the same plan, refuses a stale fingerprint with a
	// Conflict (returning the fresh preview), and writes everything in one
	// transaction. Owner-only at the route. A calendar that follows the
	// real-world date is refused (its months are the Gregorian ones).
	PreviewStructureEdit(ctx context.Context, calendarID, campaignID string, edit StructureEdit) (*StructurePreview, error)
	ApplyStructureEdit(ctx context.Context, calendarID, campaignID, fingerprint string, edit StructureEdit) (*StructurePreview, error)

	// --- Bulk structure writers ---
	//
	// SetMonths/SetWeekdays/SetMoons/SetSeasons replace a calendar's whole
	// list for that sub-resource in one call. They exist for the campaign
	// import path (calendarImportAdapter, internal/app/export_adapters.go)
	// and the calendar plugin's own native/Simple-Calendar/Calendaria import
	// (internal/plugins/calendar/import.go), neither of which has a stored
	// row per item to update incrementally the way CreateEra/CreateEventKind
	// do. No HTTP route calls them: the owner's structure editor writes
	// through ApplyStructureEdit above instead, so today's only callers are
	// trusted in-process ones; a caller reaching these through a future
	// HTTP handler must still be gated there.
	SetMonths(ctx context.Context, calendarID, campaignID string, months []MonthInput) error
	SetWeekdays(ctx context.Context, calendarID, campaignID string, weekdays []WeekdayInput) error
	SetMoons(ctx context.Context, calendarID, campaignID string, moons []MoonInput) error
	SetSeasons(ctx context.Context, calendarID, campaignID string, seasons []Season) error
	// SetCycles/SetFestivals/SetWeather are the same bulk-replace shape as
	// the four above, giving the campaign-backup importer a service-level
	// caller for the repository side (CalendarRepository.SetCycles/
	// SetFestivals, WeatherRepository.Set) from outside this package.
	SetCycles(ctx context.Context, calendarID, campaignID string, cycles []CycleInput) error
	SetFestivals(ctx context.Context, calendarID, campaignID string, festivals []FestivalInput) error
	SetWeather(ctx context.Context, calendarID, campaignID string, input WeatherInput) error

	// Day weather: one reading per calendar day. ListDayWeather gives a
	// Player only days up to the calendar's today (future weather is the
	// Director's alone); an Owner or co-Director sees every day. The writes
	// are gated CanAuthorDmOnly at the route (routes.go).
	ListDayWeather(ctx context.Context, calendarID, campaignID string, year, month int, v permissions.Viewer) ([]DayWeather, error)
	SetDayWeather(ctx context.Context, calendarID, campaignID string, days []DayWeatherInput) error
	ClearDayWeather(ctx context.Context, calendarID, campaignID string, dates []DayDate) error
	// LockDayWeather sets or clears the lock on days that already hold a
	// reading and returns how many changed. A locked day is skipped by
	// generated writes; a painted write clears the lock.
	LockDayWeather(ctx context.Context, calendarID, campaignID string, dates []DayDate, locked bool) (int, error)
	// ListWeatherForecast is the blurred outlook players are shown for the
	// days after the calendar's today. Empty when forecasts are off.
	ListWeatherForecast(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) ([]ForecastEntry, error)

	// Weather settings: the world's climate and how long weather lasts.
	// Get never returns nil (defaults when unset); Set validates and
	// stores.
	GetWeatherSettings(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (*WeatherSettings, error)
	SetWeatherSettings(ctx context.Context, calendarID, campaignID string, s WeatherSettings) error

	// ListAllEventsForCalendar returns every event for a calendar with no
	// role or per-user visibility filter — a bulk, unredacted read for
	// SYSTEM-ONLY callers that apply their own gating afterward: the
	// campaign export walk (calendarExportAdapter) and the Director-only AI
	// export (aiexport.CalendarLister). v must be a permissions.SystemViewer
	// (ADR-049); any other viewer is refused, since nothing here re-checks
	// per-event visibility the way ListEventsForMonth's SQL role filter +
	// filterEventsByUser do — a caller that isn't declaring system trust
	// must not get the unfiltered list.
	ListAllEventsForCalendar(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) ([]Event, error)

	// SearchCalendarEvents implements entities.CalendarSearcher (wired from
	// internal/app/routes.go): campaign-wide calendar-event search results
	// for the global quick-search popup. Role-only picker convention,
	// matching CalendarEventLister's shape in
	// internal/plugins/timeline/service.go: the interface carries no
	// per-request user id, so a calendar's own visibility_rules allow/deny
	// list is not evaluated — only role-level dm_only gating, at both the
	// calendar (ListCalendars already filters those out) and each event
	// (EventRepository.SearchEvents' own SQL role filter).
	SearchCalendarEvents(ctx context.Context, campaignID, query string, role int) ([]map[string]string, error)

	// ListEventsForCalendar and ListErasForCalendar back timeline's calendar
	// selector, event picker and era bands (internal/app/routes.go's
	// calendarEventListerAdapter/calendarEraListerAdapter). Both are
	// campaign-scoped: a calendar id from a different campaign, or one the
	// role cannot see, answers with an empty slice, never an error.
	// ListEventsForCalendar filters dm_only events like every other
	// role-only read here; ListErasForCalendar additionally gates on role
	// alone, Owner/co-DM only, because eras are calendar structure
	// (GetCalendarForViewer strips them the same way).
	ListEventsForCalendar(ctx context.Context, campaignID, calendarID string, role int) ([]Event, error)
	ListErasForCalendar(ctx context.Context, campaignID, calendarID string, role int) ([]Era, error)
}

CalendarService defines the calendar plugin's business logic. Handlers call it; it never imports Echo.

func NewCalendarService

func NewCalendarService(calRepo CalendarRepository, eventRepo EventRepository, kindRepo EventKindRepository, weatherRepo WeatherRepository) CalendarService

NewCalendarService constructs a CalendarService over the four repositories.

type CalendarUpcoming

type CalendarUpcoming struct {
	Next   *CalendarEventDate
	Agenda []CalendarEventDate
}

CalendarUpcoming is a calendar's next upcoming event + a short agenda, computed from the batch read relative to that calendar's own current date. Next is nil when the calendar has none upcoming.

type CalendarViewData

type CalendarViewData struct {
	CampaignID string
	CalendarID string
	Calendar   *Calendar
	// CurrentMonthEvents is ListEventsForMonth for the calendar's own
	// current (year, month) — the month the grid opens on — so first paint
	// needs no extra fetch. Later months are fetched by the widget itself.
	CurrentMonthEvents []Event
	// CanEdit gates the whole owner-editing surface (edit mode, the
	// structure/moon drawer, the bulk bar, new-kind-in-place): Owner or a
	// granted co-Director, per campaigns.CampaignContext.CanAuthorDmOnly's
	// doc comment. It does NOT mean every write it exposes will succeed —
	// deleting an event (DELETE .../events/:eid) is gated strictly RoleOwner
	// server-side (routes.go), so a co-Director sees that one affordance
	// 403; the widget checks ViewerRole for it. Event kinds, eras and the
	// moon hidden flag are CanAuthorDmOnly like everything else CanEdit
	// covers, so those affordances work for a co-Director too.
	CanEdit bool
	// CanAuthorDmOnly threads campaigns.CanAuthorDmOnly() through separately
	// from CanEdit (which already implies it) so the widget can tell "may
	// edit at all" from "may also toggle event visibility" if the two ever
	// diverge — they don't today (CanEdit's own definition is this OR
	// RoleOwner), but a future role between the two would need this.
	CanAuthorDmOnly bool
	// ViewerRole is cc.MemberRole as a plain int (campaigns.RoleOwner == 3,
	// RoleScribe == 2, RolePlayer == 1, RoleNone == 0) — ferried to the
	// widget so it can gate the one remaining Owner-only slice of the
	// editing surface (deleting an event) separately from CanEdit's broader
	// co-Director allowance.
	ViewerRole int
	// ViewerID is the viewer's own user id, so the widget can tell their
	// own row in a list of players (no reminder button on yourself).
	ViewerID string
	// Zone is the real-world calendar's own IANA zone, which game-night
	// times are shown in until a member asks for their own. Members only:
	// they are the ones shown game nights.
	Zone string
}

CalendarViewData is everything CalendarViewPage (the templ component) needs to render the page shell and seed the widget's first paint.

type CalendarsListData

type CalendarsListData struct {
	CampaignID   string
	CampaignName string
	Calendars    []Calendar
	// MonthEvents is each calendar's current-month events, keyed by
	// calendar id, for the month its card peeks on hover. A calendar whose
	// read failed is absent and peeks with no marks.
	MonthEvents map[string][]Event
	IsOwner     bool
	CSRFToken   string
	// JustCreated/NewCalendarID announce the calendar the wizard just made
	// (its redirect carries ?new=<id>). Both are "" unless that id is one of
	// the calendars listed here; the name is the stored one, never taken from
	// the URL, so a crafted link can't make the page announce arbitrary text.
	JustCreated   string
	NewCalendarID string
	// OpenWizard is the wizard step the page opens on load (?wizard=), so a
	// link can land on a step without the step's bare dialog becoming the
	// whole page. Only known steps, and only for the owner; "" otherwise.
	OpenWizard string
}

CalendarsListData is the view model for the calendars list page.

type ChronicleExport

type ChronicleExport struct {
	Format   string         `json:"format"`  // "chronicle-calendar-v1"
	Version  int            `json:"version"` // schema version (2)
	Calendar ExportCalendar `json:"calendar"`
	// Events is written by BuildExport and read back by parseChronicle into
	// ImportResult.Events (#779), then recreated by
	// CalendarService.CreateCalendarFromImport.
	Events []ExportEvent `json:"events,omitempty"`
}

ChronicleExport is the top-level JSON envelope for calendar export. This is Chronicle's native format — a superset of what can be imported from external sources (Simple Calendar, Calendaria).

func BuildExport

func BuildExport(cal *Calendar, events []Event, includeEvents bool) *ChronicleExport

BuildExport creates a ChronicleExport from a fully-loaded Calendar and optional events. The calendar must have sub-resources eager-loaded.

type ClimatePlace

type ClimatePlace struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Climate     string `json:"climate"`
	ClimateName string `json:"climate_name"`
	ParentID    string `json:"parent_id,omitempty"`
}

ClimatePlace is a page with a climate of its own.

type ClimateRef

type ClimateRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

ClimateRef names a climate.

type CreateCalendarFromImportOptions

type CreateCalendarFromImportOptions struct {
	CurrentYear  *int
	CurrentMonth *int
	CurrentDay   *int
}

CreateCalendarFromImportOptions carries the caller's explicit choice for the calendar CreateCalendarFromImport is about to create's current ("today") date. CreateCalendarFromImport never falls back to an undocumented default (#741 — "an import never silently resets the calendar's current date"): when the import itself left a field of ImportResult.Today unspecified (Month/Day nil — Calendaria only ever determines a year), the matching field here MUST be set or CreateCalendarFromImport returns a validation error instead of silently picking day 1. CurrentYear is optional even then — the import always determines a year, and this only overrides it when the caller wants the calendar to start somewhere else than the source file did.

type CreateCalendarInput

type CreateCalendarInput struct {
	Mode             string // "fantasy" or "reallife"
	Name             string
	Description      *string
	EpochName        *string
	CurrentYear      int
	HoursPerDay      int
	MinutesPerHour   int
	SecondsPerMinute int
	LeapYearEvery    int
	LeapYearOffset   int
	Visibility       string
	VisibilityRules  *string
}

CreateCalendarInput is the validated input for creating a calendar.

Visibility/VisibilityRules default to "everyone" when left blank (the ordinary create-a-calendar route never sets them), mirroring CreateEventInput's own default. The route that exposes calendar creation is Owner-only, so no separate CanAuthorDmOnly gate is needed the way CreateEvent needs one for Scribes.

type CreateEventInput

type CreateEventInput struct {
	Name                     string
	Description              *string
	DescriptionHTML          *string
	EntityID                 *string
	Year                     int
	Month                    int
	Day                      int
	StartHour                *int
	StartMinute              *int
	EndYear                  *int
	EndMonth                 *int
	EndDay                   *int
	EndHour                  *int
	EndMinute                *int
	IsRecurring              bool
	RecurrenceType           *string
	RecurrenceInterval       *int
	RecurrenceEndYear        *int
	RecurrenceEndMonth       *int
	RecurrenceEndDay         *int
	RecurrenceMaxOccurrences *int
	// RecurrenceRule is the raw rule JSON (nil or "null" for none), parsed
	// and validated by the service so a bad rule gets a precise 400.
	RecurrenceRule  json.RawMessage
	Visibility      string
	VisibilityRules *string
	// KindID references calendar_event_kinds.id; nil = no kind.
	KindID *int
	// Announced: nil = inherit from the kind's default (see
	// Event.EffectiveAnnounced).
	Announced *string
	// Tier — campaign tier definition slug; nil = use platform default
	// at render.
	Tier      *string
	Color     *string
	Icon      *string
	AllDay    bool
	Payload   *string
	CreatedBy string
	// Status, Outcome and MovedFrom restore what became of an event from a
	// campaign backup; every other caller leaves them zero (planned).
	Status    string
	Outcome   *string
	MovedFrom *DayDate
	// CanAuthorDmOnly is set by the handler from the request viewer
	// (v.SkipsPerUserRules(), true for an Owner or a granted co-DM) before
	// this reaches the service: CreateEvent has no stored row to compare a
	// visibility change against the way UpdateEvent does, so a create with
	// Visibility "dm_only" (or a non-empty VisibilityRules) is refused
	// outright for a caller this is false for, rather than silently
	// downgraded. Zero value (false) is "not authorized" — a caller that
	// never sets it is never trusted by default.
	CanAuthorDmOnly bool
	// Author is the creating viewer, used only to resolve what a
	// recurrence_rule may reference: a moon or anchor event this viewer
	// cannot see answers as unknown. The zero Viewer sees nothing hidden.
	Author permissions.Viewer
}

CreateEventInput is the validated input for creating a calendar event.

type Cycle

type Cycle struct {
	ID          int          `json:"id"`
	CalendarID  string       `json:"calendar_id"`
	Name        string       `json:"name"`
	CycleLength int          `json:"cycle_length"`
	Type        string       `json:"type"` // "yearly", "monthly", etc.
	SortOrder   int          `json:"sort_order"`
	Entries     []CycleEntry `json:"entries,omitempty"`
}

Cycle is a periodic named cycle (zodiac, elemental, seasonal, etc.). Entries rotate based on cycle_length (number of years per full rotation).

type CycleEntry

type CycleEntry struct {
	ID         int     `json:"id"`
	CycleID    int     `json:"cycle_id"`
	Name       string  `json:"name"`
	Icon       *string `json:"icon,omitempty"`
	YearOffset int     `json:"year_offset"`
	SortOrder  int     `json:"sort_order"`
}

CycleEntry is a single entry within a cycle.

type CycleEntryInput

type CycleEntryInput struct {
	Name       string  `json:"name"`
	Icon       *string `json:"icon"`
	YearOffset int     `json:"year_offset"`
	SortOrder  int     `json:"sort_order"`
}

CycleEntryInput is the input for a single cycle entry.

type CycleInput

type CycleInput struct {
	Name        string            `json:"name"`
	CycleLength int               `json:"cycle_length"`
	Type        string            `json:"type"`
	SortOrder   int               `json:"sort_order"`
	Entries     []CycleEntryInput `json:"entries"`
}

CycleInput is the input for creating/updating a cycle with its entries.

type DatePayload

type DatePayload struct {
	Year   int `json:"year"`
	Month  int `json:"month"`
	Day    int `json:"day"`
	Hour   int `json:"hour"`
	Minute int `json:"minute"`
}

DatePayload is the date.advanced payload, in the shape the Foundry module reads (year, month, day, hour, minute).

type DayDate

type DayDate struct {
	Year  int `json:"year"`
	Month int `json:"month"`
	Day   int `json:"day"`
}

DayDate names one calendar day.

type DayWeather

type DayWeather struct {
	Year               int            `json:"year"`
	Month              int            `json:"month"`
	Day                int            `json:"day"`
	PresetID           *string        `json:"preset_id,omitempty"`
	PresetLabel        *string        `json:"preset_label,omitempty"`
	Icon               *string        `json:"icon,omitempty"`
	Color              *string        `json:"color,omitempty"`
	TemperatureCelsius *float64       `json:"temperature_celsius,omitempty"`
	Wind               *Wind          `json:"wind,omitempty"`
	Precipitation      *Precipitation `json:"precipitation,omitempty"`
	ZoneID             *string        `json:"zone_id,omitempty"`
	ZoneName           *string        `json:"zone_name,omitempty"`
	Description        *string        `json:"description,omitempty"`
	Source             string         `json:"source"`
	// Locked is set only for a viewer who can author Director-only content;
	// a player's reading omits the key so they never learn a day is locked.
	Locked *bool `json:"locked,omitempty"`
	// Place names the place whose weather this is, when it is the party's
	// weather from a place with its own climate and the viewer may open
	// that page.
	Place     *string   `json:"place,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
}

DayWeather is the weather reading for one calendar day. Players see a day only once it is today or past (see CalendarService.ListDayWeather).

func PartyDays

func PartyDays(ctx context.Context, svc DayWeatherLister, calendarID, campaignID string, year, month int, v permissions.Viewer) ([]DayWeather, error)

PartyDays is the weather the world shows: the party's, for every viewer. The header, the DM Screen, Today in the world and Foundry read today's weather through it, so the Director sees there what players see. A service without places reads plain day weather.

type DayWeatherInput

type DayWeatherInput struct {
	Year   int    `json:"year"`
	Month  int    `json:"month"`
	Day    int    `json:"day"`
	Source string `json:"source"`
	WeatherInput
}

DayWeatherInput sets one day's reading: the date, the same flat fields WeatherInput takes, and the source ("manual" when empty).

type DayWeatherLister

type DayWeatherLister interface {
	ListDayWeather(ctx context.Context, calendarID, campaignID string, year, month int, v permissions.Viewer) ([]DayWeather, error)
}

DayWeatherLister is the day-weather read every "today's weather" reader already has.

type DefaultCalendarStore

type DefaultCalendarStore interface {
	// ListCampaignsWithoutDefault returns the campaigns that have calendars
	// but none marked default.
	ListCampaignsWithoutDefault(ctx context.Context) ([]string, error)
	// contains filtered or unexported methods
}

DefaultCalendarStore is the persistence surface ReconcileDefaultCalendars needs. Satisfied by the calendar repository returned from NewCalendarRepository.

type DiceExpr

type DiceExpr struct {
	Count, Sides, Modifier int
}

DiceExpr is a parsed dice expression.

func ParseDice

func ParseDice(s string) (DiceExpr, error)

ParseDice reads "NdM", "NdM+K" or "NdM-K" (N defaults to 1), within the roll limits.

func (DiceExpr) Range

func (d DiceExpr) Range() (lo, hi int)

Range is the lowest and highest total the expression can give.

func (DiceExpr) Roll

func (d DiceExpr) Roll() (total int, faces []int, err error)

Roll throws the dice with crypto/rand, as Chronicle.dice does in the browser: a stored result is a real roll, not a seeded one.

type EntityEraLink struct {
	ID                int     `json:"id"`
	EntityID          string  `json:"entity_id"`
	EraID             int     `json:"era_id"`
	ParticipationRole *string `json:"participation_role,omitempty"`
}

EntityEraLink is one entity<->era tie row. ParticipationRole is nil when the tie carries no finer semantics.

type EntityEraTie

type EntityEraTie struct {
	Era               Era     `json:"era"`
	ParticipationRole *string `json:"participation_role,omitempty"`
}

EntityEraTie is an era as seen from an entity (entity-side query).

type EntityEraVersion

type EntityEraVersion struct {
	EntityID   string
	EraID      int
	Name       *string
	ImagePath  *string
	Entry      *string
	EntryHTML  *string
	EntryRev   int
	FieldsData map[string]any
	UpdatedBy  *string
	UpdatedAt  time.Time
}

EntityEraVersion is one page's version for one era. A nil field means "as the usual page"; FieldsData holds only the values that differ from it.

type EntityEventLink struct {
	ID                int    `json:"id"`
	EntityID          string `json:"entity_id"`
	EventID           string `json:"event_id"`
	ParticipationRole string `json:"participation_role"`
}

EntityEventLink is one entity<->event tie row.

type EntityEventTie

type EntityEventTie struct {
	Event             Event  `json:"event"`
	ParticipationRole string `json:"participation_role"`
}

EntityEventTie is an event as seen from an entity (entity-side query): the linked event + the role. The embedded Event carries date/name for display and linking.

type EntityMoonRef

type EntityMoonRef struct {
	MoonID       int    `json:"moon_id"`
	MoonName     string `json:"moon_name"`
	CalendarID   string `json:"calendar_id"`
	CalendarName string `json:"calendar_name"`
	// PhaseName is the moon's named phase on the calendar's current date.
	PhaseName string `json:"phase_name"`
}

EntityMoonRef is a moon as seen from its lore page: enough to draw a chip ("Luna, Waxing Gibbous tonight") and link into that calendar, with the phase already worked out so the caller needs no calendar maths.

type EntityTieRef

type EntityTieRef struct {
	EntityID          string  `json:"entity_id"`
	EntityName        string  `json:"entity_name"`
	EntityType        string  `json:"entity_type"` // entity_types.slug (e.g. "npc")
	EntityIcon        string  `json:"entity_icon"`
	EntityColor       string  `json:"entity_color"`
	ParticipationRole *string `json:"participation_role,omitempty"`
}

EntityTieRef is an entity as seen from an event/era (event/era-side query): the entity's display info + the role of the tie. Type/Icon/Color come from the entity's entity_type, the same join the event list already uses.

type EntityVisibilityGate

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

EntityVisibilityGate resolves which of a set of entity IDs a viewer (role + user id) may actually see — the same seam maps.MapService uses (maps/service.go's EntityVisibilityGate). An event's entity_id join reads straight from the entities table with no visibility filter of its own (unlike the entity_event_links ties in entity_ties_repository.go, which already replicate entities' own filter), so this is the one place that closes it for the single linked-entity fields on Event.

type Era

type Era struct {
	ID          int     `json:"id"`
	CalendarID  string  `json:"calendar_id"`
	Name        string  `json:"name"`
	StartYear   int     `json:"start_year"`
	StartMonth  int     `json:"start_month"`
	StartDay    int     `json:"start_day"`
	EndYear     *int    `json:"end_year,omitempty"` // nil = ongoing
	EndMonth    *int    `json:"end_month,omitempty"`
	EndDay      *int    `json:"end_day,omitempty"`
	Description *string `json:"description,omitempty"`
	Color       string  `json:"color"`
	SortOrder   int     `json:"sort_order"`
	// Color2 is the era's second colour; nil draws it in Color alone.
	Color2 *string `json:"color_2,omitempty"`
	// Style is how the two colours mix behind the days (EraStyleGas or
	// EraStyleInk). Where two eras meet, the entered era's style shapes it.
	Style string `json:"style"`
	// Feel is the era's own feel (EraFeelStill/Subtle/Lively); nil follows
	// the calendar's EraLook.
	Feel *string `json:"feel,omitempty"`
	// LoreEntityID links a page about the era. LoreEntityName is read with
	// it, scoped to the calendar's campaign; both are blanked for a viewer
	// who may not see that page.
	LoreEntityID   *string `json:"lore_entity_id,omitempty"`
	LoreEntityName string  `json:"lore_entity_name,omitempty"`
	// DMNote is the Director's private note. Only a viewer who skips the
	// per-user layer (Owner, granted co-Director, system) ever receives it.
	DMNote *string `json:"dm_note,omitempty"`
	// HiddenUntilBegins keeps the whole era from players until the
	// calendar's current date reaches its start: see Calendar.EraIsSecret.
	HiddenUntilBegins bool `json:"hidden_until_begins"`
}

Era is a named time period spanning a range of dates (e.g. "First Age", "Age of Fire"). An era begins on a day, not just a year: StartMonth/ StartDay give that day within StartYear. EndYear nil means ongoing; EndMonth/EndDay are set together with EndYear (all three or none — the same all-or-nothing shape Calendar's real-date anchor uses).

func SortedEras

func SortedEras(in []Era) []Era

SortedEras returns the eras oldest first, ties by their own order.

func (*Era) ContainsDate

func (e *Era) ContainsDate(year, month, day int) bool

ContainsDate returns true if the given date falls within this era, honoring its start/end day rather than just the boundary years. Comparisons are lexicographic over (year, month, day). An end year with no end month/day (an era imported without day-level bounds) includes its whole end year, rather than only its first day.

func (*Era) ContainsYear

func (e *Era) ContainsYear(year int) bool

ContainsYear returns true if the given year falls within this era, ignoring month/day — see EraForYear's doc comment for when to prefer this over ContainsDate.

func (*Era) IsOngoing

func (e *Era) IsOngoing() bool

IsOngoing returns true if this era has no end year (still in progress).

type EraEntryConflict

type EraEntryConflict struct {
	Rev       int
	Entry     *string
	EntryHTML *string
	At        time.Time
	ByUserID  string
}

EraEntryConflict is the stored text a save collided with.

type EraExtent

type EraExtent struct {
	// Days is how long the era runs. An era with no end runs to the next
	// era's start; the last one to the calendar's date, and at least a year.
	Days int
	// Here is how far through the era the calendar's date is (0 to 1), or -1
	// when the date is not in it.
	Here float64
	// Span says when it runs, in the calendar's years.
	Span string
}

EraExtent is how one era of PageEras is drawn to scale.

type EraInput

type EraInput struct {
	// ID is nil for a new era, or an existing calendar_eras id to update in
	// place. SetEras upserts on it, so an id present in the calendar but
	// absent from the input list is deleted, and one present in both is
	// updated rather than replaced (preserving entity_era_links, which
	// cascade-delete when the era row itself is deleted and reinserted).
	// Always nil coming from an import file, which has no Chronicle ids.
	ID          *int    `json:"id,omitempty"`
	Name        string  `json:"name"`
	StartYear   int     `json:"start_year"`
	StartMonth  int     `json:"start_month"`
	StartDay    int     `json:"start_day"`
	EndYear     *int    `json:"end_year"`
	EndMonth    *int    `json:"end_month"`
	EndDay      *int    `json:"end_day"`
	Description *string `json:"description"`
	Color       string  `json:"color"`
	SortOrder   int     `json:"sort_order"`
	// Color2/Style/Feel/LoreEntityID/DMNote/HiddenUntilBegins: see Era. An
	// empty Style is read as EraStyleGas.
	Color2            *string `json:"color_2"`
	Style             string  `json:"style"`
	Feel              *string `json:"feel"`
	LoreEntityID      *string `json:"lore_entity_id"`
	DMNote            *string `json:"dm_note"`
	HiddenUntilBegins bool    `json:"hidden_until_begins"`
}

EraInput is the input for creating/updating an era. Field order matches ExportEra, which converts directly to/from this type via a Go type conversion in import.go; keep the two in lockstep.

type EraLook

type EraLook struct {
	ColorsOn  bool    `json:"colors_on"`
	Feel      string  `json:"feel"`
	Intensity float64 `json:"intensity"`
	Speed     float64 `json:"speed"`
}

EraLook is the whole calendar's era colours: ColorsOn switches the tint behind the days off; Feel names the feel, and Intensity/Speed are what it stands for (a custom feel is just numbers no preset matches).

func DefaultEraLook

func DefaultEraLook() EraLook

DefaultEraLook is a calendar's era look until its owner changes it, the same values migration 024's column defaults hold.

type EraLookEra

type EraLookEra struct {
	ID     int
	Color  patch.Field[string]
	Color2 patch.Field[string]
	Style  patch.Field[string]
	Feel   patch.Field[string]
}

EraLookEra is one era's part of a SaveEraLook: only the look fields, each a partial-update field like UpdateEraInput's.

type EraLookWrite

type EraLookWrite struct {
	ID     int
	Color  string
	Color2 *string
	Style  string
	Feel   *string
}

EraLookWrite is one era's resolved look, as SaveEraLook stores it.

type EraVersionRepository

type EraVersionRepository interface {
	EraInCampaign(ctx context.Context, eraID int, campaignID string) (bool, error)
	EntityInCampaign(ctx context.Context, entityID, campaignID string) (bool, error)
	Get(ctx context.Context, entityID string, eraID int) (*EntityEraVersion, error)
	EraIDs(ctx context.Context, entityID string) ([]int, error)
	ForEntities(ctx context.Context, entityIDs []string, eraID int) (map[string]*EntityEraVersion, error)
	ForEra(ctx context.Context, eraID int) ([]*EntityEraVersion, error)
	Create(ctx context.Context, entityID string, eraID int, userID string) error
	SetIdentity(ctx context.Context, entityID string, eraID int, name, imagePath patch.Field[string], userID string) (bool, error)
	SaveEntry(ctx context.Context, entityID string, eraID int, entry, entryHTML string, baseRev *int, userID string) (rev int, saved bool, err error)
	SaveFields(ctx context.Context, entityID string, eraID int, fieldsJSON *string, userID string) (bool, error)
	Delete(ctx context.Context, entityID string, eraID int) error
}

EraVersionRepository is the storage EraVersionService writes through.

func NewEraVersionRepository

func NewEraVersionRepository(db *sql.DB) EraVersionRepository

NewEraVersionRepository builds the MariaDB-backed EraVersionRepository.

type EraVersionService

type EraVersionService interface {
	// PageEras returns the main calendar's eras for v, or nil when the
	// campaign has no main calendar v may see, or it has no eras.
	PageEras(ctx context.Context, campaignID string, v permissions.Viewer) (*PageEras, error)
	// Get returns the page's version for an era, or nil when there is none.
	Get(ctx context.Context, entityID string, eraID int) (*EntityEraVersion, error)
	// EraIDs lists the eras the page has a version for.
	EraIDs(ctx context.Context, entityID string) ([]int, error)
	// ForEntities returns the versions for one era of the given pages, keyed
	// by page id; pages without one are absent.
	ForEntities(ctx context.Context, entityIDs []string, eraID int) (map[string]*EntityEraVersion, error)
	// ForEra lists every page's version for one era, for a campaign backup.
	ForEra(ctx context.Context, eraID int) ([]*EntityEraVersion, error)
	// Create starts an empty version (the usual page in every respect). It
	// is a no-op when one exists.
	Create(ctx context.Context, campaignID, entityID string, eraID int, userID string) error
	// SetIdentity changes the version's name and picture: absent keeps,
	// null goes back to the usual page's.
	SetIdentity(ctx context.Context, campaignID, entityID string, eraID int, name, imagePath patch.Field[string], userID string) error
	// SaveEntry stores the version's text. baseRev is the revision the
	// editor loaded; when it is behind, nothing is saved and the stored text
	// comes back as a conflict. A nil baseRev saves regardless.
	SaveEntry(ctx context.Context, campaignID, entityID string, eraID int, entry, entryHTML string, baseRev *int, userID string) (int, *EraEntryConflict, error)
	// SaveFields replaces the version's changed field values; an empty map
	// means every field is as the usual page.
	SaveFields(ctx context.Context, campaignID, entityID string, eraID int, changed map[string]any, userID string) error
	// Delete removes the version; the page shows its usual self in that era.
	Delete(ctx context.Context, campaignID, entityID string, eraID int) error
}

EraVersionService reads and writes page era versions. Every write names the campaign, and the era must belong to one of its calendars.

func NewEraVersionService

func NewEraVersionService(repo EraVersionRepository, cals mainCalendarReader) EraVersionService

NewEraVersionService builds the service over its repository and the calendar service, which already applies every era visibility rule.

type Event

type Event struct {
	ID                       string  `json:"id"`
	CalendarID               string  `json:"calendar_id"`
	EntityID                 *string `json:"entity_id,omitempty"`
	Name                     string  `json:"name"`
	Description              *string `json:"description,omitempty"`
	DescriptionHTML          *string `json:"description_html,omitempty"`
	Year                     int     `json:"year"`
	Month                    int     `json:"month"`
	Day                      int     `json:"day"`
	StartHour                *int    `json:"start_hour,omitempty"`
	StartMinute              *int    `json:"start_minute,omitempty"`
	EndYear                  *int    `json:"end_year,omitempty"`
	EndMonth                 *int    `json:"end_month,omitempty"`
	EndDay                   *int    `json:"end_day,omitempty"`
	EndHour                  *int    `json:"end_hour,omitempty"`
	EndMinute                *int    `json:"end_minute,omitempty"`
	IsRecurring              bool    `json:"is_recurring"`
	RecurrenceType           *string `json:"recurrence_type,omitempty"`
	RecurrenceInterval       *int    `json:"recurrence_interval,omitempty"`
	RecurrenceEndYear        *int    `json:"recurrence_end_year,omitempty"`
	RecurrenceEndMonth       *int    `json:"recurrence_end_month,omitempty"`
	RecurrenceEndDay         *int    `json:"recurrence_end_day,omitempty"`
	RecurrenceMaxOccurrences *int    `json:"recurrence_max_occurrences,omitempty"`
	RecurrenceDayOfWeek      *int    `json:"recurrence_day_of_week,omitempty"`
	// RecurrenceRule is the rule a RecurrenceByRule event repeats by; nil for
	// every other event. Kept (but unused) if the type later changes, so
	// switching back restores it.
	RecurrenceRule  *RecurrenceRule `json:"recurrence_rule,omitempty"`
	Visibility      string          `json:"visibility"`
	VisibilityRules *string         `json:"visibility_rules,omitempty"`
	// KindID references one of the campaign's calendar_event_kinds by id.
	// Nil means no kind assigned.
	KindID *int `json:"kind_id,omitempty"`
	// Announced is this event's override of its kind's DefaultAnnounced
	// ("ahead" or "on_day" — see EventKind). Nil means "use the kind's
	// default", falling back to "on_day" when the event has no kind, the same
	// nil-means-inherit shape Tier already uses on this struct.
	Announced *string `json:"announced,omitempty"`
	// Tier references one of the campaign's event_tier_definitions by slug.
	// Nil means "use platform default" (render-time fallback).
	Tier   *string `json:"tier,omitempty"`
	Color  *string `json:"color,omitempty"`
	Icon   *string `json:"icon,omitempty"`
	AllDay bool    `json:"all_day"`
	// Payload is one small nullable JSON slot for typed extras that vary by
	// event — a moon night, a sky event — so a new one doesn't need another
	// migration. Raw JSON text, parsed on demand via ParsePayload; nil means
	// no payload. See MoonNightPayload for the one currently-defined shape.
	Payload *string `json:"payload,omitempty"`
	// Status is what became of the event (EventStatus*): planned until
	// someone says otherwise, and an unanswered past event reads as
	// happened. It belongs to a one-off event; a repeating event answers
	// each date with a skip or move override instead.
	Status string `json:"status"`
	// Outcome is the line on what happened, plain text; nil for none. It is
	// part of the event, so whoever sees the event sees it.
	Outcome *string `json:"outcome,omitempty"`
	// MovedFrom* is the day a moved event was planned for, so the calendar
	// keeps a dashed mark there; nil unless Status is EventStatusMoved.
	MovedFromYear  *int      `json:"moved_from_year,omitempty"`
	MovedFromMonth *int      `json:"moved_from_month,omitempty"`
	MovedFromDay   *int      `json:"moved_from_day,omitempty"`
	CreatedBy      *string   `json:"created_by,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`

	// Joined fields for display (populated by some queries).
	EntityName  string `json:"entity_name,omitempty"`
	EntityIcon  string `json:"entity_icon,omitempty"`
	EntityColor string `json:"entity_color,omitempty"`
	// KindName/KindIcon/KindColor/KindSlug are joined from calendar_event_kinds
	// when KindID is set; empty when it is nil.
	KindName  string `json:"kind_name,omitempty"`
	KindSlug  string `json:"kind_slug,omitempty"`
	KindIcon  string `json:"kind_icon,omitempty"`
	KindColor string `json:"kind_color,omitempty"`

	// Occurrences are the dates a repeating event lands on within the range
	// a month read asked for, after skips and moves, worked out on the
	// server so a client never re-implements the rule math. Only month reads
	// fill it; OccurrencesTruncated says a scan bound or the request's
	// budget stopped it before the range was covered, so the list may be
	// short or empty. omitzero, not omitempty: a truncated event still sends
	// "occurrences": [] so a client can tell "unknown" from "not a month read".
	Occurrences          []Occurrence `json:"occurrences,omitzero"`
	OccurrencesTruncated bool         `json:"occurrences_truncated,omitempty"`
}

Event is a calendar entry on a specific date, optionally linked to an entity. Description stores ProseMirror JSON for rich text editing; DescriptionHTML stores pre-rendered sanitized HTML for display (same pattern as entity entries).

func (*Event) EffectiveAnnounced

func (e *Event) EffectiveAnnounced(kind *EventKind) string

EffectiveAnnounced resolves this event's announced setting, in order: the event's own override; "ahead" if the event repeats yearly (a yearly festival is expected knowledge regardless of its kind); its kind's default, only when kind actually matches e.KindID (a caller must not pass an unrelated kind and have it apply); otherwise "on_day".

func (*Event) FormatEndTime

func (e *Event) FormatEndTime() string

FormatEndTime returns the event's end time as "HH:MM", or empty if not set.

func (*Event) FormatTime

func (e *Event) FormatTime() string

FormatTime returns the event's start time as "HH:MM", or empty for all-day events.

func (*Event) FormatTimeRange

func (e *Event) FormatTimeRange() string

FormatTimeRange returns "HH:MM - HH:MM" or just "HH:MM" if no end time.

func (*Event) HasRichText

func (e *Event) HasRichText() bool

HasRichText returns true if this event has a rich text description (ProseMirror JSON with pre-rendered HTML), as opposed to a legacy plain text description.

func (*Event) HasTime

func (e *Event) HasTime() bool

HasTime returns true if this event has a specific start time (not all-day).

func (*Event) IsMultiDay

func (e *Event) IsMultiDay() bool

IsMultiDay returns true if this event spans more than one day.

func (Event) OccursOn

func (e Event) OccursOn(cal *Calendar, year, month, day int) bool

OccursOn reports whether the event lands on (year, month, day) for cal. The single recurrence-expansion predicate; every grid/list projection routes through it.

Non-recurring (or legacy/unknown recurrence_type) events match only their stored date. Recurring types expand forward from the base date:

  • weekly/biweekly/custom: every (interval × week) days, base-anchored.
  • monthly: same day-of-month every interval months, skipped (not clamped) when the month is too short (leap-aware via MonthDays).
  • yearly: same month/day every interval years, skipped when the year's month is too short for that day.

Recurrence stops at the recurrence-end date (inclusive) and/or after RecurrenceMaxOccurrences.

RecurrenceByRule events answer for their base date only here: a rule can depend on another event's dates, which this predicate has no way to see. Their dates come from the occurrence expander (occurrences.go), which every month read goes through.

Multi-day events are not expanded here — OccursOn answers only "does the rule put an instance here", not "is this day inside the stored window"; each consumer decides that separately. TODO(keyxmakerx/Chronicle#741): render a multi-day event's span as one continuous bar (currently only its start date gets marked).

func (*Event) ParsePayload

func (e *Event) ParsePayload() *MoonNightPayload

ParsePayload parses Event.Payload as a MoonNightPayload. Returns nil when there is no payload, it isn't valid JSON, or its type is not one of the MoonNight* constants (a future non-moon-night payload, or JSON "null", which unmarshals into a zero-value, untyped struct) — callers that need to tell those apart should parse e.Payload themselves instead.

func (*Event) ParseVisibilityRules

func (e *Event) ParseVisibilityRules() *VisibilityRules

ParseVisibilityRules parses the JSON visibility rules into a VisibilityRules struct. Returns nil if no rules are set.

func (*Event) PlainDescription

func (e *Event) PlainDescription() string

PlainDescription returns a plain text version of the description for tooltips. For rich text events, returns empty (tooltip should not show raw JSON). For legacy plain text events, returns the description as-is.

type EventBatchInput

type EventBatchInput struct {
	// Create events are made as POST .../events would make them. The caller
	// leaves CanAuthorDmOnly, Author and CreatedBy to ApplyEventBatch.
	Create []CreateEventInput
	// Update items change stored events as PUT .../events/:eid would.
	Update []EventBatchUpdate
	// Delete lists the ids of events to remove.
	Delete []string
	// Weather is optional; Clear runs before Set.
	Weather *EventBatchWeather
}

EventBatchInput is one draft's writes.

type EventBatchRepository

type EventBatchRepository interface {
	ApplyEventBatch(ctx context.Context, calendarID string, w EventBatchWrites) error
}

EventBatchRepository writes a batch atomically. It is separate from EventRepository because it spans events and weather, which are two repositories' tables, in one transaction.

func NewEventBatchRepository

func NewEventBatchRepository(db *sql.DB) EventBatchRepository

NewEventBatchRepository creates the MariaDB-backed batch writer.

type EventBatchResult

type EventBatchResult struct {
	// Created holds the new events' ids, in the order they were sent.
	Created []string `json:"created"`
	Updated int      `json:"updated"`
	Deleted int      `json:"deleted"`
	// WeatherSet and WeatherCleared count the days written and cleared.
	WeatherSet     int `json:"weatherSet"`
	WeatherCleared int `json:"weatherCleared"`
}

EventBatchResult says what a batch did.

type EventBatchService

type EventBatchService interface {
	// ApplyEventBatch applies in to calendarID in one transaction, or changes
	// nothing and returns the refusal.
	ApplyEventBatch(ctx context.Context, calendarID, campaignID string, in EventBatchInput, actor BatchActor) (*EventBatchResult, error)
}

EventBatchService is the batch half of the calendar service. It is its own interface, reached by a type assertion like EventRollService, so CalendarService and its fakes stay as they are.

type EventBatchUpdate

type EventBatchUpdate struct {
	ID    string
	Input UpdateEventInput
}

EventBatchUpdate is one stored event's partial update.

type EventBatchWeather

type EventBatchWeather struct {
	Clear []DayDate
	Set   []DayWeatherInput
}

EventBatchWeather is the weather half of a batch.

type EventBatchWrites

type EventBatchWrites struct {
	Create       []*Event
	Update       []*Event
	DeleteIDs    []string
	ClearWeather []DayDate
	SetWeather   []DayWeatherInput
}

EventBatchWrites is what the repository writes in its one transaction.

type EventIndexEntry

type EventIndexEntry struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Year  int    `json:"year"`
	Month int    `json:"month"`
	Day   int    `json:"day"`
	// Anchorable is false for an event that itself repeats relative to
	// another event: the rule check refuses it as an anchor, so a picker
	// must not offer it.
	Anchorable bool `json:"anchorable"`
	// PhaseOnly marks an event that only names a moon phase ("Full moon of
	// Selune") and says nothing more: the month already shows every moon's
	// phase, so the Moons panel offers these to an owner for removal.
	PhaseOnly bool `json:"phaseOnly,omitempty"`
}

EventIndexEntry is one row of the event index: just enough to name and place an event, never its description or links.

type EventKind

type EventKind struct {
	ID               int    `json:"id"`
	CampaignID       string `json:"campaign_id"`
	Slug             string `json:"slug"`
	Name             string `json:"name"`
	Icon             string `json:"icon"`
	Color            string `json:"color"`
	SortOrder        int    `json:"sort_order"`
	DefaultAnnounced string `json:"default_announced"`
}

EventKind is a campaign-defined event kind (category) for calendar events. Kinds are shared by every calendar in a campaign — keyed by CampaignID, not a single calendar — and carry a slug (referenced by events), display name, emoji icon, color, and the default Announced setting new events of this kind get unless overridden (see Event.EffectiveAnnounced).

func (*EventKind) GetCampaignID

func (k *EventKind) GetCampaignID() string

GetCampaignID implements middleware.CampaignScoped for IDOR protection.

type EventKindInput

type EventKindInput struct {
	Slug             string `json:"slug"`
	Name             string `json:"name"`
	Icon             string `json:"icon"`
	Color            string `json:"color"`
	SortOrder        int    `json:"sort_order"`
	DefaultAnnounced string `json:"default_announced"`
}

EventKindInput is the input for creating/updating an event kind.

type EventKindRepository

type EventKindRepository interface {
	Create(ctx context.Context, campaignID string, input EventKindInput) (*EventKind, error)
	Update(ctx context.Context, id int, campaignID string, input EventKindInput) error
	Delete(ctx context.Context, id int, campaignID string) error
	GetByID(ctx context.Context, id int, campaignID string) (*EventKind, error)
	List(ctx context.Context, campaignID string) ([]EventKind, error)
}

EventKindRepository defines persistence for a campaign's event kinds. Every write is scoped by campaignID in the SQL itself (not just checked after the fact), so a caller can never mutate another campaign's kind by guessing its numeric id.

func NewEventKindRepository

func NewEventKindRepository(db *sql.DB) EventKindRepository

NewEventKindRepository creates a new MariaDB-backed event kind repository.

type EventRepository

type EventRepository interface {
	CreateEvent(ctx context.Context, evt *Event) error
	GetEvent(ctx context.Context, id string) (*Event, error)
	// GetEventsByIDs batch-reads the events with the given ids that belong to
	// calendarID, in no particular order. Unknown ids and ids on another
	// calendar are simply absent. No visibility filtering: the service layer
	// applies the same per-event predicate GetEvent's callers use.
	GetEventsByIDs(ctx context.Context, calendarID string, ids []string) ([]Event, error)
	UpdateEvent(ctx context.Context, evt *Event) error
	DeleteEvent(ctx context.Context, id string) error
	ListEventsForMonth(ctx context.Context, calendarID string, year, month int, role int) ([]Event, error)
	ListEventsForYear(ctx context.Context, calendarID string, year int, role int) ([]Event, error)
	ListEventsForDateRange(ctx context.Context, calendarID string, year, startMonth, startDay, endMonth, endDay int, role int) ([]Event, error)
	ListEventsForEntity(ctx context.Context, entityID string, role int) ([]Event, error)
	ListUpcomingEvents(ctx context.Context, calendarID string, year, month, day int, role int, limit int) ([]Event, error)
	SearchEvents(ctx context.Context, calendarID, query string, role int) ([]Event, error)
	// ListAllEvents returns every event for a calendar with no role filter and
	// no date constraint: for a system caller (a public sync API, an export)
	// that gates by its own means and must apply visibility itself before any
	// of this reaches a player. Sort order is calendar-stable.
	ListAllEvents(ctx context.Context, calendarID string) ([]Event, error)
	// StrandedEventCounts reports, per calendar in a campaign, how many
	// events point at a month position the calendar no longer has. Calendars
	// with none are absent from the map, not present with a zero.
	StrandedEventCounts(ctx context.Context, campaignID string) (map[string]int, error)
	// EventDatesForCalendars batch-reads (year,month,day,name) for every
	// event in the given calendars in one query, role-filtered.
	EventDatesForCalendars(ctx context.Context, calIDs []string, role int) (map[string][]CalendarEventDate, error)

	// UpdateEventVisibility sets visibility and rules; a non-nil announced
	// sets the announce setting in the same statement, nil keeps it.
	UpdateEventVisibility(ctx context.Context, eventID string, visibility string, visRules *string, announced *string) error

	// ListRuleEvents returns a calendar's RecurrenceByRule events, unfiltered,
	// for the anchor-cycle check (an event other rules repeat relative to may
	// not itself repeat relative to another).
	ListRuleEvents(ctx context.Context, calendarID string) ([]Event, error)

	// Occurrence overrides ("this one only"). Upsert is keyed on (event,
	// occurrence date); delete reports whether a row was there.
	SetOccurrenceOverride(ctx context.Context, o OccurrenceOverride) error
	DeleteOccurrenceOverride(ctx context.Context, eventID string, year, month, day int) (bool, error)
	// ListOverridesForEvents batch-reads the overrides of the given events in
	// chunked queries, keyed by event id; events with none are absent.
	ListOverridesForEvents(ctx context.Context, eventIDs []string) (map[string][]OccurrenceOverride, error)

	// Entity ties. Cascade on entity/event/era delete is DB-enforced (ON
	// DELETE CASCADE), so there is no unlink-all.
	LinkEntityEvent(ctx context.Context, entityID, eventID, role string) error
	UnlinkEntityEvent(ctx context.Context, entityID, eventID string) error
	LinkEntityEra(ctx context.Context, entityID string, eraID int, role *string) error
	UnlinkEntityEra(ctx context.Context, entityID string, eraID int) error
	EntitiesForEvent(ctx context.Context, eventID string, role int, userID string) ([]EntityTieRef, error)
	EntitiesForEra(ctx context.Context, eraID int, role int, userID string) ([]EntityTieRef, error)
	EntitiesForCalendar(ctx context.Context, calendarID string, role int, userID string) ([]EntityTieRef, error)
	// EventsForEntity and ErasForEntity take campaignID explicitly: an entity
	// id alone carries no campaign to filter by, and every tie must be
	// confined to one campaign the same way EntitiesFor* are. EventsForEntity
	// is role-filtered like the other event lists.
	EventsForEntity(ctx context.Context, campaignID, entityID string, role int) ([]EntityEventTie, error)
	ErasForEntity(ctx context.Context, campaignID, entityID string) ([]EntityEraTie, error)
	// ListEventsForPage returns a calendar's events that belong to a page:
	// those whose linked page is entityID and those tied to it, each once,
	// role-filtered like the other event lists, in date order.
	ListEventsForPage(ctx context.Context, calendarID, entityID string, role int) ([]Event, error)
}

EventRepository defines persistence for calendar events and their links.

func NewEventRepository

func NewEventRepository(db *sql.DB) EventRepository

NewEventRepository creates a new MariaDB-backed event repository.

type EventRollBackup

type EventRollBackup struct {
	Config    RollConfig
	TableName string
	Nights    []RollNight
}

EventRollBackup is an event's roll and every night stored for it. TableName names a table roll's table, since its id means nothing in another campaign.

type EventRollRepository

type EventRollRepository interface {
	// GetConfig returns an event's roll, or (nil, nil) when it has none.
	GetConfig(ctx context.Context, eventID string) (*RollConfig, error)
	// ConfigsFor returns the rolls of the given events, by event id; an event
	// with no roll is absent.
	ConfigsFor(ctx context.Context, eventIDs []string) (map[string]*RollConfig, error)
	// SetConfig creates or replaces an event's roll.
	SetConfig(ctx context.Context, eventID string, cfg RollConfig) error
	// DeleteConfig removes an event's roll and every stored night.
	DeleteConfig(ctx context.Context, eventID string) error

	// ListNights returns the stored nights in [from, to], in date order.
	ListNights(ctx context.Context, eventID string, from, to DayDate) ([]RollNight, error)
	// PutNights stores results in one transaction. A locked night is never
	// replaced. With onlyNew, a night that already has a result is kept too,
	// so two readers rolling the same arrived night store one result. A
	// written night follows its result's own "tell players" again.
	PutNights(ctx context.Context, eventID string, nights []RollNight, onlyNew bool) error
	// LockNights sets the lock on stored nights and returns how many changed.
	LockNights(ctx context.Context, eventID string, dates []DayDate, locked bool) (int, error)
	// SetTold sets whether players are told one night (nil: as its result
	// says) and returns how many rows changed.
	SetTold(ctx context.Context, eventID string, date DayDate, told *bool) (int, error)
	// ClearNights deletes the stored nights on the given dates, keeping the
	// locked ones when keepLocked, and returns how many were deleted.
	ClearNights(ctx context.Context, eventID string, dates []DayDate, keepLocked bool) (int, error)
}

EventRollRepository defines persistence for event rolls.

func NewEventRollRepository

func NewEventRollRepository(db *sql.DB) EventRollRepository

NewEventRollRepository creates a MariaDB-backed event roll repository.

type EventRollService

type EventRollService interface {
	// GetEventRoll returns an event's roll and its nights in year. A night
	// that arrived unrolled is rolled first when the roll says so.
	GetEventRoll(ctx context.Context, eventID, calendarID, campaignID string, year int, v permissions.Viewer) (*EventRollView, error)
	// ListMonthRolls returns, by event id, the nights of every rolling event
	// the viewer can see in one month.
	ListMonthRolls(ctx context.Context, calendarID, campaignID string, year, month int, v permissions.Viewer) (map[string][]RollNightView, error)
	// SetEventRoll creates or replaces an event's roll; nil removes it and
	// every stored night. Returns the roll as GetEventRoll would for year.
	SetEventRoll(ctx context.Context, eventID, calendarID, campaignID string, cfg *RollConfig, year int, v permissions.Viewer) (*EventRollView, error)
	// RollEventNights rolls nights ahead: every night of a year (leaving a
	// past night that has a result), or the given dates. Locked nights keep
	// their result.
	RollEventNights(ctx context.Context, eventID, calendarID, campaignID string, in RollNightsInput, v permissions.Viewer) (*EventRollView, error)
	// LockEventRollNights locks or unlocks stored nights.
	LockEventRollNights(ctx context.Context, eventID, calendarID, campaignID string, dates []DayDate, locked bool, v permissions.Viewer) (int, error)
	// TellEventRollNight says whether players are told one night; nil goes
	// back to what its result says.
	TellEventRollNight(ctx context.Context, eventID, calendarID, campaignID string, date DayDate, told *bool, v permissions.Viewer) error
	// SetEventRollNight stores the result the Director chose for one night
	// instead of rolling it: a result's name, or for a dice roll a total. A
	// locked night is refused, as a reroll is.
	SetEventRollNight(ctx context.Context, eventID, calendarID, campaignID string, date DayDate, result string, v permissions.Viewer) error
	// ClearEventRollNights deletes a year's stored nights from today on,
	// keeping the locked ones when keepLocked.
	ClearEventRollNights(ctx context.Context, eventID, calendarID, campaignID string, year int, keepLocked bool, v permissions.Viewer) (int, error)
}

EventRollService is the roll half of the calendar service. It is its own interface so CalendarService and its fakes elsewhere stay as they are; calendarService implements both and the handler reaches this one by a type assertion.

type EventRollView

type EventRollView struct {
	EventID string          `json:"event_id"`
	Config  *RollConfig     `json:"config,omitempty"`
	Nights  []RollNightView `json:"nights"`
	// Upcoming are the event's dates in the asked year that have no result,
	// so the Director's list can show them. Director only.
	Upcoming []DayDate `json:"upcoming,omitempty"`
	// Unfit are the nights the roll on the night left unrolled because no
	// line of its table could come up, each with the reason. Director only.
	Unfit []UnfitNight `json:"unfit,omitempty"`
	// Truncated says the event's dates could not all be worked out.
	Truncated bool `json:"truncated,omitempty"`
}

EventRollView is everything a viewer may know about an event's roll. A player gets Nights only, and only the told ones up to today.

type ExportCalendar

type ExportCalendar struct {
	Name             string  `json:"name"`
	Description      *string `json:"description,omitempty"`
	Mode             string  `json:"mode"` // "fantasy" or "reallife"
	EpochName        *string `json:"epoch_name,omitempty"`
	CurrentYear      int     `json:"current_year"`
	CurrentMonth     int     `json:"current_month"`
	CurrentDay       int     `json:"current_day"`
	CurrentHour      int     `json:"current_hour"`
	CurrentMinute    int     `json:"current_minute"`
	HoursPerDay      int     `json:"hours_per_day"`
	MinutesPerHour   int     `json:"minutes_per_hour"`
	SecondsPerMinute int     `json:"seconds_per_minute"`
	LeapYearEvery    int     `json:"leap_year_every"`
	LeapYearOffset   int     `json:"leap_year_offset"`
	// Preserves whether the calendar is wall-clock authoritative and which
	// IANA zone anchors it, so export/re-import round-trips it. RealTimeZone is
	// omitted when unset (manual).
	TracksRealTime     bool    `json:"tracks_real_time"`
	RealTimeZone       *string `json:"real_time_zone,omitempty"`
	Hemisphere         *string `json:"hemisphere,omitempty"`
	ForecastsEnabled   bool    `json:"forecasts_enabled"`
	MonthStartsNewWeek bool    `json:"month_starts_new_week"`
	// EraLook is nil in a file written before era looks existed; the import
	// then keeps the defaults.
	EraLook *EraLook `json:"era_look,omitempty"`
	// Sun is nil in a file written before suns had a kind.
	Sun       *SunLook         `json:"sun,omitempty"`
	Months    []ExportMonth    `json:"months"`
	Weekdays  []ExportWeekday  `json:"weekdays"`
	Moons     []ExportMoon     `json:"moons,omitempty"`
	Seasons   []ExportSeason   `json:"seasons,omitempty"`
	Eras      []ExportEra      `json:"eras,omitempty"`
	Cycles    []ExportCycle    `json:"cycles,omitempty"`
	Festivals []ExportFestival `json:"festivals,omitempty"`
	Weather   *WeatherInput    `json:"weather,omitempty"`
}

ExportCalendar holds the calendar configuration for export.

type ExportCycle

type ExportCycle struct {
	Name        string             `json:"name"`
	CycleLength int                `json:"cycle_length"`
	Type        string             `json:"type"`
	SortOrder   int                `json:"sort_order"`
	Entries     []ExportCycleEntry `json:"entries,omitempty"`
}

ExportCycle is a cycle definition for export.

type ExportCycleEntry

type ExportCycleEntry struct {
	Name       string  `json:"name"`
	Icon       *string `json:"icon,omitempty"`
	YearOffset int     `json:"year_offset"`
	SortOrder  int     `json:"sort_order"`
}

ExportCycleEntry is a cycle entry for export.

type ExportEra

type ExportEra struct {
	ID          *int    `json:"id,omitempty"`
	Name        string  `json:"name"`
	StartYear   int     `json:"start_year"`
	StartMonth  int     `json:"start_month"`
	StartDay    int     `json:"start_day"`
	EndYear     *int    `json:"end_year,omitempty"`
	EndMonth    *int    `json:"end_month,omitempty"`
	EndDay      *int    `json:"end_day,omitempty"`
	Description *string `json:"description,omitempty"`
	Color       string  `json:"color"`
	SortOrder   int     `json:"sort_order"`
	// The era's look and lore (see Era). LoreEntityID is never written: a
	// page id means nothing in another campaign, and parseChronicle drops
	// one a file carries anyway.
	Color2            *string `json:"color_2,omitempty"`
	Style             string  `json:"style,omitempty"`
	Feel              *string `json:"feel,omitempty"`
	LoreEntityID      *string `json:"lore_entity_id,omitempty"`
	DMNote            *string `json:"dm_note,omitempty"`
	HiddenUntilBegins bool    `json:"hidden_until_begins,omitempty"`
}

ExportEra is an era definition for export. Field order matches EraInput's creatable fields exactly: import.go converts between the two with a direct type conversion (EraInput(e)), which requires identical field name/type/ order on both sides.

type ExportEvent

type ExportEvent struct {
	Name                     string  `json:"name"`
	Description              *string `json:"description,omitempty"`
	DescriptionHTML          *string `json:"description_html,omitempty"`
	Year                     int     `json:"year"`
	Month                    int     `json:"month"`
	Day                      int     `json:"day"`
	StartHour                *int    `json:"start_hour,omitempty"`
	StartMinute              *int    `json:"start_minute,omitempty"`
	EndYear                  *int    `json:"end_year,omitempty"`
	EndMonth                 *int    `json:"end_month,omitempty"`
	EndDay                   *int    `json:"end_day,omitempty"`
	EndHour                  *int    `json:"end_hour,omitempty"`
	EndMinute                *int    `json:"end_minute,omitempty"`
	IsRecurring              bool    `json:"is_recurring"`
	RecurrenceType           *string `json:"recurrence_type,omitempty"`
	RecurrenceInterval       *int    `json:"recurrence_interval,omitempty"`
	RecurrenceEndYear        *int    `json:"recurrence_end_year,omitempty"`
	RecurrenceEndMonth       *int    `json:"recurrence_end_month,omitempty"`
	RecurrenceEndDay         *int    `json:"recurrence_end_day,omitempty"`
	RecurrenceMaxOccurrences *int    `json:"recurrence_max_occurrences,omitempty"`
	Visibility               string  `json:"visibility"`
	// Kind is the event's kind SLUG, not its numeric id: an id only means
	// something within the campaign that minted it, while a slug can be
	// looked up or recreated by slug in the target campaign on re-import.
	Kind      *string `json:"kind,omitempty"`
	Announced *string `json:"announced,omitempty"`
	Color     *string `json:"color,omitempty"`
	Icon      *string `json:"icon,omitempty"`
	AllDay    bool    `json:"all_day"`
	Payload   *string `json:"payload,omitempty"`
	// Ref is the event's id in the exporting calendar, which another event's
	// rule may name; RecurrenceRule is carried only for a "rule" event, with
	// the exporting calendar's moon, season and event ids.
	Ref            string          `json:"ref,omitempty"`
	RecurrenceRule json.RawMessage `json:"recurrence_rule,omitempty"`
	// Status, Outcome and MovedFrom* carry what became of the event; a file
	// without them reads as planned.
	Status         string  `json:"status,omitempty"`
	Outcome        *string `json:"outcome,omitempty"`
	MovedFromYear  *int    `json:"moved_from_year,omitempty"`
	MovedFromMonth *int    `json:"moved_from_month,omitempty"`
	MovedFromDay   *int    `json:"moved_from_day,omitempty"`
}

ExportEvent is a calendar event for export.

type ExportFestival

type ExportFestival struct {
	Name        string  `json:"name"`
	Month       *int    `json:"month,omitempty"`
	Day         *int    `json:"day,omitempty"`
	AfterMonth  *int    `json:"after_month,omitempty"`
	Description *string `json:"description,omitempty"`
	Color       *string `json:"color,omitempty"`
	Icon        *string `json:"icon,omitempty"`
	SortOrder   int     `json:"sort_order"`
}

ExportFestival is a festival definition for export.

type ExportMonth

type ExportMonth struct {
	Name          string `json:"name"`
	Days          int    `json:"days"`
	SortOrder     int    `json:"sort_order"`
	IsIntercalary bool   `json:"is_intercalary"`
	LeapYearDays  int    `json:"leap_year_days"`
}

ExportMonth is a month definition for export.

type ExportMoon

type ExportMoon struct {
	Name              string  `json:"name"`
	CycleDays         float64 `json:"cycle_days"`
	PhaseOffset       float64 `json:"phase_offset"`
	Color             string  `json:"color"`
	HiddenFromPlayers bool    `json:"hidden_from_players,omitempty"`
	// Strength is how strongly the sky shows the moon's colour, 0 to 1;
	// absent when the moon uses the sky's default.
	Strength *float64 `json:"strength,omitempty"`
	// Ref is the moon's id in the exporting calendar, so a repeat rule that
	// names it can be pointed at the re-created moon on import.
	Ref int `json:"ref,omitempty"`
}

ExportMoon is a moon definition for export. It carries no lore page: a page id means nothing in another campaign (campaign export carries the page by slug instead).

type ExportSeason

type ExportSeason struct {
	Name          string  `json:"name"`
	StartMonth    int     `json:"start_month"`
	StartDay      int     `json:"start_day"`
	EndMonth      int     `json:"end_month"`
	EndDay        int     `json:"end_day"`
	Description   *string `json:"description,omitempty"`
	Color         string  `json:"color"`
	WeatherEffect *string `json:"weather_effect,omitempty"`
	// Ref is the season's id in the exporting calendar, for the same reason
	// as ExportMoon.Ref.
	Ref int `json:"ref,omitempty"`
}

ExportSeason is a season definition for export.

type ExportWeekday

type ExportWeekday struct {
	Name      string `json:"name"`
	SortOrder int    `json:"sort_order"`
	IsRestDay bool   `json:"is_rest_day"`
}

ExportWeekday is a weekday definition for export.

type Festival

type Festival struct {
	ID          int     `json:"id"`
	CalendarID  string  `json:"calendar_id"`
	Name        string  `json:"name"`
	Month       *int    `json:"month,omitempty"`
	Day         *int    `json:"day,omitempty"`
	AfterMonth  *int    `json:"after_month,omitempty"`
	Description *string `json:"description,omitempty"`
	Color       *string `json:"color,omitempty"`
	Icon        *string `json:"icon,omitempty"`
	SortOrder   int     `json:"sort_order"`
}

Festival is a fixed calendar entry (holiday) that is part of the calendar structure rather than a recurring event. month+day specifies the date; after_month is used for intercalary festivals that fall between months.

type FestivalInput

type FestivalInput struct {
	Name        string  `json:"name"`
	Month       *int    `json:"month"`
	Day         *int    `json:"day"`
	AfterMonth  *int    `json:"after_month"`
	Description *string `json:"description"`
	Color       *string `json:"color"`
	Icon        *string `json:"icon"`
	SortOrder   int     `json:"sort_order"`
}

FestivalInput is the input for creating/updating a festival.

type ForecastEntry

type ForecastEntry struct {
	Year         int     `json:"year"`
	Month        int     `json:"month"`
	Day          int     `json:"day"`
	Lead         int     `json:"lead"`
	Confidence   float64 `json:"confidence"`
	Icon         string  `json:"icon"`
	Words        string  `json:"words"`
	TempLow      *int    `json:"temp_low"`
	TempHigh     *int    `json:"temp_high"`
	PrecipChance int     `json:"precip_chance"`
}

ForecastEntry is one day of a player's forecast. TempLow and TempHigh are null when the real reading carries no temperature.

type GameNightsAffectedByAnchorMove

type GameNightsAffectedByAnchorMove interface {
	// SessionsInWorldDateRange returns up to `limit` sessions/game-nights in
	// campaignID dated on calendarID (a month/day is a position in one
	// calendar, so another calendar's nights do not count) whose in-world
	// date falls within [fromYMD, toYMD]
	// (inclusive, by the OLD anchor mapping), for previewing an anchor
	// move's blast radius. Ordered soonest-first. limit<=0 means no cap.
	SessionsInWorldDateRange(ctx context.Context, campaignID, calendarID string, fromYear, fromMonth, fromDay, toYear, toMonth, toDay, limit int) ([]AffectedSession, error)
}

GameNightsAffectedByAnchorMove is satisfied by the sessions plugin and injected from internal/app/routes.go (plugins reach each other only through service interfaces, never direct repo access) — the same cross-plugin seam EntityVisibilityGate above uses. It lets PreviewAnchorMove name the sessions/game-nights an anchor move would re-date without this plugin importing internal/plugins/sessions directly.

Wired optionally, like EntityVisibilityGate: nil-safe, so a build that hasn't wired the sessions side yet still returns a preview — just with no affected sessions listed, rather than failing the whole preview.

type Handler

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

Handler processes HTTP requests for the calendar plugin.

func NewHandler

func NewHandler(svc CalendarService) *Handler

NewHandler creates a new calendar Handler.

func (*Handler) AnchorPreviewAPI

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

AnchorPreviewAPI is a READ-ONLY preview of moving the calendar's real-date anchor: it writes nothing, and only reports the day shift + up to three affected sessions so a future UI can show the operator a warning before the real anchor write (a separate, not-yet-built endpoint) is submitted. Owner only, matching every other anchor-adjacent write in this plugin. real_date is an RFC3339 timestamp; only its calendar date is used. POST /campaigns/:id/calendars/:calid/anchor-preview

func (*Handler) ApplyEventBatchAPI

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

ApplyEventBatchAPI saves a draft's events and weather, or undoes one, all or nothing. Scribe+ on the route; the service refuses the whole batch when any item is more than the sender may do (delete is the Owner's, weather and dm_only events are the Director's). POST /campaigns/:id/calendars/:calid/events/batch

func (*Handler) CalendarEmbedFragment

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

CalendarEmbedFragment handles GET /calendars/embed on an allowed app's routes (the Foundry calendar window): the campaign's default calendar, as this member sees it, ready to mount in the window's frame. A campaign with no calendar the member may see gets a short note instead of an error page, since the window is open either way.

func (*Handler) CalendarViewPage

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

CalendarViewPage handles GET /campaigns/:id/calendars/:calid/view. Not a business-logic decision beyond what CanEdit computes from the already-resolved CampaignContext: bind, call the service twice (the calendar, then its current month's events), render. A calendar the viewer may not see, or that does not belong to this campaign, comes back as whatever error GetCalendarForViewer already returns (NotFound in both cases, per its own doc comment) — propagated as-is, no new handling here.

func (*Handler) ClearDayWeatherAPI

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

ClearDayWeatherAPI removes the readings on a set of days. A POST action, not DELETE, because it carries a body. POST /campaigns/:id/calendars/:calid/weather/days/clear {"days":[{year,month,day}]}

func (*Handler) ClearEventRollNightsAPI

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

ClearEventRollNightsAPI deletes a year's stored nights. POST /campaigns/:id/calendars/:calid/events/:eid/roll/nights/clear {"year":N,"keep_locked":bool}

func (*Handler) ClearPartyPlaceAPI

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

ClearPartyPlaceAPI takes back the mark on one day. POST /campaigns/:id/calendars/:calid/weather/party/clear {"year","month","day"}

func (*Handler) ClearPlaceDayWeatherAPI

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

ClearPlaceDayWeatherAPI removes one place's readings on a set of days. POST /campaigns/:id/calendars/:calid/weather/places/:pid/days/clear {"days":[…]}

func (*Handler) CreateCalendarAPI

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

CreateCalendarAPI creates a calendar. Owner only. POST /campaigns/:id/calendars

func (*Handler) CreateEraAPI

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

CreateEraAPI creates an era. CanAuthorDmOnly (Owner or a granted co-Director). POST /campaigns/:id/calendars/:calid/eras

func (*Handler) CreateEventAPI

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

CreateEventAPI creates an event. Scribe+; the service refuses (403) a visibility=dm_only or a visibility_rules from a caller who may not author dm_only content (CalendarService.CreateEvent's doc comment). POST /campaigns/:id/calendars/:calid/events

func (*Handler) CreateEventKindAPI

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

CreateEventKindAPI creates an event kind. CanAuthorDmOnly (Owner or a granted co-Director). POST /campaigns/:id/calendars/event-kinds

func (*Handler) CreateFromImportAPI

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

CreateFromImportAPI creates a new calendar from an uploaded file. Owner only. current_year/current_month/current_day are ordinary multipart form fields alongside "file" — see CreateCalendarFromImportOptions's doc comment on when current_month/current_day are required. POST /campaigns/:id/calendars/import (multipart, field "file")

func (*Handler) CreateFromPresetAPI

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

CreateFromPresetAPI creates a new calendar from a shipped preset by name. Owner only. The wizard's Review step is expected to have already called PreviewPresetAPI and shown ir.Today for confirmation; current_month/ current_day in the body are only REQUIRED when the preset itself left them unspecified — the Calendaria-format "elven" preset does (Calendaria has no day-level current-date concept at all, only a year — see parseCalendaria's own comment), so this is a real, exercised path, not a hypothetical one; the other three shipped presets are Chronicle-native exports that always specify a full current date. Same contract CreateFromImportAPI enforces for an upload that might. POST /campaigns/:id/calendars/presets/:name

func (*Handler) DeleteCalendarAPI

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

DeleteCalendarAPI deletes a calendar. Owner only. DELETE /campaigns/:id/calendars/:calid

func (*Handler) DeleteEraAPI

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

DeleteEraAPI deletes an era. CanAuthorDmOnly (Owner or a granted co-Director). DELETE /campaigns/:id/calendars/:calid/eras/:eraID

func (*Handler) DeleteEventAPI

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

DeleteEventAPI deletes an event. Owner only. DELETE /campaigns/:id/calendars/:calid/events/:eid

func (*Handler) DeleteEventKindAPI

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

DeleteEventKindAPI deletes an event kind. CanAuthorDmOnly (Owner or a granted co-Director). DELETE /campaigns/:id/calendars/event-kinds/:kindID

func (*Handler) DeleteMoonMarkAPI

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

DeleteMoonMarkAPI removes the mark on a day. DELETE /campaigns/:id/calendars/:calid/moons/:moonID/marks?year=&month=&day=

func (*Handler) DeleteOccurrenceAPI

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

DeleteOccurrenceAPI puts one skipped or moved occurrence back. DELETE /campaigns/:id/calendars/:calid/events/:eid/occurrences/:y/:m/:d

func (*Handler) GetCalendarAPI

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

GetCalendarAPI returns one calendar with its sub-resources. GET /campaigns/:id/calendars/:calid

func (*Handler) GetEventAPI

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

GetEventAPI returns one event. GET /campaigns/:id/calendars/:calid/events/:eid

func (*Handler) GetEventRollAPI

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

GetEventRollAPI returns an event's roll and its nights in a year. GET /campaigns/:id/calendars/:calid/events/:eid/roll?year=

func (*Handler) GetWeatherSettingsAPI

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

GetWeatherSettingsAPI returns the calendar's climate and how long weather lasts, for the weather calendar. Same gate as the day-weather writes, since only those who can store generated weather need it. GET /campaigns/:id/calendars/:calid/weather/settings

func (*Handler) Index

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

Index renders the campaign's calendar list (GET /campaigns/:id/calendars). Replaces the "calendar is being rebuilt" placeholder: app/routes.go no longer registers a handler for this exact path (see its own comment on the removed line).

func (*Handler) LinkEventPageAPI

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

LinkEventPageAPI ties a page to an event. POST /campaigns/:id/calendars/:calid/events/:eid/pages

func (*Handler) ListCalendarsAPI

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

ListCalendarsAPI lists a campaign's calendars. GET /campaigns/:id/calendars

func (*Handler) ListDayWeatherAPI

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

ListDayWeatherAPI returns a year's day readings, or one month's when month is given. Players get only days up to today (the service decides). GET /campaigns/:id/calendars/:calid/weather/days?year=Y[&month=M]

func (*Handler) ListEraEventsAPI

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

ListEraEventsAPI returns the events dated within one era, for the era panel's key events. GET /campaigns/:id/calendars/:calid/eras/:eraID/events

func (*Handler) ListEventIndexAPI

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

ListEventIndexAPI returns a compact calendar-wide event list for pickers (the repeat rule's "day of <event>"), optionally narrowed by name. GET /campaigns/:id/calendars/:calid/events/index?q=

func (*Handler) ListEventKindsAPI

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

ListEventKindsAPI lists a campaign's event kinds. GET /campaigns/:id/calendars/event-kinds

func (*Handler) ListEventPagesAPI

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

ListEventPagesAPI lists the pages tied to an event that the caller may see. GET /campaigns/:id/calendars/:calid/events/:eid/pages

func (*Handler) ListEventsAPI

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

ListEventsAPI lists a calendar's events for one (year, month). GET /campaigns/:id/calendars/:calid/events?year=YYYY&month=M

func (*Handler) ListMonthRollsAPI

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

ListMonthRollsAPI returns the nights of every rolling event in a month, by event id, for the calendar's day cells. GET /campaigns/:id/calendars/:calid/rolls?year=&month=

func (*Handler) ListPassedEventsAPI

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

ListPassedEventsAPI lists the events whose day lies in [from, to), for the sheet that asks what became of them. Owner only, like setting today. GET /campaigns/:id/calendars/:calid/events/passed?from=Y-M-D&to=Y-M-D

func (*Handler) ListPresetsAPI

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

ListPresetsAPI lists the shipped calendar presets. Owner only. GET /campaigns/:id/calendars/presets

func (*Handler) ListWeatherForecastAPI

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

ListWeatherForecastAPI returns the blurred outlook for the days after today, the same for every viewer who can see the calendar. GET /campaigns/:id/calendars/:calid/weather/forecast

func (*Handler) LockDayWeatherAPI

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

LockDayWeatherAPI locks or unlocks the readings on a set of days. Only days that already hold a reading change; the answer says how many did. A POST action like clear. "locked" must be present so an omitted field can never read as an unlock. POST /campaigns/:id/calendars/:calid/weather/days/lock {"days":[{year,month,day}],"locked":true}

func (*Handler) LockEventRollNightsAPI

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

LockEventRollNightsAPI locks or unlocks stored nights. POST /campaigns/:id/calendars/:calid/events/:eid/roll/nights/lock {"days":[...],"locked":bool}

func (*Handler) LockPlaceDayWeatherAPI

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

LockPlaceDayWeatherAPI locks or unlocks one place's readings. "locked" must be present, as for the world's days. POST /campaigns/:id/calendars/:calid/weather/places/:pid/days/lock {"days":[…],"locked":true}

func (*Handler) PlaceWeatherYearAPI

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

PlaceWeatherYearAPI returns the world climate, the places with their own, the party's marks and each place's readings for a year. GET /campaigns/:id/calendars/:calid/weather/places?year=

func (*Handler) PreviewImportAPI

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

PreviewImportAPI parses an uploaded calendar file without creating anything. Owner only. POST /campaigns/:id/calendars/import/preview (multipart, field "file")

func (*Handler) PreviewPresetAPI

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

PreviewPresetAPI parses one shipped preset without creating anything. Owner only. GET /campaigns/:id/calendars/presets/:name

func (*Handler) PreviewRecurrenceAPI

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

PreviewRecurrenceAPI lists the next dates a draft rule gives, for the event editor. Read-gated; writes nothing. POST /campaigns/:id/calendars/:calid/recurrence/preview

func (*Handler) PreviewUpcomingEvents

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

PreviewUpcomingEvents renders the small "upcoming events" HTML fragment other plugins' dashboard/category-dashboard blocks hx-get lazy-load (campaigns.dashCalendarPreview/dashCalendarFull, entities.catCalendarPreview — see dashboard_embed.templ). Public-capable and viewer-filtered like the JSON event reads: a campaign with no default calendar yet renders the "no calendar" empty state rather than an error, since that's a completely ordinary state for a campaign that has the addon enabled but never configured it. GET /campaigns/:id/calendars/upcoming?limit=N

func (*Handler) RollEventNightsAPI

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

RollEventNightsAPI rolls nights ahead: a whole year, or the given dates. POST /campaigns/:id/calendars/:calid/events/:eid/roll/nights {"year":N} | {"dates":[...]}

func (*Handler) SaveEraLookAPI

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

SaveEraLookAPI saves the calendar's era look and its eras' colours, styles and feels together. Owner only, like the other calendar settings. Each era entry is partial (absent keeps, null clears); the calendar-wide look is sent whole. PUT /campaigns/:id/calendars/:calid/era-look

func (*Handler) SaveSunLookAPI

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

SaveSunLookAPI sets the calendar's sun: its kind of star and an optional exact colour (null keeps the kind's own). Owner only, like the rest of the calendar settings. PUT /campaigns/:id/calendars/:calid/sun

func (*Handler) SetAskWhenDayPassesAPI

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

SetAskWhenDayPassesAPI saves Calendar settings' "Ask what became of events" switch the moment it changes and answers with the part redrawn, saying Saved. The checkbox sends nothing when off, so ask_sent marks a submission that carried the control. Owner only. PUT /campaigns/:id/calendars/:calid/day-passes

func (*Handler) SetDayWeatherAPI

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

SetDayWeatherAPI paints or stores generated readings on a set of days. PUT /campaigns/:id/calendars/:calid/weather/days {"days":[{year,month,day,source,...}]}

func (*Handler) SetDefaultCalendarAPI

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

SetDefaultCalendarAPI marks a calendar as the campaign's default. Owner only. PUT /campaigns/:id/calendars/:calid/default

func (*Handler) SetEventRollAPI

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

SetEventRollAPI creates, replaces or (with "config": null) removes an event's roll, and answers with the roll for year. PUT /campaigns/:id/calendars/:calid/events/:eid/roll {"config":{...}|null,"year":N}

func (*Handler) SetEventVisibilityAPI

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

SetEventVisibilityAPI is the dm_only toggle. Gated on campaigns.CanAuthorDmOnly (the Owner, or a co-DM with a grant), not RequireRole(Owner) — see routes.go. PUT /campaigns/:id/calendars/:calid/events/:eid/visibility

func (*Handler) SetMoonHiddenAPI

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

SetMoonHiddenAPI toggles a moon's visibility to players. CanAuthorDmOnly (Owner or a granted co-Director). PUT /campaigns/:id/calendars/:calid/moons/:moonID/hidden

func (*Handler) SetMoonLookAPI

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

SetMoonLookAPI sets one moon's colour and colour strength, from the sky's hand controls. Owner only, like the sun's look; a null strength returns the moon to the sky's default. PUT /campaigns/:id/calendars/:calid/moons/:moonID/look

func (*Handler) SetMoonMarkAPI

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

SetMoonMarkAPI sets a hand-set moon's state from a day on. PUT /campaigns/:id/calendars/:calid/moons/:moonID/marks {"year":1043,"month":3,"day":22,"state":"vanished","shown":true}

func (*Handler) SetMoonModeAPI

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

SetMoonModeAPI switches a moon between its cycle and being set by hand. PUT /campaigns/:id/calendars/:calid/moons/:moonID/mode {"mode":"manual","state_names":{"vanished":"Gone below"}}

func (*Handler) SetOccurrenceAPI

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

SetOccurrenceAPI skips or moves one occurrence of a repeating event ("this one only"). Scribe+, and the event must be visible to the caller. Body: {"action":"skip"} or {"action":"move","year":Y,"month":M,"day":D}. PUT /campaigns/:id/calendars/:calid/events/:eid/occurrences/:y/:m/:d

func (*Handler) SetPartyPlaceAPI

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

SetPartyPlaceAPI marks where the party is from a day on. POST /campaigns/:id/calendars/:calid/weather/party {"year","month","day","place_id"}

func (*Handler) SetPlaceDayWeatherAPI

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

SetPlaceDayWeatherAPI paints or stores generated readings for one place. PUT /campaigns/:id/calendars/:calid/weather/places/:pid/days {"days":[…]}

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) SetTimezoneLookup

func (h *Handler) SetTimezoneLookup(l timezoneLookup)

SetTimezoneLookup wires the optional owner-account-timezone lookup used to suggest a starting default on the real-world calendar's review step (see WizardRealWorldReview). Wiring it is a setter, not a NewHandler parameter, so every existing caller of NewHandler (production and tests alike) is unaffected; a Handler with no lookup wired simply falls back to the browser's own detection or UTC.

func (*Handler) StructureEditApply

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

StructureEditApply saves the previewed structure and sends the owner to the calendar. If the calendar changed since the preview, nothing is written and the up-to-date preview replaces the old one. POST /campaigns/:id/calendars/:calid/structure

func (*Handler) StructureEditPage

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

StructureEditPage renders the editor prefilled from the calendar. GET /campaigns/:id/calendars/:calid/structure

func (*Handler) StructureEditPreview

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

StructureEditPreview shows what saving the submitted structure would do. POST /campaigns/:id/calendars/:calid/structure/preview

func (*Handler) TellEventRollNightAPI

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

TellEventRollNightAPI says whether players are told one night; "told": null goes back to what the night's result says. POST /campaigns/:id/calendars/:calid/events/:eid/roll/nights/tell {"year","month","day","told"}

func (*Handler) TodayInWorldBlock

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

TodayInWorldBlock draws the block, or an empty answer that removes the placeholder. It reads as the players' audience for an owner who is viewing as a player, and always through the viewer's own filter otherwise. A guest of a public campaign gets it only where the owner placed it on the Guests home, and then only what the public may see of the calendar. GET /campaigns/:id/today-in-world

func (*Handler) UnlinkEventPageAPI

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

UnlinkEventPageAPI removes a page's tie to an event. DELETE /campaigns/:id/calendars/:calid/events/:eid/pages/:entityID

func (*Handler) UpdateCalendarAPI

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

UpdateCalendarAPI applies a partial settings update. Owner only. PUT /campaigns/:id/calendars/:calid

func (*Handler) UpdateEraAPI

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

UpdateEraAPI applies a partial update to an era. CanAuthorDmOnly (Owner or a granted co-Director). PUT /campaigns/:id/calendars/:calid/eras/:eraID

func (*Handler) UpdateEventAPI

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

UpdateEventAPI applies a partial update to an event. Scribe+; the service (CalendarService.UpdateEvent) refuses (403) a caller who may not author dm_only content changing visibility/visibility_rules to anything other than what is already stored, and answers NotFound for an event the caller cannot see at all. PUT /campaigns/:id/calendars/:calid/events/:eid

func (*Handler) UpdateEventKindAPI

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

UpdateEventKindAPI applies a partial update to an event kind. CanAuthorDmOnly (Owner or a granted co-Director). PUT /campaigns/:id/calendars/event-kinds/:kindID

func (*Handler) WizardBuildPreview

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

WizardBuildPreview re-validates the structure the browser just built (Alpine-serialized into import_json exactly like the Review step's own round-tripped field — see parseWizardImportJSON's doc comment for why this can't be trusted outright) and renders the shared Review step. A failure here re-renders the editor with fresh defaults rather than the owner's in-progress edits: parseWizardImportJSON only rejects an oversized payload, unparsable JSON, or a structure over the same limits checkCalendarImportLimits enforces everywhere else — none of which the editor's own client-side soft caps let a normal session reach, so this path is realistically only hit by a tampered request, not a lost edit. POST /campaigns/:id/calendars/wizard/build/preview

func (*Handler) WizardBuildStep

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

WizardBuildStep renders the "Build your own" structure editor. GET /campaigns/:id/calendars/wizard/build

func (*Handler) WizardCreate

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

WizardCreate resolves the review step's source — a preset re-fetched by name, an uploaded file's or hand-built calendar's ImportResult carried forward as JSON, or the fixed real-world Gregorian structure — applies the confirmed name/date, and creates the calendar. On success it redirects to the calendars list (HTMXRedirect: a real navigation, not a swap, so the new card renders through the ordinary list read rather than needing an out-of-band insert) with ?created=<name>&new=<id> for the list page's toast + entrance animation. On failure it re-renders the Review step with the error and the caller's own submitted values, never the original source's defaults, so a correction doesn't lose what was already typed. POST /campaigns/:id/calendars/wizard/create

func (*Handler) WizardGeneratePreview

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

WizardGeneratePreview re-validates the calendar the browser's generator engine just produced (parseGeneratedCalendarJSON) and renders the SAME Review step every other source uses, with source="generate" so WizardCreate re-validates it exactly like "import"/"build" already do (see that switch's own comment). A failure re-renders the Generate step fresh (a new seed, not the owner's in-progress recipe sheet) rather than trying to restore client state the server never held — matching WizardBuildPreview's own precedent, and just as realistically unreached: parseGeneratedCalendarJSON only rejects an oversized payload or a structure over the same limits every other import path enforces, neither of which the engine's own generators ever produce on their own. POST /campaigns/:id/calendars/wizard/generate/preview

func (*Handler) WizardGenerateStep

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

WizardGenerateStep renders the Generate step: recipe chips, shape steppers, the "work it out from the sky" switch, and the live result — all driven client-side once chronicle_gen.js loads (wizardGenerateBody's own x-init handles that on demand; nothing here waits for it). GET /campaigns/:id/calendars/wizard/generate

func (*Handler) WizardImportPreview

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

WizardImportPreview parses the uploaded file (a dry-run — no DB write, see CalendarService.PreviewImport's doc comment) and renders the Review step, carrying the parsed *ImportResult forward as JSON in a hidden field (see this file's package doc for why). POST /campaigns/:id/calendars/wizard/import/preview (multipart, field "file")

func (*Handler) WizardImportStep

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

WizardImportStep renders the Import step's drop zone. GET /campaigns/:id/calendars/wizard/import

func (*Handler) WizardPresetReview

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

WizardPresetReview renders the Review step for one shipped preset. GET /campaigns/:id/calendars/wizard/presets/:name

func (*Handler) WizardPresets

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

WizardPresets renders the preset-picker step. GET /campaigns/:id/calendars/wizard/presets

func (*Handler) WizardRealWorldReview

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

WizardRealWorldReview renders the Review step for the "Real-world calendar" tile: its structure is fixed (GregorianImportResult, never client-controlled — see this file's package doc), so unlike the preset and import sources there is no separate picker/upload step first. GET /campaigns/:id/calendars/wizard/reallife

func (*Handler) WizardStart

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

WizardStart renders the wizard's Start step. GET /campaigns/:id/calendars/wizard

type HarptosSeasonStore

type HarptosSeasonStore interface {
	ListCalendarIDsWithSeasonNamed(ctx context.Context, name string) ([]string, error)
	GetMonths(ctx context.Context, calendarID string) ([]Month, error)
	GetSeasons(ctx context.Context, calendarID string) ([]Season, error)
	// RewriteSeasonsIfUnchanged applies replacement only if the calendar's
	// stored seasons still equal expected at write time, reporting whether it
	// did. The check and the write share one transaction so an owner's edit
	// landing between the read and the write is never overwritten.
	RewriteSeasonsIfUnchanged(ctx context.Context, calendarID string, expected, replacement []Season) (bool, error)
}

HarptosSeasonStore is the persistence surface ReconcileHarptosSeasons needs. Satisfied by the calendar repository returned from NewCalendarRepository.

type ImportFormat

type ImportFormat string

ImportFormat identifies which JSON format was detected.

const (
	FormatChronicle  ImportFormat = "chronicle"
	FormatSimpleCal  ImportFormat = "simple-calendar"
	FormatCalendaria ImportFormat = "calendaria"
	FormatFantasyCal ImportFormat = "fantasy-calendar"
	FormatUnknown    ImportFormat = "unknown"
	// FormatRealWorld and FormatBuilt never reach DetectAndParse — they mark
	// an ImportResult the wizard built server-side (reallife.go) or from the
	// browser's "Build your own" step (parseWizardImportJSON), never a file
	// on disk. Informational only (ImportResult.Format has no other reader),
	// kept distinct from the upload-format constants above for clarity.
	FormatRealWorld ImportFormat = "reallife-gregorian"
	FormatBuilt     ImportFormat = "built"
)

type ImportResult

type ImportResult struct {
	Format       ImportFormat   `json:"format"`
	CalendarName string         `json:"calendar_name"`
	Months       []MonthInput   `json:"months"`
	Weekdays     []WeekdayInput `json:"weekdays"`
	Moons        []MoonInput    `json:"moons"`
	Seasons      []Season       `json:"seasons"`
	Eras         []EraInput     `json:"eras"`
	// Cycles and Festivals are Chronicle-native sub-resources: parseChronicle
	// is the only parser that populates Cycles (no external format models a
	// repeating named cycle); Calendaria also carries festivals of its own,
	// read into Festivals alongside Chronicle's.
	Cycles    []CycleInput     `json:"cycles,omitempty"`
	Festivals []FestivalInput  `json:"festivals,omitempty"`
	Settings  ImportedSettings `json:"settings"`
	// Events carries a Chronicle-native export's own events forward through a
	// re-import (#779): parseChronicle is the only parser that populates it —
	// Simple Calendar, Calendaria and Fantasy-Calendar files never had
	// Chronicle events to bring over in the first place. Shaped exactly like
	// ExportEvent (kind by SLUG, never EntityID/KindID/VisibilityRules/
	// RecurrenceDayOfWeek — see ExportEvent's own doc comment on why a
	// portable event excludes those), so CreateCalendarFromImport resolves
	// the kind slug against the TARGET campaign rather than trusting a
	// numeric id that means nothing there.
	Events []ExportEvent `json:"events,omitempty"`
	// MoonRefs and SeasonRefs are each moon's and season's id in the
	// exporting calendar, in the same order as Moons and Seasons, so the
	// repeat rules in Events can be pointed at the re-created ones. Only
	// parseChronicle fills them; a length that no longer matches (the list
	// was edited on the way) means no mapping at all.
	MoonRefs   []int `json:"moon_refs,omitempty"`
	SeasonRefs []int `json:"season_refs,omitempty"`
	// Today is what the import file itself determined for the created
	// calendar's current ("today") date — never a fallback this package
	// invented on the file's behalf. Month/Day are nil when the format
	// carries no day-level current date at all (Calendaria only ever
	// specifies a year); CreateCalendarFromImport then REQUIRES the caller
	// to supply an explicit override for whichever of the two is nil rather
	// than silently defaulting either to 1 (#741: "an import never silently
	// resets the calendar's current date").
	Today ImportedToday `json:"today"`
	// Warnings are user-facing notes about data this import clamped or
	// filled in rather than failing the whole import over (#741: "warn,
	// never refuse, when a structural oddity is found") — an out-of-range
	// season date, a non-positive month length, a blank name, an event whose
	// kind slug doesn't exist in the target campaign. Populated at parse
	// time by clampCalendarStructure for Calendaria/Simple Calendar (real
	// exports in the wild carry values Chronicle's own schema can't store
	// as-is; Chronicle's own export and Fantasy-Calendar's computed ranges
	// never produce these shapes) and appended to at apply time by
	// CreateCalendarFromImport (an unresolved event kind slug).
	Warnings []string `json:"warnings,omitempty"`
}

ImportResult holds the parsed calendar data ready to be applied.

func DetectAndParse

func DetectAndParse(data []byte) (*ImportResult, error)

DetectAndParse auto-detects the format of raw JSON bytes and parses into an ImportResult. Returns an error if the format cannot be detected or parsed.

func GregorianImportResult

func GregorianImportResult() (*ImportResult, error)

func LoadPreset

func LoadPreset(name string) (*ImportResult, error)

LoadPreset parses one shipped preset through the ordinary import path.

The return type is the importer's own ImportResult on purpose — a caller cannot tell a preset from an uploaded file, which is the whole point of the ruling above.

type ImportedSettings

type ImportedSettings struct {
	// Mode is only ever set by parseChronicle (from the export's own Mode):
	// every external format (Simple Calendar, Calendaria, Fantasy-Calendar)
	// describes a custom fantasy calendar with no Gregorian/real-time
	// concept, so their parsers leave this "" and CreateCalendarFromImport's
	// CreateCalendar call defaults an empty Mode to ModeFantasy — the same
	// default CreateCalendar already applies to a manual create with no
	// mode specified.
	Mode      string  `json:"mode,omitempty"`
	EpochName *string `json:"epoch_name,omitempty"`
	// Description is only carried by the Foundry module's payload.
	Description      *string `json:"description,omitempty"`
	CurrentYear      int     `json:"current_year"`
	HoursPerDay      int     `json:"hours_per_day"`
	MinutesPerHour   int     `json:"minutes_per_hour"`
	SecondsPerMinute int     `json:"seconds_per_minute"`
	LeapYearEvery    int     `json:"leap_year_every"`
	LeapYearOffset   int     `json:"leap_year_offset"`
	// Only the Chronicle native format carries these — external formats are
	// all fantasy calendars and leave TracksRealTime=false with a nil zone.
	// ApplyImport validates them through the same rules as the enable flow.
	TracksRealTime bool    `json:"tracks_real_time,omitempty"`
	RealTimeZone   *string `json:"real_time_zone,omitempty"`
	// Also Chronicle-native only: external formats have no concept of a
	// hemisphere, forecast toggle or week-start rule.
	Hemisphere       *string `json:"hemisphere,omitempty"`
	ForecastsEnabled bool    `json:"forecasts_enabled,omitempty"`
	// MonthStartsNewWeek is a pointer so a structure save can tell "the
	// editor said off" from "the submission never mentioned it" (an older
	// page): absent keeps the stored switch, as every partial update does.
	// A new calendar reads nil as off.
	MonthStartsNewWeek *bool `json:"month_starts_new_week,omitempty"`
	// EraLook is Chronicle-native only too; nil keeps the defaults.
	EraLook *EraLook `json:"era_look,omitempty"`
	// Sun is Chronicle-native only too; nil keeps the yellow sun.
	Sun *SunLook `json:"sun,omitempty"`
}

ImportedSettings holds calendar-level settings extracted from the import.

type ImportedToday

type ImportedToday struct {
	Year  int  `json:"year"`
	Month *int `json:"month,omitempty"`
	Day   *int `json:"day,omitempty"`
	// Hour and Minute are the time of day, 0 for every format but the Foundry
	// module's payload, which carries the world's current time.
	Hour   int `json:"hour,omitempty"`
	Minute int `json:"minute,omitempty"`
}

ImportedToday is the day-level "today" ImportResult carries forward — see ImportResult.Today's doc comment for the rule it exists to enforce.

type Month

type Month struct {
	ID            int    `json:"id"`
	CalendarID    string `json:"calendar_id"`
	Name          string `json:"name"`
	Days          int    `json:"days"`
	SortOrder     int    `json:"sort_order"`
	IsIntercalary bool   `json:"is_intercalary"`
	LeapYearDays  int    `json:"leap_year_days"`
}

Month is a named period in the calendar with a configurable number of days.

type MonthInput

type MonthInput struct {
	Name          string `json:"name"`
	Days          int    `json:"days"`
	SortOrder     int    `json:"sort_order"`
	IsIntercalary bool   `json:"is_intercalary"`
	LeapYearDays  int    `json:"leap_year_days"`
}

MonthInput is the input for creating/updating a month.

type Moon

type Moon struct {
	ID          int     `json:"id"`
	CalendarID  string  `json:"calendar_id"`
	Name        string  `json:"name"`
	CycleDays   float64 `json:"cycle_days"`
	PhaseOffset float64 `json:"phase_offset"`
	Color       string  `json:"color"`
	BaseDesign  string  `json:"base_design"`
	Tint        *string `json:"tint,omitempty"`
	PhaseSource string  `json:"phase_source"`
	Size        float64 `json:"size"`
	OrbitSpeed  float64 `json:"orbit_speed"`
	// HiddenFromPlayers lets the Director hide a moon from players entirely
	// (undiscovered, or secret world lore) while it still renders for the GM.
	HiddenFromPlayers bool `json:"hidden_from_players"`
	// LoreEntityID links a page about the moon. LoreEntityName is read with
	// it, scoped to the calendar's campaign; both are blanked for a viewer
	// who may not see that page, exactly as an era's are.
	LoreEntityID   *string `json:"lore_entity_id,omitempty"`
	LoreEntityName string  `json:"lore_entity_name,omitempty"`
	// PhaseMode is MoonCycle or MoonManual. A manual moon has no cycle: it
	// holds the state of its latest mark (moon_marks.go). CycleDays and
	// PhaseOffset are kept, so switching back restores the cycle.
	PhaseMode string `json:"phase_mode"`
	// StateNames are the Director's words for a manual moon's states, by
	// state; a state not named reads its default.
	StateNames map[string]string `json:"state_names,omitempty"`
	// Marks are a manual moon's marks, oldest first, once loaded and
	// indexed (Calendar.indexMoonMarks). A player's copy holds only the
	// marks they were shown.
	Marks []MoonMark `json:"marks,omitempty"`
	// contains filtered or unexported fields
}

Moon is a celestial body with a phase cycle used for moon phase display.

BaseDesign / Tint / PhaseSource / Size / OrbitSpeed are the moon-library render params, mirroring the showcase's MOON_DESIGNS parameters so a moon's appearance can be authored rather than hardcoded in JS.

func (*Moon) CycleDay

func (m *Moon) CycleDay(abs int) int

CycleDay is the day of the moon's cycle, the new moon's day being 1, or 0 for a moon set by hand or with no cycle.

func (*Moon) Manual

func (m *Moon) Manual() bool

Manual reports whether the moon is set by hand.

func (*Moon) MoonPhase

func (m *Moon) MoonPhase(absoluteDay int) float64

MoonPhase returns the phase (0.0–1.0) of this moon on a given absolute day number (days since year 0 day 0). 0=new, 0.25=first quarter, 0.5=full, 0.75=last quarter.

func (*Moon) MoonPhaseIcon

func (m *Moon) MoonPhaseIcon(absoluteDay int) string

MoonPhaseIcon returns the icon for the same centered phase as MoonPhaseName.

func (*Moon) MoonPhaseName

func (m *Moon) MoonPhaseName(absoluteDay int) string

MoonPhaseName returns the nearest named phase, centered on its turning point. A manual moon reads its state's word instead.

func (*Moon) PhaseWords

func (m *Moon) PhaseWords(abs int) []string

PhaseWords are the words a moon's phase on one day answers to, for rules other plugins keep: its phase name ("Waning Crescent", or a hand-set moon's state word), each turning point it sits on (new, full, first-quarter, last-quarter, the day nearest each) and each stretch it is in (waxing, waning, crescent, gibbous), matched as roll-table conditions match them.

func (*Moon) StateOn

func (m *Moon) StateOn(abs int) string

StateOn is a manual moon's state on the day abs, "" before its first mark (the viewer knows nothing of it yet).

func (*Moon) StateWord

func (m *Moon) StateWord(state string) string

StateWord is the Director's word for state, or its default.

func (*Moon) StateWordOn

func (m *Moon) StateWordOn(abs int) string

StateWordOn is the word for a manual moon's state on the day abs, "Not set" before its first mark.

type MoonHand

type MoonHand struct {
	StateNames map[string]string
	Marks      []MoonMark
}

MoonHand is what a hand-set moon carries beyond its row: the Director's words for its states, and its marks.

type MoonInput

type MoonInput struct {
	// ID is nil for a new moon, or an existing calendar_moons id to update in
	// place. SetMoons upserts on it, so an id present in the calendar but
	// absent from the input list is deleted, and one present in both is
	// updated rather than replaced. An update never touches
	// HiddenFromPlayers or the render parameters; a fresh insert sets both
	// from this input, which is how an imported hidden or custom-look moon
	// keeps that on arrival.
	ID                *int    `json:"id,omitempty"`
	Name              string  `json:"name"`
	CycleDays         float64 `json:"cycle_days"`
	PhaseOffset       float64 `json:"phase_offset"`
	Color             string  `json:"color"`
	HiddenFromPlayers bool    `json:"hidden_from_players,omitempty"`
	BaseDesign        string  `json:"base_design,omitempty"`
	Tint              *string `json:"tint,omitempty"`
	PhaseSource       string  `json:"phase_source,omitempty"`
	Size              float64 `json:"size,omitempty"`
	OrbitSpeed        float64 `json:"orbit_speed,omitempty"`
	// LoreEntityID is the moon's lore page. A plain pointer cannot tell an
	// absent key from an explicit null, so LoreSet says whether the writer
	// means it: an update with LoreSet false keeps the stored page, with
	// LoreSet true replaces it (nil clears). A fresh insert always stores
	// it. A file or a wizard round trip never reaches the database with
	// either (a page id names a page in some other campaign, if any).
	LoreEntityID *string `json:"lore_entity_id,omitempty"`
	LoreSet      bool    `json:"lore_set,omitempty"`
}

MoonInput is the input for creating/updating a moon.

BaseDesign/Tint/PhaseSource/Size/OrbitSpeed are the sky-pane render params (mirroring Moon's own doc comment); an input built by a caller that doesn't set them (the calendar-native and campaign importers) is zero-valued for these fields, and upsertMoons falls back through to the same DB column defaults a hand-created moon gets, never an empty/invalid render.

type MoonMark

type MoonMark struct {
	Year  int    `json:"year"`
	Month int    `json:"month"`
	Day   int    `json:"day"`
	State string `json:"state"`
	// Shown says players see this change. A player's copy of a moon keeps
	// only its shown marks.
	Shown bool `json:"shown"`
	// contains filtered or unexported fields
}

MoonMark is one day the Director set a manual moon.

type MoonMarkRepository

type MoonMarkRepository interface {
	// MarksFor returns the marks of the calendar's moons, by moon id, in no
	// particular order (Calendar.indexMoonMarks sorts them).
	MarksFor(ctx context.Context, calendarID string) (map[int][]MoonMark, error)
	// CountMarks is how many marks one moon has.
	CountMarks(ctx context.Context, moonID int) (int, error)
	// SetMode writes a moon's phase mode and state words; false when the
	// moon is not in the calendar.
	SetMode(ctx context.Context, calendarID string, moonID int, mode string, names map[string]string) (bool, error)
	// PutMark stores or replaces the mark on its day.
	PutMark(ctx context.Context, moonID int, mark MoonMark) error
	// DeleteMark removes the mark on a day; false when there was none.
	DeleteMark(ctx context.Context, moonID int, d DayDate) (bool, error)
}

MoonMarkRepository stores manual moons: each moon's mode and state words on calendar_moons, and its marks in calendar_moon_marks. Every write is scoped to the moon's calendar, so an id from another calendar changes nothing.

func NewMoonMarkRepository

func NewMoonMarkRepository(db *sql.DB) MoonMarkRepository

NewMoonMarkRepository returns the MariaDB moon mark store.

type MoonMarkService

type MoonMarkService interface {
	// SetMoonMode switches a moon between following its cycle and being set
	// by hand, with the Director's words for its states (nil: defaults).
	SetMoonMode(ctx context.Context, calendarID, campaignID string, moonID int, mode string, names map[string]string, v permissions.Viewer) (*Moon, error)
	// SetMoonMark sets a manual moon's state from a day on.
	SetMoonMark(ctx context.Context, calendarID, campaignID string, moonID int, mark MoonMark, v permissions.Viewer) (*Moon, error)
	// DeleteMoonMark removes the mark on a day, so the one before holds on.
	DeleteMoonMark(ctx context.Context, calendarID, campaignID string, moonID int, d DayDate, v permissions.Viewer) (*Moon, error)
}

MoonMarkService is the Director's control of a manual moon. Reads need no method of their own: a calendar's moons carry their marks, cut to the shown ones for a player (finishCalendarForViewer).

type MoonNightPayload

type MoonNightPayload struct {
	Type  string `json:"type"`
	Moons []int  `json:"moons,omitempty"`
}

MoonNightPayload is one shape an Event.Payload JSON blob can carry. "a sky event" is a second shape the same column is meant to hold — its fields aren't decided yet, so it isn't typed here.

type Occurrence

type Occurrence struct {
	Year      int      `json:"year"`
	Month     int      `json:"month"`
	Day       int      `json:"day"`
	Skipped   bool     `json:"skipped,omitempty"`
	MovedFrom *DayDate `json:"moved_from,omitempty"`
}

Occurrence is one date a repeating event lands on. Skipped and MovedFrom are filled only for a viewer who may edit the event; anyone else simply never sees a skipped date, and sees a moved one at its new date.

type OccurrenceOverride

type OccurrenceOverride struct {
	EventID   string    `json:"event_id"`
	Year      int       `json:"year"`
	Month     int       `json:"month"`
	Day       int       `json:"day"`
	Action    string    `json:"action"`
	NewYear   *int      `json:"new_year,omitempty"`
	NewMonth  *int      `json:"new_month,omitempty"`
	NewDay    *int      `json:"new_day,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

OccurrenceOverride is a stored "this one only" change: the occurrence the event's own repeat put on Year/Month/Day is skipped, or moved to New*.

type OccurrenceOverrideInput

type OccurrenceOverrideInput struct {
	Action string
	Year   int
	Month  int
	Day    int
}

OccurrenceOverrideInput is a request to skip, or move, one occurrence. Year/Month/Day are the new date and are used only for a move.

type PageEras

type PageEras struct {
	Calendar *Calendar
	Eras     []Era
	Current  *Era
}

PageEras is what a page needs to know about eras for one viewer: the campaign's main calendar, the eras that viewer may see (oldest first), and the era its current date is in.

func (*PageEras) Extents

func (pe *PageEras) Extents() []EraExtent

Extents returns the extent of each of pe.Eras, in order.

type PageTimeline

type PageTimeline struct {
	CalendarID   string
	CalendarName string
	// TodayLabel is the campaign's today, as the calendar writes a date.
	TodayLabel string
	Events     []PageTimelineEvent
	// Total counts the events the viewer may see before the cap.
	Total int
	// Start and End bound the line and Today marks the calendar's current
	// date, all as Calendar.AbsoluteDay numbers.
	Start, End, Today int
	// Dead is set when one of the page's events is a death (isDeathKind);
	// DeathAbs is that day. The line is then lit to the death, not to today.
	Dead     bool
	DeathAbs int
	// OpenURL and OpenLabel are the link under the line: the calendar by
	// default, or a time line page that follows this calendar when the app
	// finds one (the calendar plugin cannot see time lines itself).
	OpenURL, OpenLabel string
}

PageTimeline is one page's events on its campaign's calendar, already filtered for the viewer, with the day numbers the line is drawn from.

func (*PageTimeline) FillPercent

func (t *PageTimeline) FillPercent() float64

FillPercent is how far the filled part of the line runs: up to today, or up to the death on a dead subject's line.

func (*PageTimeline) Later

func (t *PageTimeline) Later(e PageTimelineEvent) bool

Later says whether an event is still to come. A dead subject's line has no today, so nothing on it is.

func (*PageTimeline) Percent

func (t *PageTimeline) Percent(abs int) float64

Percent places a day on the line, 0 at Start and 100 at End. A line one day long puts everything in the middle.

func (*PageTimeline) ShowsToday

func (t *PageTimeline) ShowsToday() bool

ShowsToday says whether the line marks today: a living subject's line that reaches it.

func (*PageTimeline) Truncated

func (t *PageTimeline) Truncated() bool

Truncated reports whether the cap left events off the line.

type PageTimelineEvent

type PageTimelineEvent struct {
	ID        string
	Name      string
	Year      int
	Month     int
	Day       int
	DateLabel string
	KindName  string
	KindIcon  string
	// Abs is the event's day on the calendar's day counter.
	Abs int
	// DMOnly marks an event only the Director sees; a player's line never
	// holds one.
	DMOnly bool
	// Repeats is true for a repeating event, which sits on its first date.
	Repeats bool
	// EndLabel is the last day of an event that runs over several, as the
	// calendar writes a date; empty for a one-day event.
	EndLabel string
	// Death marks the event that ends a dead subject's line.
	Death bool
	// Labelled says whether the dot carries its year under it; see
	// labelYears.
	Labelled bool
	// Status is what became of the event (EventStatus*), and Outcome the
	// line on what happened; both follow the event, already filtered.
	Status  string
	Outcome string
}

PageTimelineEvent is one dot: what the peek says and where it goes.

func (PageTimelineEvent) StatusWord

func (e PageTimelineEvent) StatusWord() string

StatusWord is how the hover card names what became of the event; empty for a planned one, which shows as it always has.

type ParticipationRole

type ParticipationRole string

ParticipationRole is an entity's role in an event/era tie.

const (
	// RoleInvolved — an active participant in the event/era.
	RoleInvolved ParticipationRole = "involved"
	// RolePresent — physically present but not a driver.
	RolePresent ParticipationRole = "present"
	// RoleAffected — impacted by it without being present.
	RoleAffected ParticipationRole = "affected"
	// RoleMentioned — referenced only.
	RoleMentioned ParticipationRole = "mentioned"
)

func (ParticipationRole) IsValid

func (r ParticipationRole) IsValid() bool

IsValid reports whether r is one of the four roles.

type PartyMark

type PartyMark struct {
	Year    int    `json:"year"`
	Month   int    `json:"month"`
	Day     int    `json:"day"`
	PlaceID string `json:"place_id,omitempty"`
}

PartyMark says the party is at PlaceID from this day until the next mark. An empty PlaceID means nowhere with a climate of its own.

type PartyMarkView

type PartyMarkView struct {
	PartyMark
	PlaceName string `json:"place_name,omitempty"`
	// RegionID is the place whose weather the party has from this day; empty
	// for the world's weather.
	RegionID string `json:"region_id,omitempty"`
}

PartyMarkView is a party mark with the names the Director sees.

type PartyNow

type PartyNow struct {
	// PlaceName and RegionName are empty when there is none or the viewer may
	// not open that page.
	PlaceName   string `json:"place_name,omitempty"`
	RegionName  string `json:"region_name,omitempty"`
	ClimateName string `json:"climate_name"`
	// Since is the day of the mark in force; nil when the party was never
	// placed.
	Since *DayDate `json:"since,omitempty"`
}

PartyNow is where the party is today, as one viewer may know it.

type PassedEvent

type PassedEvent struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Visibility string `json:"visibility"`
	Year       int    `json:"year"`
	Month      int    `json:"month"`
	Day        int    `json:"day"`
	EndYear    *int   `json:"end_year,omitempty"`
	EndMonth   *int   `json:"end_month,omitempty"`
	EndDay     *int   `json:"end_day,omitempty"`
	// Repeating marks one date of a repeating event, answered with a skip
	// or move override rather than the event's own status.
	Repeating bool    `json:"repeating"`
	Outcome   *string `json:"outcome,omitempty"`
}

PassedEvent is one event the calendar asks about after today moves past its day: a one-off event still planned whose last day is now behind, or one date of a repeating event. Year/Month/Day is the event's start (for a repeating event, the date in question).

type PassedEvents

type PassedEvents struct {
	Events    []PassedEvent `json:"events"`
	Truncated bool          `json:"truncated"`
}

PassedEvents is the sheet's list; Truncated says more passed than it holds, which the sheet tells the Director in words.

type PlaceBackup

type PlaceBackup struct {
	Days  map[string][]DayWeather
	Marks []PartyMark
}

PlaceBackup is a calendar's place weather as a backup carries it.

type PlaceBackupService

type PlaceBackupService interface {
	// PlaceWeatherForBackup returns every stored place reading, by place
	// id, and every party move. Nil when place weather is not wired.
	PlaceWeatherForBackup(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (*PlaceBackup, error)
	// RestorePlaceWeather stores one place's readings as they were, source
	// and lock included. A reading that fails the usual checks is skipped
	// and counted.
	RestorePlaceWeather(ctx context.Context, calendarID, campaignID, placeID string, days []DayWeather, v permissions.Viewer) (skipped int, err error)
	// RestorePartyMoves puts the party's moves back. A move on a day the
	// calendar does not have, or to a page the campaign does not have, is
	// skipped and counted.
	RestorePartyMoves(ctx context.Context, calendarID, campaignID string, marks []PartyMark, v permissions.Viewer) (skipped int, err error)
}

PlaceBackupService is reached by a type assertion on CalendarService, so a service without place weather (or a test fake) simply backs up none.

type PlaceDirectory

type PlaceDirectory interface {
	// ClimatePlaces is every page of the campaign with a climate of its own.
	ClimatePlaces(ctx context.Context, campaignID string) ([]ClimatePlace, error)
	// RegionOf is the page whose climate covers entityID: the page itself or
	// its nearest parent with a climate. Nil when none does, or the page is
	// not in the campaign.
	RegionOf(ctx context.Context, campaignID, entityID string) (*ClimatePlace, error)
	// Viewable is the subset of ids the viewer may open.
	Viewable(ctx context.Context, campaignID string, ids []string, v permissions.Viewer) map[string]bool
	// PlaceName is a page's name when it is a live page of the campaign.
	PlaceName(ctx context.Context, campaignID, entityID string) (string, bool)
}

PlaceDirectory is the campaign's places as the calendar reads them. It belongs to the entities plugin and is wired in internal/app; reads are unfiltered, so every answer that reaches a viewer goes through Viewable.

type PlaceToday

type PlaceToday struct {
	Date    string      `json:"date"`
	Reading *DayWeather `json:"reading,omitempty"`
	// PartyHere is set when the party is in this region today.
	PartyHere bool `json:"party_here,omitempty"`
}

PlaceToday is today's weather at one region of the main calendar.

type PlaceWeatherRepository

type PlaceWeatherRepository interface {
	// ListPlaceDays returns the readings of the given places for a year, or
	// one month of it when month > 0, keyed by place.
	ListPlaceDays(ctx context.Context, calendarID string, placeIDs []string, year, month int) (map[string][]DayWeather, error)
	// ListAllPlaceDays returns every stored place reading of the calendar,
	// keyed by place, each place's in date order.
	ListAllPlaceDays(ctx context.Context, calendarID string) (map[string][]DayWeather, error)
	// SetPlaceDays upserts one place's readings in one transaction, with the
	// same manual and lock rules as WeatherRepository.SetDays.
	SetPlaceDays(ctx context.Context, calendarID, placeID string, days []DayWeatherInput) error
	// ClearPlaceDays deletes one place's readings on the given days.
	ClearPlaceDays(ctx context.Context, calendarID, placeID string, dates []DayDate) error
	// LockPlaceDays sets the lock on one place's stored readings and returns
	// how many changed; a day with no reading is skipped.
	LockPlaceDays(ctx context.Context, calendarID, placeID string, dates []DayDate, locked bool) (int, error)

	// ListPartyMarks returns every mark of the calendar in date order.
	ListPartyMarks(ctx context.Context, calendarID string) ([]PartyMark, error)
	// SetPartyMark creates or replaces the mark on one day.
	SetPartyMark(ctx context.Context, calendarID string, m PartyMark) error
	// ClearPartyMark deletes the mark on one day, if any.
	ClearPartyMark(ctx context.Context, calendarID string, d DayDate) error
}

PlaceWeatherRepository stores per-place day readings and the party's marks.

func NewPlaceWeatherRepository

func NewPlaceWeatherRepository(db *sql.DB) PlaceWeatherRepository

NewPlaceWeatherRepository creates the MariaDB-backed place weather store.

type PlaceWeatherService

type PlaceWeatherService interface {
	PlaceWeatherYear(ctx context.Context, calendarID, campaignID string, year int) (*PlaceWeatherYear, error)
	SetPlaceDayWeather(ctx context.Context, calendarID, campaignID, placeID string, days []DayWeatherInput) error
	ClearPlaceDayWeather(ctx context.Context, calendarID, campaignID, placeID string, dates []DayDate) error
	LockPlaceDayWeather(ctx context.Context, calendarID, campaignID, placeID string, dates []DayDate, locked bool) (int, error)
	// SetPartyPlace marks the party at placeID from day d; "" is nowhere
	// with a climate of its own.
	SetPartyPlace(ctx context.Context, calendarID, campaignID string, d DayDate, placeID string) error
	ClearPartyPlace(ctx context.Context, calendarID, campaignID string, d DayDate) error
	// ListPartyDayWeather is the party's weather by day, as players see it,
	// with the Director also getting days to come.
	ListPartyDayWeather(ctx context.Context, calendarID, campaignID string, year, month int, v permissions.Viewer) ([]DayWeather, error)
	// PlaceToday is today's weather in a region on the main calendar; nil
	// when a player asks about a region the party is not in today, or there
	// is no calendar.
	PlaceToday(ctx context.Context, campaignID, regionID string, v permissions.Viewer) (*PlaceToday, error)
	// WorldClimate is the main calendar's climate; false without one.
	WorldClimate(ctx context.Context, campaignID string, v permissions.Viewer) (ClimateRef, bool)
	// PartyNow is where the party is on the calendar's today.
	PartyNow(ctx context.Context, calendarID, campaignID string, v permissions.Viewer) (*PartyNow, error)
}

PlaceWeatherService is the per-place half of the calendar's weather. The writes and PlaceWeatherYear are for the Director: their routes require CanAuthorDmOnly, as the day-weather writes do.

type PlaceWeatherYear

type PlaceWeatherYear struct {
	World  ClimateRef              `json:"world"`
	Places []ClimatePlace          `json:"places"`
	Party  []PartyMarkView         `json:"party"`
	Days   map[string][]DayWeather `json:"days"`
}

PlaceWeatherYear is the Director's view of every place's weather for a year: the world climate, the places with their own, the party's marks and each place's readings.

type Precipitation

type Precipitation struct {
	Type      *string  `json:"type,omitempty"`
	Intensity *float64 `json:"intensity,omitempty"`
}

Precipitation describes the type and intensity of precipitation.

type RecurrencePreview

type RecurrencePreview struct {
	Dates     []DayDate `json:"dates"`
	Truncated bool      `json:"truncated"`
}

RecurrencePreview is the preview's answer. Truncated means the scan hit its bound before finding Count dates (a rare rule, or one far away).

type RecurrencePreviewInput

type RecurrencePreviewInput struct {
	Rule                     json.RawMessage
	Start                    DayDate
	Count                    int
	RecurrenceMaxOccurrences *int
	RecurrenceEnd            *DayDate
}

RecurrencePreviewInput is a draft rule to preview: the first Count dates it gives from Start, honouring the optional max-occurrences and end date exactly as a saved event would.

type RecurrenceRule

type RecurrenceRule struct {
	Match      []RuleCondition `json:"match"`
	Every      int             `json:"every,omitempty"`
	OffsetDays int             `json:"offset_days,omitempty"`
}

RecurrenceRule is what a RecurrenceByRule event repeats by: the days every condition in Match holds, taking every Every-th one (default 1), each moved by OffsetDays (negative moves earlier).

func ParseRecurrenceRule

func ParseRecurrenceRule(raw []byte) (*RecurrenceRule, error)

ParseRecurrenceRule decodes and shape-checks a rule. A nil, empty or JSON null input is "no rule" (nil, nil). Unknown keys, unknown kinds, fields a kind does not use, and out-of-bounds values are all validation errors.

type RollBand

type RollBand struct {
	Max  *int   `json:"max,omitempty"`
	Name string `json:"name"`
	// Players is what players are told on the night, when they are told.
	Players string `json:"players,omitempty"`
	// Director is for the Director alone.
	Director string `json:"director,omitempty"`
	// TellPlayers shows the night's player text once the night arrives.
	TellPlayers bool `json:"tell_players,omitempty"`
}

RollBand is one result of a dice roll.

type RollConfig

type RollConfig struct {
	Source string `json:"source"`
	// Dice is the expression for a dice roll: "2d10", "1d20+3", "3d6-1".
	Dice string `json:"dice,omitempty"`
	// TableID names one of the campaign's rolling tables for a table roll.
	TableID string `json:"table_id,omitempty"`
	// OnTheNight rolls a night that arrives without a result.
	OnTheNight bool `json:"on_the_night"`
	// Results are a dice roll's bands, lowest first. Every band but the last
	// has Max, the highest total it covers; the last covers the rest.
	Results []RollBand `json:"results,omitempty"`
	// TellPlayers is a table roll's "tell players on the night": a table has
	// no bands to carry it.
	TellPlayers bool `json:"tell_players,omitempty"`
	// contains filtered or unexported fields
}

RollConfig is an event's roll, stored as JSON on calendar_event_rolls.

func (*RollConfig) Normalize

func (c *RollConfig) Normalize() error

Normalize checks and tidies a roll's settings. A dice roll needs at least one band, bands in rising order with Max on every one but the last; a table roll needs a table id and keeps no bands.

type RollNight

type RollNight struct {
	Year  int `json:"year"`
	Month int `json:"month"`
	Day   int `json:"day"`
	// Total and Faces are a dice roll's; Entry a table roll's name.
	Total  *int   `json:"total,omitempty"`
	Faces  []int  `json:"faces,omitempty"`
	Entry  string `json:"entry,omitempty"`
	Source string `json:"source"`
	Locked bool   `json:"locked"`
	// Told is nil when the night follows its result's own setting.
	Told *bool `json:"told,omitempty"`
}

RollNight is one night's stored result, as the repository reads it.

type RollNightView

type RollNightView struct {
	Year  int `json:"year"`
	Month int `json:"month"`
	Day   int `json:"day"`
	// Result is the band's or table entry's name.
	Result string `json:"result,omitempty"`
	// Players is the player text; for a player it is set only when told.
	Players  string `json:"players,omitempty"`
	Director string `json:"director,omitempty"`
	Total    *int   `json:"total,omitempty"`
	Faces    []int  `json:"faces,omitempty"`
	Source   string `json:"source,omitempty"`
	Locked   *bool  `json:"locked,omitempty"`
	Told     *bool  `json:"told,omitempty"`
	// BandIndex is the band a dice total falls in, -1 for none. Director only.
	BandIndex *int `json:"band_index,omitempty"`
}

RollNightView is a night shaped for one viewer. A player gets the date, the result's name and its player text for a night they were told about, nothing else: no total, no lock, no Director's text.

type RollNightsInput

type RollNightsInput struct {
	// Year rolls every night of that year, when Dates is empty.
	Year int `json:"year"`
	// Dates rolls just these nights; each must be a night the event lands on.
	Dates []DayDate `json:"dates,omitempty"`
	// OnlyUnrolled keeps a night that already has a result.
	OnlyUnrolled bool `json:"only_unrolled,omitempty"`
}

RollNightsInput says which nights to roll ahead.

type RollTable

type RollTable struct {
	Name string
	// Visibility is who sees what a roll on the table puts on a night:
	// "dm_only" keeps a night's result from players unless the Director
	// tells that night; anything else follows the roll's own setting.
	Visibility string
	Entries    []RollTableEntry
}

RollTable is a rolling table as an event roll reads it.

type RollTableEntry

type RollTableEntry struct {
	Name, Brief string
	Weight      float64
	// When is the line's day conditions as the rolling tables plugin stores
	// them (see roll_table_when.go); empty means any night.
	When json.RawMessage
}

RollTableEntry is one entry of a rolling table.

type RollTableFinder

type RollTableFinder interface {
	RollTableIDByName(ctx context.Context, campaignID, name string) (string, error)
}

RollTableFinder finds a campaign's rolling table by name. The rolling table adapter provides it beside RollTableSource; without it a restored table roll is always dropped.

type RollTableSource

type RollTableSource interface {
	// RollTable returns the table, or (nil, nil) when the campaign has none
	// with that id.
	RollTable(ctx context.Context, campaignID, tableID string) (*RollTable, error)
}

RollTableSource finds one of a campaign's rolling tables. The rolltables plugin provides it through an adapter wired in internal/app, so this plugin never reaches its storage.

type RuleCondition

type RuleCondition struct {
	Kind     string `json:"kind"`
	MoonID   int    `json:"moon_id,omitempty"`
	Phase    string `json:"phase,omitempty"`
	Weekdays []int  `json:"weekdays,omitempty"`
	N        int    `json:"n,omitempty"`
	Weekday  *int   `json:"weekday,omitempty"`
	Day      int    `json:"day,omitempty"`
	Months   []int  `json:"months,omitempty"`
	Month    int    `json:"month,omitempty"`
	SeasonID int    `json:"season_id,omitempty"`
	EventID  string `json:"event_id,omitempty"`
	Days     *int   `json:"days,omitempty"`
}

RuleCondition is one tagged condition. Only the fields its Kind names may be set; the pointers are the fields where zero is a real value (weekday 0, "0 days after").

type RuleUpdate

type RuleUpdate struct {
	EventID string
	JSON    string
}

RuleUpdate is a rule's rewritten JSON for the repository to store.

type Season

type Season struct {
	ID            int     `json:"id"`
	CalendarID    string  `json:"calendar_id"`
	Name          string  `json:"name"`
	StartMonth    int     `json:"start_month"`
	StartDay      int     `json:"start_day"`
	EndMonth      int     `json:"end_month"`
	EndDay        int     `json:"end_day"`
	Description   *string `json:"description,omitempty"`
	Color         string  `json:"color"`
	WeatherEffect *string `json:"weather_effect,omitempty"`
}

Season is a named period spanning a range of month+day to month+day.

func (*Season) ContainsDate

func (s *Season) ContainsDate(month, day int) bool

ContainsDate returns true if the given month+day falls within this season. Handles wrap-around (e.g. Winter: month 11 day 1 → month 2 day 28).

type SessionMonthRemapper

type SessionMonthRemapper interface {
	// RemapMonthPositions maps each old 1-based month position to its new
	// one; only months that moved are present.
	RemapMonthPositions(ctx context.Context, campaignID, calendarID string, remap map[int]int) error
}

SessionMonthRemapper is satisfied by the sessions plugin and injected from internal/app/routes.go, the same seam as GameNightsAffectedByAnchorMove. After a structure edit reorders months it moves the game nights dated on that calendar with their month. Optional and nil-safe: unwired, a save still succeeds and game nights keep their stored month positions.

type StructureEdit

type StructureEdit struct {
	Months        []MonthInput
	Weekdays      []WeekdayInput
	Moons         []MoonInput
	Seasons       []Season
	LeapYearEvery int
	// MonthStartsNewWeek is the calendar's "each month starts a new week"
	// switch. nil keeps the stored value, so a submission that does not
	// mention it (an older editor page, the assistant) never flips it.
	MonthStartsNewWeek *bool
	// Warnings are clamp notes from validating the submitted structure,
	// passed through to the preview so the owner sees them before saving.
	Warnings []string
}

StructureEdit is an owner's whole-structure save for an existing calendar. Unlike an Update*Input it is not a partial update: the lists it carries are the calendar's complete new months, weekdays, moons and seasons. Existing moons and seasons are identified by ID; fields the editor does not show (a moon's colour, phase offset and look, a season's colour and description) are left as stored rather than echoed back.

func StructureEditFromImport

func StructureEditFromImport(ir *ImportResult) StructureEdit

StructureEditFromImport takes the structure editor's submission, already size-checked and clamped by the same path a wizard build goes through, and keeps only the parts a structure save writes.

type StructureEventChange

type StructureEventChange struct {
	EventID string
	Name    string
	// Date is the event's date as it reads before the save.
	Date string
	// Note says what happens to it, in words.
	Note string
}

StructureEventChange names one event a structure save affects.

type StructureOverride

type StructureOverride struct {
	EventID  string
	Year     int
	Month    int
	Day      int
	NewMonth *int
}

StructureOverride is one skip/move override as a structure save reads it: the month it is keyed by and, for a move, the month it moves to.

type StructurePreview

type StructurePreview struct {
	CalendarName string
	// MonthNotes describe each month that moves, is renamed, removed, added
	// or changes length.
	MonthNotes []string
	// OtherNotes cover the week, the leap rule, and removed moons/seasons.
	OtherNotes []string
	// MovedEvents counts events that follow their month to its new place.
	MovedEvents int
	// Redated lists events left on a month position that now holds a
	// different month, so they will show in that month instead.
	Redated      []StructureEventChange
	RedatedTotal int
	// Stranded lists events whose date (or end date) will no longer exist.
	// They are kept, untouched, but the calendar cannot show them there.
	Stranded      []StructureEventChange
	StrandedTotal int
	// CurrentDate and NewCurrentDate read as "<Month> <Day>, <Year>".
	CurrentDate        string
	NewCurrentDate     string
	CurrentDateClamped bool
	// Day-weather readings: moved with their month, now in a different
	// month (theirs is gone but its position remains), replaced by a moved
	// reading on the same day, or left on a day that no longer exists.
	WeatherMoved    int
	WeatherRedated  int
	WeatherReplaced int
	WeatherStranded int
	// Repeat rules that name months follow them (RulesUpdated); rules that
	// name a removed month, or a removed moon or season, are left as written
	// and named in OtherNotes. One-off changes to repeats follow their month
	// (OverridesMoved), stay in a removed month (OverridesRemoved), or give
	// way to a moved one on the same date (OverridesReplaced).
	RulesUpdated      int
	RulesRemovedMonth int
	RulesRemovedRef   int
	OverridesMoved    int
	OverridesRemoved  int
	OverridesReplaced int
	Warnings          []string
	Fingerprint       string
}

StructurePreview is what a structure save would do, shown before it is confirmed. Fingerprint identifies the calendar state the preview was computed against; the save refuses a fingerprint that no longer matches, so what is confirmed is always what was shown.

type StructureRule

type StructureRule struct {
	EventID string
	Name    string
	Raw     string
}

StructureRule is one rule event as a structure save reads it. Raw is the stored JSON text, kept so the fingerprint notices any change to it and so the plan can run it through the strict parser.

type StructureState

type StructureState struct {
	Calendar    *Calendar
	Events      []Event
	WeatherDays []DayDate
	Rules       []StructureRule
	Overrides   []StructureOverride
}

StructureState is everything a structure save is planned from, as CalendarRepository reads it: the calendar with Months, Weekdays, Moons, Seasons and Eras loaded, every event's dates, every day-weather reading's date, every rule event's stored rule and every override.

type StructureWrite

type StructureWrite struct {
	Months        []MonthInput
	Weekdays      []WeekdayInput
	Moons         []MoonInput
	Seasons       []Season
	LeapYearEvery int
	// MonthStartsNewWeek is the resolved switch to store (the edit's value,
	// or the stored one when the edit left it out).
	MonthStartsNewWeek bool
	CurrentMonth       int
	CurrentDay         int
	MonthRemap         map[int]int
	RuleUpdates        []RuleUpdate
}

StructureWrite is one atomic structure save for CalendarRepository. MonthRemap maps an old month position (1-based) to its new one, holding only positions that change; every month column that stores a position (events, their end and recurrence-end dates, eras, day weather, and overrides) is remapped through it. RuleUpdates are the rewritten rules, which name months inside their JSON.

type SunLook

type SunLook struct {
	Kind  string  `json:"kind"`
	Color *string `json:"color,omitempty"`
}

SunLook is the calendar's sun: its kind of star, and an optional exact colour that overrides the kind's own.

func DefaultSunLook

func DefaultSunLook() SunLook

DefaultSunLook is a calendar's sun until its owner changes it, the same values migration 030's column defaults hold.

func (SunLook) SunDescription

func (l SunLook) SunDescription() string

SunDescription is the sun in words, for the AI's calendar lookup.

type UnfitNight

type UnfitNight struct {
	DayDate
	// Why names the conditions that ruled the lines out, in words.
	Why string `json:"why"`
}

UnfitNight is a night left unrolled because no table line fits it.

type UpdateCalendarInput

type UpdateCalendarInput struct {
	Name             string
	Description      patch.Field[string]
	EpochName        patch.Field[string]
	Mode             patch.Field[string]
	CurrentYear      patch.Field[int]
	CurrentMonth     patch.Field[int]
	CurrentDay       patch.Field[int]
	CurrentHour      patch.Field[int]
	CurrentMinute    patch.Field[int]
	HoursPerDay      patch.Field[int]
	MinutesPerHour   patch.Field[int]
	SecondsPerMinute patch.Field[int]
	LeapYearEvery    patch.Field[int]
	LeapYearOffset   patch.Field[int]
	// Hemisphere flips how a real-world calendar's seasons read (see
	// Calendar.Hemisphere's doc comment). When present, must be
	// HemisphereNorth or HemisphereSouth. Setting it for the first time on a
	// real-life calendar with no seasons yet auto-seeds the four default
	// seasons for that hemisphere (see UpdateCalendar and
	// defaultRealLifeSeasons) — a calendar that already has any seasons is
	// never touched by this field.
	Hemisphere patch.Field[string]
	// ForecastsEnabled/MonthStartsNewWeek mirror the two Calendar fields of
	// the same name, so the campaign-backup importer can restore them:
	// CreateCalendarInput has no field for either, the same reason
	// CreateCalendarFromImport patches Hemisphere/ForecastsEnabled/
	// MonthStartsNewWeek onto the row directly after CreateCalendar.
	ForecastsEnabled   patch.Field[bool]
	MonthStartsNewWeek patch.Field[bool]
	// SetRealTime is nil for every caller that does not manage the flag (e.g.
	// PutDate, worldstate advance/time, seed/create), so their update
	// preserves the stored TracksRealTime/RealTimeZone — a *bool so "absent"
	// (leave unchanged) is distinct from "false" (disable). RealTimeZone is
	// the IANA anchor, required and validated when enabling; ignored and
	// cleared when disabling.
	SetRealTime  *bool
	RealTimeZone *string
}

UpdateCalendarInput is the validated input for updating calendar settings. Partial update (internal/patch's Field type): an absent field preserves the stored value, an explicit null clears it, a present value replaces it. Name stays a plain string: UpdateCalendar rejects a blank merged name with 400, so an absent name fails loudly instead of silently overwriting — the same governedFieldExceptions shape as maps.UpdateMapInput.Name and timeline.UpdateTimelineInput.Name. Mode, when present, must be one of the calendar Mode constants (ModeFantasy / ModeRealLife).

type UpdateCalendarVisibilityInput

type UpdateCalendarVisibilityInput struct {
	Visibility      string
	VisibilityRules patch.Field[string]
}

UpdateCalendarVisibilityInput is the validated input for updating a calendar's per-calendar visibility. Same shape as the event one — the calendar reuses the event visibility model + resolver.

type UpdateEraInput

type UpdateEraInput struct {
	Name              string
	StartYear         patch.Field[int]
	StartMonth        patch.Field[int]
	StartDay          patch.Field[int]
	EndYear           patch.Field[int]
	EndMonth          patch.Field[int]
	EndDay            patch.Field[int]
	Description       patch.Field[string]
	Color             patch.Field[string]
	SortOrder         patch.Field[int]
	Color2            patch.Field[string]
	Style             patch.Field[string]
	Feel              patch.Field[string]
	LoreEntityID      patch.Field[string]
	DMNote            patch.Field[string]
	HiddenUntilBegins patch.Field[bool]
}

UpdateEraInput is the validated PARTIAL-update input for an existing era: an absent field preserves the stored value, an explicit null clears it, a present value replaces it. Name stays a plain string — UpdateEra rejects a blank merged name with 400, so an absent name fails loudly instead of silently overwriting (the same governedFieldExceptions shape as calendar.UpdateCalendarInput.Name).

type UpdateEventInput

type UpdateEventInput struct {
	Name                     patch.Field[string]
	Description              patch.Field[string]
	DescriptionHTML          patch.Field[string]
	EntityID                 patch.Field[string]
	Year                     patch.Field[int]
	Month                    patch.Field[int]
	Day                      patch.Field[int]
	StartHour                patch.Field[int]
	StartMinute              patch.Field[int]
	EndYear                  patch.Field[int]
	EndMonth                 patch.Field[int]
	EndDay                   patch.Field[int]
	EndHour                  patch.Field[int]
	EndMinute                patch.Field[int]
	IsRecurring              patch.Field[bool]
	RecurrenceType           patch.Field[string]
	RecurrenceInterval       patch.Field[int]
	RecurrenceEndYear        patch.Field[int]
	RecurrenceEndMonth       patch.Field[int]
	RecurrenceEndDay         patch.Field[int]
	RecurrenceMaxOccurrences patch.Field[int]
	// RecurrenceRule carries raw rule JSON; see CreateEventInput.
	RecurrenceRule  patch.Field[json.RawMessage]
	Visibility      patch.Field[string]
	VisibilityRules patch.Field[string]
	KindID          patch.Field[int]
	Announced       patch.Field[string]
	// Tier — see CreateEventInput.Tier doc.
	Tier    patch.Field[string]
	Color   patch.Field[string]
	Icon    patch.Field[string]
	AllDay  patch.Field[bool]
	Payload patch.Field[string]
	// Status and Outcome say what became of the event; see
	// mergeEventStatus for how a move keeps the day it was planned for.
	Status  patch.Field[string]
	Outcome patch.Field[string]
}

UpdateEventInput is the validated input for updating an event.

Partial update: an absent key preserves the stored value, an explicit null clears it, a present value replaces it (internal/patch's Field type). Every field uses patch.Field, including EntityID: a plain nil-preserving pointer would have made the link impossible to clear, so it needs the three-way absent/null/value distinction like the rest.

type UpdateEventKindInput

type UpdateEventKindInput struct {
	Slug             patch.Field[string]
	Name             string
	Icon             patch.Field[string]
	Color            patch.Field[string]
	SortOrder        patch.Field[int]
	DefaultAnnounced patch.Field[string]
}

UpdateEventKindInput is the validated PARTIAL-update input for an existing event kind: an absent field preserves the stored value, an explicit null clears it, a present value replaces it. Name stays a plain string for the same reason UpdateCalendarInput.Name does (a blank merged name fails loudly rather than silently overwriting).

type UpdateEventVisibilityInput

type UpdateEventVisibilityInput struct {
	Visibility      string
	VisibilityRules patch.Field[string]
	Announced       string
}

UpdateEventVisibilityInput is the validated input for updating event visibility. Visibility stays a plain string: this is a "set visibility" action, not a general settings save, so the caller always states the new visibility outright — there is no absent-preserves case for it (see governedFieldExceptions in internal/patch/partial_update_contract_test.go). VisibilityRules is patch.Field so a visibility-only call (flip everyone/dm_only) can leave an existing per-user rules blob untouched: absent preserves it, explicit null clears it, a value replaces it. Announced is "" to leave the stored setting alone, or AnnouncedAhead / AnnouncedOnDay to set it in the same write as the visibility, so a reveal is never half applied (shown, but still under the wrong announce rule).

type VisibilityRules

type VisibilityRules struct {
	AllowedUsers []string `json:"allowed_users,omitempty"`
	DeniedUsers  []string `json:"denied_users,omitempty"`
}

VisibilityRules defines per-user visibility overrides for calendar events. If AllowedUsers is set, only those users can see the item (whitelist). If DeniedUsers is set, those users cannot see the item (blacklist). AllowedUsers takes precedence: if set, DeniedUsers is ignored.

func ParseVisibilityRules

func ParseVisibilityRules(raw *string) *VisibilityRules

ParseVisibilityRules parses raw JSON (Calendar.VisibilityRules or Event.VisibilityRules) into a *VisibilityRules, or nil when unset. Shared by both owners of a visibility_rules column so the parse can't drift between them; Event additionally exposes it as a method (below) for existing callers.

func (*VisibilityRules) Allows

func (v *VisibilityRules) Allows(userID string) bool

Allows reports whether userID may see an item carrying these rules — a nil receiver (no rules stored) allows everyone. This is a VERBATIM MIRROR of maps.VisibilityRules.Allows (internal/plugins/maps/model.go) and the allow/deny half of timeline's canUserView: cross-plugin repo/model access is forbidden (plugins reach each other only through service interfaces), so the policy is replicated rather than imported.

SECURITY-SENSITIVE: keep in lockstep with maps' and timeline's twins, including the ADR-049 DeniesAnonymous check — a logged-out viewer can't be proven not to be the specific player a deny list names, so a non-empty DeniedUsers excludes them too, even though they match no literal entry.

type Weather

type Weather struct {
	ID                 int            `json:"id"`
	CalendarID         string         `json:"calendar_id"`
	PresetID           *string        `json:"preset_id,omitempty"`
	PresetLabel        *string        `json:"preset_label,omitempty"`
	Icon               *string        `json:"icon,omitempty"`
	Color              *string        `json:"color,omitempty"`
	TemperatureCelsius *float64       `json:"temperature_celsius,omitempty"`
	Wind               *Wind          `json:"wind,omitempty"`
	Precipitation      *Precipitation `json:"precipitation,omitempty"`
	ZoneID             *string        `json:"zone_id,omitempty"`
	ZoneName           *string        `json:"zone_name,omitempty"`
	Description        *string        `json:"description,omitempty"`
	UpdatedAt          time.Time      `json:"updated_at"`
}

Weather represents the current weather state for a calendar. Set manually by the GM or synced from external tools (Calendaria).

type WeatherChoice

type WeatherChoice struct{ ID, Label string }

WeatherChoice is one built-in weather or sky effect, as AI Import lists them. Read from the generator's own tables, so a new entry shows up there without a change elsewhere.

func WeatherEffects

func WeatherEffects() []WeatherChoice

WeatherEffects lists the sky effects the renderer can draw, in its order.

func WeatherPresets

func WeatherPresets() []WeatherChoice

WeatherPresets lists the generator's built-in weathers in its order.

type WeatherClimate

type WeatherClimate struct {
	ID    string
	Name  string
	Magic bool
}

WeatherClimate is one selectable climate. Magic climates are listed apart from the natural ones in the settings form.

type WeatherInput

type WeatherInput struct {
	PresetID               *string  `json:"preset_id"`
	PresetLabel            *string  `json:"preset_label"`
	Icon                   *string  `json:"icon"`
	Color                  *string  `json:"color"`
	TemperatureCelsius     *float64 `json:"temperature_celsius"`
	WindSpeedKPH           *float64 `json:"wind_speed_kph"`
	WindSpeedTier          *string  `json:"wind_speed_tier"`
	WindDirection          *string  `json:"wind_direction"`
	WindDirectionDeg       *int     `json:"wind_direction_degrees"`
	PrecipitationType      *string  `json:"precipitation_type"`
	PrecipitationIntensity *float64 `json:"precipitation_intensity"`
	ZoneID                 *string  `json:"zone_id"`
	ZoneName               *string  `json:"zone_name"`
	Description            *string  `json:"description"`
}

WeatherInput is the input for setting weather state.

type WeatherKind

type WeatherKind struct {
	ID      string             `json:"id"`
	Name    string             `json:"name"`
	Icon    string             `json:"icon"`
	Color   string             `json:"color"`
	Like    string             `json:"like"`
	Seasons WeatherKindSeasons `json:"seasons"`
	Lasts   string             `json:"lasts,omitempty"`
	Words   []string           `json:"words,omitempty"`
	Magic   bool               `json:"magic,omitempty"`
	Look    *WeatherKindLook   `json:"look,omitempty"`
}

WeatherKind is one of the owner's own kinds of weather, in exactly the shape the generator accepts as its `kinds` option. Optional parts are omitted when they hold their default, so a stored kind stays minimal.

type WeatherKindLook

type WeatherKindLook struct {
	Effect string `json:"effect"`
}

WeatherKindLook is the sky effect drawn for a kind; without one the sky uses the effect of the built-in weather the kind is like.

type WeatherKindSeasons

type WeatherKindSeasons struct {
	Winter string `json:"winter"`
	Spring string `json:"spring"`
	Summer string `json:"summer"`
	Autumn string `json:"autumn"`
}

WeatherKindSeasons is how often a kind comes in each season: off, rare, normal or often. A missing level reads as normal.

type WeatherRepository

type WeatherRepository interface {
	Get(ctx context.Context, calendarID string) (*Weather, error)
	Set(ctx context.Context, calendarID string, input WeatherInput) error

	// ListDays returns the stored day readings for year, or for one month of
	// it when month > 0, in date order.
	ListDays(ctx context.Context, calendarID string, year, month int) ([]DayWeather, error)
	// ListAllDays returns every stored day reading, in date order.
	ListAllDays(ctx context.Context, calendarID string) ([]DayWeather, error)
	// SetDays upserts day readings in one transaction. A generated reading
	// never replaces a stored manual one or a locked one; a manual reading
	// replaces anything and clears the lock.
	SetDays(ctx context.Context, calendarID string, days []DayWeatherInput) error
	// ClearDays deletes the readings on the given days, whatever their source.
	ClearDays(ctx context.Context, calendarID string, dates []DayDate) error

	// LockDays sets the lock on the stored readings on the given days and
	// returns how many rows changed. A day with no reading is skipped, never
	// created.
	LockDays(ctx context.Context, calendarID string, dates []DayDate, locked bool) (int, error)

	// GetSettings returns the calendar's climate settings, or (nil, nil)
	// when none were ever stored.
	GetSettings(ctx context.Context, calendarID string) (*WeatherSettings, error)
	// SetSettings creates or replaces the calendar's climate settings.
	SetSettings(ctx context.Context, calendarID string, s WeatherSettings) error
}

WeatherRepository defines persistence for a calendar's current weather.

func NewWeatherRepository

func NewWeatherRepository(db *sql.DB) WeatherRepository

NewWeatherRepository creates a new MariaDB-backed weather repository.

type WeatherSettings

type WeatherSettings struct {
	Climate    string        `json:"climate"`
	Continuity float64       `json:"continuity"`
	Kinds      []WeatherKind `json:"kinds"`
	// ForecastDays is how many days ahead a player's forecast reaches
	// (1..MaxForecastDays). ForecastsEnabled mirrors calendars.forecasts_enabled:
	// the service fills it on read and writes it through UpdateCalendar, so
	// the switch has one home and the repository never owns it.
	ForecastDays     int  `json:"forecast_days"`
	ForecastsEnabled bool `json:"forecasts_enabled"`
}

WeatherSettings is a calendar's world climate and how long weather lasts (0 changes every day, 1 settles into long spells). The weather calendar starts from these. Kinds are the owner's own kinds of weather.

func (WeatherSettings) MarshalJSON

func (s WeatherSettings) MarshalJSON() ([]byte, error)

MarshalJSON writes Kinds as [] rather than null when there are none, so a client can always iterate it.

type WeatherZone

type WeatherZone struct {
	CalendarID string         `json:"calendar_id"`
	ZoneID     string         `json:"zone_id"`
	Name       string         `json:"name"`
	Payload    map[string]any `json:"payload"`
	CreatedAt  time.Time      `json:"created_at,omitempty"`
	UpdatedAt  time.Time      `json:"updated_at,omitempty"`
}

WeatherZone is a per-calendar climate region definition (e.g. "temperate", "tropical", "arctic"). The zone's payload carries the active presets + per-season overrides as opaque JSON — the structural shape is owned by Calendaria/Foundry sync (presets array, season_overrides map) and Chronicle stores it verbatim with a small validation helper (see service.go validateWeatherZonePayload).

Zones are calendar-scoped: each calendar has its own zones. The active-zone reference lives on calendar_weather.zone_id + zone_name; the zone definitions live in this table.

type WeatherZonesState

type WeatherZonesState struct {
	ActiveZone string        `json:"active_zone"`
	Zones      []WeatherZone `json:"zones"`
}

WeatherZonesState bundles the per-calendar active-zone reference + the full zone definitions list — the canonical GET response from /api/v1/campaigns/:cid/calendar/weather/zones. ActiveZone is "" when no zone is currently active; Zones may be empty.

type Weekday

type Weekday struct {
	ID         int    `json:"id"`
	CalendarID string `json:"calendar_id"`
	Name       string `json:"name"`
	SortOrder  int    `json:"sort_order"`
	IsRestDay  bool   `json:"is_rest_day"`
}

Weekday is a named day in the repeating weekly cycle.

type WeekdayInput

type WeekdayInput struct {
	Name      string `json:"name"`
	SortOrder int    `json:"sort_order"`
	IsRestDay bool   `json:"is_rest_day"`
}

WeekdayInput is the input for creating/updating a weekday.

type Wind

type Wind struct {
	SpeedKPH         *float64 `json:"speed_kph,omitempty"`
	SpeedTier        *string  `json:"speed_tier,omitempty"`
	Direction        *string  `json:"direction,omitempty"`
	DirectionDegrees *int     `json:"direction_degrees,omitempty"`
}

Wind describes wind speed and direction.

Directories

Path Synopsis
Package calendarai is the calendar's part of the AI engine (aiplug, ADR-071): the blocks an AI can ask to write onto the calendar (the calendar itself, events, a day's weather, a moon set by hand, a rolled night and Chronicle's generators) and the calendar lookups (the calendar, kinds of weather, events and weather by day).
Package calendarai is the calendar's part of the AI engine (aiplug, ADR-071): the blocks an AI can ask to write onto the calendar (the calendar itself, events, a day's weather, a moon set by hand, a rolled night and Chronicle's generators) and the calendar lookups (the calendar, kinds of weather, events and weather by day).

Jump to

Keyboard shortcuts

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