Add ticket create notification event support
linter / quality (pull_request) Successful in 1m25s
tests / ci (8.4) (pull_request) Successful in 1m42s

This commit is contained in:
2026-04-24 19:35:13 +00:00
parent 083328f9de
commit 5f74ddd964
12 changed files with 262 additions and 18 deletions
@@ -38,7 +38,7 @@ class BuildProjectNotificationSettingsPayload
{ {
return [ return [
[ [
'description' => 'Absolute ticket URL for the status change event.', 'description' => 'Absolute ticket URL for the notification event.',
'value' => '$url', 'value' => '$url',
], ],
[ [
@@ -46,7 +46,7 @@ class BuildProjectNotificationSettingsPayload
'value' => '$ticket_key', 'value' => '$ticket_key',
], ],
[ [
'description' => 'Ticket title from the changed ticket.', 'description' => 'Ticket title for the notification event.',
'value' => '$ticket_title', 'value' => '$ticket_title',
], ],
[ [
@@ -54,15 +54,15 @@ class BuildProjectNotificationSettingsPayload
'value' => '$project_name', 'value' => '$project_name',
], ],
[ [
'description' => 'Origin status label before the move.', 'description' => 'Origin status label for status moves; blank for ticket create.',
'value' => '$status_from', 'value' => '$status_from',
], ],
[ [
'description' => 'Destination status label after the move.', 'description' => 'Destination or initial status label for the ticket event.',
'value' => '$status_to', 'value' => '$status_to',
], ],
[ [
'description' => 'Actor name when the move has a known user.', 'description' => 'Actor name when the event has a known user.',
'value' => '$actor_name', 'value' => '$actor_name',
], ],
]; ];
@@ -0,0 +1,50 @@
<?php
namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
use App\Models\Project;
use App\Models\Ticket;
use App\Models\TicketStatus;
use App\Models\User;
use Carbon\CarbonImmutable;
class BuildTicketCreatedPayload
{
public function handle(
Project $project,
Ticket $ticket,
TicketStatus $ticketStatus,
?User $actor,
CarbonImmutable $occurredAt,
): TicketStatusChangedPayload {
return new TicketStatusChangedPayload(
eventType: NotificationEventType::TicketCreate,
projectId: $project->id,
projectKey: $project->key,
projectName: $project->name,
ticketId: $ticket->id,
ticketKey: $ticket->ticket_key,
ticketTitle: $ticket->title,
ticketUrl: route('projects.tickets.show', [$project, $ticket]),
actorId: $actor?->id,
actorName: $actor?->name,
fromStatusId: null,
fromStatusLabel: null,
toStatusId: $ticketStatus->id,
toStatusLabel: $this->statusLabel($ticketStatus),
occurredAt: $occurredAt,
);
}
private function statusLabel(TicketStatus $ticketStatus): string
{
$ticketStatus->loadMissing('boardColumn');
if ($ticketStatus->boardColumn === null || $ticketStatus->boardColumn->name === $ticketStatus->name) {
return $ticketStatus->name;
}
return "{$ticketStatus->boardColumn->name} / {$ticketStatus->name}";
}
}
@@ -9,7 +9,7 @@ use App\Models\NotificationDeliveryLog;
class QueueTicketStatusChangedNotificationDeliveries class QueueTicketStatusChangedNotificationDeliveries
{ {
public function handle(TicketStatusChanged $event): void public function handle(TicketStatusChanged|TicketCreated $event): void
{ {
NotificationAction::query() NotificationAction::query()
->enabled() ->enabled()
@@ -13,7 +13,7 @@ class RenderDiscordMessageTemplate
'$ticket_key' => $payload->ticketKey, '$ticket_key' => $payload->ticketKey,
'$ticket_title' => $payload->ticketTitle, '$ticket_title' => $payload->ticketTitle,
'$project_name' => $payload->projectName, '$project_name' => $payload->projectName,
'$status_from' => $payload->fromStatusLabel, '$status_from' => $payload->fromStatusLabel ?? '',
'$status_to' => $payload->toStatusLabel, '$status_to' => $payload->toStatusLabel,
'$actor_name' => $payload->actorName ?? '', '$actor_name' => $payload->actorName ?? '',
]); ]);
@@ -0,0 +1,15 @@
<?php
namespace App\Actions\Notifications;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
final readonly class TicketCreated implements ShouldDispatchAfterCommit
{
use Dispatchable;
public function __construct(
public TicketStatusChangedPayload $payload,
) {}
}
@@ -22,8 +22,8 @@ final readonly class TicketStatusChangedPayload implements Arrayable
public string $ticketUrl, public string $ticketUrl,
public ?int $actorId, public ?int $actorId,
public ?string $actorName, public ?string $actorName,
public int $fromStatusId, public ?int $fromStatusId,
public string $fromStatusLabel, public ?string $fromStatusLabel,
public int $toStatusId, public int $toStatusId,
public string $toStatusLabel, public string $toStatusLabel,
public CarbonImmutable $occurredAt, public CarbonImmutable $occurredAt,
@@ -35,7 +35,7 @@ final readonly class TicketStatusChangedPayload implements Arrayable
* project: array{id: int, key: string, name: string}, * project: array{id: int, key: string, name: string},
* ticket: array{id: int, key: string, title: string}, * ticket: array{id: int, key: string, title: string},
* actor: array{id: int, name: string}|null, * actor: array{id: int, name: string}|null,
* from: array{id: int, label: string}, * from: array{id: int, label: string}|null,
* to: array{id: int, label: string}, * to: array{id: int, label: string},
* ticket_url: string, * ticket_url: string,
* occurred_at: string * occurred_at: string
@@ -61,10 +61,12 @@ final readonly class TicketStatusChangedPayload implements Arrayable
'id' => $this->actorId, 'id' => $this->actorId,
'name' => $this->actorName, 'name' => $this->actorName,
], ],
'from' => [ 'from' => $this->fromStatusId === null || $this->fromStatusLabel === null
'id' => $this->fromStatusId, ? null
'label' => $this->fromStatusLabel, : [
], 'id' => $this->fromStatusId,
'label' => $this->fromStatusLabel,
],
'to' => [ 'to' => [
'id' => $this->toStatusId, 'id' => $this->toStatusId,
'label' => $this->toStatusLabel, 'label' => $this->toStatusLabel,
@@ -2,17 +2,21 @@
namespace App\Actions\Tickets; namespace App\Actions\Tickets;
use App\Actions\Notifications\BuildTicketCreatedPayload;
use App\Actions\Notifications\TicketCreated;
use App\Enums\TicketWorklogEntryType; use App\Enums\TicketWorklogEntryType;
use App\Models\Project; use App\Models\Project;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\TicketStatus; use App\Models\TicketStatus;
use App\Models\User; use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
class CreateProjectTicket class CreateProjectTicket
{ {
public function __construct( public function __construct(
private readonly BuildTicketCreatedPayload $buildTicketCreatedPayload,
private readonly CreateTicketWorklogEntry $createTicketWorklogEntry, private readonly CreateTicketWorklogEntry $createTicketWorklogEntry,
) {} ) {}
@@ -53,6 +57,8 @@ class CreateProjectTicket
'story_points' => Arr::get($attributes, 'story_points'), 'story_points' => Arr::get($attributes, 'story_points'),
]); ]);
$occurredAt = CarbonImmutable::now();
if ($actor !== null) { if ($actor !== null) {
$this->createTicketWorklogEntry->handle( $this->createTicketWorklogEntry->handle(
$ticket, $ticket,
@@ -69,6 +75,16 @@ class CreateProjectTicket
); );
} }
TicketCreated::dispatch(
$this->buildTicketCreatedPayload->handle(
$project,
$ticket,
$ticketStatus,
$actor,
$occurredAt,
),
);
return $ticket; return $ticket;
}); });
} }
+2
View File
@@ -5,11 +5,13 @@ namespace App\Enums;
enum NotificationEventType: string enum NotificationEventType: string
{ {
case TicketStatusChanged = 'ticket_status_changed'; case TicketStatusChanged = 'ticket_status_changed';
case TicketCreate = 'ticket_create';
public function label(): string public function label(): string
{ {
return match ($this) { return match ($this) {
self::TicketStatusChanged => 'Ticket status changed', self::TicketStatusChanged => 'Ticket status changed',
self::TicketCreate => 'Ticket create',
}; };
} }
+6
View File
@@ -3,6 +3,7 @@
namespace App\Providers; namespace App\Providers;
use App\Actions\Notifications\QueueTicketStatusChangedNotificationDeliveries; use App\Actions\Notifications\QueueTicketStatusChangedNotificationDeliveries;
use App\Actions\Notifications\TicketCreated;
use App\Actions\Notifications\TicketStatusChanged; use App\Actions\Notifications\TicketStatusChanged;
use App\Actions\Permissions\PermissionService; use App\Actions\Permissions\PermissionService;
use App\Enums\Permission; use App\Enums\Permission;
@@ -99,5 +100,10 @@ class AppServiceProvider extends ServiceProvider
TicketStatusChanged::class, TicketStatusChanged::class,
QueueTicketStatusChangedNotificationDeliveries::class, QueueTicketStatusChangedNotificationDeliveries::class,
); );
Event::listen(
TicketCreated::class,
QueueTicketStatusChangedNotificationDeliveries::class,
);
} }
} }
@@ -99,7 +99,7 @@ const notificationActionTimestamp = (
</Badge> </Badge>
<Heading <Heading
:title="`${project.name} notification settings`" :title="`${project.name} notification settings`"
description="Configure project-scoped webhook and Discord notification actions for ticket status changes." description="Configure project-scoped webhook and Discord notification actions for ticket events."
/> />
</div> </div>
@@ -152,7 +152,7 @@ const notificationActionTimestamp = (
<CardTitle>Create notification</CardTitle> <CardTitle>Create notification</CardTitle>
<CardDescription> <CardDescription>
Add a project-scoped notification action for Add a project-scoped notification action for
the supported ticket status change event. supported ticket events.
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
@@ -270,7 +270,7 @@ const notificationActionTimestamp = (
? 'hidden' ? 'hidden'
: 'block', : 'block',
]" ]"
placeholder="$ticket_key moved from $status_from to $status_to by $actor_name: $url" placeholder="$ticket_key in $project_name ($status_to) by $actor_name: $url"
/> />
<p class="text-muted-foreground text-sm"> <p class="text-muted-foreground text-sm">
{{ {{
@@ -558,7 +558,7 @@ const notificationActionTimestamp = (
? 'hidden' ? 'hidden'
: 'block', : 'block',
]" ]"
placeholder="$ticket_key moved from $status_from to $status_to by $actor_name: $url" placeholder="$ticket_key in $project_name ($status_to) by $actor_name: $url"
/> />
<p class="text-muted-foreground text-sm"> <p class="text-muted-foreground text-sm">
{{ {{
@@ -0,0 +1,152 @@
<?php
namespace Tests\Feature\Notifications;
use App\Actions\Notifications\DeliverNotificationAction;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Enums\NotificationDeliveryStatus;
use App\Enums\NotificationEventType;
use App\Models\NotificationAction;
use App\Models\Project;
use App\Models\TicketStatus;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class TicketCreatedNotificationDispatchTest extends TestCase
{
use RefreshDatabase;
/**
* Ensure ticket creation queues deliveries only for enabled matching actions in the ticket project.
*/
public function test_ticket_creation_queues_delivery_jobs_for_enabled_matching_actions(): void
{
Queue::fake();
$user = User::factory()->create([
'name' => 'Erica Example',
]);
$project = Project::factory()->create([
'key' => 'CORE',
'name' => 'Core Platform',
]);
$otherProject = Project::factory()->create();
app(InitializeProjectTicketMetadata::class)->handle($project);
app(InitializeProjectTicketMetadata::class)->handle($otherProject);
$backlogStatus = $this->backlogStatus($project);
$ticketType = $project->ticketTypes()
->where('is_parent', false)
->orderBy('position')
->firstOrFail();
$priority = $project->ticketPriorities()->firstOrFail();
$webhookAction = NotificationAction::factory()
->webhook()
->for($project)
->create([
'name' => 'Primary webhook',
'event_type' => NotificationEventType::TicketCreate,
]);
$discordAction = NotificationAction::factory()
->discord()
->for($project)
->create([
'name' => 'Discord alerts',
'event_type' => NotificationEventType::TicketCreate,
]);
$disabledAction = NotificationAction::factory()
->disabled()
->for($project)
->create([
'name' => 'Disabled webhook',
'event_type' => NotificationEventType::TicketCreate,
]);
$statusChangedAction = NotificationAction::factory()
->for($project)
->create([
'name' => 'Status changed webhook',
'event_type' => NotificationEventType::TicketStatusChanged,
]);
$foreignProjectAction = NotificationAction::factory()
->for($otherProject)
->create([
'name' => 'Foreign webhook',
'event_type' => NotificationEventType::TicketCreate,
]);
$this->syncProjectPermissions($project, $user, ['edit', 'view']);
$response = $this->actingAs($user)
->post(route('projects.tickets.store', $project), [
'acceptance_criteria' => 'Ship it.',
'assignee_user_id' => null,
'description' => 'Created from notification dispatch test.',
'story_points' => 3,
'ticket_priority_id' => $priority->id,
'ticket_status_id' => $backlogStatus->id,
'ticket_type_id' => $ticketType->id,
'title' => 'Trigger ticket created notification',
]);
$ticket = $project->tickets()
->where('ticket_key', 'CORE-1')
->firstOrFail();
$response
->assertRedirect(route('projects.tickets.show', [$project, $ticket]))
->assertSessionHas('status', 'CORE-1 was created.');
Queue::assertPushed(DeliverNotificationAction::class, 2);
Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($webhookAction, $project, $ticket, $user, $backlogStatus): bool {
return $job->notificationActionId === $webhookAction->id
&& $job->payload->projectId === $project->id
&& $job->payload->projectKey === 'CORE'
&& $job->payload->projectName === 'Core Platform'
&& $job->payload->ticketId === $ticket->id
&& $job->payload->ticketKey === $ticket->ticket_key
&& $job->payload->ticketTitle === 'Trigger ticket created notification'
&& $job->payload->ticketUrl === route('projects.tickets.show', [$project, $ticket])
&& $job->payload->actorId === $user->id
&& $job->payload->actorName === 'Erica Example'
&& $job->payload->fromStatusId === null
&& $job->payload->fromStatusLabel === null
&& $job->payload->toStatusId === $backlogStatus->id
&& $job->payload->toStatusLabel === 'Backlog'
&& $job->payload->eventType === NotificationEventType::TicketCreate
&& $job->notificationDeliveryLogId !== null;
});
Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $discordAction->id
&& $job->payload->eventType === NotificationEventType::TicketCreate
&& $job->notificationDeliveryLogId !== null);
Queue::assertNotPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $disabledAction->id);
Queue::assertNotPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $statusChangedAction->id);
Queue::assertNotPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $foreignProjectAction->id);
$this->assertDatabaseCount('notification_delivery_logs', 2);
$this->assertDatabaseHas('notification_delivery_logs', [
'notification_action_id' => $webhookAction->id,
'delivery_status' => NotificationDeliveryStatus::Pending->value,
'event_type' => NotificationEventType::TicketCreate->value,
'attempt_count' => 0,
'http_status' => null,
]);
$this->assertDatabaseHas('notification_delivery_logs', [
'notification_action_id' => $discordAction->id,
'delivery_status' => NotificationDeliveryStatus::Pending->value,
'event_type' => NotificationEventType::TicketCreate->value,
'attempt_count' => 0,
'http_status' => null,
]);
}
private function backlogStatus(Project $project): TicketStatus
{
return $project->ticketStatuses()
->whereNull('board_column_id')
->firstOrFail();
}
}
@@ -47,6 +47,7 @@ class ProjectNotificationSettingsControllerTest extends TestCase
->where('notificationActions.0.updated_at', $notificationAction->updated_at?->toISOString()) ->where('notificationActions.0.updated_at', $notificationAction->updated_at?->toISOString())
->where('channelOptions.0.value', NotificationChannel::Discord->value) ->where('channelOptions.0.value', NotificationChannel::Discord->value)
->where('eventTypeOptions.0.value', NotificationEventType::TicketStatusChanged->value) ->where('eventTypeOptions.0.value', NotificationEventType::TicketStatusChanged->value)
->where('eventTypeOptions.1.value', NotificationEventType::TicketCreate->value)
->where('templateVariables.0.value', '$url') ->where('templateVariables.0.value', '$url')
->where('templateVariables.6.value', '$actor_name') ->where('templateVariables.6.value', '$actor_name')
->missing('notificationActions.0.delivery_url'), ->missing('notificationActions.0.delivery_url'),