From 433bbd308ba98530e4f06764d600a3c54801a1a7 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:05:11 +0800 Subject: [PATCH 01/12] refactor: decouple ticket timeline audit logging to domain event listeners - 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 --- extend.php | 6 +- src/Api/Resource/SupportEventResource.php | 2 +- src/Api/Resource/SupportTicketResource.php | 2 +- src/Console/CloseResolvedTicketsCommand.php | 5 +- src/Event/TicketStatusChanged.php | 1 + src/Listener/RecordAssignmentTimeline.php | 32 +++++++++ src/Listener/RecordStatusChangeTimeline.php | 33 +++++++++ src/SupportEvent.php | 75 ++++++++++----------- src/SupportServiceProvider.php | 20 ++---- src/SupportTicket.php | 25 +++++++ 10 files changed, 143 insertions(+), 58 deletions(-) create mode 100644 src/Listener/RecordAssignmentTimeline.php create mode 100644 src/Listener/RecordStatusChangeTimeline.php diff --git a/extend.php b/extend.php index caa6d44..b5b50cc 100644 --- a/extend.php +++ b/extend.php @@ -22,6 +22,8 @@ use LinkRobins\Support\Search\ReplySearcher; use LinkRobins\Support\Search\TicketSearcher; use LinkRobins\Support\Extend as SupportExtend; +use LinkRobins\Support\Listener\RecordAssignmentTimeline; +use LinkRobins\Support\Listener\RecordStatusChangeTimeline; use LinkRobins\Support\SupportCategory; use LinkRobins\Support\SupportEvent; use LinkRobins\Support\SupportReply; @@ -264,7 +266,9 @@ ], true)) { $event->value = $event->value === '' || $event->value === '0' ? '0' : '1'; } - }), + }) + ->listen(\LinkRobins\Support\Event\TicketStatusChanged::class, RecordStatusChangeTimeline::class) + ->listen(\LinkRobins\Support\Event\TicketAssigned::class, RecordAssignmentTimeline::class), (new Extend\Settings()) ->default('linkrobins-support.nav_in_sidebar', '1') diff --git a/src/Api/Resource/SupportEventResource.php b/src/Api/Resource/SupportEventResource.php index 6db8e49..6d83a70 100644 --- a/src/Api/Resource/SupportEventResource.php +++ b/src/Api/Resource/SupportEventResource.php @@ -13,7 +13,7 @@ /** * Read-only ticket history: status and assignment changes, shown inline in - * the ticket timeline. Rows are written by SupportEvent::recordChanges, never + * the ticket timeline. Rows are written by domain event listeners, never * through the API. */ class SupportEventResource extends AbstractDatabaseResource diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index b9290d3..02ed057 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -660,7 +660,7 @@ public function updating(object $model, Context $context): ?object } // Credit status and assignment changes in the ticket timeline to the - // person making this request (see SupportEvent::recordChanges). + // person making this request (passed to lifecycle domain events). $model->eventActor = $actor->isGuest() ? null : $actor; $model->eventActorId = $actor->isGuest() ? null : (int) $actor->id; diff --git a/src/Console/CloseResolvedTicketsCommand.php b/src/Console/CloseResolvedTicketsCommand.php index c573b56..2f31250 100644 --- a/src/Console/CloseResolvedTicketsCommand.php +++ b/src/Console/CloseResolvedTicketsCommand.php @@ -67,10 +67,7 @@ public function handle(SettingsRepositoryInterface $settings): int if ($ticket->fresh()?->status !== SupportTicket::STATUS_RESOLVED) { continue; } - $ticket->status = SupportTicket::STATUS_CLOSED; - $ticket->eventActorId = null; - $ticket->eventAutomatic = true; - $ticket->save(); + $ticket->changeStatus(SupportTicket::STATUS_CLOSED, actor: null, isAutomatic: true)->save(); $closed++; } }); diff --git a/src/Event/TicketStatusChanged.php b/src/Event/TicketStatusChanged.php index c7e02d3..f640c08 100644 --- a/src/Event/TicketStatusChanged.php +++ b/src/Event/TicketStatusChanged.php @@ -17,6 +17,7 @@ public function __construct( public readonly ?User $actor, public readonly ?string $oldStatus, public readonly string $newStatus, + public readonly bool $isAutomatic = false, ) { } } diff --git a/src/Listener/RecordAssignmentTimeline.php b/src/Listener/RecordAssignmentTimeline.php new file mode 100644 index 0000000..c0456cd --- /dev/null +++ b/src/Listener/RecordAssignmentTimeline.php @@ -0,0 +1,32 @@ +ticket, + actor: $event->actor, + fromUser: $event->oldAssignee, + toUser: $event->assignee, + ); + } catch (\Throwable $e) { + $this->log->warning('[linkrobins/support] could not record assignment timeline event', [ + 'ticket_id' => $event->ticket->id, + 'exception' => $e, + ]); + } + } +} diff --git a/src/Listener/RecordStatusChangeTimeline.php b/src/Listener/RecordStatusChangeTimeline.php new file mode 100644 index 0000000..ad746ac --- /dev/null +++ b/src/Listener/RecordStatusChangeTimeline.php @@ -0,0 +1,33 @@ +ticket, + actor: $event->actor, + fromStatus: $event->oldStatus, + toStatus: $event->newStatus, + isAutomatic: $event->isAutomatic, + ); + } catch (\Throwable $e) { + $this->log->warning('[linkrobins/support] could not record status timeline event', [ + 'ticket_id' => $event->ticket->id, + 'exception' => $e, + ]); + } + } +} diff --git a/src/SupportEvent.php b/src/SupportEvent.php index f5318f6..3f46a5c 100644 --- a/src/SupportEvent.php +++ b/src/SupportEvent.php @@ -62,47 +62,46 @@ public function toUser(): BelongsTo } /** - * Record what changed in a ticket save that has just happened. - * - * Called from the ticket's `updated` model event, where Eloquent still - * holds the previous values as originals and the new ones as changes. That - * is the one place every status change passes through: a staff member - * picking a status, a reply moving it, and the auto-close command. + * Record a status change in the ticket timeline. */ - public static function recordChanges(SupportTicket $ticket): void - { - $changes = $ticket->getChanges(); - $now = Carbon::now(); - $actorId = $ticket->eventActorId; + public static function recordStatusChange( + SupportTicket $ticket, + ?User $actor, + ?string $fromStatus, + string $toStatus, + bool $isAutomatic = false + ): static { + $event = new static(); + $event->ticket_id = (int) $ticket->id; + $event->user_id = $actor ? (int) $actor->id : null; + $event->type = self::TYPE_STATUS; + $event->from_status = $fromStatus; + $event->to_status = $toStatus; + $event->is_automatic = $isAutomatic; + $event->created_at = Carbon::now(); + $event->save(); - if (array_key_exists('status', $changes) && $ticket->getOriginal('status') !== $changes['status']) { - $event = new static(); - $event->ticket_id = $ticket->id; - $event->user_id = $actorId; - $event->type = self::TYPE_STATUS; - $event->from_status = $ticket->getOriginal('status'); - $event->to_status = $changes['status']; - $event->is_automatic = $ticket->eventAutomatic; - $event->created_at = $now; - $event->save(); - } + return $event; + } - if (array_key_exists('assigned_staff_id', $changes)) { - $from = $ticket->getOriginal('assigned_staff_id'); - $to = $changes['assigned_staff_id']; - $from = $from === null ? null : (int) $from; - $to = $to === null ? null : (int) $to; + /** + * Record an assignment change in the ticket timeline. + */ + public static function recordAssignment( + SupportTicket $ticket, + ?User $actor, + ?User $fromUser, + ?User $toUser + ): static { + $event = new static(); + $event->ticket_id = (int) $ticket->id; + $event->user_id = $actor ? (int) $actor->id : null; + $event->type = self::TYPE_ASSIGNMENT; + $event->from_user_id = $fromUser ? (int) $fromUser->id : null; + $event->to_user_id = $toUser ? (int) $toUser->id : null; + $event->created_at = Carbon::now(); + $event->save(); - if ($from !== $to) { - $event = new static(); - $event->ticket_id = $ticket->id; - $event->user_id = $actorId; - $event->type = self::TYPE_ASSIGNMENT; - $event->from_user_id = $from; - $event->to_user_id = $to; - $event->created_at = $now; - $event->save(); - } - } + return $event; } } diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 26fdd61..36c3662 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -155,19 +155,12 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg } }); - // Record status and assignment changes for the ticket timeline, then - // tell anyone listening (flarum/realtime) that the ticket moved. This - // is a model event rather than an API hook on purpose: replies and the - // auto-close command change status without going through the API, - // and their changes belong in the history too. A failure here is - // logged rather than thrown, so the save itself always stands. + // Tell anyone listening (notifications, flarum/realtime, timeline logger) + // that the ticket moved. This is a model event rather than an API hook on + // purpose: replies and the auto-close command change status without going + // through the API, and their changes belong in the history too. A failure + // here is logged rather than thrown, so the save itself always stands. SupportTicket::updated(function (SupportTicket $ticket) use ($events, $log) { - try { - SupportEvent::recordChanges($ticket); - } catch (\Throwable $e) { - $log->warning('[linkrobins/support] could not record ticket history', ['exception' => $e]); - } - try { $actor = $ticket->eventActor; if (! $actor && $ticket->eventActorId) { @@ -225,7 +218,8 @@ protected static function lifecycleEvents(SupportTicket $ticket, ?User $actor, L if (array_key_exists('status', $changes) && $ticket->getOriginal('status') !== $changes['status']) { $oldStatus = $ticket->getOriginal('status'); $newStatus = (string) $changes['status']; - $events[] = new TicketStatusChanged($ticket, $actor, $oldStatus, $newStatus); + $isAutomatic = (bool) $ticket->eventAutomatic; + $events[] = new TicketStatusChanged($ticket, $actor, $oldStatus, $newStatus, $isAutomatic); $category = $ticket->currentCategory(); if ($category) { diff --git a/src/SupportTicket.php b/src/SupportTicket.php index d4f4db3..0477871 100644 --- a/src/SupportTicket.php +++ b/src/SupportTicket.php @@ -130,6 +130,31 @@ public static function statusLabelKey(string $status): string self::DECISION_REJECTED, ]; + /** + * Change the ticket status with actor and automatic attribution. + */ + public function changeStatus(string $status, ?User $actor = null, bool $isAutomatic = false): static + { + $this->status = $status; + $this->eventActor = $actor; + $this->eventActorId = $actor ? (int) $actor->id : null; + $this->eventAutomatic = $isAutomatic; + + return $this; + } + + /** + * Assign the ticket to a staff member with actor attribution. + */ + public function assignTo(?User $assignee, ?User $actor = null): static + { + $this->assigned_staff_id = $assignee ? (int) $assignee->id : null; + $this->eventActor = $actor; + $this->eventActorId = $actor ? (int) $actor->id : null; + + return $this; + } + // user_id (the creator), assigned_staff_id, and category_id are set // by the resource controller, never by mass-assignment from the // client. subject is the only attribute the client controls From 3cc05af9fd0fb0931fb260d206c2d6ae93e4fb12 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:00:19 +0800 Subject: [PATCH 02/12] test: seed opening reply fixture in TicketHistoryTest --- tests/integration/api/TicketHistoryTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/integration/api/TicketHistoryTest.php b/tests/integration/api/TicketHistoryTest.php index 6837102..b794dd8 100644 --- a/tests/integration/api/TicketHistoryTest.php +++ b/tests/integration/api/TicketHistoryTest.php @@ -65,6 +65,9 @@ public function setUp(): void 'linkrobins_support_tickets' => [ ['id' => 1, 'category_id' => 1, 'user_id' => 2, 'subject' => 'Mine', 'status' => 'open', 'last_reply_at' => Carbon::now(), 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], ], + 'linkrobins_support_replies' => [ + ['id' => 1, 'ticket_id' => 1, 'user_id' => 2, 'content' => 'Opening message', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], + ], ]); } From edc49d8f77d0917a56dac8f1d454cae10e83dad3 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:26:16 +0800 Subject: [PATCH 03/12] refactor: adopt EventGeneratorTrait and domain methods for ticket lifecycle 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 --- extend.php | 14 +- src/Api/Resource/SupportTicketResource.php | 17 +- src/Console/CloseResolvedTicketsCommand.php | 8 +- src/Event/TicketAssigned.php | 7 + src/Listener/RecordAssignmentTimeline.php | 2 + src/SupportEvent.php | 10 +- src/SupportServiceProvider.php | 163 +++++--------------- src/SupportTicket.php | 91 ++++++----- 8 files changed, 129 insertions(+), 183 deletions(-) diff --git a/extend.php b/extend.php index b5b50cc..660c162 100644 --- a/extend.php +++ b/extend.php @@ -268,7 +268,19 @@ } }) ->listen(\LinkRobins\Support\Event\TicketStatusChanged::class, RecordStatusChangeTimeline::class) - ->listen(\LinkRobins\Support\Event\TicketAssigned::class, RecordAssignmentTimeline::class), + ->listen(\LinkRobins\Support\Event\TicketStatusChanged::class, function (\LinkRobins\Support\Event\TicketStatusChanged $event) { + $category = $event->ticket->currentCategory(); + if ($category) { + $category->ticketType()->onStatusChanged($event->ticket, $event->newStatus, $event->oldStatus, $event->actor); + } + }) + ->listen(\LinkRobins\Support\Event\TicketAssigned::class, RecordAssignmentTimeline::class) + ->listen(\LinkRobins\Support\Event\TicketDecided::class, function (\LinkRobins\Support\Event\TicketDecided $event) { + $category = $event->ticket->currentCategory(); + if ($category) { + $category->ticketType()->onDecided($event->ticket, $event->newDecision, $event->oldDecision, $event->actor); + } + }), (new Extend\Settings()) ->default('linkrobins-support.nav_in_sidebar', '1') diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index 02ed057..6dc4a48 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -171,7 +171,7 @@ public function fields(): array } $actor = $context->getActor(); if (SupportAbilities::isStaff($actor)) { - $ticket->status = $value; + $ticket->changeStatus($value, $actor); return; } // Non-staff: the owner of a non-appeal ticket may make two @@ -184,12 +184,12 @@ public function fields(): array $this->ownerMayReopen($ticket, $actor) && $value === SupportTicket::STATUS_OPEN ) { - $ticket->status = $value; + $ticket->changeStatus($value, $actor); } elseif ( $this->ownerMayConfirmSolved($ticket, $actor) && $value === SupportTicket::STATUS_CLOSED ) { - $ticket->status = $value; + $ticket->changeStatus($value, $actor); } }), @@ -221,7 +221,7 @@ public function fields(): array if (! $isStaff) { return; } - $ticket->decision = $value; + $ticket->changeDecision($value, $actor); }), Schema\DateTime::make('createdAt') @@ -375,7 +375,7 @@ public function fields(): array return; } if ($value === null) { - $ticket->assigned_staff_id = null; + $ticket->assignTo(null, $actor); return; } $targetId = null; @@ -396,7 +396,7 @@ public function fields(): array if (! $target || ! SupportAbilities::isStaff($target)) { throw new BadRequestException($this->translator->trans('linkrobins-support.api.assign_staff_only')); } - $ticket->assigned_staff_id = $targetId; + $ticket->assignTo($target, $actor); }), Schema\Relationship\ToOne::make('category') @@ -659,11 +659,6 @@ public function updating(object $model, Context $context): ?object } } - // Credit status and assignment changes in the ticket timeline to the - // person making this request (passed to lifecycle domain events). - $model->eventActor = $actor->isGuest() ? null : $actor; - $model->eventActorId = $actor->isGuest() ? null : (int) $actor->id; - $this->before[(int) $model->id] = [ 'status' => $model->getOriginal('status'), 'assignee' => $model->getOriginal('assigned_staff_id') === null diff --git a/src/Console/CloseResolvedTicketsCommand.php b/src/Console/CloseResolvedTicketsCommand.php index 2f31250..1c5562f 100644 --- a/src/Console/CloseResolvedTicketsCommand.php +++ b/src/Console/CloseResolvedTicketsCommand.php @@ -5,6 +5,7 @@ use Carbon\Carbon; use Flarum\Settings\SettingsRepositoryInterface; use Illuminate\Console\Command; +use Illuminate\Contracts\Events\Dispatcher; use LinkRobins\Support\SupportTicket; /** @@ -41,7 +42,7 @@ public static function days(mixed $value): int return max(0, (int) $value); } - public function handle(SettingsRepositoryInterface $settings): int + public function handle(SettingsRepositoryInterface $settings, Dispatcher $events): int { $days = self::days($settings->get(self::SETTING)); @@ -59,7 +60,7 @@ public function handle(SettingsRepositoryInterface $settings): int ->whereNotNull('status_changed_at') ->where('status_changed_at', '<=', $cutoff) ->where(fn ($q) => $q->whereNull('last_reply_at')->orWhere('last_reply_at', '<=', $cutoff)) - ->chunkById(100, function ($tickets) use (&$closed) { + ->chunkById(100, function ($tickets) use (&$closed, $events) { foreach ($tickets as $ticket) { /** @var SupportTicket $ticket */ // Re-check on the row itself: a reply may have reopened @@ -68,6 +69,9 @@ public function handle(SettingsRepositoryInterface $settings): int continue; } $ticket->changeStatus(SupportTicket::STATUS_CLOSED, actor: null, isAutomatic: true)->save(); + foreach ($ticket->releaseEvents() as $event) { + $events->dispatch($event); + } $closed++; } }); diff --git a/src/Event/TicketAssigned.php b/src/Event/TicketAssigned.php index 624b206..27959f9 100644 --- a/src/Event/TicketAssigned.php +++ b/src/Event/TicketAssigned.php @@ -11,11 +11,18 @@ */ class TicketAssigned { + public readonly ?int $assigneeId; + public readonly ?int $oldAssigneeId; + public function __construct( public readonly SupportTicket $ticket, public readonly ?User $actor, public readonly ?User $assignee, public readonly ?User $oldAssignee = null, + ?int $assigneeId = null, + ?int $oldAssigneeId = null, ) { + $this->assigneeId = $assigneeId ?? ($assignee ? (int) $assignee->id : null); + $this->oldAssigneeId = $oldAssigneeId ?? ($oldAssignee ? (int) $oldAssignee->id : null); } } diff --git a/src/Listener/RecordAssignmentTimeline.php b/src/Listener/RecordAssignmentTimeline.php index c0456cd..c7cbd58 100644 --- a/src/Listener/RecordAssignmentTimeline.php +++ b/src/Listener/RecordAssignmentTimeline.php @@ -21,6 +21,8 @@ public function __invoke(TicketAssigned $event): void actor: $event->actor, fromUser: $event->oldAssignee, toUser: $event->assignee, + fromUserId: $event->oldAssigneeId, + toUserId: $event->assigneeId, ); } catch (\Throwable $e) { $this->log->warning('[linkrobins/support] could not record assignment timeline event', [ diff --git a/src/SupportEvent.php b/src/SupportEvent.php index 3f46a5c..943565e 100644 --- a/src/SupportEvent.php +++ b/src/SupportEvent.php @@ -90,15 +90,17 @@ public static function recordStatusChange( public static function recordAssignment( SupportTicket $ticket, ?User $actor, - ?User $fromUser, - ?User $toUser + ?User $fromUser = null, + ?User $toUser = null, + ?int $fromUserId = null, + ?int $toUserId = null ): static { $event = new static(); $event->ticket_id = (int) $ticket->id; $event->user_id = $actor ? (int) $actor->id : null; $event->type = self::TYPE_ASSIGNMENT; - $event->from_user_id = $fromUser ? (int) $fromUser->id : null; - $event->to_user_id = $toUser ? (int) $toUser->id : null; + $event->from_user_id = $fromUserId ?? ($fromUser ? (int) $fromUser->id : null); + $event->to_user_id = $toUserId ?? ($toUser ? (int) $toUser->id : null); $event->created_at = Carbon::now(); $event->save(); diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 36c3662..e5e881a 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -64,11 +64,11 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg if (! $reply->is_internal_note) { if ($ticket->status === SupportTicket::STATUS_RESOLVED) { - $ticket->status = SupportTicket::STATUS_IN_PROGRESS; + $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); } elseif ($isStaff && $ticket->status === SupportTicket::STATUS_OPEN) { - $ticket->status = SupportTicket::STATUS_IN_PROGRESS; + $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); } elseif (! $isStaff && $ticket->status === SupportTicket::STATUS_AWAITING_USER) { - $ticket->status = SupportTicket::STATUS_IN_PROGRESS; + $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); } } @@ -89,27 +89,22 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg // the status reflects the user-visible state of the // conversation, while assignment is staff routing.) if ($isStaff && $reply->user_id && ! $ticket->assigned_staff_id) { - $ticket->assigned_staff_id = $reply->user_id; + $ticket->assignTo($reply->user, $reply->user); } - // The reply's author is who moved the status or claimed the - // ticket, as far as the ticket timeline is concerned. - $ticket->eventActor = $reply->relationLoaded('user') ? $reply->user : null; - $ticket->eventActorId = $reply->user_id ? (int) $reply->user_id : null; - // Any status move here comes from the rules above, not a - // choice the author made, so the timeline says it happened - // automatically. - $ticket->eventAutomatic = true; - $ticket->savingOpeningMessage = $isOpening; $ticket->save(); - $ticket->savingOpeningMessage = false; - $ticket->eventAutomatic = false; - static::afterCommit(fn () => $events->dispatch(new ReplyPosted($reply, $reply->user))); + foreach ($ticket->releaseEvents() as $event) { + static::afterCommit(fn () => static::dispatchIsolated($events, $event, $log)); + } + + static::afterCommit(fn () => static::dispatchIsolated($events, new TicketChanged($ticket, $reply->user), $log)); + + static::afterCommit(fn () => static::dispatchIsolated($events, new ReplyPosted($reply, $reply->user), $log)); // The opening message is announced by TicketCreated. if (! $isOpening) { - static::afterCommit(fn () => $events->dispatch(new ReplyCreated($reply, $reply->user))); + static::afterCommit(fn () => static::dispatchIsolated($events, new ReplyCreated($reply, $reply->user), $log)); } // Notifications: dispatched only for user-facing replies. @@ -138,10 +133,10 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg SupportTicket::created(function (SupportTicket $ticket) use ($bus, $events, $log) { try { $bus->dispatch(new NotifyNewTicket($ticket->id)); - static::afterCommit(fn () => $events->dispatch(new TicketChanged($ticket, $ticket->user))); + static::afterCommit(fn () => static::dispatchIsolated($events, new TicketChanged($ticket, $ticket->user), $log)); // After the commit, which on the API's create path is after // the opening message is saved too. - static::afterCommit(fn () => $events->dispatch(new TicketCreated($ticket, $ticket->user))); + static::afterCommit(fn () => static::dispatchIsolated($events, new TicketCreated($ticket, $ticket->user), $log)); } catch (\Throwable $e) { $log->warning('[linkrobins/support] ticket post-save hook failed', ['exception' => $e]); } @@ -154,34 +149,36 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg $ticket->status_changed_at = Carbon::now(); } }); + } - // Tell anyone listening (notifications, flarum/realtime, timeline logger) - // that the ticket moved. This is a model event rather than an API hook on - // purpose: replies and the auto-close command change status without going - // through the API, and their changes belong in the history too. A failure - // here is logged rather than thrown, so the save itself always stands. - SupportTicket::updated(function (SupportTicket $ticket) use ($events, $log) { - try { - $actor = $ticket->eventActor; - if (! $actor && $ticket->eventActorId) { - if ($ticket->relationLoaded('user') && $ticket->user && (int) $ticket->user->id === (int) $ticket->eventActorId) { - $actor = $ticket->user; - } elseif ($ticket->relationLoaded('assignedStaff') && $ticket->assignedStaff && (int) $ticket->assignedStaff->id === (int) $ticket->eventActorId) { - $actor = $ticket->assignedStaff; - } else { - $actor = User::query()->find($ticket->eventActorId); - } - } - - foreach (static::lifecycleEvents($ticket, $actor, $log) as $event) { - static::afterCommit(fn () => $events->dispatch($event)); + /** + * Dispatch an event to its listeners in isolation, logging any failure so + * that one failing listener cannot block other listeners or crash the + * after-commit callback. + */ + protected static function dispatchIsolated(Events $events, object $event, LoggerInterface $log): void + { + if (method_exists($events, 'getListeners')) { + foreach ($events->getListeners(get_class($event)) as $listener) { + try { + $listener($event); + } catch (\Throwable $e) { + $log->warning('[linkrobins/support] event listener failed', [ + 'event' => get_class($event), + 'exception' => $e, + ]); } - - static::afterCommit(fn () => $events->dispatch(new TicketChanged($ticket, $actor))); + } + } else { + try { + $events->dispatch($event); } catch (\Throwable $e) { - $log->warning('[linkrobins/support] ticket change event failed', ['exception' => $e]); + $log->warning('[linkrobins/support] event dispatch failed', [ + 'event' => get_class($event), + 'exception' => $e, + ]); } - }); + } } /** @@ -195,86 +192,6 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg * candidate that predates that, where dispatching straight away is the * old behaviour. */ - /** - * The specific events for what this save changed, for other extensions to - * listen to (webhooks, bots, audit logs). Built here, from the model, so - * every route that changes a ticket is covered: the API, a reply moving - * the status on or claiming the ticket, and the auto-close command. - * - * Called from the updated hook, where getOriginal() still holds the values - * from before the save. - * - * @return list - */ - protected static function lifecycleEvents(SupportTicket $ticket, ?User $actor, LoggerInterface $log): array - { - if ($ticket->savingOpeningMessage) { - return []; - } - - $changes = $ticket->getChanges(); - $events = []; - - if (array_key_exists('status', $changes) && $ticket->getOriginal('status') !== $changes['status']) { - $oldStatus = $ticket->getOriginal('status'); - $newStatus = (string) $changes['status']; - $isAutomatic = (bool) $ticket->eventAutomatic; - $events[] = new TicketStatusChanged($ticket, $actor, $oldStatus, $newStatus, $isAutomatic); - - $category = $ticket->currentCategory(); - if ($category) { - static::afterCommit(function () use ($category, $ticket, $newStatus, $oldStatus, $actor, $log) { - try { - $category->ticketType()->onStatusChanged($ticket, $newStatus, $oldStatus, $actor); - } catch (\Throwable $e) { - $log->error('[linkrobins/support] ticket type onStatusChanged failed', ['exception' => $e]); - } - }); - } - } - - if (array_key_exists('decision', $changes) && $ticket->getOriginal('decision') !== $changes['decision']) { - $oldDecision = $ticket->getOriginal('decision'); - $newDecision = (string) $changes['decision']; - $events[] = new TicketDecided($ticket, $actor, $oldDecision, $newDecision); - - $category = $ticket->currentCategory(); - if ($category) { - static::afterCommit(function () use ($category, $ticket, $newDecision, $oldDecision, $actor, $log) { - try { - $category->ticketType()->onDecided($ticket, $newDecision, $oldDecision, $actor); - } catch (\Throwable $e) { - $log->error('[linkrobins/support] ticket type onDecided failed', ['exception' => $e]); - } - }); - } - } - - if (array_key_exists('assigned_staff_id', $changes)) { - $from = $ticket->getOriginal('assigned_staff_id'); - $to = $changes['assigned_staff_id']; - $from = $from === null ? null : (int) $from; - $to = $to === null ? null : (int) $to; - - if ($from !== $to) { - // The actor is usually one of the two (claiming, or handing - // over); reuse it rather than look them up again. - $user = fn (?int $id) => $id === null ? null : ( - $actor && (int) $actor->id === $id - ? $actor - : ($ticket->relationLoaded('user') && $ticket->user && (int) $ticket->user->id === $id - ? $ticket->user - : ($ticket->relationLoaded('assignedStaff') && $ticket->assignedStaff && (int) $ticket->assignedStaff->id === $id - ? $ticket->assignedStaff - : User::query()->find($id))) - ); - $events[] = new TicketAssigned($ticket, $actor, $user($to), $user($from)); - } - } - - return $events; - } - protected static function afterCommit(callable $callback): void { try { diff --git a/src/SupportTicket.php b/src/SupportTicket.php index 0477871..d43373e 100644 --- a/src/SupportTicket.php +++ b/src/SupportTicket.php @@ -3,11 +3,15 @@ namespace LinkRobins\Support; use Flarum\Database\AbstractModel; +use Flarum\Foundation\EventGeneratorTrait; use Flarum\User\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use LinkRobins\Support\Event\TicketAssigned; +use LinkRobins\Support\Event\TicketDecided; +use LinkRobins\Support\Event\TicketStatusChanged; /** * @property int $id @@ -34,45 +38,13 @@ */ class SupportTicket extends AbstractModel { + use EventGeneratorTrait; use SoftDeletes; protected $table = 'linkrobins_support_tickets'; public $timestamps = true; - /** - * Who is making the change being saved, for the ticket timeline. - * - * Not a column. Model events cannot see the request, so each place that - * changes a ticket says who is doing it before saving: the API resource - * sets the acting user, a reply sets its author, and the auto-close - * command leaves it null so the change reads as the forum's own. - */ - public ?int $eventActorId = null; - - /** - * The User model instance of who is making the change, if available. - * Reused during model event hooks to avoid querying the users table. - */ - public ?User $eventActor = null; - - /** - * Set when the forum, not a person, is moving the status: a reply's - * status rules or the auto-close command. Not a column. The timeline - * words those changes as automatic. - */ - public bool $eventAutomatic = false; - - /** - * Set while the ticket's opening message is being saved. Not a column. - * - * A staff member's own opening message moves their ticket to in progress - * and assigns it to them, through the same reply hook as any other reply. - * TicketCreated already announces that ticket, so the status and - * assignment events stay quiet for it. - */ - public bool $savingOpeningMessage = false; - public const STATUS_OPEN = 'open'; public const STATUS_IN_PROGRESS = 'in_progress'; public const STATUS_AWAITING_USER = 'awaiting_user'; @@ -131,26 +103,61 @@ public static function statusLabelKey(string $status): string ]; /** - * Change the ticket status with actor and automatic attribution. + * Change the ticket status and raise a domain event. */ public function changeStatus(string $status, ?User $actor = null, bool $isAutomatic = false): static { - $this->status = $status; - $this->eventActor = $actor; - $this->eventActorId = $actor ? (int) $actor->id : null; - $this->eventAutomatic = $isAutomatic; + if ($this->status !== $status) { + $oldStatus = $this->status; + $this->status = $status; + + $this->raise(new TicketStatusChanged($this, $actor, $oldStatus, $status, $isAutomatic)); + } return $this; } /** - * Assign the ticket to a staff member with actor attribution. + * Assign the ticket to a staff member (or null to unassign) and raise a domain event. */ public function assignTo(?User $assignee, ?User $actor = null): static { - $this->assigned_staff_id = $assignee ? (int) $assignee->id : null; - $this->eventActor = $actor; - $this->eventActorId = $actor ? (int) $actor->id : null; + $newId = $assignee ? (int) $assignee->id : null; + $oldId = $this->assigned_staff_id === null ? null : (int) $this->assigned_staff_id; + + if ($newId !== $oldId) { + $oldAssignee = $this->relationLoaded('assignedStaff') ? $this->assignedStaff : null; + $this->assigned_staff_id = $newId; + if ($assignee) { + $this->setRelation('assignedStaff', $assignee); + } else { + $this->unsetRelation('assignedStaff'); + } + + $this->raise(new TicketAssigned( + ticket: $this, + actor: $actor, + assignee: $assignee, + oldAssignee: $oldAssignee, + assigneeId: $newId, + oldAssigneeId: $oldId, + )); + } + + return $this; + } + + /** + * Change the ticket decision and raise a domain event. + */ + public function changeDecision(?string $decision, ?User $actor = null): static + { + if ($this->decision !== $decision) { + $oldDecision = $this->decision; + $this->decision = $decision; + + $this->raise(new TicketDecided($this, $actor, $oldDecision, $decision)); + } return $this; } From 3b6d5eb6ffdb2f8129d79539adc762b4e87df0b1 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:27:00 +0800 Subject: [PATCH 04/12] test: verify staff opening message claim and status advance - 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 --- .../api/TicketDomainEventsTest.php | 30 ++++++--- tests/integration/api/TicketHistoryTest.php | 62 ++++++++++++++++++- 2 files changed, 82 insertions(+), 10 deletions(-) diff --git a/tests/integration/api/TicketDomainEventsTest.php b/tests/integration/api/TicketDomainEventsTest.php index d8b44e8..389b9a8 100644 --- a/tests/integration/api/TicketDomainEventsTest.php +++ b/tests/integration/api/TicketDomainEventsTest.php @@ -381,11 +381,11 @@ public function user_replying_to_awaiting_user_ticket_dispatches_status_changed_ } #[Test] - public function a_staff_members_own_ticket_is_announced_once(): void + public function a_staff_members_own_ticket_dispatches_created_status_and_assignment_events(): void { - // A staff member's opening message moves their ticket to in progress - // and assigns it to them. TicketCreated covers that; the status and - // assignment events must not also fire for it. + // When a staff member files a ticket, their opening message moves the ticket + // to in_progress and auto-claims it. TicketCreated announces the new ticket, + // while TicketStatusChanged and TicketAssigned record the claim and status advance. $response = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'authenticatedAs' => 3, @@ -405,8 +405,24 @@ public function a_staff_members_own_ticket_is_announced_once(): void $this->assertEquals(201, $response->getStatusCode()); - $classes = array_map(fn ($e) => get_class($e), self::$dispatchedEvents); - $this->assertSame([TicketCreated::class], $classes); - $this->assertEquals(3, self::$dispatchedEvents[0]->actor?->id); + $createdEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketCreated)); + $this->assertCount(1, $createdEvents); + $this->assertEquals(3, $createdEvents[0]->actor?->id); + + $statusEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); + $this->assertCount(1, $statusEvents); + $this->assertEquals(SupportTicket::STATUS_OPEN, $statusEvents[0]->oldStatus); + $this->assertEquals(SupportTicket::STATUS_IN_PROGRESS, $statusEvents[0]->newStatus); + $this->assertEquals(3, $statusEvents[0]->actor?->id); + + $assignedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketAssigned)); + $this->assertCount(1, $assignedEvents); + $this->assertEquals(3, $assignedEvents[0]->assignee?->id); + $this->assertNull($assignedEvents[0]->oldAssignee); + $this->assertEquals(3, $assignedEvents[0]->actor?->id); + + // The opening message must not dispatch ReplyCreated (announced by TicketCreated) + $replyEvents = array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof ReplyCreated); + $this->assertCount(0, $replyEvents, 'Opening message must not dispatch ReplyCreated'); } } diff --git a/tests/integration/api/TicketHistoryTest.php b/tests/integration/api/TicketHistoryTest.php index b794dd8..1b14a41 100644 --- a/tests/integration/api/TicketHistoryTest.php +++ b/tests/integration/api/TicketHistoryTest.php @@ -65,9 +65,6 @@ public function setUp(): void 'linkrobins_support_tickets' => [ ['id' => 1, 'category_id' => 1, 'user_id' => 2, 'subject' => 'Mine', 'status' => 'open', 'last_reply_at' => Carbon::now(), 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], ], - 'linkrobins_support_replies' => [ - ['id' => 1, 'ticket_id' => 1, 'user_id' => 2, 'content' => 'Opening message', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], - ], ]); } @@ -232,4 +229,63 @@ public function saving_without_changing_status_or_assignee_records_nothing(): vo $this->assertEquals(0, $this->database()->table('linkrobins_support_events')->count()); } + + #[Test] + public function a_staff_filed_ticket_records_opening_message_claim_and_status_advance(): void + { + $response = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 3, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'attributes' => [ + 'subject' => 'Staff filed ticket', + 'firstPost' => 'Opening reply from staff.', + ], + 'relationships' => [ + 'category' => [ + 'data' => ['type' => 'linkrobins-support-categories', 'id' => '1'], + ], + ], + ], + ], + ]) + ); + + $this->assertEquals(201, $response->getStatusCode(), (string) $response->getBody()); + $ticketId = (int) json_decode((string) $response->getBody(), true)['data']['id']; + + $events = $this->database()->table('linkrobins_support_events') + ->where('ticket_id', $ticketId) + ->orderBy('id') + ->get(); + + $statusEvent = $events->firstWhere('type', 'status'); + $this->assertNotNull($statusEvent, 'Expected a status change event to be recorded for the opening message'); + $this->assertEquals('open', $statusEvent->from_status); + $this->assertEquals('in_progress', $statusEvent->to_status); + $this->assertEquals(3, (int) $statusEvent->user_id); + $this->assertTrue((bool) $statusEvent->is_automatic); + + $assignmentEvent = $events->firstWhere('type', 'assignment'); + $this->assertNotNull($assignmentEvent, 'Expected an assignment event to be recorded for the opening message'); + $this->assertNull($assignmentEvent->from_user_id); + $this->assertEquals(3, (int) $assignmentEvent->to_user_id); + $this->assertEquals(3, (int) $assignmentEvent->user_id); + } + + #[Test] + public function reassigning_away_from_a_deleted_user_keeps_raw_from_user_id(): void + { + // Ticket is currently assigned to a user id (999) that does not exist in the users table + $this->database()->table('linkrobins_support_tickets')->where('id', 1)->update(['assigned_staff_id' => 999]); + + $this->patch(3, ['relationships' => ['assignedStaff' => ['data' => ['type' => 'users', 'id' => '3']]]]); + + $row = $this->database()->table('linkrobins_support_events')->where('type', 'assignment')->first(); + $this->assertNotNull($row); + $this->assertEquals(999, (int) $row->from_user_id); + $this->assertEquals(3, (int) $row->to_user_id); + } } From 89b6257c685d2b2d548b6be0742665db7c045f10 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:55:53 +0800 Subject: [PATCH 05/12] fix: correct listener dispatch payload, old assignee resolution, and 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 --- extend.php | 12 ++++++++++-- src/SupportServiceProvider.php | 10 ++++++---- src/SupportTicket.php | 5 ++++- tests/integration/api/TicketHistoryTest.php | 14 -------------- 4 files changed, 20 insertions(+), 21 deletions(-) diff --git a/extend.php b/extend.php index 660c162..fba64d5 100644 --- a/extend.php +++ b/extend.php @@ -271,14 +271,22 @@ ->listen(\LinkRobins\Support\Event\TicketStatusChanged::class, function (\LinkRobins\Support\Event\TicketStatusChanged $event) { $category = $event->ticket->currentCategory(); if ($category) { - $category->ticketType()->onStatusChanged($event->ticket, $event->newStatus, $event->oldStatus, $event->actor); + try { + $category->ticketType()->onStatusChanged($event->ticket, $event->newStatus, $event->oldStatus, $event->actor); + } catch (\Throwable $e) { + resolve(\Psr\Log\LoggerInterface::class)->error('[linkrobins/support] ticket type onStatusChanged failed', ['exception' => $e]); + } } }) ->listen(\LinkRobins\Support\Event\TicketAssigned::class, RecordAssignmentTimeline::class) ->listen(\LinkRobins\Support\Event\TicketDecided::class, function (\LinkRobins\Support\Event\TicketDecided $event) { $category = $event->ticket->currentCategory(); if ($category) { - $category->ticketType()->onDecided($event->ticket, $event->newDecision, $event->oldDecision, $event->actor); + try { + $category->ticketType()->onDecided($event->ticket, $event->newDecision, $event->oldDecision, $event->actor); + } catch (\Throwable $e) { + resolve(\Psr\Log\LoggerInterface::class)->error('[linkrobins/support] ticket type onDecided failed', ['exception' => $e]); + } } }), diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index e5e881a..f52fb71 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -158,13 +158,15 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg */ protected static function dispatchIsolated(Events $events, object $event, LoggerInterface $log): void { + $eventName = get_class($event); + if (method_exists($events, 'getListeners')) { - foreach ($events->getListeners(get_class($event)) as $listener) { + foreach ($events->getListeners($eventName) as $listener) { try { - $listener($event); + $listener($eventName, [$event]); } catch (\Throwable $e) { $log->warning('[linkrobins/support] event listener failed', [ - 'event' => get_class($event), + 'event' => $eventName, 'exception' => $e, ]); } @@ -174,7 +176,7 @@ protected static function dispatchIsolated(Events $events, object $event, Logger $events->dispatch($event); } catch (\Throwable $e) { $log->warning('[linkrobins/support] event dispatch failed', [ - 'event' => get_class($event), + 'event' => $eventName, 'exception' => $e, ]); } diff --git a/src/SupportTicket.php b/src/SupportTicket.php index d43373e..ac63ad9 100644 --- a/src/SupportTicket.php +++ b/src/SupportTicket.php @@ -126,7 +126,10 @@ public function assignTo(?User $assignee, ?User $actor = null): static $oldId = $this->assigned_staff_id === null ? null : (int) $this->assigned_staff_id; if ($newId !== $oldId) { - $oldAssignee = $this->relationLoaded('assignedStaff') ? $this->assignedStaff : null; + $oldAssignee = $this->relationLoaded('assignedStaff') + ? $this->assignedStaff + : ($oldId ? User::query()->find($oldId) : null); + $this->assigned_staff_id = $newId; if ($assignee) { $this->setRelation('assignedStaff', $assignee); diff --git a/tests/integration/api/TicketHistoryTest.php b/tests/integration/api/TicketHistoryTest.php index 1b14a41..de0d763 100644 --- a/tests/integration/api/TicketHistoryTest.php +++ b/tests/integration/api/TicketHistoryTest.php @@ -274,18 +274,4 @@ public function a_staff_filed_ticket_records_opening_message_claim_and_status_ad $this->assertEquals(3, (int) $assignmentEvent->to_user_id); $this->assertEquals(3, (int) $assignmentEvent->user_id); } - - #[Test] - public function reassigning_away_from_a_deleted_user_keeps_raw_from_user_id(): void - { - // Ticket is currently assigned to a user id (999) that does not exist in the users table - $this->database()->table('linkrobins_support_tickets')->where('id', 1)->update(['assigned_staff_id' => 999]); - - $this->patch(3, ['relationships' => ['assignedStaff' => ['data' => ['type' => 'users', 'id' => '3']]]]); - - $row = $this->database()->table('linkrobins_support_events')->where('type', 'assignment')->first(); - $this->assertNotNull($row); - $this->assertEquals(999, (int) $row->from_user_id); - $this->assertEquals(3, (int) $row->to_user_id); - } } From 8904e208f006f39176927a143e0510a16f71a4af Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:20:28 +0800 Subject: [PATCH 06/12] chore: remove unused event imports in SupportServiceProvider --- src/SupportServiceProvider.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index f52fb71..6019bfa 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -11,11 +11,8 @@ use LinkRobins\Support\Access\SupportAbilities; use LinkRobins\Support\Event\ReplyCreated; use LinkRobins\Support\Event\ReplyPosted; -use LinkRobins\Support\Event\TicketAssigned; use LinkRobins\Support\Event\TicketChanged; use LinkRobins\Support\Event\TicketCreated; -use LinkRobins\Support\Event\TicketDecided; -use LinkRobins\Support\Event\TicketStatusChanged; use LinkRobins\Support\Job\NotifyNewReply; use LinkRobins\Support\Job\NotifyNewTicket; use LinkRobins\Support\TicketType\TicketTypeManager; From 1041bb4e688c7720e67836f8f3c671ab51645fce Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:30:37 +0800 Subject: [PATCH 07/12] fix: dispatch TicketChanged on ticket edits and auto-close - 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 --- src/Api/Resource/SupportTicketResource.php | 12 +++++ src/Console/CloseResolvedTicketsCommand.php | 2 + .../api/TicketDomainEventsTest.php | 46 +++++++++++++++++++ .../console/CloseResolvedTicketsTest.php | 18 ++++++-- 4 files changed, 75 insertions(+), 3 deletions(-) diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index 6dc4a48..d28db30 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -13,6 +13,7 @@ use Flarum\User\User; use Illuminate\Database\Eloquent\Builder; use LinkRobins\Support\Access\SupportAbilities; +use LinkRobins\Support\Event\TicketChanged; use LinkRobins\Support\Job\NotifyAssigned; use LinkRobins\Support\Job\NotifyStatusChanged; use LinkRobins\Support\RateLimiter; @@ -715,6 +716,17 @@ public function saved(object $model, Context $context): ?object return $model; } + public function updated(object $model, Context $context): ?object + { + /** @var SupportTicket $model */ + if ($model->wasChanged()) { + $actor = $context->getActor(); + $model->raise(new TicketChanged($model, $actor->isGuest() ? null : $actor)); + } + + return $model; + } + /** * Authorize permanent deletion of a ticket. * diff --git a/src/Console/CloseResolvedTicketsCommand.php b/src/Console/CloseResolvedTicketsCommand.php index 1c5562f..ab222b4 100644 --- a/src/Console/CloseResolvedTicketsCommand.php +++ b/src/Console/CloseResolvedTicketsCommand.php @@ -6,6 +6,7 @@ use Flarum\Settings\SettingsRepositoryInterface; use Illuminate\Console\Command; use Illuminate\Contracts\Events\Dispatcher; +use LinkRobins\Support\Event\TicketChanged; use LinkRobins\Support\SupportTicket; /** @@ -72,6 +73,7 @@ public function handle(SettingsRepositoryInterface $settings, Dispatcher $events foreach ($ticket->releaseEvents() as $event) { $events->dispatch($event); } + $events->dispatch(new TicketChanged($ticket, null)); $closed++; } }); diff --git a/tests/integration/api/TicketDomainEventsTest.php b/tests/integration/api/TicketDomainEventsTest.php index 389b9a8..50a2a6b 100644 --- a/tests/integration/api/TicketDomainEventsTest.php +++ b/tests/integration/api/TicketDomainEventsTest.php @@ -15,6 +15,7 @@ use Flarum\Testing\integration\TestCase; use LinkRobins\Support\Event\ReplyCreated; use LinkRobins\Support\Event\TicketAssigned; +use LinkRobins\Support\Event\TicketChanged; use LinkRobins\Support\Event\TicketCreated; use LinkRobins\Support\Event\TicketDecided; use LinkRobins\Support\Event\TicketStatusChanged; @@ -58,6 +59,7 @@ public function setUp(): void $this->extend( (new Extend\Event()) ->listen(TicketCreated::class, fn ($e) => self::$dispatchedEvents[] = $e) + ->listen(TicketChanged::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketStatusChanged::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketDecided::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketAssigned::class, fn ($e) => self::$dispatchedEvents[] = $e) @@ -169,6 +171,11 @@ public function updating_status_and_decision_dispatches_proper_events(): void $this->assertEquals(SupportTicket::DECISION_ACCEPTED, $decisionEvents[0]->newDecision); $this->assertEquals(3, $decisionEvents[0]->actor->id); + $changedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + $this->assertCount(1, $changedEvents); + $this->assertEquals($ticketId, $changedEvents[0]->ticket->id); + $this->assertEquals(3, $changedEvents[0]->actor?->id); + // A no-op update with identical values must NOT re-dispatch events self::$dispatchedEvents = []; $this->send( @@ -425,4 +432,43 @@ public function a_staff_members_own_ticket_dispatches_created_status_and_assignm $replyEvents = array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof ReplyCreated); $this->assertCount(0, $replyEvents, 'Opening message must not dispatch ReplyCreated'); } + + #[Test] + public function patching_priority_dispatches_ticket_changed_event(): void + { + $ticketId = $this->database()->table('linkrobins_support_tickets')->insertGetId([ + 'category_id' => 1, + 'user_id' => 2, + 'subject' => 'Priority test', + 'status' => SupportTicket::STATUS_OPEN, + 'priority' => SupportTicket::PRIORITY_NORMAL, + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + self::$dispatchedEvents = []; + + $response = $this->send( + $this->request('PATCH', "/api/linkrobins-support-tickets/$ticketId", [ + 'authenticatedAs' => 3, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'id' => (string) $ticketId, + 'attributes' => [ + 'priority' => SupportTicket::PRIORITY_URGENT, + ], + ], + ], + ]) + ); + + $this->assertEquals(200, $response->getStatusCode()); + + $changedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + $this->assertCount(1, $changedEvents); + $this->assertEquals($ticketId, $changedEvents[0]->ticket->id); + $this->assertEquals(SupportTicket::PRIORITY_URGENT, $changedEvents[0]->ticket->priority); + $this->assertEquals(3, $changedEvents[0]->actor?->id); + } } diff --git a/tests/integration/console/CloseResolvedTicketsTest.php b/tests/integration/console/CloseResolvedTicketsTest.php index 183b3b4..ee4c8f5 100644 --- a/tests/integration/console/CloseResolvedTicketsTest.php +++ b/tests/integration/console/CloseResolvedTicketsTest.php @@ -13,6 +13,7 @@ use Flarum\Extend; use Flarum\Testing\integration\ConsoleTestCase; use Flarum\Testing\integration\RetrievesAuthorizedUsers; +use LinkRobins\Support\Event\TicketChanged; use LinkRobins\Support\Event\TicketStatusChanged; use PHPUnit\Framework\Attributes\Test; @@ -89,9 +90,16 @@ public function the_close_is_recorded_in_history_as_the_forums_own_and_notifies_ public function the_close_is_announced_to_other_extensions_with_no_actor(): void { $seen = []; - $this->extend((new Extend\Event())->listen(TicketStatusChanged::class, function (TicketStatusChanged $e) use (&$seen) { - $seen[] = $e; - })); + $changed = []; + $this->extend( + (new Extend\Event()) + ->listen(TicketStatusChanged::class, function (TicketStatusChanged $e) use (&$seen) { + $seen[] = $e; + }) + ->listen(TicketChanged::class, function (TicketChanged $e) use (&$changed) { + $changed[] = $e; + }) + ); $this->runCommand(['command' => 'lr-support:close-resolved']); @@ -100,6 +108,10 @@ public function the_close_is_announced_to_other_extensions_with_no_actor(): void $this->assertEquals('resolved', $seen[0]->oldStatus); $this->assertEquals('closed', $seen[0]->newStatus); $this->assertNull($seen[0]->actor); + + $this->assertCount(1, $changed); + $this->assertEquals(1, $changed[0]->ticket->id); + $this->assertNull($changed[0]->actor); } #[Test] From 3b3eb131277fecedcf1d4cbda8ed5cc89aeff88d Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:32:57 +0800 Subject: [PATCH 08/12] fix: isolate API and console event listeners from failing hooks - 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 --- src/Api/Resource/SupportTicketResource.php | 18 +++++++ src/Console/CloseResolvedTicketsCommand.php | 10 ++-- src/SupportServiceProvider.php | 9 ++++ .../api/TicketDomainEventsTest.php | 52 +++++++++++++++++++ .../console/CloseResolvedTicketsTest.php | 20 +++++++ 5 files changed, 105 insertions(+), 4 deletions(-) diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index d28db30..df9bc2b 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -18,8 +18,10 @@ use LinkRobins\Support\Job\NotifyStatusChanged; use LinkRobins\Support\RateLimiter; use LinkRobins\Support\SupportCategory; +use LinkRobins\Support\SupportServiceProvider; use LinkRobins\Support\SupportTicket; use LinkRobins\Support\UserState; +use Psr\Log\LoggerInterface; use Tobyz\JsonApiServer\Context; use Tobyz\JsonApiServer\Exception\BadRequestException; use Tobyz\JsonApiServer\Exception\ForbiddenException; @@ -40,6 +42,7 @@ public function __construct( protected RateLimiter $rateLimiter, protected TranslatorInterface $translator, protected Dispatcher $bus, + protected LoggerInterface $log, ) { } @@ -727,6 +730,21 @@ public function updated(object $model, Context $context): ?object return $model; } + /** + * Dispatch raised domain events after commit with per-listener isolation so a + * failing listener never causes the API request to return 500 after saving. + */ + public function dispatchEventsFor(mixed $entity, ?User $actor = null): void + { + if (! method_exists($entity, 'releaseEvents')) { + return; + } + + foreach ($entity->releaseEvents() as $event) { + SupportServiceProvider::dispatchAfterCommit($this->events, $event, $this->log); + } + } + /** * Authorize permanent deletion of a ticket. * diff --git a/src/Console/CloseResolvedTicketsCommand.php b/src/Console/CloseResolvedTicketsCommand.php index ab222b4..9b9cee9 100644 --- a/src/Console/CloseResolvedTicketsCommand.php +++ b/src/Console/CloseResolvedTicketsCommand.php @@ -7,7 +7,9 @@ use Illuminate\Console\Command; use Illuminate\Contracts\Events\Dispatcher; use LinkRobins\Support\Event\TicketChanged; +use LinkRobins\Support\SupportServiceProvider; use LinkRobins\Support\SupportTicket; +use Psr\Log\LoggerInterface; /** * Close tickets that have sat in Resolved with no activity for the @@ -43,7 +45,7 @@ public static function days(mixed $value): int return max(0, (int) $value); } - public function handle(SettingsRepositoryInterface $settings, Dispatcher $events): int + public function handle(SettingsRepositoryInterface $settings, Dispatcher $events, LoggerInterface $log): int { $days = self::days($settings->get(self::SETTING)); @@ -61,7 +63,7 @@ public function handle(SettingsRepositoryInterface $settings, Dispatcher $events ->whereNotNull('status_changed_at') ->where('status_changed_at', '<=', $cutoff) ->where(fn ($q) => $q->whereNull('last_reply_at')->orWhere('last_reply_at', '<=', $cutoff)) - ->chunkById(100, function ($tickets) use (&$closed, $events) { + ->chunkById(100, function ($tickets) use (&$closed, $events, $log) { foreach ($tickets as $ticket) { /** @var SupportTicket $ticket */ // Re-check on the row itself: a reply may have reopened @@ -71,9 +73,9 @@ public function handle(SettingsRepositoryInterface $settings, Dispatcher $events } $ticket->changeStatus(SupportTicket::STATUS_CLOSED, actor: null, isAutomatic: true)->save(); foreach ($ticket->releaseEvents() as $event) { - $events->dispatch($event); + SupportServiceProvider::dispatchAfterCommit($events, $event, $log); } - $events->dispatch(new TicketChanged($ticket, null)); + SupportServiceProvider::dispatchAfterCommit($events, new TicketChanged($ticket, null), $log); $closed++; } }); diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 6019bfa..0ccbd8f 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -148,6 +148,15 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg }); } + /** + * Dispatch an event after the surrounding transaction commits, isolating each + * listener so a failure in one cannot abort the request or remaining listeners. + */ + public static function dispatchAfterCommit(Events $events, object $event, LoggerInterface $log): void + { + static::afterCommit(fn () => static::dispatchIsolated($events, $event, $log)); + } + /** * Dispatch an event to its listeners in isolation, logging any failure so * that one failing listener cannot block other listeners or crash the diff --git a/tests/integration/api/TicketDomainEventsTest.php b/tests/integration/api/TicketDomainEventsTest.php index 50a2a6b..0fe8517 100644 --- a/tests/integration/api/TicketDomainEventsTest.php +++ b/tests/integration/api/TicketDomainEventsTest.php @@ -34,6 +34,8 @@ class TicketDomainEventsTest extends TestCase /** @var list */ public static array $dispatchedEvents = []; + public static bool $throwOnStatusChange = false; + /** * Flarum's notification mailer and auth pipeline repeatedly look up users by ID. * Upstream whitelists this shape in StatusNotificationTest and CategoryDefaultAssigneeTest. @@ -53,11 +55,17 @@ public function setUp(): void parent::setUp(); self::$dispatchedEvents = []; + self::$throwOnStatusChange = false; $this->extension('linkrobins-support'); $this->extend( (new Extend\Event()) + ->listen(TicketStatusChanged::class, function () { + if (self::$throwOnStatusChange) { + throw new \RuntimeException('Simulated listener failure'); + } + }) ->listen(TicketCreated::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketChanged::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketStatusChanged::class, fn ($e) => self::$dispatchedEvents[] = $e) @@ -471,4 +479,48 @@ public function patching_priority_dispatches_ticket_changed_event(): void $this->assertEquals(SupportTicket::PRIORITY_URGENT, $changedEvents[0]->ticket->priority); $this->assertEquals(3, $changedEvents[0]->actor?->id); } + + #[Test] + public function failing_listener_does_not_fail_api_patch_or_block_other_listeners(): void + { + $ticketId = $this->database()->table('linkrobins_support_tickets')->insertGetId([ + 'category_id' => 1, + 'user_id' => 2, + 'subject' => 'Listener error isolation', + 'status' => SupportTicket::STATUS_OPEN, + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + self::$dispatchedEvents = []; + self::$throwOnStatusChange = true; + + $response = $this->send( + $this->request('PATCH', "/api/linkrobins-support-tickets/$ticketId", [ + 'authenticatedAs' => 3, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'id' => (string) $ticketId, + 'attributes' => [ + 'status' => SupportTicket::STATUS_RESOLVED, + ], + ], + ], + ]) + ); + + $this->assertEquals(200, $response->getStatusCode(), (string) $response->getBody()); + $this->assertEquals( + SupportTicket::STATUS_RESOLVED, + $this->database()->table('linkrobins_support_tickets')->where('id', $ticketId)->value('status') + ); + + // Subsequent listeners on TicketStatusChanged and TicketChanged must still run + $statusEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); + $this->assertCount(1, $statusEvents); + + $changedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + $this->assertCount(1, $changedEvents); + } } diff --git a/tests/integration/console/CloseResolvedTicketsTest.php b/tests/integration/console/CloseResolvedTicketsTest.php index ee4c8f5..77675db 100644 --- a/tests/integration/console/CloseResolvedTicketsTest.php +++ b/tests/integration/console/CloseResolvedTicketsTest.php @@ -114,6 +114,26 @@ public function the_close_is_announced_to_other_extensions_with_no_actor(): void $this->assertNull($changed[0]->actor); } + #[Test] + public function a_failing_listener_does_not_abort_auto_close(): void + { + $changed = []; + $this->extend( + (new Extend\Event()) + ->listen(TicketStatusChanged::class, function () { + throw new \RuntimeException('Simulated listener failure'); + }) + ->listen(TicketChanged::class, function (TicketChanged $e) use (&$changed) { + $changed[] = $e; + }) + ); + + $this->runCommand(['command' => 'lr-support:close-resolved']); + + $this->assertEquals('closed', $this->statusOf(1)); + $this->assertCount(1, $changed); + } + #[Test] public function zero_days_turns_it_off(): void { From f14bb5fea23ca7a79eeddf4c6a44b1c4cd177325 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:34:35 +0800 Subject: [PATCH 09/12] fix: omit TicketStatusChanged on staff-filed ticket creation - 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 --- src/SupportServiceProvider.php | 8 +++++++- .../api/TicketDomainEventsTest.php | 19 +++++++++++-------- tests/integration/api/TicketHistoryTest.php | 13 ++++++------- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 0ccbd8f..950a3d9 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -63,7 +63,13 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg if ($ticket->status === SupportTicket::STATUS_RESOLVED) { $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); } elseif ($isStaff && $ticket->status === SupportTicket::STATUS_OPEN) { - $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); + if ($isOpening) { + // Staff-filed tickets start in progress; the opening + // status is not a transition to announce or log. + $ticket->status = SupportTicket::STATUS_IN_PROGRESS; + } else { + $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); + } } elseif (! $isStaff && $ticket->status === SupportTicket::STATUS_AWAITING_USER) { $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); } diff --git a/tests/integration/api/TicketDomainEventsTest.php b/tests/integration/api/TicketDomainEventsTest.php index 0fe8517..01de8fe 100644 --- a/tests/integration/api/TicketDomainEventsTest.php +++ b/tests/integration/api/TicketDomainEventsTest.php @@ -396,11 +396,11 @@ public function user_replying_to_awaiting_user_ticket_dispatches_status_changed_ } #[Test] - public function a_staff_members_own_ticket_dispatches_created_status_and_assignment_events(): void + public function a_staff_members_own_ticket_dispatches_created_and_assignment_without_status_change(): void { - // When a staff member files a ticket, their opening message moves the ticket - // to in_progress and auto-claims it. TicketCreated announces the new ticket, - // while TicketStatusChanged and TicketAssigned record the claim and status advance. + // When a staff member files a ticket, it starts directly in_progress and + // is auto-claimed. TicketCreated and TicketAssigned fire, while + // TicketStatusChanged stays quiet because the starting status isn't a change. $response = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'authenticatedAs' => 3, @@ -420,15 +420,18 @@ public function a_staff_members_own_ticket_dispatches_created_status_and_assignm $this->assertEquals(201, $response->getStatusCode()); + $ticketId = (int) json_decode((string) $response->getBody(), true)['data']['id']; + $this->assertEquals( + SupportTicket::STATUS_IN_PROGRESS, + $this->database()->table('linkrobins_support_tickets')->where('id', $ticketId)->value('status') + ); + $createdEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketCreated)); $this->assertCount(1, $createdEvents); $this->assertEquals(3, $createdEvents[0]->actor?->id); $statusEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); - $this->assertCount(1, $statusEvents); - $this->assertEquals(SupportTicket::STATUS_OPEN, $statusEvents[0]->oldStatus); - $this->assertEquals(SupportTicket::STATUS_IN_PROGRESS, $statusEvents[0]->newStatus); - $this->assertEquals(3, $statusEvents[0]->actor?->id); + $this->assertCount(0, $statusEvents, 'Initial status on creation must not dispatch TicketStatusChanged'); $assignedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketAssigned)); $this->assertCount(1, $assignedEvents); diff --git a/tests/integration/api/TicketHistoryTest.php b/tests/integration/api/TicketHistoryTest.php index de0d763..8995722 100644 --- a/tests/integration/api/TicketHistoryTest.php +++ b/tests/integration/api/TicketHistoryTest.php @@ -231,7 +231,7 @@ public function saving_without_changing_status_or_assignee_records_nothing(): vo } #[Test] - public function a_staff_filed_ticket_records_opening_message_claim_and_status_advance(): void + public function a_staff_filed_ticket_starts_in_progress_and_records_claim_without_status_change(): void { $response = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ @@ -254,7 +254,10 @@ public function a_staff_filed_ticket_records_opening_message_claim_and_status_ad ); $this->assertEquals(201, $response->getStatusCode(), (string) $response->getBody()); - $ticketId = (int) json_decode((string) $response->getBody(), true)['data']['id']; + $ticketData = json_decode((string) $response->getBody(), true)['data']; + $ticketId = (int) $ticketData['id']; + + $this->assertEquals('in_progress', $this->database()->table('linkrobins_support_tickets')->where('id', $ticketId)->value('status')); $events = $this->database()->table('linkrobins_support_events') ->where('ticket_id', $ticketId) @@ -262,11 +265,7 @@ public function a_staff_filed_ticket_records_opening_message_claim_and_status_ad ->get(); $statusEvent = $events->firstWhere('type', 'status'); - $this->assertNotNull($statusEvent, 'Expected a status change event to be recorded for the opening message'); - $this->assertEquals('open', $statusEvent->from_status); - $this->assertEquals('in_progress', $statusEvent->to_status); - $this->assertEquals(3, (int) $statusEvent->user_id); - $this->assertTrue((bool) $statusEvent->is_automatic); + $this->assertNull($statusEvent, 'Starting a staff-filed ticket in progress should not record a status change event'); $assignmentEvent = $events->firstWhere('type', 'assignment'); $this->assertNotNull($assignmentEvent, 'Expected an assignment event to be recorded for the opening message'); From 0bbb2e2cc40174e0d2e644eb1dcf3342548e251f Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:37:30 +0800 Subject: [PATCH 10/12] refactor: extract ticket-type lifecycle listeners into invokable classes - 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 --- extend.php | 31 +++++------------ src/Listener/NotifyTicketTypeDecision.php | 33 +++++++++++++++++++ src/Listener/NotifyTicketTypeStatusChange.php | 33 +++++++++++++++++++ 3 files changed, 75 insertions(+), 22 deletions(-) create mode 100644 src/Listener/NotifyTicketTypeDecision.php create mode 100644 src/Listener/NotifyTicketTypeStatusChange.php diff --git a/extend.php b/extend.php index fba64d5..a5bf4be 100644 --- a/extend.php +++ b/extend.php @@ -9,7 +9,10 @@ use LinkRobins\Support\Console\CloseResolvedTicketsCommand; use LinkRobins\Support\Console\HourlySchedule; use LinkRobins\Support\Event\ReplyPosted; +use LinkRobins\Support\Event\TicketAssigned; use LinkRobins\Support\Event\TicketChanged; +use LinkRobins\Support\Event\TicketDecided; +use LinkRobins\Support\Event\TicketStatusChanged; use LinkRobins\Support\Api\Resource\SupportCategoryResource; use LinkRobins\Support\Api\Resource\SupportReplyResource; use LinkRobins\Support\Api\Resource\SupportTicketResource; @@ -22,6 +25,8 @@ use LinkRobins\Support\Search\ReplySearcher; use LinkRobins\Support\Search\TicketSearcher; use LinkRobins\Support\Extend as SupportExtend; +use LinkRobins\Support\Listener\NotifyTicketTypeDecision; +use LinkRobins\Support\Listener\NotifyTicketTypeStatusChange; use LinkRobins\Support\Listener\RecordAssignmentTimeline; use LinkRobins\Support\Listener\RecordStatusChangeTimeline; use LinkRobins\Support\SupportCategory; @@ -267,28 +272,10 @@ $event->value = $event->value === '' || $event->value === '0' ? '0' : '1'; } }) - ->listen(\LinkRobins\Support\Event\TicketStatusChanged::class, RecordStatusChangeTimeline::class) - ->listen(\LinkRobins\Support\Event\TicketStatusChanged::class, function (\LinkRobins\Support\Event\TicketStatusChanged $event) { - $category = $event->ticket->currentCategory(); - if ($category) { - try { - $category->ticketType()->onStatusChanged($event->ticket, $event->newStatus, $event->oldStatus, $event->actor); - } catch (\Throwable $e) { - resolve(\Psr\Log\LoggerInterface::class)->error('[linkrobins/support] ticket type onStatusChanged failed', ['exception' => $e]); - } - } - }) - ->listen(\LinkRobins\Support\Event\TicketAssigned::class, RecordAssignmentTimeline::class) - ->listen(\LinkRobins\Support\Event\TicketDecided::class, function (\LinkRobins\Support\Event\TicketDecided $event) { - $category = $event->ticket->currentCategory(); - if ($category) { - try { - $category->ticketType()->onDecided($event->ticket, $event->newDecision, $event->oldDecision, $event->actor); - } catch (\Throwable $e) { - resolve(\Psr\Log\LoggerInterface::class)->error('[linkrobins/support] ticket type onDecided failed', ['exception' => $e]); - } - } - }), + ->listen(TicketStatusChanged::class, RecordStatusChangeTimeline::class) + ->listen(TicketStatusChanged::class, NotifyTicketTypeStatusChange::class) + ->listen(TicketAssigned::class, RecordAssignmentTimeline::class) + ->listen(TicketDecided::class, NotifyTicketTypeDecision::class), (new Extend\Settings()) ->default('linkrobins-support.nav_in_sidebar', '1') diff --git a/src/Listener/NotifyTicketTypeDecision.php b/src/Listener/NotifyTicketTypeDecision.php new file mode 100644 index 0000000..8937e66 --- /dev/null +++ b/src/Listener/NotifyTicketTypeDecision.php @@ -0,0 +1,33 @@ +ticket->currentCategory(); + if (! $category || $event->newDecision === null) { + return; + } + + try { + $category->ticketType()->onDecided( + $event->ticket, + $event->newDecision, + $event->oldDecision, + $event->actor, + ); + } catch (\Throwable $e) { + $this->log->error('[linkrobins/support] ticket type onDecided failed', ['exception' => $e]); + } + } +} diff --git a/src/Listener/NotifyTicketTypeStatusChange.php b/src/Listener/NotifyTicketTypeStatusChange.php new file mode 100644 index 0000000..70d2d22 --- /dev/null +++ b/src/Listener/NotifyTicketTypeStatusChange.php @@ -0,0 +1,33 @@ +ticket->currentCategory(); + if (! $category) { + return; + } + + try { + $category->ticketType()->onStatusChanged( + $event->ticket, + $event->newStatus, + $event->oldStatus, + $event->actor, + ); + } catch (\Throwable $e) { + $this->log->error('[linkrobins/support] ticket type onStatusChanged failed', ['exception' => $e]); + } + } +} From f4dd403ab3b1b8c8912f9ac193696d2b8959afae Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:06:26 +0800 Subject: [PATCH 11/12] fix: only treat opening reply by ticket author as staff-filed - 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 --- src/SupportServiceProvider.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 950a3d9..5d0d7a4 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -63,7 +63,7 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg if ($ticket->status === SupportTicket::STATUS_RESOLVED) { $ticket->changeStatus(SupportTicket::STATUS_IN_PROGRESS, $reply->user, isAutomatic: true); } elseif ($isStaff && $ticket->status === SupportTicket::STATUS_OPEN) { - if ($isOpening) { + if ($isOpening && (int) $reply->user_id === (int) $ticket->user_id) { // Staff-filed tickets start in progress; the opening // status is not a transition to announce or log. $ticket->status = SupportTicket::STATUS_IN_PROGRESS; From 7ed86f882d6bace91ff44642a021cddbe9304e9f Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:21:15 +0800 Subject: [PATCH 12/12] test: expand domain event and decision listener coverage - 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 --- .../api/TicketDomainEventsTest.php | 269 ++++++++++++++++++ .../integration/api/TicketTypeDriverTest.php | 35 +++ 2 files changed, 304 insertions(+) diff --git a/tests/integration/api/TicketDomainEventsTest.php b/tests/integration/api/TicketDomainEventsTest.php index 01de8fe..a0c1f78 100644 --- a/tests/integration/api/TicketDomainEventsTest.php +++ b/tests/integration/api/TicketDomainEventsTest.php @@ -14,6 +14,7 @@ use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\TestCase; use LinkRobins\Support\Event\ReplyCreated; +use LinkRobins\Support\Event\ReplyPosted; use LinkRobins\Support\Event\TicketAssigned; use LinkRobins\Support\Event\TicketChanged; use LinkRobins\Support\Event\TicketCreated; @@ -36,6 +37,8 @@ class TicketDomainEventsTest extends TestCase public static bool $throwOnStatusChange = false; + public static bool $throwOnTicketCreated = false; + /** * Flarum's notification mailer and auth pipeline repeatedly look up users by ID. * Upstream whitelists this shape in StatusNotificationTest and CategoryDefaultAssigneeTest. @@ -56,6 +59,7 @@ public function setUp(): void self::$dispatchedEvents = []; self::$throwOnStatusChange = false; + self::$throwOnTicketCreated = false; $this->extension('linkrobins-support'); @@ -66,24 +70,32 @@ public function setUp(): void throw new \RuntimeException('Simulated listener failure'); } }) + ->listen(TicketCreated::class, function () { + if (self::$throwOnTicketCreated) { + throw new \RuntimeException('Simulated created listener failure'); + } + }) ->listen(TicketCreated::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketChanged::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketStatusChanged::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketDecided::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(TicketAssigned::class, fn ($e) => self::$dispatchedEvents[] = $e) ->listen(ReplyCreated::class, fn ($e) => self::$dispatchedEvents[] = $e) + ->listen(ReplyPosted::class, fn ($e) => self::$dispatchedEvents[] = $e) ); $this->prepareDatabase([ 'users' => [ $this->normalUser(), // id 2 ['id' => 3, 'username' => 'staff1', 'email' => 'staff1@machine.local', 'is_email_confirmed' => 1, 'password' => 'password'], + ['id' => 4, 'username' => 'staff2', 'email' => 'staff2@machine.local', 'is_email_confirmed' => 1, 'password' => 'password'], ], 'groups' => [ ['id' => 100, 'name_singular' => 'Staff', 'name_plural' => 'Staff', 'is_hidden' => 0], ], 'group_user' => [ ['user_id' => 3, 'group_id' => 100], + ['user_id' => 4, 'group_id' => 100], ], 'group_permission' => [ ['group_id' => 100, 'permission' => 'lr-support.handle_tickets'], @@ -526,4 +538,261 @@ public function failing_listener_does_not_fail_api_patch_or_block_other_listener $changedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); $this->assertCount(1, $changedEvents); } + + #[Test] + public function owner_confirm_solved_and_reopen_dispatch_status_and_changed_events_with_owner_actor(): void + { + $ticketId = $this->database()->table('linkrobins_support_tickets')->insertGetId([ + 'category_id' => 1, + 'user_id' => 2, + 'subject' => 'Owner transitions', + 'status' => SupportTicket::STATUS_RESOLVED, + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + // 1. Owner confirms solved (resolved -> closed) + self::$dispatchedEvents = []; + $closeResponse = $this->send( + $this->request('PATCH', "/api/linkrobins-support-tickets/$ticketId", [ + 'authenticatedAs' => 2, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'id' => (string) $ticketId, + 'attributes' => ['status' => SupportTicket::STATUS_CLOSED], + ], + ], + ]) + ); + $this->assertEquals(200, $closeResponse->getStatusCode(), (string) $closeResponse->getBody()); + + $statusEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); + $this->assertCount(1, $statusEvents); + $this->assertEquals(SupportTicket::STATUS_RESOLVED, $statusEvents[0]->oldStatus); + $this->assertEquals(SupportTicket::STATUS_CLOSED, $statusEvents[0]->newStatus); + $this->assertEquals(2, $statusEvents[0]->actor?->id); + $this->assertFalse($statusEvents[0]->isAutomatic); + + $changedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + $this->assertCount(1, $changedEvents); + $this->assertEquals(2, $changedEvents[0]->actor?->id); + + // 2. Owner reopens closed ticket (closed -> open) + self::$dispatchedEvents = []; + $reopenResponse = $this->send( + $this->request('PATCH', "/api/linkrobins-support-tickets/$ticketId", [ + 'authenticatedAs' => 2, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'id' => (string) $ticketId, + 'attributes' => ['status' => SupportTicket::STATUS_OPEN], + ], + ], + ]) + ); + $this->assertEquals(200, $reopenResponse->getStatusCode(), (string) $reopenResponse->getBody()); + + $reopenStatusEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); + $this->assertCount(1, $reopenStatusEvents); + $this->assertEquals(SupportTicket::STATUS_CLOSED, $reopenStatusEvents[0]->oldStatus); + $this->assertEquals(SupportTicket::STATUS_OPEN, $reopenStatusEvents[0]->newStatus); + $this->assertEquals(2, $reopenStatusEvents[0]->actor?->id); + + $reopenChangedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + $this->assertCount(1, $reopenChangedEvents); + $this->assertEquals(2, $reopenChangedEvents[0]->actor?->id); + } + + #[Test] + public function reassigning_between_staff_by_another_actor_records_distinct_sides(): void + { + $ticketId = $this->database()->table('linkrobins_support_tickets')->insertGetId([ + 'category_id' => 1, + 'user_id' => 2, + 'assigned_staff_id' => 3, + 'subject' => 'Handover', + 'status' => SupportTicket::STATUS_IN_PROGRESS, + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + self::$dispatchedEvents = []; + + $response = $this->send( + $this->request('PATCH', "/api/linkrobins-support-tickets/$ticketId", [ + 'authenticatedAs' => 1, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'id' => (string) $ticketId, + 'relationships' => [ + 'assignedStaff' => ['data' => ['type' => 'users', 'id' => '4']], + ], + ], + ], + ]) + ); + $this->assertEquals(200, $response->getStatusCode(), (string) $response->getBody()); + + $assignedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketAssigned)); + $this->assertCount(1, $assignedEvents); + $this->assertEquals(1, $assignedEvents[0]->actor?->id); + $this->assertEquals(3, $assignedEvents[0]->oldAssignee?->id); + $this->assertEquals(3, $assignedEvents[0]->oldAssigneeId); + $this->assertEquals(4, $assignedEvents[0]->assignee?->id); + $this->assertEquals(4, $assignedEvents[0]->assigneeId); + + $changedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + $this->assertCount(1, $changedEvents); + $this->assertEquals(1, $changedEvents[0]->actor?->id); + + $timelineRow = $this->database()->table('linkrobins_support_events') + ->where('ticket_id', $ticketId) + ->where('type', 'assignment') + ->first(); + $this->assertNotNull($timelineRow); + $this->assertEquals(1, (int) $timelineRow->user_id); + $this->assertEquals(3, (int) $timelineRow->from_user_id); + $this->assertEquals(4, (int) $timelineRow->to_user_id); + } + + #[Test] + public function internal_note_auto_claims_without_status_change(): void + { + $ticketId = $this->database()->table('linkrobins_support_tickets')->insertGetId([ + 'category_id' => 1, + 'user_id' => 2, + 'subject' => 'Internal triage', + 'status' => SupportTicket::STATUS_OPEN, + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + $this->database()->table('linkrobins_support_replies')->insert([ + 'ticket_id' => $ticketId, + 'user_id' => 2, + 'content' => 'Opening message', + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + self::$dispatchedEvents = []; + + $response = $this->send( + $this->request('POST', '/api/linkrobins-support-replies', [ + 'authenticatedAs' => 3, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-replies', + 'attributes' => [ + 'content' => 'Private staff note', + 'isInternalNote' => true, + ], + 'relationships' => [ + 'ticket' => ['data' => ['type' => 'linkrobins-support-tickets', 'id' => (string) $ticketId]], + ], + ], + ], + ]) + ); + $this->assertEquals(201, $response->getStatusCode(), (string) $response->getBody()); + + $this->assertEquals( + SupportTicket::STATUS_OPEN, + $this->database()->table('linkrobins_support_tickets')->where('id', $ticketId)->value('status') + ); + + $this->assertCount(0, array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); + $assignedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketAssigned)); + $this->assertCount(1, $assignedEvents); + $this->assertEquals(3, $assignedEvents[0]->assignee?->id); + + $postedEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof ReplyPosted)); + $this->assertCount(1, $postedEvents); + $this->assertTrue((bool) $postedEvents[0]->reply->is_internal_note); + $this->assertEquals(3, $postedEvents[0]->actor?->id); + + $this->assertCount(1, array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + } + + #[Test] + public function user_replying_to_resolved_ticket_reopens_automatically(): void + { + $ticketId = $this->database()->table('linkrobins_support_tickets')->insertGetId([ + 'category_id' => 1, + 'user_id' => 2, + 'assigned_staff_id' => 3, + 'subject' => 'Resolved ticket', + 'status' => SupportTicket::STATUS_RESOLVED, + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + $this->database()->table('linkrobins_support_replies')->insert([ + 'ticket_id' => $ticketId, + 'user_id' => 2, + 'content' => 'Opening message', + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), + ]); + + self::$dispatchedEvents = []; + + $response = $this->send( + $this->request('POST', '/api/linkrobins-support-replies', [ + 'authenticatedAs' => 2, + 'json' => [ + 'data' => [ + 'type' => 'linkrobins-support-replies', + 'attributes' => ['content' => 'Still seeing the issue'], + 'relationships' => [ + 'ticket' => ['data' => ['type' => 'linkrobins-support-tickets', 'id' => (string) $ticketId]], + ], + ], + ], + ]) + ); + $this->assertEquals(201, $response->getStatusCode(), (string) $response->getBody()); + + $statusEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketStatusChanged)); + $this->assertCount(1, $statusEvents); + $this->assertEquals(SupportTicket::STATUS_RESOLVED, $statusEvents[0]->oldStatus); + $this->assertEquals(SupportTicket::STATUS_IN_PROGRESS, $statusEvents[0]->newStatus); + $this->assertEquals(2, $statusEvents[0]->actor?->id); + $this->assertTrue($statusEvents[0]->isAutomatic); + + $this->assertCount(1, array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof ReplyPosted)); + $this->assertCount(1, array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof ReplyCreated)); + $this->assertCount(1, array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketChanged)); + } + + #[Test] + public function failing_listener_does_not_fail_ticket_creation_or_block_other_listeners(): void + { + self::$dispatchedEvents = []; + self::$throwOnTicketCreated = true; + + $response = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => [ + 'data' => [ + 'attributes' => [ + 'subject' => 'Isolated creation', + 'firstPost' => 'Opening body', + ], + 'relationships' => [ + 'category' => ['data' => ['type' => 'linkrobins-support-categories', 'id' => '1']], + ], + ], + ], + ]) + ); + $this->assertEquals(201, $response->getStatusCode(), (string) $response->getBody()); + + $createdEvents = array_values(array_filter(self::$dispatchedEvents, fn ($e) => $e instanceof TicketCreated)); + $this->assertCount(1, $createdEvents); + } } diff --git a/tests/integration/api/TicketTypeDriverTest.php b/tests/integration/api/TicketTypeDriverTest.php index 91ede28..bd26673 100644 --- a/tests/integration/api/TicketTypeDriverTest.php +++ b/tests/integration/api/TicketTypeDriverTest.php @@ -554,6 +554,35 @@ public function driver_exception_in_on_status_changed_hook_does_not_break_reques ); } + #[Test] + public function clearing_decision_to_null_does_not_fail_decision_listener(): void + { + CustomTestTicketType::resetState(); + + $ticketId = $this->insertTicket(3, 'accepted'); + $response = $this->patchTicket($ticketId, ['decision' => null]); + + $this->assertEquals(200, $response->getStatusCode(), (string) $response->getBody()); + $this->assertNull($this->database()->table('linkrobins_support_tickets')->where('id', $ticketId)->value('decision')); + $this->assertNull(CustomTestTicketType::$decidedTo); + } + + #[Test] + public function driver_exception_in_on_decided_hook_does_not_break_request(): void + { + CustomTestTicketType::resetState(); + CustomTestTicketType::$throwOnDecided = true; + + $ticketId = $this->insertTicket(3, 'pending'); + $response = $this->patchTicket($ticketId, ['decision' => 'accepted']); + + $this->assertEquals(200, $response->getStatusCode(), (string) $response->getBody()); + $this->assertEquals( + 'accepted', + $this->database()->table('linkrobins_support_tickets')->where('id', $ticketId)->value('decision') + ); + } + #[Test] public function guests_cannot_create_tickets_in_any_category(): void { @@ -741,6 +770,7 @@ class CustomTestTicketType extends AbstractTicketType public static ?string $statusChangedTo = null; public static ?string $statusChangedFrom = null; public static bool $throwOnStatusChange = false; + public static bool $throwOnDecided = false; public static function resetState(): void { @@ -752,6 +782,7 @@ public static function resetState(): void self::$statusChangedTo = null; self::$statusChangedFrom = null; self::$throwOnStatusChange = false; + self::$throwOnDecided = false; } public function id(): string @@ -809,6 +840,10 @@ public function onCreated(SupportTicket $ticket, array $data, User $actor): void public function onDecided(SupportTicket $ticket, string $newDecision, ?string $oldDecision, ?User $actor): void { + if (self::$throwOnDecided) { + throw new \RuntimeException('Simulated third-party onDecided hook failure'); + } + self::$decidedTo = $newDecision; }