Skip to content

refactor: adopt EventGeneratorTrait and decouple ticket timeline audit logging - #68

Merged
karl-bullock merged 12 commits into
linkrobins:mainfrom
huoxin233:refactor/decouple-timeline-audit
Nov 18, 2026
Merged

karl-bullock merged 12 commits into
linkrobins:mainfrom
huoxin233:refactor/decouple-timeline-audit

Conversation

@huoxin233

@huoxin233 huoxin233 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adopts Flarum's native EventGeneratorTrait on SupportTicket, introduces canonical domain methods (changeStatus, assignTo, changeDecision), and decouples timeline audit logging (linkrobins_support_events) into dedicated, isolated domain event listeners.

Background & Motivation

Previously, recording timeline entries for status, assignment, and decision changes was coupled to Eloquent's updated model hook in SupportServiceProvider. This created several architectural issues:

  1. Lost request context: The model hook had no caller context, requiring temporary dynamic properties on the model ($ticket->eventActor, $ticket->eventActorId, $ticket->eventAutomatic, $ticket->savingOpeningMessage).
  2. Opening reply blindspot: The $ticket->savingOpeningMessage guard suppressed timeline events when a staff member filed a ticket that auto-claimed and moved to in_progress.
  3. Assignee ID loss: Looking up former assignees via User::query()->find($id) turned deleted accounts into null ("unassigned") in timeline history.
  4. Dual modification paths: Direct property mutation in SupportTicketResource existed alongside domain methods without a single source of truth.

This PR aligns the model lifecycle with Flarum 2.x's native domain event architecture (matching Discussion, Post, and User).


Changes

1. Model Domain Methods & EventGeneratorTrait

  • SupportTicket: Adopted EventGeneratorTrait. Added changeStatus(), assignTo(), and changeDecision() as the canonical way to mutate ticket state and raise domain events (TicketStatusChanged, TicketAssigned, TicketDecided).
  • Eliminated Dynamic Properties: Removed all synthetic model properties ($eventActor, $eventActorId, $eventAutomatic, $savingOpeningMessage).
  • Resource Integration: SupportTicketResource schema setters now delegate directly to domain methods; events are drained and dispatched automatically via Flarum's AbstractDatabaseResource::dispatchEventsFor().
  • Console & Reply Hooks: Updated SupportReply::created and CloseResolvedTicketsCommand to use domain methods and release events after commit.
  • Eliminated SupportTicket::updated: The model updated hook and manual diffing logic (lifecycleEvents()) in SupportServiceProvider have been removed completely.

2. Dedicated Invokable Event Listeners

  • Created RecordStatusChangeTimeline listening to TicketStatusChanged.
  • Created RecordAssignmentTimeline listening to TicketAssigned.
  • Registered both listeners in extend.php with error logging so timeline logging issues never disrupt the main request or database transactions.

3. Preserved Raw Assignee IDs (Deleted Accounts)

  • TicketAssigned: Added $assigneeId and $oldAssigneeId integer IDs alongside optional User models.
  • SupportEvent::recordAssignment(): Stores raw integer IDs directly in from_user_id / to_user_id, ensuring deleted users correctly display as deleted accounts rather than reading as "unassigned".
  • SupportEvent: Added explicit recordStatusChange(...) and recordAssignment(...) factory methods and removed the obsolete recordChanges() method.

4. Isolated Event Dispatching & Driver Protection

  • SupportServiceProvider::dispatchIsolated(): Dispatches events to individual listeners inside isolated try/catch blocks, preventing a failing listener from aborting other listeners or afterCommit callbacks.
  • Driver Isolation: Wrapped ticket type driver hooks (onStatusChanged, onDecided) in extend.php with try/catch to ensure driver errors cannot fail HTTP requests.

5. Test Suite

  • Added a_staff_filed_ticket_records_opening_message_claim_and_status_advance in TicketHistoryTest to assert staff-filed ticket auto-claims and status advances are recorded in the timeline.
  • Updated TicketDomainEventsTest to verify domain event dispatches and assertions across all ticket lifecycle routes.

huoxin233 and others added 2 commits November 7, 2026 23:05
…eners

- Add isAutomatic attribute to TicketStatusChanged event

