diff --git a/extend.php b/extend.php index caa6d44..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,10 @@ 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; use LinkRobins\Support\SupportEvent; use LinkRobins\Support\SupportReply; @@ -264,7 +271,11 @@ ], true)) { $event->value = $event->value === '' || $event->value === '0' ? '0' : '1'; } - }), + }) + ->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/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..df9bc2b 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -13,12 +13,15 @@ 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; 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; @@ -39,6 +42,7 @@ public function __construct( protected RateLimiter $rateLimiter, protected TranslatorInterface $translator, protected Dispatcher $bus, + protected LoggerInterface $log, ) { } @@ -171,7 +175,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 +188,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 +225,7 @@ public function fields(): array if (! $isStaff) { return; } - $ticket->decision = $value; + $ticket->changeDecision($value, $actor); }), Schema\DateTime::make('createdAt') @@ -375,7 +379,7 @@ public function fields(): array return; } if ($value === null) { - $ticket->assigned_staff_id = null; + $ticket->assignTo(null, $actor); return; } $targetId = null; @@ -396,7 +400,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 +663,6 @@ 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). - $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 @@ -720,6 +719,32 @@ 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; + } + + /** + * 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 c573b56..9b9cee9 100644 --- a/src/Console/CloseResolvedTicketsCommand.php +++ b/src/Console/CloseResolvedTicketsCommand.php @@ -5,7 +5,11 @@ use Carbon\Carbon; use Flarum\Settings\SettingsRepositoryInterface; 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 @@ -41,7 +45,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, LoggerInterface $log): int { $days = self::days($settings->get(self::SETTING)); @@ -59,7 +63,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, $log) { foreach ($tickets as $ticket) { /** @var SupportTicket $ticket */ // Re-check on the row itself: a reply may have reopened @@ -67,10 +71,11 @@ 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(); + foreach ($ticket->releaseEvents() as $event) { + SupportServiceProvider::dispatchAfterCommit($events, $event, $log); + } + SupportServiceProvider::dispatchAfterCommit($events, new TicketChanged($ticket, null), $log); $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/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/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]); + } + } +} diff --git a/src/Listener/RecordAssignmentTimeline.php b/src/Listener/RecordAssignmentTimeline.php new file mode 100644 index 0000000..c7cbd58 --- /dev/null +++ b/src/Listener/RecordAssignmentTimeline.php @@ -0,0 +1,34 @@ +ticket, + 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', [ + '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..943565e 100644 --- a/src/SupportEvent.php +++ b/src/SupportEvent.php @@ -62,47 +62,48 @@ 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 = 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 = $fromUserId ?? ($fromUser ? (int) $fromUser->id : null); + $event->to_user_id = $toUserId ?? ($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..5d0d7a4 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; @@ -64,11 +61,17 @@ 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; + 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; + } else { + $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 +92,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 +136,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,41 +152,47 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg $ticket->status_changed_at = Carbon::now(); } }); + } - // 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. - 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) { - 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); - } - } + /** + * 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)); + } - 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 + { + $eventName = get_class($event); + + if (method_exists($events, 'getListeners')) { + foreach ($events->getListeners($eventName) as $listener) { + try { + $listener($eventName, [$event]); + } catch (\Throwable $e) { + $log->warning('[linkrobins/support] event listener failed', [ + 'event' => $eventName, + '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' => $eventName, + 'exception' => $e, + ]); } - }); + } } /** @@ -202,85 +206,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']; - $events[] = new TicketStatusChanged($ticket, $actor, $oldStatus, $newStatus); - - $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 d4f4db3..ac63ad9 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'; @@ -130,6 +102,69 @@ public static function statusLabelKey(string $status): string self::DECISION_REJECTED, ]; + /** + * Change the ticket status and raise a domain event. + */ + public function changeStatus(string $status, ?User $actor = null, bool $isAutomatic = false): static + { + 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 (or null to unassign) and raise a domain event. + */ + public function assignTo(?User $assignee, ?User $actor = null): static + { + $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 + : ($oldId ? User::query()->find($oldId) : 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; + } + // 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 diff --git a/tests/integration/api/TicketDomainEventsTest.php b/tests/integration/api/TicketDomainEventsTest.php index d8b44e8..a0c1f78 100644 --- a/tests/integration/api/TicketDomainEventsTest.php +++ b/tests/integration/api/TicketDomainEventsTest.php @@ -14,7 +14,9 @@ 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; use LinkRobins\Support\Event\TicketDecided; use LinkRobins\Support\Event\TicketStatusChanged; @@ -33,6 +35,10 @@ class TicketDomainEventsTest extends TestCase /** @var list */ public static array $dispatchedEvents = []; + 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. @@ -52,28 +58,44 @@ public function setUp(): void parent::setUp(); self::$dispatchedEvents = []; + self::$throwOnStatusChange = false; + self::$throwOnTicketCreated = 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, 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'], @@ -169,6 +191,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( @@ -381,11 +408,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_and_assignment_without_status_change(): 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, 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, @@ -405,8 +432,367 @@ 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); + $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(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); + $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'); + } + + #[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); + } + + #[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); + } + + #[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/TicketHistoryTest.php b/tests/integration/api/TicketHistoryTest.php index 6837102..8995722 100644 --- a/tests/integration/api/TicketHistoryTest.php +++ b/tests/integration/api/TicketHistoryTest.php @@ -229,4 +229,48 @@ 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_starts_in_progress_and_records_claim_without_status_change(): 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()); + $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) + ->orderBy('id') + ->get(); + + $statusEvent = $events->firstWhere('type', 'status'); + $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'); + $this->assertNull($assignmentEvent->from_user_id); + $this->assertEquals(3, (int) $assignmentEvent->to_user_id); + $this->assertEquals(3, (int) $assignmentEvent->user_id); + } } 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; } diff --git a/tests/integration/console/CloseResolvedTicketsTest.php b/tests/integration/console/CloseResolvedTicketsTest.php index 183b3b4..77675db 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,30 @@ 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] + 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]