diff --git a/.ai/rules/downtime.md b/.ai/rules/downtime.md new file mode 100644 index 0000000..87470ce --- /dev/null +++ b/.ai/rules/downtime.md @@ -0,0 +1,9 @@ +--- +paths: + - 'app/Livewire/Downtime/**' +--- + +# Downtime + +## Downtime is gated by the character, written by the character's player, and one component in three places +downtime_activities has no visibility column. DowntimeActivity::scopeVisibleTo(user, role) is a whereIn over Entity::visibleTo(), so a row is read by whoever may read the character and a GM-only NPC's month never loads for a player. DowntimeActivityPolicy follows the character, not the author: a GM or entities.player_user_id may create, edit, and delete, the rule EntityPolicy::update() already spells. Downtime\Log renders on the character page (scoped to the character, form writes under it), the session page (scoped to the session, character picker), and /downtime (both pickers); do not fork it. The character picker's list is also the validation rule, so a posted id it never offered is an error rather than a write. The start date goes through the same calendar check as the session form and the end date is computed, never stored. diff --git a/.ai/rules/index.md b/.ai/rules/index.md index 31b9e10..3e7ccc1 100644 --- a/.ai/rules/index.md +++ b/.ai/rules/index.md @@ -20,6 +20,7 @@ Before planning or editing, find the row whose globs match the file's path and r | app/Livewire/Decisions/** | .ai/rules/decisions.md | | app/Support/Dice/** | .ai/rules/dice.md | | app/Discord/** | .ai/rules/discord.md | +| app/Livewire/Downtime/** | .ai/rules/downtime.md | | app/Support/Encounters/** | .ai/rules/encounters.md | | app/Livewire/Entities/** | .ai/rules/entities.md | | app/Events/** | .ai/rules/events.md | diff --git a/README.md b/README.md index bd0b6d4..238f49c 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Slice 23 adds **a ceiling on a campaign's files**. `CAMPAIGN_STORAGE_MB`, 500 by Slice 24 adds **the player screen**, for the television at the end of the table. `/screen` is one page with no sidebar and no controls that shows what the whole party may see and nothing else, whoever opened it: the turn order with health as a word, a handout full size, a map with the pins the party found, or the revealed clocks, with the clocks in a strip along the bottom the rest of the time. The GM chooses from a card on the Run screen, and putting a hidden handout up shows the party on the way. It changes on every open screen at once over the same channel as the table, and it falls back on its own: to the fight while one runs, then to the campaign's name and the party. +Slice 25 adds **downtime**, what each character did between sessions. A row is what they did, how many days it cost, an optional note in Markdown, the session it happened around, and, when the campaign has a calendar, the day in the world it began, from which the page prints the range it covered. A player writes their own PC's rows and a GM writes anyone's; whoever may see the character reads them, and there is no second switch. The same log sits on the character's page, on the session's page, and at `/downtime`, where the days are summed per character on every read. It travels in the export and lands on the character's page in the vault. + Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text. ## Local setup diff --git a/app/Actions/Campaigns/ExportCampaign.php b/app/Actions/Campaigns/ExportCampaign.php index 9ac22be..f67d358 100644 --- a/app/Actions/Campaigns/ExportCampaign.php +++ b/app/Actions/Campaigns/ExportCampaign.php @@ -9,6 +9,7 @@ use App\Models\Combatant; use App\Models\Decision; use App\Models\DiceRoll; +use App\Models\DowntimeActivity; use App\Models\Encounter; use App\Models\Entity; use App\Models\EntityBodyRevision; @@ -97,6 +98,7 @@ class ExportCampaign 'game_sessions' => 'sessions', 'decisions' => 'decisions', 'ledger_entries' => 'ledger', + 'downtime_activities' => 'downtime', 'reputation_changes' => 'reputation', 'stat_blocks' => 'stat_blocks', 'encounters' => 'encounters', @@ -162,6 +164,7 @@ public function handle(Campaign $campaign): array 'clocks' => $this->clocks($campaign), 'decisions' => $this->decisions($campaign), 'ledger' => $this->ledger($campaign), + 'downtime' => $this->downtime($campaign), 'reputation' => $this->reputation($campaign), ]; } @@ -637,6 +640,30 @@ private function ledger(Campaign $campaign): iterable ]); } + /** + * @return iterable> A LazyCollection: it streams row by row. + */ + private function downtime(Campaign $campaign): iterable + { + return DowntimeActivity::query() + ->withoutGlobalScopes() + ->where('campaign_id', $campaign->id) + ->orderBy('created_at') + ->orderBy('id') + ->cursor() + ->map(fn (DowntimeActivity $activity) => [ + 'id' => $activity->id, + 'entity_id' => $activity->entity_id, + 'game_session_id' => $activity->game_session_id, + 'activity' => $activity->activity, + 'days' => $activity->days, + 'notes' => $activity->notes, + 'starts_on' => $activity->starts_on?->toArray(), + 'created_at' => $activity->created_at?->toIso8601String(), + 'updated_at' => $activity->updated_at?->toIso8601String(), + ]); + } + /** * @return iterable> A LazyCollection: it streams row by row. */ diff --git a/app/Actions/Campaigns/ImportCampaign.php b/app/Actions/Campaigns/ImportCampaign.php index 70d00bd..0f372b5 100644 --- a/app/Actions/Campaigns/ImportCampaign.php +++ b/app/Actions/Campaigns/ImportCampaign.php @@ -8,6 +8,7 @@ use App\Models\Clock; use App\Models\Combatant; use App\Models\Decision; +use App\Models\DowntimeActivity; use App\Models\Encounter; use App\Models\Entity; use App\Models\EntityBodyRevision; @@ -93,6 +94,7 @@ public function handle(array $document, User $importer, array $restored = []): C $this->decisions($document, $campaign, $importer, $ids); $this->ledger($document, $campaign, $importer, $ids); $this->reputation($document, $campaign, $importer, $ids); + $this->downtime($document, $campaign, $importer, $ids); $this->screen($document, $campaign, $ids); }); @@ -506,6 +508,31 @@ private function prepped(array $document, IdMap $ids): void } } + /** + * What each character did between sessions. The character and the session are + * remapped; the date travels as the triple; the importer is the author, because + * the file cannot say who was. + * + * @param array $document + */ + private function downtime(array $document, Campaign $campaign, User $importer, IdMap $ids): void + { + foreach ($document['downtime'] as $row) { + $this->write(new DowntimeActivity, [ + 'id' => $ids->remember($row['id']), + 'campaign_id' => $campaign->id, + 'entity_id' => $ids->newFor($row['entity_id']), + 'game_session_id' => $ids->newForNullable($row['game_session_id']), + 'activity' => $row['activity'], + 'days' => $row['days'], + 'notes' => $row['notes'], + 'starts_on' => $row['starts_on'], + 'created_at' => $row['created_at'], + 'created_by' => $importer->id, + ]); + } + } + /** * What the screen on the wall shows, written after the page it names exists. The * focus travels as it is; the page is remapped like every other id. diff --git a/app/Actions/Campaigns/ReadCampaignFile.php b/app/Actions/Campaigns/ReadCampaignFile.php index 85b4868..53c0a46 100644 --- a/app/Actions/Campaigns/ReadCampaignFile.php +++ b/app/Actions/Campaigns/ReadCampaignFile.php @@ -17,6 +17,7 @@ use App\Models\Campaign; use App\Models\Combatant; use App\Models\Decision; +use App\Models\DowntimeActivity; use App\Models\Encounter; use App\Models\EntityRelation; use App\Models\GameSession; @@ -135,6 +136,7 @@ public function handle(string $json): ReadResult 'clocks' => $this->clocks($this->list($decoded, 'clocks')), 'decisions' => $this->decisions($this->list($decoded, 'decisions')), 'ledger' => $this->ledger($this->list($decoded, 'ledger')), + 'downtime' => $this->downtime($this->list($decoded, 'downtime')), 'reputation' => $this->reputation($this->list($decoded, 'reputation')), ]; @@ -952,6 +954,49 @@ private function signedInteger(array $row, string $key): ?int return is_string($value) && preg_match('/^-?\\d+$/', $value) === 1 ? (int) $value : null; } + /** + * What each character did between sessions. A row is its character and its + * activity; one with neither is a row nothing can show. Absent from a file older + * than slice 25, and an empty list is what that means. + * + * @param list> $rows + * @return list> + */ + private function downtime(array $rows): array + { + $activities = []; + + foreach ($rows as $index => $row) { + $id = $this->id($row, 'downtime', $index); + + if ($id === null) { + continue; + } + + $activity = $this->text($row, 'activity', DowntimeActivity::MAX_ACTIVITY_LENGTH); + $character = $this->reference($row, 'entity_id'); + + if ($activity === null || $character === null) { + continue; + } + + $activities[] = [ + 'id' => $id, + 'entity_id' => $character, + 'game_session_id' => $this->reference($row, 'game_session_id'), + 'activity' => $activity, + 'days' => max(0, min(DowntimeActivity::MAX_DAYS, $this->integer($row, 'days') ?? 0)), + 'notes' => $this->text($row, 'notes', DowntimeActivity::MAX_NOTES_LENGTH), + 'starts_on' => $this->gameDate($row, 'starts_on'), + 'created_at' => $this->text($row, 'created_at', 40), + ]; + } + + $this->report->count('downtime', count($activities)); + + return $activities; + } + /** * @param list $rows * @return list> @@ -1044,6 +1089,8 @@ private function checkReferences(array $document): void $ledger = $document['ledger']; /** @var list> $reputation */ $reputation = $document['reputation']; + /** @var list> $downtime */ + $downtime = $document['downtime']; // An arc is an entity of one type, so the reference is checked against the // arcs the file carries rather than every page in it. @@ -1120,6 +1167,11 @@ private function checkReferences(array $document): void $this->mustResolve($change['game_session_id'], $this->sessionIds, 'session', 'a reputation change'); } + foreach ($downtime as $activity) { + $this->mustResolve($activity['entity_id'], $this->entityIds, 'character', 'a downtime row'); + $this->mustResolve($activity['game_session_id'], $this->sessionIds, 'session', 'a downtime row'); + } + $this->checkCycles($entities, 'parent_id', 'The pages in that file nest inside each other in a loop'); $this->checkCycles($tables, 'nested_table_id', 'The tables in that file nest inside each other in a loop'); } diff --git a/app/Actions/Campaigns/WriteCampaignMarkdown.php b/app/Actions/Campaigns/WriteCampaignMarkdown.php index e434083..5e672f7 100644 --- a/app/Actions/Campaigns/WriteCampaignMarkdown.php +++ b/app/Actions/Campaigns/WriteCampaignMarkdown.php @@ -4,6 +4,7 @@ use App\Models\Campaign; use App\Models\Decision; +use App\Models\DowntimeActivity; use App\Models\Entity; use App\Models\EntityRelation; use App\Models\GameSession; @@ -51,7 +52,7 @@ public function handle(Campaign $campaign): array $entities = Entity::withoutGlobalScopes() ->where('campaign_id', $campaign->id) ->whereNull('deleted_at') - ->with(['tags', 'parent', 'arc', 'player', 'objectives', 'relations.target', 'incomingRelations.source', 'reputationChanges.gameSession']) + ->with(['tags', 'parent', 'arc', 'player', 'objectives', 'relations.target', 'incomingRelations.source', 'reputationChanges.gameSession', 'downtimeActivities.gameSession']) ->orderBy('name') ->get(); @@ -242,6 +243,21 @@ private function entity(Entity $entity): string ->implode("\n"); } + // What the character did between sessions, oldest first, with the days, the + // range in the world when there is one, and the session it happened around. + if ($entity->isCharacter() && $entity->downtimeActivities->isNotEmpty()) { + $body[] = "## Downtime\n\n".$entity->downtimeActivities + ->map(function (DowntimeActivity $activity): string { + $range = $this->reckoning === null ? null : $activity->range($this->reckoning); + $line = '- '.$activity->activity.', '.DowntimeActivity::dayCount($activity->days) + .($range !== null ? ', '.$range : '') + .($activity->gameSession !== null ? ' *('.$activity->gameSession->label().')*' : ''); + + return $activity->hasNotes() ? $line."\n ".$activity->notes : $line; + }) + ->implode("\n"); + } + $body[] = $this->section('Rewards', $entity->rewards); $body[] = $this->section('GM notes', $entity->dm_notes); diff --git a/app/Actions/Downtime/DeleteDowntime.php b/app/Actions/Downtime/DeleteDowntime.php new file mode 100644 index 0000000..914d543 --- /dev/null +++ b/app/Actions/Downtime/DeleteDowntime.php @@ -0,0 +1,13 @@ +delete(); + } +} diff --git a/app/Actions/Downtime/RecordDowntime.php b/app/Actions/Downtime/RecordDowntime.php new file mode 100644 index 0000000..5b4a101 --- /dev/null +++ b/app/Actions/Downtime/RecordDowntime.php @@ -0,0 +1,33 @@ + $campaign->id, + 'entity_id' => $character->id, + 'game_session_id' => ($parts['session'] ?? null)?->id, + 'activity' => trim($parts['activity']), + 'days' => $parts['days'], + 'notes' => filled($parts['notes'] ?? null) ? trim((string) $parts['notes']) : null, + 'starts_on' => $parts['starts_on'] ?? null, + 'created_by' => $actor->id, + ]); + } +} diff --git a/app/Actions/Downtime/UpdateDowntime.php b/app/Actions/Downtime/UpdateDowntime.php new file mode 100644 index 0000000..0772544 --- /dev/null +++ b/app/Actions/Downtime/UpdateDowntime.php @@ -0,0 +1,29 @@ +fill([ + 'game_session_id' => ($parts['session'] ?? null)?->id, + 'activity' => trim($parts['activity']), + 'days' => $parts['days'], + 'notes' => filled($parts['notes'] ?? null) ? trim((string) $parts['notes']) : null, + 'starts_on' => $parts['starts_on'] ?? null, + ])->save(); + + return $activity; + } +} diff --git a/app/Livewire/Downtime/Index.php b/app/Livewire/Downtime/Index.php new file mode 100644 index 0000000..5d7d300 --- /dev/null +++ b/app/Livewire/Downtime/Index.php @@ -0,0 +1,65 @@ +enterCampaign($campaign); + $this->authorize('viewAny', [DowntimeActivity::class, $campaign]); + } + + public function render(): View + { + return view('livewire.downtime.index', [ + 'role' => $this->role(), + 'totals' => $this->totals(), + ])->title('Downtime'); + } + + /** + * Days per character, summed on every read over the rows this viewer may see, + * in name order. Two queries: the sums, then the names for the ids that came back. + * + * @return Collection + */ + private function totals(): Collection + { + /** @var User $user */ + $user = auth()->user(); + + $sums = DowntimeActivity::query() + ->visibleTo($user, $this->role()) + ->selectRaw('entity_id, sum(days) as total_days') + ->groupBy('entity_id') + ->pluck('total_days', 'entity_id'); + + if ($sums->isEmpty()) { + return collect(); + } + + return Entity::query() + ->whereKey($sums->keys()->all()) + ->orderBy('name') + ->get() + ->map(fn (Entity $character) => ['character' => $character, 'days' => (int) $sums[$character->id]]) + ->values(); + } +} diff --git a/app/Livewire/Downtime/Log.php b/app/Livewire/Downtime/Log.php new file mode 100644 index 0000000..faa28f2 --- /dev/null +++ b/app/Livewire/Downtime/Log.php @@ -0,0 +1,406 @@ + '', 'month' => '', 'day' => '']; + + public ?string $editingId = null; + + public string $editingActivity = ''; + + public string $editingDays = ''; + + public string $editingNotes = ''; + + public string $editingSessionId = ''; + + /** @var array{year: string, month: string, day: string} */ + public array $editingStartsOn = ['year' => '', 'month' => '', 'day' => '']; + + public function mount(Campaign $campaign, ?Entity $character = null, ?GameSession $session = null): void + { + $this->enterCampaign($campaign); + $this->authorize('viewAny', [DowntimeActivity::class, $campaign]); + + $this->character = $character; + $this->session = $session; + $this->newSessionId = $session === null ? '' : $session->id; + } + + public function record(RecordDowntime $recordDowntime): void + { + $character = $this->character ?? $this->pickedCharacter(); + + if ($character === null) { + return; + } + + $this->authorize('create', [DowntimeActivity::class, $character]); + + $validated = $this->validate([ + 'newActivity' => ['required', 'string', 'max:'.DowntimeActivity::MAX_ACTIVITY_LENGTH], + 'newDays' => ['required', 'integer', 'min:0', 'max:'.DowntimeActivity::MAX_DAYS], + 'newNotes' => ['nullable', 'string', 'max:'.DowntimeActivity::MAX_NOTES_LENGTH], + 'newSessionId' => $this->sessionRule(), + ]); + + $startsOn = $this->startsOn('newStartsOn'); + + if ($this->getErrorBag()->isNotEmpty()) { + return; + } + + $recordDowntime->handle($this->campaign, $this->user(), $character, [ + 'activity' => $validated['newActivity'], + 'days' => (int) $validated['newDays'], + 'notes' => $validated['newNotes'] ?? null, + 'session' => $this->sessionFor($validated['newSessionId'] ?? ''), + 'starts_on' => $startsOn, + ]); + + $this->reset('newActivity', 'newNotes', 'newStartsOn', 'newCharacterId'); + $this->newDays = '1'; + $this->newSessionId = $this->session === null ? '' : $this->session->id; + } + + public function edit(string $activityId): void + { + $activity = $this->activity($activityId); + + $this->authorize('update', $activity); + + $this->editingId = $activity->id; + $this->editingActivity = $activity->activity; + $this->editingDays = (string) $activity->days; + $this->editingNotes = $activity->notes ?? ''; + $this->editingSessionId = $activity->game_session_id ?? ''; + $this->editingStartsOn = $activity->starts_on === null + ? ['year' => '', 'month' => '', 'day' => ''] + : array_map(fn (int $part) => (string) $part, $activity->starts_on->toArray()); + } + + public function cancelEdit(): void + { + $this->reset('editingId', 'editingActivity', 'editingDays', 'editingNotes', 'editingSessionId', 'editingStartsOn'); + } + + public function save(UpdateDowntime $updateDowntime): void + { + $activity = $this->activity((string) $this->editingId); + + $this->authorize('update', $activity); + + $validated = $this->validate([ + 'editingActivity' => ['required', 'string', 'max:'.DowntimeActivity::MAX_ACTIVITY_LENGTH], + 'editingDays' => ['required', 'integer', 'min:0', 'max:'.DowntimeActivity::MAX_DAYS], + 'editingNotes' => ['nullable', 'string', 'max:'.DowntimeActivity::MAX_NOTES_LENGTH], + 'editingSessionId' => $this->sessionRule(), + ]); + + $startsOn = $this->startsOn('editingStartsOn'); + + if ($this->getErrorBag()->isNotEmpty()) { + return; + } + + $updateDowntime->handle($activity, [ + 'activity' => $validated['editingActivity'], + 'days' => (int) $validated['editingDays'], + 'notes' => $validated['editingNotes'] ?? null, + 'session' => $this->sessionFor($validated['editingSessionId'] ?? ''), + 'starts_on' => $startsOn, + ]); + + $this->cancelEdit(); + } + + public function delete(string $activityId, DeleteDowntime $deleteDowntime): void + { + $activity = $this->activity($activityId); + + $this->authorize('delete', $activity); + + $deleteDowntime->handle($activity); + + if ($this->editingId === $activityId) { + $this->cancelEdit(); + } + } + + public function render(MarkdownRenderer $renderer): View + { + $role = $this->role(); + $user = $this->user(); + $wikiLinks = WikiLinkRenderer::for($this->campaign, $user, $role); + $reckoning = $this->reckoning(); + $activities = $this->activities(); + $characterOptions = $this->characterOptions(); + + // Rendered here, per row, so the Blade prints what it was handed and never + // reads a field the query did not load. + $html = $activities->mapWithKeys(fn (DowntimeActivity $activity) => [ + $activity->id => $activity->hasNotes() ? $renderer->render($activity->notes, $wikiLinks) : '', + ]); + + $ranges = $activities->mapWithKeys(fn (DowntimeActivity $activity) => [ + $activity->id => $reckoning === null ? null : $activity->range($reckoning), + ]); + + return view('livewire.downtime.log', [ + 'activities' => $activities, + 'html' => $html, + 'ranges' => $ranges, + 'sessionLinks' => $this->sessionLinks($activities), + 'editable' => $activities->filter(fn (DowntimeActivity $activity) => $user->can('update', $activity))->pluck('id')->all(), + 'canWrite' => $this->character !== null + ? $user->can('create', [DowntimeActivity::class, $this->character]) + : $characterOptions->isNotEmpty(), + 'total' => $this->character === null ? null : (int) $activities->sum('days'), + 'scopedToCharacter' => $this->character !== null, + 'scopedToSession' => $this->session !== null, + 'characterOptions' => $characterOptions, + 'sessionOptions' => $this->session === null + ? GameSession::query()->visibleTo($role)->orderByDesc('number')->get(['id', 'number', 'title']) + : collect(), + 'months' => $reckoning === null ? [] : $reckoning->months, + 'hasCalendar' => $reckoning !== null, + ]); + } + + /** + * @return Collection + */ + private function activities(): Collection + { + return DowntimeActivity::query() + ->visibleTo($this->user(), $this->role()) + ->when($this->character !== null, fn (Builder $query) => $query->forCharacter($this->character)) + ->when($this->session !== null, fn (Builder $query) => $query->around($this->session)) + ->with('character') + ->orderByDesc('created_at') + ->orderByDesc('id') + ->get(); + } + + /** + * The characters this member may write on: a GM every one, a player their own. + * The list is also the rule the picker is checked against, so a posted id the + * picker never offered is a validation error rather than a write. + * + * @return Collection + */ + private function characterOptions(): Collection + { + $user = $this->user(); + $role = $this->role(); + + return Entity::query() + ->ofType(EntityType::Character) + ->visibleTo($user, $role) + ->when(! $role->isDm(), fn (Builder $query) => $query->where('player_user_id', $user->id)) + ->orderBy('name') + ->get(['id', 'name', 'campaign_id', 'player_user_id']); + } + + private function pickedCharacter(): ?Entity + { + $options = $this->characterOptions(); + + $this->validate([ + 'newCharacterId' => ['required', Rule::in($options->pluck('id')->all())], + ], [ + 'newCharacterId.required' => 'Pick a character.', + 'newCharacterId.in' => 'Pick a character.', + ]); + + /** @var Entity|null $character */ + $character = Entity::query()->whereKey($this->newCharacterId)->first(); + + return $character; + } + + /** + * The session each row happened around, keyed by id, and only the ones this + * viewer may see. One query for the whole log, with the filter in it. + * + * @param Collection $activities + * @return Collection + */ + private function sessionLinks(Collection $activities): Collection + { + /** @var Collection $ids */ + $ids = $activities->pluck('game_session_id')->filter()->unique()->values(); + + if ($ids->isEmpty()) { + /** @var Collection $empty */ + $empty = new Collection; + + return $empty; + } + + return GameSession::query() + ->visibleTo($this->role()) + ->whereKey($ids->all()) + ->get() + ->keyBy('id'); + } + + /** + * The start date, checked against the calendar the way the session form checks + * its two. All blank is null; a part that fails lands its error on its own input. + * Without a calendar the picker is not offered, and whatever was posted is ignored. + */ + private function startsOn(string $field): ?GameDate + { + $reckoning = $this->reckoning(); + + if ($reckoning === null) { + return null; + } + + /** @var array{year?: string, month?: string, day?: string} $parts */ + $parts = $this->{$field}; + + if (($parts['year'] ?? '') === '' && ($parts['month'] ?? '') === '' && ($parts['day'] ?? '') === '') { + return null; + } + + $validator = Validator::make([$field => $parts], [ + $field.'.year' => ['required', 'integer', 'min:'.Bounds::MIN_YEAR, 'max:'.Bounds::MAX_YEAR], + $field.'.month' => ['required', 'integer', 'min:1', 'max:'.$reckoning->monthCount()], + $field.'.day' => ['required', 'integer', 'min:1', 'max:'.Bounds::MAX_DAYS], + ], [ + $field.'.*.required' => 'Fill in the day, the month, and the year, or leave all three blank.', + ]); + + $validator->after(function (ValidatorInstance $validator) use ($field, $parts, $reckoning): void { + if ($validator->errors()->isNotEmpty()) { + return; + } + + $date = new GameDate((int) $parts['year'], (int) $parts['month'], (int) $parts['day']); + + if (! $reckoning->isValid($date)) { + $validator->errors()->add($field.'.day', $reckoning->monthName($date->month).' has '.$reckoning->daysInMonth($date->month, $date->year).' days that year.'); + } + }); + + if ($validator->fails()) { + $this->getErrorBag()->merge($validator->errors()); + + return null; + } + + return new GameDate((int) $parts['year'], (int) $parts['month'], (int) $parts['day']); + } + + /** + * @return list + */ + private function sessionRule(): array + { + return [ + 'nullable', + Rule::exists('game_sessions', 'id') + ->where('campaign_id', $this->campaign->id) + ->whereNull('deleted_at'), + ]; + } + + private function sessionFor(string $id): ?GameSession + { + if ($id === '') { + return null; + } + + return GameSession::query()->whereKey($id)->first(); + } + + /** + * A row this viewer may read, or a 404: a hidden character's row is one a player + * may not learn exists. + */ + private function activity(string $activityId): DowntimeActivity + { + /** @var DowntimeActivity $activity */ + $activity = DowntimeActivity::query() + ->visibleTo($this->user(), $this->role()) + ->whereKey($activityId) + ->firstOrFail(); + + return $activity; + } + + private function reckoning(): ?Reckoning + { + return Calendar::query()->first()?->reckoning(); + } + + private function user(): User + { + /** @var User $user */ + $user = auth()->user(); + + return $user; + } +} diff --git a/app/Livewire/Entities/Show.php b/app/Livewire/Entities/Show.php index 9acbfac..dcd170a 100644 --- a/app/Livewire/Entities/Show.php +++ b/app/Livewire/Entities/Show.php @@ -119,6 +119,10 @@ public function render(MarkdownRenderer $renderer): View 'dmNotesHtml' => $role->isDm() ? $renderer->render($this->entity->dm_notes, $wikiLinks) : null, 'rewardsHtml' => $this->entity->isQuest() ? $renderer->render($this->entity->rewards, $wikiLinks) : '', 'questStatus' => $this->entity->questStatus(), + // A PC always carries the downtime card, so its player has the form. An NPC + // carries it once a GM has written a row, and never an empty one. + 'showDowntime' => $this->entity->isCharacter() + && ($this->entity->is_pc || $this->entity->downtimeActivities()->exists()), 'happensOn' => $this->entity->happens_on === null ? null : Calendar::query()->first()?->reckoning()->format($this->entity->happens_on), 'giver' => $this->visibleGiver($user, $role), 'arc' => $this->visibleArc($user, $role), diff --git a/app/Models/DowntimeActivity.php b/app/Models/DowntimeActivity.php new file mode 100644 index 0000000..2d32862 --- /dev/null +++ b/app/Models/DowntimeActivity.php @@ -0,0 +1,168 @@ + */ + use HasFactory, HasUlids; + + public const MAX_ACTIVITY_LENGTH = 120; + + public const MAX_NOTES_LENGTH = 2000; + + public const MAX_DAYS = 999; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'days' => 'integer', + 'starts_on' => GameDateCast::class.':starts', + ]; + } + + /** + * The character who spent the days. + * + * @return BelongsTo + */ + public function character(): BelongsTo + { + return $this->belongsTo(Entity::class, 'entity_id'); + } + + /** + * The session it happened around. Null for downtime with no session near it. + * + * @return BelongsTo + */ + public function gameSession(): BelongsTo + { + return $this->belongsTo(GameSession::class); + } + + /** + * The one filter for a player: the rows of the characters they may see. In the + * query, as .ai/rules/table.md asks, so a hidden character's row never loads. + * + * @param Builder $query + * @return Builder + */ + public function scopeVisibleTo(Builder $query, User $user, CampaignRole $role): Builder + { + if ($role->isDm()) { + return $query; + } + + return $query->whereIn( + $query->qualifyColumn('entity_id'), + Entity::query()->visibleTo($user, $role)->select('entities.id'), + ); + } + + /** + * @param Builder $query + * @return Builder + */ + public function scopeForCharacter(Builder $query, Entity $character): Builder + { + return $query->where($query->qualifyColumn('entity_id'), $character->id); + } + + /** + * @param Builder $query + * @return Builder + */ + public function scopeAround(Builder $query, GameSession $session): Builder + { + return $query->where($query->qualifyColumn('game_session_id'), $session->id); + } + + /** + * The last day the activity covers: the start plus the days less one, or the + * start itself for a thing that cost no whole day. Null without a start. + */ + public function endsOn(Reckoning $reckoning): ?GameDate + { + if ($this->starts_on === null) { + return null; + } + + return $this->days > 0 ? $reckoning->add($this->starts_on, $this->days - 1) : $this->starts_on; + } + + /** + * "18 Harvest 1042 AR to 2 Frost 1042 AR", or the one day. Null without a start. + */ + public function range(Reckoning $reckoning): ?string + { + if ($this->starts_on === null) { + return null; + } + + return $reckoning->formatRange($this->starts_on, $this->endsOn($reckoning)); + } + + /** + * "5 days", "1 day". The sentence the page and the vault both print. + */ + public static function dayCount(int $days): string + { + return $days.' '.($days === 1 ? 'day' : 'days'); + } + + public function hasNotes(): bool + { + return filled($this->notes); + } +} diff --git a/app/Models/Entity.php b/app/Models/Entity.php index d79fa0d..917aa00 100644 --- a/app/Models/Entity.php +++ b/app/Models/Entity.php @@ -363,6 +363,16 @@ public function clocks(): HasMany return $this->hasMany(Clock::class)->orderBy('position'); } + /** + * What this character did between sessions, oldest first. + * + * @return HasMany + */ + public function downtimeActivities(): HasMany + { + return $this->hasMany(DowntimeActivity::class, 'entity_id')->orderBy('created_at')->orderBy('id'); + } + public function isCharacter(): bool { return $this->type === EntityType::Character; diff --git a/app/Policies/DowntimeActivityPolicy.php b/app/Policies/DowntimeActivityPolicy.php new file mode 100644 index 0000000..e2f50c8 --- /dev/null +++ b/app/Policies/DowntimeActivityPolicy.php @@ -0,0 +1,70 @@ +roleFor($user) !== null; + } + + public function create(User $user, Entity $character): bool + { + return $this->mayWriteOn($user, $character); + } + + public function update(User $user, DowntimeActivity $activity): bool + { + return $this->mayWriteOn($user, $activity->character); + } + + public function delete(User $user, DowntimeActivity $activity): bool + { + return $this->mayWriteOn($user, $activity->character); + } + + private function mayWriteOn(User $user, Entity $character): bool + { + $role = $this->roleFor($user, $character); + + if ($role === null) { + return false; + } + + return $role->isDm() || $character->player_user_id === $user->id; + } + + /** + * The request context answers first, so a page load costs no extra query. A nested + * component without that context falls back to the database, which is what keeps + * a removed member from writing on their next request. + */ + private function roleFor(User $user, Entity $character): ?CampaignRole + { + $current = app(CurrentCampaign::class); + + if ($current->isSet() && $current->id() === $character->campaign_id && $user->is(auth()->user())) { + return $current->role(); + } + + return $character->campaign->roleFor($user); + } +} diff --git a/database/factories/DowntimeActivityFactory.php b/database/factories/DowntimeActivityFactory.php new file mode 100644 index 0000000..6429792 --- /dev/null +++ b/database/factories/DowntimeActivityFactory.php @@ -0,0 +1,55 @@ + + */ +class DowntimeActivityFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'campaign_id' => Campaign::factory(), + 'entity_id' => Entity::factory(), + 'game_session_id' => null, + 'activity' => fake()->sentence(3), + 'days' => 1, + 'notes' => null, + 'created_by' => null, + ]; + } + + public function forCharacter(Entity $character): static + { + return $this->state([ + 'campaign_id' => $character->campaign_id, + 'entity_id' => $character->id, + ]); + } + + public function around(GameSession $session): static + { + return $this->state(['game_session_id' => $session->id]); + } + + public function days(int $days): static + { + return $this->state(['days' => $days]); + } + + public function startingOn(GameDate $date): static + { + return $this->state(['starts_on' => $date]); + } +} diff --git a/database/migrations/2026_09_13_192940_create_downtime_activities_table.php b/database/migrations/2026_09_13_192940_create_downtime_activities_table.php new file mode 100644 index 0000000..d197d27 --- /dev/null +++ b/database/migrations/2026_09_13_192940_create_downtime_activities_table.php @@ -0,0 +1,42 @@ +ulid('id')->primary(); + $table->foreignUlid('campaign_id')->constrained()->cascadeOnDelete(); + $table->foreignUlid('entity_id')->constrained('entities')->cascadeOnDelete(); + $table->foreignUlid('game_session_id')->nullable()->constrained('game_sessions')->nullOnDelete(); + $table->string('activity', 120); + $table->unsignedSmallInteger('days')->default(0); + $table->text('notes')->nullable(); + $table->integer('starts_year')->nullable(); + $table->integer('starts_month')->nullable(); + $table->integer('starts_day')->nullable(); + $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamps(); + + $table->index(['entity_id', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('downtime_activities'); + } +}; diff --git a/database/seeders/DemoCampaignSeeder.php b/database/seeders/DemoCampaignSeeder.php index 6f4b670..8fe8078 100644 --- a/database/seeders/DemoCampaignSeeder.php +++ b/database/seeders/DemoCampaignSeeder.php @@ -11,6 +11,7 @@ use App\Actions\Decisions\RecordDecision; use App\Actions\Decisions\SetDecisionVisibility; use App\Actions\Dice\RollDice; +use App\Actions\Downtime\RecordDowntime; use App\Actions\Encounters\AddCombatants; use App\Actions\Encounters\ApplyDamage; use App\Actions\Encounters\CreateEncounter; @@ -206,6 +207,7 @@ public function run(): void $this->seedJournals($campaign, $dm, $player); $this->seedReputation($campaign, $dm); $this->seedLedger($campaign, $dm, $player); + $this->seedDowntime($campaign, $dm, $player); $this->seedEncounter($campaign, $dm); $this->seedTables($campaign, $dm); $this->seedGenerators($campaign, $dm); @@ -503,6 +505,42 @@ private function seedLedger(Campaign $campaign, User $dm, User $player): void $record->item($campaign, $player, 'Torch', -2, null, 'Burned in the corridor', $second); } + /** + * What the party did in the fortnight between the first two sessions: two rows + * of Wren's, written by her player, and one of Halder's, written by the GM, each + * with a day in the world so the calendar prints a range. + */ + private function seedDowntime(Campaign $campaign, User $dm, User $player): void + { + $record = app(RecordDowntime::class); + $first = $campaign->gameSessions()->where('number', 1)->first(); + $wren = $campaign->entities()->where('name', 'Wren Ashgrove')->firstOrFail(); + $halder = $campaign->entities()->where('name', 'Halder Bream')->firstOrFail(); + + $record->handle($campaign, $player, $wren, [ + 'activity' => 'Forged the harbor papers', + 'days' => 5, + 'notes' => 'A clerk at the customs house owed [[Mara Voss]] a favour. Now he owes two.', + 'session' => $first, + 'starts_on' => new GameDate(312, 2, 22), + ]); + + $record->handle($campaign, $dm, $halder, [ + 'activity' => 'Drank the Tidewardens under the table', + 'days' => 3, + 'notes' => 'Learned two names and forgot one of them.', + 'session' => $first, + 'starts_on' => new GameDate(312, 2, 25), + ]); + + $record->handle($campaign, $player, $wren, [ + 'activity' => 'Copied the tide charts', + 'days' => 7, + 'session' => $first, + 'starts_on' => new GameDate(312, 2, 28), + ]); + } + /** * Three choices the party made: two revealed, one the GM is keeping to see how it * lands, and one consequence already written in. diff --git a/docs/plans/2026-09-13-feat-downtime-plan.md b/docs/plans/2026-09-13-feat-downtime-plan.md new file mode 100644 index 0000000..374d60b --- /dev/null +++ b/docs/plans/2026-09-13-feat-downtime-plan.md @@ -0,0 +1,171 @@ +--- +title: "feat: Downtime, what each character did between sessions" +type: feat +date: 2026-09-13 +status: implemented +brainstorm: docs/brainstorms/2026-09-02-demgem-campaign-manager-brainstorm.md +follows: docs/plans/2026-09-13-feat-player-screen-plan.md +--- + +# feat: Downtime, what each character did between sessions + +## Overview + +The brainstorm's players table has one P3 row, "Downtime tracking", with no notes. What a table means by it is settled enough: between two sessions each character did something, it took some days in the world, and somebody wants it written down where the next session can find it. + +| Feature | What it adds | +|---|---| +| The downtime log | A table of what a character did, how many days it cost, the session it happened around, and where in the world's calendar it started. | +| Who writes it | A player writes their own PC's downtime. A GM writes anyone's. Everyone who may see the character reads it. | +| Three places | The character's page, the session's page, and `/downtime`, one component in each, the decision log's way. | +| The sum | Days are summed on every read, per character and for the campaign. Nothing is stored. | +| The round trip | A new top-level section in the export, the reader, the importer, and a section on the character's vault page. | + +When this slice is done a player opens Wren Ashgrove's page after session 2 and writes "Trained with the Tidewardens, 5 days, from 22 Saltrise 312", and the page says Wren has spent 5 days of downtime and the training ran to 26 Saltrise. The GM opens session 2 and reads what all four characters did before session 3. + +**On scope.** Phase 0 is the table, the model, the policy, and the actions. Phase 1 is the component and its three homes. Phase 2 is the export, the vault, the seeder, the rules, and the pass. + +## Problem Statement + +**Downtime is where a campaign's between-session play goes to be forgotten.** A player says "I spend the week forging the papers" at the end of a session, and by the next one nobody remembers whether it was a week or a fortnight, or whether it was this player or that one. The recap is the GM's and covers the session, not the gap after it. + +**Days are a cost, and a cost wants a ledger.** Slice 19 gave coin a ledger because a purse in someone's head drifts. Downtime days are the same shape: a number per event, summed. A character who has spent forty days of downtime while another spent four is a fact the GM needs when the party splits. + +**The calendar exists and nothing a player writes is on it.** Slice 12 gave the world months and a today. A session carries its days. A player's own activity has no day, so "the forgery was ready before the Duke's feast" is a sentence nobody can check. + +## Proposed Solution + +**One table, gated by the character's own gate.** `downtime_activities` is a list: many rows per character, each with a name, a day count, an optional note, an optional session, and an optional start date in the world. A row is visible to whoever may see the character, through `Entity::visibleTo()` in the query. There is no eye of its own: a character the party may see did what they did, and a GM-only character's rows are gone with the character. The session link is loaded separately through `GameSession::visibleTo()`, the clock's way. + +**A player writes their own PC's rows, and a GM writes anyone's.** That is `EntityPolicy::update()`'s rule, and the downtime policy reads the same two facts: the role, and `entities.player_user_id`. Editing and deleting follow the same rule, not the author: a GM who wrote a row on Wren's page has written it for Wren's player to correct. + +**`Downtime\Log` is one component in three places.** On a character's page it lists that character's rows and the form writes under them. On a session's page it lists the rows around that session, with a character picker. At `/downtime` it is the whole campaign, newest first, with a character picker and a session picker. The same shape as `Decisions\Log`, and for the same reason: three forks would drift. + +**Days are summed on every read.** The character's page shows the total, the index shows a total per character. The sum is `sum(days)` over the rows the viewer may see, never a column. + +**A start date is optional, and it is checked against the calendar.** With a calendar, the form offers the world's date picker, the same one the session form uses, and a row with a date prints "from 22 Saltrise 312 to 26 Saltrise 312" through `Reckoning::add()`. Without a calendar the picker is absent and a row prints its days. A date is three integer columns read as one `GameDate`, the models rule. + +## Technical Approach + +### No new dependency + +### What slices 1 to 24 give us for free + +| Piece | Reuse | +|---|---| +| `Decisions\Log` and its view | The nested component in three places, the inline edit, the session link gated separately. | +| `LedgerEntryPolicy` | The role fallback through `CurrentCampaign`. | +| `EntityPolicy::update()` | The rule for who writes a character's things. | +| `x-ui.game-date`, `Sessions\Form::gameDate()` | The date picker and its validation against the calendar. | +| `GameDateCast`, `Bounds`, `Reckoning::add()` | Storage, limits, arithmetic. | +| `ExportCampaign::SECTION_TABLES`, `RoundTripTest` | The round trip joins the comparison on its own. | +| `WriteCampaignMarkdown::entity()` | The character's page in the vault gains a section. | + +### The data + +``` +downtime_activities + id ulid + campaign_id ulid -> campaigns, cascade + entity_id ulid -> entities (the character), cascade + game_session_id ulid nullable -> game_sessions, nullOnDelete + activity string(120) + days smallint unsigned, 0..999 + notes text nullable, Markdown + starts_year, starts_month, starts_day integer nullable, as a group + created_by user id nullable, nullOnDelete + created_at, updated_at + index (entity_id, created_at) +``` + +No column on `entities`. The total is a sum, computed every time. + +### Scope and decisions + +| Question | Decision | +|---|---| +| Which characters | Any character. A player may write on a PC that is theirs. A GM may write on any character, PC or not, because an NPC's month matters to a GM too. | +| Who reads a row | Whoever may see the character. `scopeVisibleTo(user, role)` is a `whereIn` over `Entity::visibleTo()`. No eye. | +| Who edits or deletes | A GM, or the character's player. Not the author. | +| Zero days | Allowed. "Sold the signet" costs an afternoon. | +| The date | Optional. Checked against the calendar at write time, the session form's way. A row keeps its date when the GM later reshapes the calendar, and it prints "month 13" rather than failing, the reckoning rule. | +| The end date | Computed: `add(start, days - 1)` when days is above zero, else the start. Never stored. | +| No calendar | No picker, no date on the row. The days still count. | +| The card on a character's page | Shown when the character is a PC or already has rows. An NPC's page does not carry an empty card. | +| The card on a session's page | Always, under the decisions. | +| `/downtime` | Every member. The whole campaign's rows, with a total per character at the top. In the sidebar under Ledger. | +| Markdown | `notes` renders through `MarkdownRenderer`, like a decision. Not a mention source. | +| The API | None. Like a clock. | +| The vault | A "Downtime" section on the character's page, oldest first, with days, session, and date. | + +### Actions + +| Action | Does | +|---|---| +| `Downtime\RecordDowntime` | One row from validated parts. | +| `Downtime\UpdateDowntime` | The same parts, on a row. | +| `Downtime\DeleteDowntime` | Deletes the row. | + +### Screens + +- **The character's page** gains a "Downtime" card under the body: the total, the rows newest first, and for a writer the form and the controls. +- **The session's page** gains a "Downtime" card under the decisions: the rows around this session, with a character picker in the form. +- **`/downtime`** is a page header, a totals table, and the log. + +### The round trip + +- `downtime` is a new top-level section with `entity_id` and `game_session_id` remapped, the date as the triple every date in the document uses, and the reader refusing a row whose character the file does not carry. +- No version bump. + +## Verification + + php artisan test --compact tests/Feature/Downtime + php artisan test --compact --filter=RoundTrip + php artisan test --compact --filter=DemoSeeder + vendor/bin/pint --dirty --format agent + vendor/bin/phpstan analyse + +Then the full suite with `memory_limit=1G`, and a browser pass: as the player, write a row on Wren's page with a date and read the total and the range; as the GM, read it on session 2's page and on `/downtime`; as the player, open Halder's page and find no form. + +## Open Questions + +1. **Should downtime carry a cost in coin as well?** The ledger already does that, and a ledger row can name the session. Recommendation: no. Two purses is how they disagree. +2. **Should the timeline show a dated downtime row?** Recommendation: not now. The timeline lists events and sessions; a player's week is a different grain. +3. **Should a GM be able to hide a row from the party?** Recommendation: no. The character's own gate is the gate. A GM who wants a secret week writes it in GM notes. + +## References + +- `.ai/rules/decisions.md` — one component in three places, never forked. +- `.ai/rules/models.md` — a list gets a child table; a date is three columns read as one `GameDate`; the ledger is summed on every read. +- `.ai/rules/livewire.md` — nested and it writes, so it enters the campaign itself. +- `.ai/rules/campaigns.md` — a new table joins the export in the same commit. +- `.ai/rules/reckoning.md` — every number from a browser or a file goes through `Bounds`. + +## Implementation Results — 2026-09-13 + +Implemented in full. 12 new tests; the suite is 1434 tests, 1433 passing, 1 skipped, with Larastan clean and Pint clean. + +### What shipped, against the plan + +| Planned | Shipped | +|---|---| +| `downtime_activities` | As planned, with the date as three columns under `GameDateCast` and the total never stored. | +| The character's gate | `DowntimeActivity::scopeVisibleTo()` is a `whereIn` over `Entity::visibleTo()`. The snapshot test holds that a GM-only character's row never reaches a player's payload. | +| The policy | `DowntimeActivityPolicy` follows the character, not the author, with the `CurrentCampaign` fallback the ledger's policy uses. | +| `Downtime\Log` in three places | The character's page, the session's page, and `/downtime`. The character picker's list is also its validation rule. | +| The date | The session form's check, copied into the component. The end date is computed through `Reckoning::add()` and the row prints the range. | +| The round trip and the vault | `downtime` is a new top-level section with both links remapped; the character's vault page gains a "Downtime" section. | +| The demo world | Three rows in the fortnight between sessions 1 and 2, two of Wren's and one of Halder's, each with a day in the world. | + +### Deviations + +None from the plan's decisions. The `/downtime` page's totals are two queries rather than one join, so the names go through `Entity`'s own scope and not a raw select. + +### Browser checks + +Driven end to end on the seeded world at 1024px as the player and 1400px as the GM: + +- Wren's page shows the player the "Downtime" card with the form, the calendar's date picker, and "0 days of downtime" before the first row. +- The player writes "Forged the harbor papers", 5 days, from 22 Saltrise 312, around session 1. The page reads "5 days of downtime, over 1 entry" and the row prints "22 Saltrise 312 AF to 26 Saltrise 312 AF". +- Halder's page shows the same player no form and "No downtime recorded yet". +- Session 1's page shows the GM the row under the decisions, with a character picker in the form, and `/downtime` shows "Days spent" with Wren at 5 days above the log. diff --git a/resources/views/livewire/downtime/index.blade.php b/resources/views/livewire/downtime/index.blade.php new file mode 100644 index 0000000..88de8c7 --- /dev/null +++ b/resources/views/livewire/downtime/index.blade.php @@ -0,0 +1,28 @@ +
+ + Sessions + + +
+ @if ($totals->isNotEmpty()) + + + + @endif + + +
+
diff --git a/resources/views/livewire/downtime/log.blade.php b/resources/views/livewire/downtime/log.blade.php new file mode 100644 index 0000000..7fdef36 --- /dev/null +++ b/resources/views/livewire/downtime/log.blade.php @@ -0,0 +1,131 @@ +{{-- + The downtime log, drawn for whoever is looking. The rows are the ones the query + loaded under this viewer's own role; the form appears when the policy says this + member may write on the character in question. Nothing in here decides either. +--}} +
+ @if ($total !== null) +

+ {{ \App\Models\DowntimeActivity::dayCount($total) }} + of downtime{{ $activities->isEmpty() ? '.' : ', over '.$activities->count().' '.Str::plural('entry', $activities->count()).'.' }} +

+ @endif + + @if ($canWrite) +
+ @unless ($scopedToCharacter) + + + @foreach ($characterOptions as $option) + + @endforeach + + @endunless +
+ + +
+ @if ($hasCalendar) + + @endif + + @unless ($scopedToSession) + + + @foreach ($sessionOptions as $option) + + @endforeach + + @endunless +
+ Record it +
+ + @endif + + @if ($activities->isEmpty() && ($scopedToCharacter || $scopedToSession)) +

{{ $scopedToSession ? 'Nothing recorded around this session.' : 'No downtime recorded yet.' }}

+ @elseif ($activities->isEmpty()) + + @else +
    + @foreach ($activities as $activity) +
  1. + @if ($editingId === $activity->id) +
    +
    + + +
    + @if ($hasCalendar) + + @endif + + @unless ($scopedToSession) + + + @foreach ($sessionOptions as $option) + + @endforeach + + @endunless +
    + Save + Cancel +
    + + @else +
    +

    {{ $activity->activity }}

    + {{ \App\Models\DowntimeActivity::dayCount($activity->days) }} +
    + + @if ($ranges[$activity->id]) +

    {{ $ranges[$activity->id] }}

    + @endif + + @if ($html[$activity->id] !== '') +
    {!! $html[$activity->id] !!}
    + @endif + +
    + @unless ($scopedToCharacter) + + + {{ $activity->character->name }} + + @endunless + {{-- Absent when this viewer may not see the session, which is the + whole gate: the query never loaded it. --}} + @php($link = $activity->game_session_id ? ($sessionLinks[$activity->game_session_id] ?? null) : null) + @if ($link && ! $scopedToSession) + + + {{ $link->label() }}{{ $link->title ? ' · '.$link->title : '' }} + + @endif + {{ $activity->created_at?->diffForHumans() }} + + @if (in_array($activity->id, $editable, true)) +
    + + + + + + +
    + @endif +
    + @endif +
  2. + @endforeach +
+ @endif +
diff --git a/resources/views/livewire/entities/show.blade.php b/resources/views/livewire/entities/show.blade.php index a307a93..5c7dc82 100644 --- a/resources/views/livewire/entities/show.blade.php +++ b/resources/views/livewire/entities/show.blade.php @@ -228,6 +228,14 @@ class="ml-auto" @endif + {{-- What the character did between sessions. A PC always carries the card, + so its player has the form; an NPC carries it once it has a row. --}} + @if ($showDowntime) + + + + @endif + @if ($role->isDm()) diff --git a/resources/views/livewire/sessions/show.blade.php b/resources/views/livewire/sessions/show.blade.php index cead91e..ebc249c 100644 --- a/resources/views/livewire/sessions/show.blade.php +++ b/resources/views/livewire/sessions/show.blade.php @@ -105,6 +105,12 @@ + {{-- What each character did around this session. The same component as + /downtime, scoped to this session. --}} + + + + {{-- A poll is names against dates and needs the width; an RSVP list does not. --}} @if ($session->isPolling()) diff --git a/resources/views/partials/sidebar.blade.php b/resources/views/partials/sidebar.blade.php index 46652e9..a5cd143 100644 --- a/resources/views/partials/sidebar.blade.php +++ b/resources/views/partials/sidebar.blade.php @@ -80,6 +80,11 @@ :active="request()->routeIs('ledger.*')" icon="box" >Ledger + Downtime @if ($currentRole?->isDm()) name('ledger.index'); + // What each character did between sessions. Every member; what a player + // reads and writes is the log's own query and policy. + Route::get('/downtime', DowntimeIndex::class)->name('downtime.index'); + // The shipped reference data. Addressed by slug, unlike an entity: a stat // block is not a GM's to rename, so the slug is stable in a way an entity's // never is. {statBlockSlug} rather than {statBlock} keeps route binding off diff --git a/tests/Feature/Campaigns/DemoSeederTest.php b/tests/Feature/Campaigns/DemoSeederTest.php index 900d468..732b801 100644 --- a/tests/Feature/Campaigns/DemoSeederTest.php +++ b/tests/Feature/Campaigns/DemoSeederTest.php @@ -3,6 +3,7 @@ use App\Enums\CampaignRole; use App\Models\Campaign; use App\Models\Decision; +use App\Models\DowntimeActivity; use App\Models\Encounter; use App\Models\Entity; use App\Models\EntityTemplate; @@ -33,6 +34,7 @@ ->and($campaign->roleFor($dm))->toBe(CampaignRole::Owner) ->and($campaign->roleFor($player))->toBe(CampaignRole::Player) ->and($campaign->screen()->entity?->name)->toBe("The duke's letter") + ->and((int) DowntimeActivity::query()->sum('days'))->toBe(15) ->and(Entity::query()->count())->toBeGreaterThan(10) ->and(EntityTemplate::query()->count())->toBe(2) ->and(GameSession::query()->count())->toBe(4) @@ -112,6 +114,7 @@ route('entities.show', [$campaign, 'arcs', 'the-duke-beneath']), route('decisions.index', $campaign), route('ledger.index', $campaign), + route('downtime.index', $campaign), route('entities.index', [$campaign, 'journals']), route('entities.show', [$campaign, 'journals', 'after-the-fire']), route('entities.index', [$campaign, 'factions']), diff --git a/tests/Feature/Downtime/DowntimeTest.php b/tests/Feature/Downtime/DowntimeTest.php new file mode 100644 index 0000000..9bc33c6 --- /dev/null +++ b/tests/Feature/Downtime/DowntimeTest.php @@ -0,0 +1,338 @@ +create(); + $tobin = memberOf($campaign, CampaignRole::Player); + $mira = memberOf($campaign, CampaignRole::Player); + + $wren = Entity::factory()->for($campaign)->pcOf($tobin)->forPlayers()->create(['name' => 'Wren Ashgrove', 'slug' => 'wren-ashgrove']); + $halder = Entity::factory()->for($campaign)->pcOf($mira)->forPlayers()->create(['name' => 'Halder Bream', 'slug' => 'halder-bream']); + $abbess = Entity::factory()->for($campaign)->dmOnly()->create(['name' => 'Abbess Corvane', 'slug' => 'abbess-corvane']); + + $open = GameSession::factory()->for($campaign)->number(1)->played()->create(['title' => 'The Harbor Fire']); + $draft = GameSession::factory()->for($campaign)->number(2)->hidden()->create(['title' => 'The Secret Night']); + + $forge = DowntimeActivity::factory()->forCharacter($wren)->around($open)->days(5)->create(['activity' => 'Forged the harbor papers']); + $carouse = DowntimeActivity::factory()->forCharacter($halder)->around($draft)->days(3)->create(['activity' => 'Drank the Tidewardens under the table']); + $plot = DowntimeActivity::factory()->forCharacter($abbess)->days(12)->create(['activity' => 'Wrote to the Duke']); + + return compact('campaign', 'tobin', 'mira', 'wren', 'halder', 'abbess', 'open', 'draft', 'forge', 'carouse', 'plot'); +} + +it('shows a player the rows of the characters they may see, with a session link only when they may see the session', function () { + ['campaign' => $campaign, 'tobin' => $tobin] = aPartyWithDowntime(); + + $component = Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign]) + ->assertSee('Forged the harbor papers') + ->assertSee('The Harbor Fire') + ->assertSee('Drank the Tidewardens under the table') + ->assertDontSee('The Secret Night') + ->assertDontSee('Wrote to the Duke'); + + expect(json_encode($component->snapshot))->not->toContain('Wrote to the Duke') + ->not->toContain('The Secret Night'); +}); + +it('sums the days on every read, per character and for the campaign', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren] = aPartyWithDowntime(); + + DowntimeActivity::factory()->forCharacter($wren)->days(2)->create(['activity' => 'Rested']); + + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign, 'character' => $wren]) + ->assertSee('7 days') + ->assertDontSee('Drank the Tidewardens'); + + // The abbess's twelve days are not in a player's total, because her rows never + // reached the query. + Livewire::actingAs($tobin) + ->test(Index::class, ['campaign' => $campaign]) + ->assertSee('Wren Ashgrove') + ->assertSee('Halder Bream') + ->assertDontSee('Abbess Corvane') + ->assertSeeInOrder(['Wren Ashgrove', '7 days']) + ->assertSeeInOrder(['Halder Bream', '3 days']); + + Livewire::actingAs(ownerOf($campaign)) + ->test(Index::class, ['campaign' => $campaign]) + ->assertSeeInOrder(['Abbess Corvane', '12 days']); +}); + +it('lets a player record, edit, and delete downtime on their own character', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren, 'open' => $open] = aPartyWithDowntime(); + + $component = Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign, 'character' => $wren]) + ->set('newActivity', 'Trained with the Tidewardens') + ->set('newDays', '4') + ->set('newNotes', 'Mara Voss took the coin and taught the [[Tidewardens]] salute.') + ->set('newSessionId', $open->id) + ->call('record') + ->assertHasNoErrors() + ->assertSee('Trained with the Tidewardens') + ->assertSee('9 days'); + + $row = DowntimeActivity::query()->where('activity', 'Trained with the Tidewardens')->firstOrFail(); + + expect($row->entity_id)->toBe($wren->id) + ->and($row->days)->toBe(4) + ->and($row->game_session_id)->toBe($open->id) + ->and($row->created_by)->toBe($tobin->id); + + $component->call('edit', $row->id) + ->set('editingDays', '6') + ->set('editingActivity', 'Trained with the Tidewardens, twice') + ->call('save') + ->assertHasNoErrors() + ->assertSee('11 days'); + + expect($row->fresh()->days)->toBe(6) + ->and($row->fresh()->activity)->toBe('Trained with the Tidewardens, twice'); + + $component->call('delete', $row->id)->assertSee('5 days'); + + expect(DowntimeActivity::query()->whereKey($row->id)->exists())->toBeFalse(); +}); + +it('keeps a player off another character, and lets a GM write on anyone', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'halder' => $halder, 'abbess' => $abbess, 'carouse' => $carouse] = aPartyWithDowntime(); + + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign, 'character' => $halder]) + ->assertDontSee('Record it') + ->set('newActivity', 'Stole the boat') + ->set('newDays', '1') + ->call('record') + ->assertForbidden(); + + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign]) + ->call('delete', $carouse->id) + ->assertForbidden(); + + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign]) + ->call('edit', $carouse->id) + ->assertForbidden(); + + // The abbess is GM-only, so from a player's seat she is a 404 rather than a 403. + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign]) + ->set('newCharacterId', $abbess->id) + ->set('newActivity', 'Stole the boat') + ->set('newDays', '1') + ->call('record') + ->assertHasErrors('newCharacterId'); + + Livewire::actingAs(ownerOf($campaign)) + ->test(Log::class, ['campaign' => $campaign, 'character' => $halder]) + ->set('newActivity', 'Carried the tide charts to the abbey') + ->set('newDays', '2') + ->call('record') + ->assertHasNoErrors(); + + expect(DowntimeActivity::query()->where('entity_id', $halder->id)->count())->toBe(2) + ->and(DowntimeActivity::query()->where('activity', 'Stole the boat')->exists())->toBeFalse(); +}); + +it('offers a player only their own characters in the picker, and a GM every one', function () { + ['campaign' => $campaign, 'tobin' => $tobin] = aPartyWithDowntime(); + + expect(Livewire::actingAs($tobin)->test(Log::class, ['campaign' => $campaign])->viewData('characterOptions')->pluck('name')->all()) + ->toBe(['Wren Ashgrove']) + ->and(Livewire::actingAs(ownerOf($campaign))->test(Log::class, ['campaign' => $campaign])->viewData('characterOptions')->pluck('name')->all()) + ->toBe(['Abbess Corvane', 'Halder Bream', 'Wren Ashgrove']); +}); + +it('refuses an empty activity and a day count outside the bounds', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren] = aPartyWithDowntime(); + + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign, 'character' => $wren]) + ->set('newActivity', '') + ->set('newDays', '1000') + ->call('record') + ->assertHasErrors(['newActivity', 'newDays']); + + expect(DowntimeActivity::query()->where('entity_id', $wren->id)->count())->toBe(1); +}); + +it('takes a start date checked against the calendar, and prints the range it covers', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren] = aPartyWithDowntime(); + + // Harvest has 20 days in the factory's calendar. + Calendar::factory()->inCampaign($campaign)->create(); + + $component = Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign, 'character' => $wren]) + ->set('newActivity', 'Walked to the abbey') + ->set('newDays', '5') + ->set('newStartsOn', ['year' => '1042', 'month' => '2', 'day' => '18']) + ->call('record') + ->assertHasNoErrors() + ->assertSee('18 Harvest 1042 AR to 2 Frost 1042 AR'); + + $row = DowntimeActivity::query()->where('activity', 'Walked to the abbey')->firstOrFail(); + + expect($row->starts_on)->toEqual(new GameDate(1042, 2, 18)); + + $component + ->set('newActivity', 'Fell off the calendar') + ->set('newDays', '1') + ->set('newStartsOn', ['year' => '1042', 'month' => '2', 'day' => '25']) + ->call('record') + ->assertHasErrors('newStartsOn.day'); + + // A single day, or none, prints the one date. + $component + ->set('newActivity', 'Slept') + ->set('newDays', '0') + ->set('newStartsOn', ['year' => '1042', 'month' => '1', 'day' => '3']) + ->call('record') + ->assertHasNoErrors() + ->assertSee('3 Thaw 1042 AR') + ->assertDontSee('3 Thaw 1042 AR to'); +}); + +it('offers no date without a calendar, and prints days alone', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren] = aPartyWithDowntime(); + + Livewire::actingAs($tobin) + ->test(Log::class, ['campaign' => $campaign, 'character' => $wren]) + ->assertDontSee('Starting on') + ->assertSee('5 days'); +}); + +it('sits on the character page for a PC, on the session page, and in the sidebar', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren, 'abbess' => $abbess, 'open' => $open] = aPartyWithDowntime(); + $gm = ownerOf($campaign); + + Livewire::actingAs($tobin) + ->test(EntityShow::class, ['campaign' => $campaign, 'type' => 'characters', 'slug' => $wren->slug]) + ->assertSee('Downtime') + ->assertSee('Forged the harbor papers') + ->assertSeeLivewire(Log::class); + + // An NPC with rows carries the card for the GM; an NPC with none does not. + Livewire::actingAs($gm) + ->test(EntityShow::class, ['campaign' => $campaign, 'type' => 'characters', 'slug' => $abbess->slug]) + ->assertSee('Wrote to the Duke'); + + $quiet = Entity::factory()->for($campaign)->forPlayers()->create(['name' => 'Mara Voss', 'slug' => 'mara-voss']); + + Livewire::actingAs($gm) + ->test(EntityShow::class, ['campaign' => $campaign, 'type' => 'characters', 'slug' => $quiet->slug]) + ->assertDontSeeLivewire(Log::class); + + Livewire::actingAs($tobin) + ->test(SessionShow::class, ['campaign' => $campaign, 'number' => $open->number]) + ->assertSee('Forged the harbor papers') + ->assertDontSee('Drank the Tidewardens'); + + $this->actingAs($tobin)->get(route('downtime.index', $campaign)) + ->assertOk() + ->assertSee('Forged the harbor papers'); + + $this->actingAs($tobin)->get(route('campaigns.show', $campaign)) + ->assertSee(route('downtime.index', $campaign), false); + + $this->actingAs(User::factory()->create())->get(route('downtime.index', $campaign))->assertNotFound(); +}); + +it('travels in the export, comes back remapped, and lands in the vault', function () { + ['campaign' => $campaign, 'wren' => $wren, 'open' => $open] = aPartyWithDowntime(); + + Calendar::factory()->inCampaign($campaign)->create(); + + app(RecordDowntime::class)->handle($campaign, ownerOf($campaign), $wren, [ + 'activity' => 'Walked to the abbey', + 'days' => 5, + 'notes' => 'Along the sea wall.', + 'session' => $open, + 'starts_on' => new GameDate(1042, 2, 18), + ]); + + $document = exportedArray($campaign); + + expect($document['downtime'])->toHaveCount(4); + + $walk = collect($document['downtime'])->firstWhere('activity', 'Walked to the abbey'); + + expect($walk['entity_id'])->toBe($wren->id) + ->and($walk['game_session_id'])->toBe($open->id) + ->and($walk['days'])->toBe(5) + ->and($walk['starts_on'])->toBe(['year' => 1042, 'month' => 2, 'day' => 18]); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeTrue(); + + $copy = app(ImportCampaign::class)->handle($read->document, User::factory()->create()); + + $newWren = Entity::withoutGlobalScopes()->where('campaign_id', $copy->id)->where('slug', 'wren-ashgrove')->firstOrFail(); + $newOpen = GameSession::withoutGlobalScopes()->where('campaign_id', $copy->id)->where('number', 1)->firstOrFail(); + $copied = DowntimeActivity::withoutGlobalScopes()->where('campaign_id', $copy->id)->where('activity', 'Walked to the abbey')->firstOrFail(); + + expect(DowntimeActivity::withoutGlobalScopes()->where('campaign_id', $copy->id)->count())->toBe(4) + ->and($copied->entity_id)->toBe($newWren->id) + ->and($copied->game_session_id)->toBe($newOpen->id) + ->and($copied->days)->toBe(5) + ->and($copied->notes)->toBe('Along the sea wall.') + ->and($copied->starts_on)->toEqual(new GameDate(1042, 2, 18)); + + $vault = app(WriteCampaignMarkdown::class)->handle($campaign)['markdown/characters/wren-ashgrove.md']; + + expect($vault)->toContain('## Downtime') + ->toContain('- Forged the harbor papers, 5 days *(Session 1)*') + ->toContain('- Walked to the abbey, 5 days, 18 Harvest 1042 AR to 2 Frost 1042 AR *(Session 1)*') + ->toContain(' Along the sea wall.'); +}); + +it('refuses a file whose downtime points at a character it does not carry', function () { + ['campaign' => $campaign] = aPartyWithDowntime(); + + $document = exportedArray($campaign); + $document['downtime'][0]['entity_id'] = '01JNOTINTHISFILE0000000000'; + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeFalse() + ->and(implode(' ', $read->errors))->toContain('downtime'); +}); + +it('reads an older file with no downtime section', function () { + ['campaign' => $campaign] = aPartyWithDowntime(); + + $document = exportedArray($campaign); + unset($document['downtime']); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeTrue() + ->and($read->document['downtime'])->toBe([]); +});