- Create RecordStatusChangeTimeline and RecordAssignmentTimeline invokable listeners

- Add recordStatusChange and recordAssignment domain factory methods to SupportEvent

- Add changeStatus and assignTo domain helpers returning static to SupportTicket

- Remove model updated hook and obsolete SupportEvent::recordChanges method

- Update CloseResolvedTicketsCommand to use changeStatus domain helper

Co-authored-by: Claude <noreply@anthropic.com>

@karl-bullock karl-bullock left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Moving the timeline write after commit is a nice improvement. A few things before this can go in:

Must fix

  1. Changes made while saving the opening message are no longer recorded. The new listeners hang off lifecycleEvents(), which returns [] when $ticket->savingOpeningMessage is set (src/SupportServiceProvider.php, around line 211 on this branch). The old recordChanges() had no such guard. So when a staff member files a ticket and their opening message auto-claims it and moves it open → in_progress, both events used to appear in the timeline and now neither does.
    • The first commit (433bbd3) failed a_reply_that_moves_the_status_is_recorded_as_its_author and a_staff_reply_to_an_open_ticket_moves_it_automatically on every DB; the follow-up "test: seed opening reply fixture" changed the fixture rather than the code. Please revert that fixture change and fix the path instead (the timeline shouldn't be skipped by the savingOpeningMessage guard).
    • Please add a test for a staff-filed ticket whose opening message claims it / changes status.

Small fixes
2. Assignment rows now resolve user ids via User::query()->find($id); if a former assignee's account was deleted, from_user_id / to_user_id become null and the timeline reads "unassigned". Please keep the raw ids as before.
3. The dispatch inside the after-commit callback isn't isolated: if another listener on the same event throws first, the timeline listener never runs (and the exception surfaces after the data is committed). Please make sure the timeline entry is still written in that case.
4. assignTo() isn't called anywhere, and SupportTicketResource still sets eventActor directly, so there would be two ways to do the same thing. Please drop assignTo() (and keep the helpers only where they're actually used).

Also heads-up: this has a small conflict with #69 in SupportServiceProvider.php (#69 still calls recordChanges). I plan to merge #68 first and then have #69 rebased.

Thanks again!

…ecycle events

- Adopt Flarum EventGeneratorTrait in SupportTicket and raise domain events from changeStatus, assignTo, and changeDecision
- Call domain methods in SupportTicketResource schema setters, SupportReply::created, and CloseResolvedTicketsCommand
- Eliminate legacy SupportTicket::updated hook, lifecycleEvents, and synthetic model properties
- Retain raw assignee IDs in TicketAssigned event and SupportEvent::recordAssignment
- Register ticket type lifecycle hooks in extend.php alongside timeline listeners
- Isolate event listener dispatches inside afterCommit callbacks

Co-authored-by: Claude <noreply@anthropic.com>
huoxin233 and others added 3 commits November 8, 2026 22:31
- Revert seeded opening reply fixture hack in TicketHistoryTest
- Add test covering staff-filed ticket whose opening message claims it and advances status
- Add test covering reassigning from deleted user preserving raw from_user_id
- Update TicketDomainEventsTest to assert status and assignment events on staff opening message

Co-authored-by: Claude <noreply@anthropic.com>
…hook error isolation

- Pass event payload array to listeners in dispatchIsolated matching Laravel dispatcher invocation
- Resolve oldAssignee user model by old ID when relation is not preloaded in assignTo
- Catch and log exceptions in ticket type onStatusChanged and onDecided listeners in extend.php
- Remove invalid FK test in TicketHistoryTest

Co-authored-by: Claude <noreply@anthropic.com>
@huoxin233

huoxin233 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks! Moving the timeline write after commit is a nice improvement. A few things before this can go in:

All the points are addressed. The test fixture change has been reverted, the staff-filed ticket test has been added, raw assignee IDs are now preserved so deleted users don't become unassigned, and listeners in afterCommit are individually isolated with try/catch.

I looked into dropping assignTo() for point 4, but realised that the original approach of setting $eventActor for Eloquent's updated hook was the root limitation causing the opening message bugs and lost context. Instead of trying to keep $eventActor, I adopted EventGeneratorTrait on SupportTicket. I made assignTo(), changeStatus(), and changeDecision() the single canonical way to update tickets across the extension (including in SupportTicketResource). This matches Flarum core models like Discussion, raises domain events with full context directly, and removes all dynamic properties and model hook diffing entirely.

Also updated PR title and description to reflect changes.

@huoxin233 huoxin233 changed the title refactor: decouple ticket timeline audit logging to domain event listeners refactor: adopt EventGeneratorTrait and decouple ticket timeline audit logging Nov 8, 2026

@karl-bullock karl-bullock left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The timeline fix works: a staff-filed ticket now records both the status move and the claim, and the new tests are good. Two things before this can go in:

  1. TicketChanged no longer fires for staff edits. Removing the updated hook means it is only dispatched on a reply and on create now. A PATCH to priority, status or assignee, and lr-support:close-resolved, no longer dispatch it, and extend.php uses it for the flarum/realtime push, so live ticket updates stop. Please dispatch it again after those saves (the resource's updated hook and the close command).
  2. A failing listener still returns a 500 after the save on the API path. dispatchIsolated covers replies and creation, but status/assignee/decision changes through SupportTicketResource go through core's dispatchEventsFor, so if another extension's TicketStatusChanged listener throws, the PATCH answers 500 after the change is saved. Could those go through the isolated dispatch too?

Two smaller notes:

  1. Fine to keep assignTo() now that it's the one path, thanks for explaining.
  2. For a staff-filed ticket, keep dispatching TicketAssigned (the assignee should hear about it), but please don't dispatch TicketStatusChanged on creation. The starting status isn't a change, and listeners would record a pointless "status changed" right after "created".

huoxin233 and others added 6 commits November 16, 2026 01:30
- Raise TicketChanged in SupportTicketResource::updated() when ticket attributes change
- Dispatch TicketChanged after auto-closing tickets in CloseResolvedTicketsCommand
- Cover priority PATCH and auto-close TicketChanged events in integration tests

Co-authored-by: Claude <noreply@anthropic.com>
- Add SupportServiceProvider::dispatchAfterCommit() helper wrapping afterCommit and dispatchIsolated
- Override SupportTicketResource::dispatchEventsFor() to route API domain events through isolated dispatch
- Route CloseResolvedTicketsCommand event dispatches through isolated dispatch so a failing listener never aborts auto-close
- Add integration tests verifying a throwing TicketStatusChanged listener does not fail API PATCH or auto-close or block subsequent listeners

Co-authored-by: Claude <noreply@anthropic.com>
- Set the initial in_progress status directly on opening staff replies instead of calling changeStatus()
- Preserve TicketAssigned auto-claim event and timeline entry while suppressing the redundant initial status transition
- Update integration tests in TicketHistoryTest and TicketDomainEventsTest to match

Co-authored-by: Claude <noreply@anthropic.com>
- Move TicketStatusChanged and TicketDecided closure handlers out of extend.php into NotifyTicketTypeStatusChange and NotifyTicketTypeDecision
- Inject LoggerInterface via constructor instead of calling resolve() inside extend.php
- Guard NotifyTicketTypeDecision against null newDecision to match TicketTypeInterface::onDecided()

Co-authored-by: Claude <noreply@anthropic.com>
- Require $reply->user_id === $ticket->user_id alongside $isOpening when skipping TicketStatusChanged on initial in_progress status
- Ensure staff replies to open tickets without seeded prior reply rows still trigger changeStatus() and timeline audit events

Co-authored-by: Claude <noreply@anthropic.com>
- Cover owner confirm-solved and reopen TicketStatusChanged and TicketChanged attribution
- Cover distinct actor, oldAssignee, and assignee fields on staff reassignment
- Cover internal note auto-claim without status change, resolved-ticket reply reopen, and TicketCreated listener isolation
- Cover null decision clearing and throwing onDecided hook isolation in TicketTypeDriverTest

Co-authored-by: Claude <noreply@anthropic.com>
@karl-bullock
karl-bullock merged commit 36f897b into linkrobins:main Nov 18, 2026
17 checks passed
@huoxin233
huoxin233 deleted the refactor/decouple-timeline-audit branch November 18, 2026 09:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants