Merge main into notification filters
linter / quality (pull_request) Successful in 3m31s
tests / ci (8.4) (pull_request) Successful in 2m0s

This commit is contained in:
2026-04-29 10:41:51 +00:00
28 changed files with 700 additions and 192 deletions
@@ -2,6 +2,7 @@
namespace App\Actions\Notifications; namespace App\Actions\Notifications;
use App\Enums\DiscordAllowedMentionType;
use App\Enums\NotificationChannel; use App\Enums\NotificationChannel;
use App\Enums\NotificationEventType; use App\Enums\NotificationEventType;
use App\Enums\NotificationFilterAttribute; use App\Enums\NotificationFilterAttribute;
@@ -26,6 +27,7 @@ class BuildProjectNotificationSettingsPayload
'eventTypeOptions' => NotificationEventType::options(), 'eventTypeOptions' => NotificationEventType::options(),
'filterAttributeOptions' => NotificationFilterAttribute::options(), 'filterAttributeOptions' => NotificationFilterAttribute::options(),
'filterOperatorOptions' => NotificationFilterOperator::options(), 'filterOperatorOptions' => NotificationFilterOperator::options(),
'discordAllowedMentionOptions' => DiscordAllowedMentionType::options(),
'notificationActions' => NotificationActionResource::collection( 'notificationActions' => NotificationActionResource::collection(
$this->listProjectNotificationActions->handle($project), $this->listProjectNotificationActions->handle($project),
)->resolve(), )->resolve(),
@@ -2,7 +2,6 @@
namespace App\Actions\Notifications; namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
use App\Models\Project; use App\Models\Project;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\TicketStatus; use App\Models\TicketStatus;
@@ -17,9 +16,8 @@ class BuildTicketCreatedPayload
TicketStatus $ticketStatus, TicketStatus $ticketStatus,
?User $actor, ?User $actor,
CarbonImmutable $occurredAt, CarbonImmutable $occurredAt,
): TicketStatusChangedPayload { ): TicketCreatedPayload {
return new TicketStatusChangedPayload( return new TicketCreatedPayload(
eventType: NotificationEventType::TicketCreate,
projectId: $project->id, projectId: $project->id,
projectKey: $project->key, projectKey: $project->key,
projectName: $project->name, projectName: $project->name,
@@ -29,8 +27,6 @@ class BuildTicketCreatedPayload
ticketUrl: route('projects.tickets.show', [$project, $ticket]), ticketUrl: route('projects.tickets.show', [$project, $ticket]),
actorId: $actor?->id, actorId: $actor?->id,
actorName: $actor?->name, actorName: $actor?->name,
fromStatusId: null,
fromStatusLabel: null,
toStatusId: $ticketStatus->id, toStatusId: $ticketStatus->id,
toStatusLabel: $this->statusLabel($ticketStatus), toStatusLabel: $this->statusLabel($ticketStatus),
occurredAt: $occurredAt, occurredAt: $occurredAt,
@@ -2,7 +2,6 @@
namespace App\Actions\Notifications; namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
use App\Models\Project; use App\Models\Project;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\TicketStatus; use App\Models\TicketStatus;
@@ -22,7 +21,6 @@ class BuildTicketStatusChangedPayload
CarbonImmutable $occurredAt, CarbonImmutable $occurredAt,
): TicketStatusChangedPayload { ): TicketStatusChangedPayload {
return new TicketStatusChangedPayload( return new TicketStatusChangedPayload(
eventType: NotificationEventType::TicketStatusChanged,
projectId: $project->id, projectId: $project->id,
projectKey: $project->key, projectKey: $project->key,
projectName: $project->name, projectName: $project->name,
@@ -2,6 +2,7 @@
namespace App\Actions\Notifications; namespace App\Actions\Notifications;
use App\Enums\DiscordAllowedMentionType;
use App\Enums\NotificationChannel; use App\Enums\NotificationChannel;
use App\Enums\NotificationDeliveryStatus; use App\Enums\NotificationDeliveryStatus;
use App\Models\NotificationAction; use App\Models\NotificationAction;
@@ -27,7 +28,7 @@ class DeliverNotificationAction implements ShouldQueue
public function __construct( public function __construct(
public int $notificationActionId, public int $notificationActionId,
public TicketStatusChangedPayload $payload, public NotificationEvent $event,
public ?int $notificationDeliveryLogId, public ?int $notificationDeliveryLogId,
) {} ) {}
@@ -59,7 +60,7 @@ class DeliverNotificationAction implements ShouldQueue
if ($notificationAction->channel === NotificationChannel::Discord) { if ($notificationAction->channel === NotificationChannel::Discord) {
$discordMessage = app(RenderDiscordMessageTemplate::class)->handle( $discordMessage = app(RenderDiscordMessageTemplate::class)->handle(
$notificationAction->message_template, $notificationAction->message_template,
$this->payload, $this->event,
); );
$validationError = $this->discordMessageValidationError($discordMessage); $validationError = $this->discordMessageValidationError($discordMessage);
@@ -244,7 +245,7 @@ class DeliverNotificationAction implements ShouldQueue
'attempt_count' => 0, 'attempt_count' => 0,
'channel' => $notificationAction->channel, 'channel' => $notificationAction->channel,
'delivery_status' => NotificationDeliveryStatus::Pending, 'delivery_status' => NotificationDeliveryStatus::Pending,
'event_type' => $this->payload->eventType, 'event_type' => $this->event->eventType(),
'notification_action_id' => $notificationAction->id, 'notification_action_id' => $notificationAction->id,
'payload_metadata' => $this->payloadMetadata(), 'payload_metadata' => $this->payloadMetadata(),
]); ]);
@@ -280,18 +281,60 @@ class DeliverNotificationAction implements ShouldQueue
->post($notificationAction->delivery_url, [ ->post($notificationAction->delivery_url, [
'content' => $message, 'content' => $message,
'allowed_mentions' => [ 'allowed_mentions' => [
'parse' => [], 'parse' => $this->discordAllowedMentions($notificationAction),
], ],
]); ]);
} }
/**
* @return list<string>
*/
private function discordAllowedMentions(NotificationAction $notificationAction): array
{
$configuredAllowedMentions = data_get(
$notificationAction->channel_configuration,
'allowed_mentions',
[],
);
if (! is_array($configuredAllowedMentions)) {
return [];
}
$allowedMentions = [];
foreach ($configuredAllowedMentions as $allowedMention) {
if (! is_string($allowedMention)) {
continue;
}
$allowedMention = Str::lower(trim($allowedMention));
if ($allowedMention === '') {
continue;
}
if (! in_array($allowedMention, DiscordAllowedMentionType::values(), true)) {
continue;
}
if (in_array($allowedMention, $allowedMentions, true)) {
continue;
}
$allowedMentions[] = $allowedMention;
}
return $allowedMentions;
}
private function sendWebhookRequest(NotificationAction $notificationAction): Response private function sendWebhookRequest(NotificationAction $notificationAction): Response
{ {
return Http::acceptJson() return Http::acceptJson()
->asJson() ->asJson()
->connectTimeout(5) ->connectTimeout(5)
->timeout(10) ->timeout(10)
->post($notificationAction->delivery_url, $this->payload->toArray()); ->post($notificationAction->delivery_url, $this->event->payload()->toArray());
} }
private function hasAttemptsRemaining(int $attemptCount): bool private function hasAttemptsRemaining(int $attemptCount): bool
@@ -355,14 +398,11 @@ class DeliverNotificationAction implements ShouldQueue
} }
/** /**
* @return array{project_key: string, ticket_key: string} * @return array<string, scalar|null>
*/ */
private function payloadMetadata(): array private function payloadMetadata(): array
{ {
return [ return $this->event->payload()->deliveryMetadata();
'project_key' => $this->payload->projectKey,
'ticket_key' => $this->payload->ticketKey,
];
} }
private function excerpt(?string $value): ?string private function excerpt(?string $value): ?string
@@ -10,7 +10,7 @@ class MatchNotificationFilters
/** /**
* @param array<int, array{attribute?: mixed, operator?: mixed, value?: mixed}> $filters * @param array<int, array{attribute?: mixed, operator?: mixed, value?: mixed}> $filters
*/ */
public function handle(array $filters, TicketStatusChangedPayload $payload): bool public function handle(array $filters, NotificationEventPayload $payload): bool
{ {
if ($filters === []) { if ($filters === []) {
return true; return true;
@@ -175,32 +175,46 @@ class MatchNotificationFilters
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
private function payloadContext(TicketStatusChangedPayload $payload): array private function payloadContext(NotificationEventPayload $payload): array
{ {
$projectId = property_exists($payload, 'projectId') ? $payload->projectId : $payload->projectId();
$projectKey = property_exists($payload, 'projectKey') ? $payload->projectKey : null;
$projectName = property_exists($payload, 'projectName') ? $payload->projectName : null;
$ticketId = property_exists($payload, 'ticketId') ? $payload->ticketId : null;
$ticketKey = property_exists($payload, 'ticketKey') ? $payload->ticketKey : null;
$ticketTitle = property_exists($payload, 'ticketTitle') ? $payload->ticketTitle : null;
$ticketUrl = property_exists($payload, 'ticketUrl') ? $payload->ticketUrl : null;
$actorId = property_exists($payload, 'actorId') ? $payload->actorId : null;
$actorName = property_exists($payload, 'actorName') ? $payload->actorName : null;
$fromStatusId = property_exists($payload, 'fromStatusId') ? $payload->fromStatusId : null;
$fromStatusLabel = property_exists($payload, 'fromStatusLabel') ? $payload->fromStatusLabel : null;
$toStatusId = property_exists($payload, 'toStatusId') ? $payload->toStatusId : null;
$toStatusLabel = property_exists($payload, 'toStatusLabel') ? $payload->toStatusLabel : null;
return [ return [
'project' => [ 'project' => [
'id' => $payload->projectId, 'id' => $projectId,
'key' => $payload->projectKey, 'key' => $projectKey,
'name' => $payload->projectName, 'name' => $projectName,
], ],
'ticket' => [ 'ticket' => [
'id' => $payload->ticketId, 'id' => $ticketId,
'key' => $payload->ticketKey, 'key' => $ticketKey,
'title' => $payload->ticketTitle, 'title' => $ticketTitle,
'url' => $payload->ticketUrl, 'url' => $ticketUrl,
], ],
'actor' => [ 'actor' => [
'id' => $payload->actorId, 'id' => $actorId,
'name' => $payload->actorName, 'name' => $actorName,
], ],
'status' => [ 'status' => [
'from' => [ 'from' => [
'id' => $payload->fromStatusId, 'id' => $fromStatusId,
'label' => $payload->fromStatusLabel, 'label' => $fromStatusLabel,
], ],
'to' => [ 'to' => [
'id' => $payload->toStatusId, 'id' => $toStatusId,
'label' => $payload->toStatusLabel, 'label' => $toStatusLabel,
], ],
], ],
]; ];
@@ -0,0 +1,12 @@
<?php
namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
interface NotificationEvent
{
public function eventType(): NotificationEventType;
public function payload(): NotificationEventPayload;
}
@@ -0,0 +1,23 @@
<?php
namespace App\Actions\Notifications;
use Illuminate\Contracts\Support\Arrayable;
/**
* @extends Arrayable<string, mixed>
*/
interface NotificationEventPayload extends Arrayable
{
public function projectId(): int;
/**
* @return array<string, scalar|null>
*/
public function deliveryMetadata(): array;
/**
* @return array<string, string>
*/
public function discordTemplateVariables(): array;
}
@@ -7,24 +7,26 @@ use App\Enums\NotificationDeliveryStatus;
use App\Models\NotificationAction; use App\Models\NotificationAction;
use App\Models\NotificationDeliveryLog; use App\Models\NotificationDeliveryLog;
class QueueTicketStatusChangedNotificationDeliveries class QueueNotificationEventDeliveries
{ {
public function __construct( public function __construct(
private readonly MatchNotificationFilters $matchNotificationFilters, private readonly MatchNotificationFilters $matchNotificationFilters,
) {} ) {}
public function handle(TicketStatusChanged|TicketCreated $event): void public function handle(NotificationEvent $event): void
{ {
$payload = $event->payload();
$eventType = $event->eventType();
NotificationAction::query() NotificationAction::query()
->enabled() ->enabled()
->where('project_id', $event->payload->projectId) ->where('project_id', $payload->projectId())
->where('event_type', $event->payload->eventType->value) ->where('event_type', $eventType->value)
->get(['channel', 'filters', 'id']) ->get(['channel', 'filters', 'id'])
->each(function (NotificationAction $notificationAction) use ($event): void { ->each(function (NotificationAction $notificationAction) use ($event, $payload): void {
if (! $this->matchNotificationFilters->handle($notificationAction->filters ?? [], $event->payload)) { if (! $this->matchNotificationFilters->handle($notificationAction->filters ?? [], $payload)) {
return; return;
} }
$notificationDeliveryLogId = null; $notificationDeliveryLogId = null;
if (in_array($notificationAction->channel, [NotificationChannel::Discord, NotificationChannel::Webhook], true)) { if (in_array($notificationAction->channel, [NotificationChannel::Discord, NotificationChannel::Webhook], true)) {
@@ -32,18 +34,15 @@ class QueueTicketStatusChangedNotificationDeliveries
'attempt_count' => 0, 'attempt_count' => 0,
'channel' => $notificationAction->channel, 'channel' => $notificationAction->channel,
'delivery_status' => NotificationDeliveryStatus::Pending, 'delivery_status' => NotificationDeliveryStatus::Pending,
'event_type' => $event->payload->eventType, 'event_type' => $event->eventType(),
'notification_action_id' => $notificationAction->id, 'notification_action_id' => $notificationAction->id,
'payload_metadata' => [ 'payload_metadata' => $payload->deliveryMetadata(),
'project_key' => $event->payload->projectKey,
'ticket_key' => $event->payload->ticketKey,
],
])->id; ])->id;
} }
DeliverNotificationAction::dispatch( DeliverNotificationAction::dispatch(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $event->payload, event: $event,
notificationDeliveryLogId: $notificationDeliveryLogId, notificationDeliveryLogId: $notificationDeliveryLogId,
); );
}); });
@@ -6,16 +6,8 @@ use Illuminate\Support\Str;
class RenderDiscordMessageTemplate class RenderDiscordMessageTemplate
{ {
public function handle(?string $messageTemplate, TicketStatusChangedPayload $payload): string public function handle(?string $messageTemplate, NotificationEvent $event): string
{ {
return strtr((string) Str::of((string) $messageTemplate), [ return strtr((string) Str::of((string) $messageTemplate), $event->payload()->discordTemplateVariables());
'$url' => $payload->ticketUrl,
'$ticket_key' => $payload->ticketKey,
'$ticket_title' => $payload->ticketTitle,
'$project_name' => $payload->projectName,
'$status_from' => $payload->fromStatusLabel ?? '',
'$status_to' => $payload->toStatusLabel,
'$actor_name' => $payload->actorName ?? '',
]);
} }
} }
+13 -2
View File
@@ -2,14 +2,25 @@
namespace App\Actions\Notifications; namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
final readonly class TicketCreated implements ShouldDispatchAfterCommit final readonly class TicketCreated implements NotificationEvent, ShouldDispatchAfterCommit
{ {
use Dispatchable; use Dispatchable;
public function __construct( public function __construct(
public TicketStatusChangedPayload $payload, public TicketCreatedPayload $payload,
) {} ) {}
public function eventType(): NotificationEventType
{
return NotificationEventType::TicketCreate;
}
public function payload(): NotificationEventPayload
{
return $this->payload;
}
} }
@@ -0,0 +1,105 @@
<?php
namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
use Carbon\CarbonImmutable;
final readonly class TicketCreatedPayload implements NotificationEventPayload
{
public ?int $fromStatusId;
public ?string $fromStatusLabel;
public function __construct(
public int $projectId,
public string $projectKey,
public string $projectName,
public int $ticketId,
public string $ticketKey,
public string $ticketTitle,
public string $ticketUrl,
public ?int $actorId,
public ?string $actorName,
public int $toStatusId,
public string $toStatusLabel,
public CarbonImmutable $occurredAt,
) {
$this->fromStatusId = null;
$this->fromStatusLabel = null;
}
public function projectId(): int
{
return $this->projectId;
}
/**
* @return array<string, scalar|null>
*/
public function deliveryMetadata(): array
{
return [
'project_key' => $this->projectKey,
'ticket_key' => $this->ticketKey,
];
}
/**
* @return array<string, string>
*/
public function discordTemplateVariables(): array
{
return [
'$url' => $this->ticketUrl,
'$ticket_key' => $this->ticketKey,
'$ticket_title' => $this->ticketTitle,
'$project_name' => $this->projectName,
'$status_from' => '',
'$status_to' => $this->toStatusLabel,
'$actor_name' => $this->actorName ?? '',
];
}
/**
* @return array{
* event_type: string,
* project: array{id: int, key: string, name: string},
* ticket: array{id: int, key: string, title: string},
* actor: array{id: int, name: string}|null,
* from: null,
* to: array{id: int, label: string},
* ticket_url: string,
* occurred_at: string
* }
*/
public function toArray(): array
{
return [
'event_type' => NotificationEventType::TicketCreate->value,
'project' => [
'id' => $this->projectId,
'key' => $this->projectKey,
'name' => $this->projectName,
],
'ticket' => [
'id' => $this->ticketId,
'key' => $this->ticketKey,
'title' => $this->ticketTitle,
],
'actor' => $this->actorId === null || $this->actorName === null
? null
: [
'id' => $this->actorId,
'name' => $this->actorName,
],
'from' => null,
'to' => [
'id' => $this->toStatusId,
'label' => $this->toStatusLabel,
],
'ticket_url' => $this->ticketUrl,
'occurred_at' => $this->occurredAt->toISOString(),
];
}
}
@@ -2,14 +2,25 @@
namespace App\Actions\Notifications; namespace App\Actions\Notifications;
use App\Enums\NotificationEventType;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
final readonly class TicketStatusChanged implements ShouldDispatchAfterCommit final readonly class TicketStatusChanged implements NotificationEvent, ShouldDispatchAfterCommit
{ {
use Dispatchable; use Dispatchable;
public function __construct( public function __construct(
public TicketStatusChangedPayload $payload, public TicketStatusChangedPayload $payload,
) {} ) {}
public function eventType(): NotificationEventType
{
return NotificationEventType::TicketStatusChanged;
}
public function payload(): NotificationEventPayload
{
return $this->payload;
}
} }
@@ -4,15 +4,10 @@ namespace App\Actions\Notifications;
use App\Enums\NotificationEventType; use App\Enums\NotificationEventType;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Contracts\Support\Arrayable;
/** final readonly class TicketStatusChangedPayload implements NotificationEventPayload
* @implements Arrayable<string, mixed>
*/
final readonly class TicketStatusChangedPayload implements Arrayable
{ {
public function __construct( public function __construct(
public NotificationEventType $eventType,
public int $projectId, public int $projectId,
public string $projectKey, public string $projectKey,
public string $projectName, public string $projectName,
@@ -22,20 +17,52 @@ 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,
) {} ) {}
public function projectId(): int
{
return $this->projectId;
}
/**
* @return array<string, scalar|null>
*/
public function deliveryMetadata(): array
{
return [
'project_key' => $this->projectKey,
'ticket_key' => $this->ticketKey,
];
}
/**
* @return array<string, string>
*/
public function discordTemplateVariables(): array
{
return [
'$url' => $this->ticketUrl,
'$ticket_key' => $this->ticketKey,
'$ticket_title' => $this->ticketTitle,
'$project_name' => $this->projectName,
'$status_from' => $this->fromStatusLabel,
'$status_to' => $this->toStatusLabel,
'$actor_name' => $this->actorName ?? '',
];
}
/** /**
* @return array{ * @return array{
* event_type: string, * event_type: string,
* 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}|null, * from: array{id: int, label: string},
* to: array{id: int, label: string}, * to: array{id: int, label: string},
* ticket_url: string, * ticket_url: string,
* occurred_at: string * occurred_at: string
@@ -44,7 +71,7 @@ final readonly class TicketStatusChangedPayload implements Arrayable
public function toArray(): array public function toArray(): array
{ {
return [ return [
'event_type' => $this->eventType->value, 'event_type' => NotificationEventType::TicketStatusChanged->value,
'project' => [ 'project' => [
'id' => $this->projectId, 'id' => $this->projectId,
'key' => $this->projectKey, 'key' => $this->projectKey,
@@ -61,12 +88,10 @@ final readonly class TicketStatusChangedPayload implements Arrayable
'id' => $this->actorId, 'id' => $this->actorId,
'name' => $this->actorName, 'name' => $this->actorName,
], ],
'from' => $this->fromStatusId === null || $this->fromStatusLabel === null 'from' => [
? null 'id' => $this->fromStatusId,
: [ 'label' => $this->fromStatusLabel,
'id' => $this->fromStatusId, ],
'label' => $this->fromStatusLabel,
],
'to' => [ 'to' => [
'id' => $this->toStatusId, 'id' => $this->toStatusId,
'label' => $this->toStatusLabel, 'label' => $this->toStatusLabel,
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Enums;
enum DiscordAllowedMentionType: string
{
case Everyone = 'everyone';
case Roles = 'roles';
case Users = 'users';
public function label(): string
{
return match ($this) {
self::Everyone => '@everyone and @here',
self::Roles => 'Role mentions (@role)',
self::Users => 'User mentions (@username)',
};
}
/**
* @return array<int, array{label: string, value: string}>
*/
public static function options(): array
{
return array_map(
fn (self $eventType): array => [
'label' => $eventType->label(),
'value' => $eventType->value,
],
self::cases(),
);
}
/**
* @param array<int, self>|null $discordAllowedMentionTypes
* @return array<int, string>
*/
public static function values(?array $discordAllowedMentionTypes = null): array
{
return array_map(
fn (self $discordAllowedMentionType): string => $discordAllowedMentionType->value,
$discordAllowedMentionTypes ?? self::cases(),
);
}
}
+12
View File
@@ -28,4 +28,16 @@ enum NotificationChannel: string
self::cases(), self::cases(),
); );
} }
/**
* @param array<int, self>|null $notificationChannels
* @return array<int, string>
*/
public static function values(?array $notificationChannels = null): array
{
return array_map(
fn (self $notificationChannel): string => $notificationChannel->value,
$notificationChannels ?? self::cases(),
);
}
} }
+12
View File
@@ -28,4 +28,16 @@ enum NotificationEventType: string
self::cases(), self::cases(),
); );
} }
/**
* @param array<int, self>|null $notificationEventTypes
* @return array<int, string>
*/
public static function values(?array $notificationEventTypes = null): array
{
return array_map(
fn (self $notificationEventType): string => $notificationEventType->value,
$notificationEventTypes ?? self::cases(),
);
}
} }
@@ -2,6 +2,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Enums\DiscordAllowedMentionType;
use App\Enums\NotificationChannel; use App\Enums\NotificationChannel;
use App\Enums\NotificationEventType; use App\Enums\NotificationEventType;
use App\Http\Requests\Concerns\InteractsWithNotificationFilters; use App\Http\Requests\Concerns\InteractsWithNotificationFilters;
@@ -29,10 +30,17 @@ class StoreProjectNotificationActionRequest extends FormRequest
*/ */
public function rules(): array public function rules(): array
{ {
$messageTemplateRules = $this->input('channel') === NotificationChannel::Discord->value
? ['required', 'string', 'max:2000']
: ['nullable', 'string', 'max:2000'];
return [ return [
'name' => ['required', 'string', 'max:255'], 'name' => ['required', 'string', 'max:255'],
'event_type' => ['required', 'string', Rule::in($this->eventTypes())], 'event_type' => ['required', 'string', Rule::in(NotificationEventType::values())],
'channel' => ['required', 'string', Rule::in($this->channels())], 'channel' => ['required', 'string', Rule::in(NotificationChannel::values())],
'channel_configuration' => ['nullable', 'array'],
'channel_configuration.allowed_mentions' => ['nullable', 'array'],
'channel_configuration.allowed_mentions.*' => ['nullable', 'string', Rule::in(DiscordAllowedMentionType::values())],
'enabled' => ['required', 'boolean'], 'enabled' => ['required', 'boolean'],
'delivery_url' => ['required', 'string', 'max:2048', 'url'], 'delivery_url' => ['required', 'string', 'max:2048', 'url'],
'message_template' => $this->messageTemplateRules(), 'message_template' => $this->messageTemplateRules(),
@@ -2,6 +2,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Enums\DiscordAllowedMentionType;
use App\Enums\NotificationChannel; use App\Enums\NotificationChannel;
use App\Enums\NotificationEventType; use App\Enums\NotificationEventType;
use App\Http\Requests\Concerns\InteractsWithNotificationFilters; use App\Http\Requests\Concerns\InteractsWithNotificationFilters;
@@ -29,10 +30,17 @@ class UpdateProjectNotificationActionRequest extends FormRequest
*/ */
public function rules(): array public function rules(): array
{ {
$messageTemplateRules = $this->input('channel') === NotificationChannel::Discord->value
? ['required', 'string', 'max:2000']
: ['nullable', 'string', 'max:2000'];
return [ return [
'name' => ['required', 'string', 'max:255'], 'name' => ['required', 'string', 'max:255'],
'event_type' => ['required', 'string', Rule::in($this->eventTypes())], 'event_type' => ['required', 'string', Rule::in(NotificationEventType::values())],
'channel' => ['required', 'string', Rule::in($this->channels())], 'channel' => ['required', 'string', Rule::in(NotificationChannel::values())],
'channel_configuration' => ['nullable', 'array'],
'channel_configuration.allowed_mentions' => ['nullable', 'array'],
'channel_configuration.allowed_mentions.*' => ['nullable', 'string', Rule::in(DiscordAllowedMentionType::values())],
'enabled' => ['required', 'boolean'], 'enabled' => ['required', 'boolean'],
'delivery_url' => ['nullable', 'string', 'max:2048', 'url'], 'delivery_url' => ['nullable', 'string', 'max:2048', 'url'],
'message_template' => $this->messageTemplateRules(), 'message_template' => $this->messageTemplateRules(),
+3 -3
View File
@@ -2,7 +2,7 @@
namespace App\Providers; namespace App\Providers;
use App\Actions\Notifications\QueueTicketStatusChangedNotificationDeliveries; use App\Actions\Notifications\QueueNotificationEventDeliveries;
use App\Actions\Notifications\TicketCreated; 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;
@@ -98,12 +98,12 @@ class AppServiceProvider extends ServiceProvider
{ {
Event::listen( Event::listen(
TicketStatusChanged::class, TicketStatusChanged::class,
QueueTicketStatusChangedNotificationDeliveries::class, QueueNotificationEventDeliveries::class,
); );
Event::listen( Event::listen(
TicketCreated::class, TicketCreated::class,
QueueTicketStatusChangedNotificationDeliveries::class, QueueNotificationEventDeliveries::class,
); );
} }
} }
@@ -192,6 +192,41 @@ props.notificationActions.forEach((notificationAction) => {
const selectedChannel = (notificationAction: NotificationActionModel): string => const selectedChannel = (notificationAction: NotificationActionModel): string =>
editChannelState[notificationAction.id] ?? notificationAction.channel; editChannelState[notificationAction.id] ?? notificationAction.channel;
const notificationActionAllowedMentions = (
notificationAction: NotificationActionModel,
): string[] => {
const allowedMentions =
notificationAction.channel_configuration['allowed_mentions'];
if (!Array.isArray(allowedMentions)) {
return [];
}
return allowedMentions
.filter(
(allowedMention): allowedMention is string =>
typeof allowedMention === 'string',
)
.map((allowedMention) => allowedMention.trim().toLowerCase())
.filter((allowedMention) => allowedMention !== '');
};
const allowedMentionsError = (
errors: Record<string, string>,
): string | undefined => {
const generalError = errors['channel_configuration.allowed_mentions'];
if (generalError !== undefined) {
return generalError;
}
const itemErrorKey = Object.keys(errors).find((key) =>
key.startsWith('channel_configuration.allowed_mentions.'),
);
return itemErrorKey === undefined ? undefined : errors[itemErrorKey];
};
const notificationActionTimestamp = ( const notificationActionTimestamp = (
notificationAction: NotificationActionModel, notificationAction: NotificationActionModel,
): string => { ): string => {
@@ -336,7 +371,9 @@ const notificationActionTimestamp = (
</div> </div>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="create-notification-channel"> <Label
for="create-notification-channel"
>
Channel Channel
</Label> </Label>
<select <select
@@ -358,7 +395,9 @@ const notificationActionTimestamp = (
</div> </div>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="create-notification-delivery-url"> <Label
for="create-notification-delivery-url"
>
Delivery URL Delivery URL
</Label> </Label>
<Input <Input
@@ -372,7 +411,55 @@ const notificationActionTimestamp = (
never rendered back to the browser after never rendered back to the browser after
save. save.
</p> </p>
<InputError :message="errors.delivery_url" /> <InputError
:message="errors.delivery_url"
/>
</div>
<div class="grid gap-2">
<Label>Allowed mentions</Label>
<div
:class="[
'grid gap-2',
createChannelState.value !==
'discord'
? 'hidden'
: '',
]"
>
<label
v-for="allowedMentionOption in discordAllowedMentionOptions"
:key="`create-allowed-mention-${allowedMentionOption.value}`"
class="border-border flex items-center gap-2 rounded-lg border px-3 py-2"
>
<input
type="checkbox"
name="channel_configuration[allowed_mentions][]"
:value="
allowedMentionOption.value
"
:disabled="
createChannelState.value !==
'discord'
"
class="border-input text-primary focus:ring-ring size-4 rounded"
/>
<span>
{{ allowedMentionOption.label }}
</span>
</label>
</div>
<p class="text-muted-foreground text-sm">
{{
createChannelState.value ===
'discord'
? 'Pick which Discord mention types are allowed. Leave all unchecked to keep mentions fully disabled.'
: 'Allowed mentions are only used when the channel is Discord.'
}}
</p>
<InputError
:message="allowedMentionsError(errors)"
/>
</div> </div>
<div class="grid gap-2"> <div class="grid gap-2">
@@ -661,7 +748,11 @@ const notificationActionTimestamp = (
</Badge> </Badge>
</div> </div>
<CardDescription> <CardDescription>
{{ notificationActionTimestamp(notificationAction) }} {{
notificationActionTimestamp(
notificationAction,
)
}}
</CardDescription> </CardDescription>
</div> </div>
</CardHeader> </CardHeader>
@@ -673,25 +764,19 @@ const notificationActionTimestamp = (
[project.id, notificationAction.id], [project.id, notificationAction.id],
) )
" "
:error-bag=" :error-bag="`updateNotificationAction-${notificationAction.id}`"
`updateNotificationAction-${notificationAction.id}`
"
class="space-y-4" class="space-y-4"
v-slot="{ errors, processing }" v-slot="{ errors, processing }"
> >
<div class="grid gap-4 md:grid-cols-2"> <div class="grid gap-4 md:grid-cols-2">
<div class="grid gap-2"> <div class="grid gap-2">
<Label <Label
:for=" :for="`notification-name-${notificationAction.id}`"
`notification-name-${notificationAction.id}`
"
> >
Name Name
</Label> </Label>
<Input <Input
:id=" :id="`notification-name-${notificationAction.id}`"
`notification-name-${notificationAction.id}`
"
name="name" name="name"
:default-value=" :default-value="
notificationAction.name notificationAction.name
@@ -702,16 +787,12 @@ const notificationActionTimestamp = (
<div class="grid gap-2"> <div class="grid gap-2">
<Label <Label
:for=" :for="`notification-delivery-url-${notificationAction.id}`"
`notification-delivery-url-${notificationAction.id}`
"
> >
Delivery URL Delivery URL
</Label> </Label>
<Input <Input
:id=" :id="`notification-delivery-url-${notificationAction.id}`"
`notification-delivery-url-${notificationAction.id}`
"
name="delivery_url" name="delivery_url"
type="url" type="url"
:placeholder=" :placeholder="
@@ -736,16 +817,12 @@ const notificationActionTimestamp = (
<div class="grid gap-2"> <div class="grid gap-2">
<Label <Label
:for=" :for="`notification-event-type-${notificationAction.id}`"
`notification-event-type-${notificationAction.id}`
"
> >
Event type Event type
</Label> </Label>
<select <select
:id=" :id="`notification-event-type-${notificationAction.id}`"
`notification-event-type-${notificationAction.id}`
"
name="event_type" name="event_type"
:default-value=" :default-value="
notificationAction.event_type notificationAction.event_type
@@ -767,16 +844,12 @@ const notificationActionTimestamp = (
<div class="grid gap-2"> <div class="grid gap-2">
<Label <Label
:for=" :for="`notification-channel-${notificationAction.id}`"
`notification-channel-${notificationAction.id}`
"
> >
Channel Channel
</Label> </Label>
<select <select
:id=" :id="`notification-channel-${notificationAction.id}`"
`notification-channel-${notificationAction.id}`
"
name="channel" name="channel"
v-model=" v-model="
editChannelState[ editChannelState[
@@ -797,18 +870,70 @@ const notificationActionTimestamp = (
</div> </div>
</div> </div>
<div class="grid gap-2">
<Label>Allowed mentions</Label>
<div
:class="[
'grid gap-2',
selectedChannel(
notificationAction,
) !== 'discord'
? 'hidden'
: '',
]"
>
<label
v-for="allowedMentionOption in discordAllowedMentionOptions"
:key="`notification-allowed-mention-${notificationAction.id}-${allowedMentionOption.value}`"
class="border-border flex items-center gap-2 rounded-lg border px-3 py-2"
>
<input
type="checkbox"
name="channel_configuration[allowed_mentions][]"
:value="
allowedMentionOption.value
"
:default-checked="
notificationActionAllowedMentions(
notificationAction,
).includes(
allowedMentionOption.value,
)
"
:disabled="
selectedChannel(
notificationAction,
) !== 'discord'
"
class="border-input text-primary focus:ring-ring size-4 rounded"
/>
<span>
{{ allowedMentionOption.label }}
</span>
</label>
</div>
<p class="text-muted-foreground text-sm">
{{
selectedChannel(
notificationAction,
) === 'discord'
? 'Pick which Discord mention types are allowed. Leave all unchecked to keep mentions fully disabled.'
: 'Allowed mentions are only used when the channel is Discord.'
}}
</p>
<InputError
:message="allowedMentionsError(errors)"
/>
</div>
<div class="grid gap-2"> <div class="grid gap-2">
<Label <Label
:for=" :for="`notification-message-template-${notificationAction.id}`"
`notification-message-template-${notificationAction.id}`
"
> >
Discord message template Discord message template
</Label> </Label>
<textarea <textarea
:id=" :id="`notification-message-template-${notificationAction.id}`"
`notification-message-template-${notificationAction.id}`
"
name="message_template" name="message_template"
rows="4" rows="4"
:value=" :value="
@@ -816,13 +941,15 @@ const notificationActionTimestamp = (
'' ''
" "
:disabled=" :disabled="
selectedChannel(notificationAction) !== selectedChannel(
'discord' notificationAction,
) !== 'discord'
" "
:class="[ :class="[
'border-input bg-background shadow-xs focus-visible:border-ring focus-visible:ring-ring/50 min-h-28 rounded-md border px-3 py-2 text-sm outline-none transition-[color,box-shadow] focus-visible:ring-[3px]', 'border-input bg-background shadow-xs focus-visible:border-ring focus-visible:ring-ring/50 min-h-28 rounded-md border px-3 py-2 text-sm outline-none transition-[color,box-shadow] focus-visible:ring-[3px]',
selectedChannel(notificationAction) !== selectedChannel(
'discord' notificationAction,
) !== 'discord'
? 'hidden' ? 'hidden'
: 'block', : 'block',
]" ]"
@@ -830,8 +957,9 @@ const notificationActionTimestamp = (
/> />
<p class="text-muted-foreground text-sm"> <p class="text-muted-foreground text-sm">
{{ {{
selectedChannel(notificationAction) === selectedChannel(
'discord' notificationAction,
) === 'discord'
? 'Available for Discord actions only. Use the fixed variables listed in the sidebar.' ? 'Available for Discord actions only. Use the fixed variables listed in the sidebar.'
: 'Discord message templates are only used when the channel is Discord.' : 'Discord message templates are only used when the channel is Discord.'
}} }}
@@ -999,9 +1127,7 @@ const notificationActionTimestamp = (
> >
<div class="grid gap-2"> <div class="grid gap-2">
<Label <Label
:for=" :for="`notification-enabled-${notificationAction.id}`"
`notification-enabled-${notificationAction.id}`
"
class="flex items-center gap-3" class="flex items-center gap-3"
> >
<input <input
@@ -1010,9 +1136,7 @@ const notificationActionTimestamp = (
value="0" value="0"
/> />
<input <input
:id=" :id="`notification-enabled-${notificationAction.id}`"
`notification-enabled-${notificationAction.id}`
"
type="checkbox" type="checkbox"
name="enabled" name="enabled"
value="1" value="1"
+1
View File
@@ -111,6 +111,7 @@ export type ProjectNotificationSettingsPageProps = {
eventTypeOptions: NotificationActionOptionModel[]; eventTypeOptions: NotificationActionOptionModel[];
filterAttributeOptions: NotificationActionOptionModel[]; filterAttributeOptions: NotificationActionOptionModel[];
filterOperatorOptions: NotificationActionOptionModel[]; filterOperatorOptions: NotificationActionOptionModel[];
discordAllowedMentionOptions: NotificationActionOptionModel[];
notificationActions: NotificationActionModel[]; notificationActions: NotificationActionModel[];
project: ProjectModel; project: ProjectModel;
status?: string | null; status?: string | null;
+2 -2
View File
@@ -233,8 +233,8 @@ class TicketApiTest extends TestCase
Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($notificationAction): bool { Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($notificationAction): bool {
return $job->notificationActionId === $notificationAction->id return $job->notificationActionId === $notificationAction->id
&& $job->payload->ticketKey === 'CORE-1' && $job->event->payload()->ticketKey === 'CORE-1'
&& $job->payload->toStatusLabel === 'Doing' && $job->event->payload()->toStatusLabel === 'Doing'
&& $job->notificationDeliveryLogId !== null; && $job->notificationDeliveryLogId !== null;
}); });
+2 -2
View File
@@ -359,8 +359,8 @@ class KanbanGitMcpTest extends TestCase
Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($notificationAction): bool { Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($notificationAction): bool {
return $job->notificationActionId === $notificationAction->id return $job->notificationActionId === $notificationAction->id
&& $job->payload->ticketKey === 'CORE-1' && $job->event->payload()->ticketKey === 'CORE-1'
&& $job->payload->toStatusLabel === 'Doing' && $job->event->payload()->toStatusLabel === 'Doing'
&& $job->notificationDeliveryLogId !== null; && $job->notificationDeliveryLogId !== null;
}); });
@@ -3,9 +3,9 @@
namespace Tests\Feature\Notifications; namespace Tests\Feature\Notifications;
use App\Actions\Notifications\DeliverNotificationAction; use App\Actions\Notifications\DeliverNotificationAction;
use App\Actions\Notifications\TicketStatusChanged;
use App\Actions\Notifications\TicketStatusChangedPayload; use App\Actions\Notifications\TicketStatusChangedPayload;
use App\Enums\NotificationDeliveryStatus; use App\Enums\NotificationDeliveryStatus;
use App\Enums\NotificationEventType;
use App\Models\NotificationAction; use App\Models\NotificationAction;
use App\Models\NotificationDeliveryLog; use App\Models\NotificationDeliveryLog;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
@@ -35,7 +35,7 @@ class DeliverNotificationActionTest extends TestCase
(new DeliverNotificationAction( (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->handle(); ))->handle();
@@ -77,7 +77,7 @@ class DeliverNotificationActionTest extends TestCase
(new DeliverNotificationAction( (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->handle(); ))->handle();
@@ -106,6 +106,44 @@ class DeliverNotificationActionTest extends TestCase
$this->assertNotNull($deliveryLog->delivered_at); $this->assertNotNull($deliveryLog->delivered_at);
} }
/**
* Ensure Discord deliveries include configured allowed mention parse values.
*/
public function test_discord_delivery_includes_configured_allowed_mentions(): void
{
Http::preventStrayRequests();
Http::fake([
'https://discord.com/api/webhooks/123456/discord-alerts' => Http::response('', 204),
]);
$notificationAction = NotificationAction::factory()->discord()->create([
'delivery_url' => 'https://discord.com/api/webhooks/123456/discord-alerts',
'channel_configuration' => [
'allowed_mentions' => ['users', 'roles', 'users', 'EVERYONE', 'invalid'],
],
'message_template' => '$ticket_key moved to $status_to',
]);
$deliveryLog = $this->createPendingDeliveryLog($notificationAction);
(new DeliverNotificationAction(
notificationActionId: $notificationAction->id,
event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id,
))->handle();
Http::assertSentCount(1);
Http::assertSent(function (Request $request): bool {
return $request->method() === 'POST'
&& $request->url() === 'https://discord.com/api/webhooks/123456/discord-alerts'
&& $request->data() === [
'content' => 'CORE-42 moved to Doing',
'allowed_mentions' => [
'parse' => ['users', 'roles', 'everyone'],
],
];
});
}
/** /**
* Ensure retryable webhook responses release the job and update the delivery log. * Ensure retryable webhook responses release the job and update the delivery log.
*/ */
@@ -124,7 +162,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -162,7 +200,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -199,7 +237,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -236,7 +274,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -272,7 +310,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -311,7 +349,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -347,7 +385,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -375,7 +413,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(actorName: null), event: $this->event(actorName: null),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -407,7 +445,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(ticketTitle: str_repeat('A', 2001)), event: $this->event(ticketTitle: str_repeat('A', 2001)),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -444,7 +482,7 @@ class DeliverNotificationActionTest extends TestCase
$deliveryLog = $this->createPendingDeliveryLog($notificationAction); $deliveryLog = $this->createPendingDeliveryLog($notificationAction);
$job = (new DeliverNotificationAction( $job = (new DeliverNotificationAction(
notificationActionId: $notificationAction->id, notificationActionId: $notificationAction->id,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: $deliveryLog->id, notificationDeliveryLogId: $deliveryLog->id,
))->withFakeQueueInteractions(); ))->withFakeQueueInteractions();
@@ -470,7 +508,7 @@ class DeliverNotificationActionTest extends TestCase
{ {
$job = new DeliverNotificationAction( $job = new DeliverNotificationAction(
notificationActionId: 1, notificationActionId: 1,
payload: $this->payload(), event: $this->event(),
notificationDeliveryLogId: 1, notificationDeliveryLogId: 1,
); );
@@ -492,12 +530,11 @@ class DeliverNotificationActionTest extends TestCase
]); ]);
} }
private function payload( private function event(
?string $actorName = 'Erica Example', ?string $actorName = 'Erica Example',
string $ticketTitle = 'Fix webhook delivery', string $ticketTitle = 'Fix webhook delivery',
): TicketStatusChangedPayload { ): TicketStatusChanged {
return new TicketStatusChangedPayload( return new TicketStatusChanged(new TicketStatusChangedPayload(
eventType: NotificationEventType::TicketStatusChanged,
projectId: 10, projectId: 10,
projectKey: 'CORE', projectKey: 'CORE',
projectName: 'Core Platform', projectName: 'Core Platform',
@@ -512,7 +549,7 @@ class DeliverNotificationActionTest extends TestCase
toStatusId: 2, toStatusId: 2,
toStatusLabel: 'Doing', toStatusLabel: 'Doing',
occurredAt: CarbonImmutable::parse('2026-04-24T09:15:30+00:00'), occurredAt: CarbonImmutable::parse('2026-04-24T09:15:30+00:00'),
); ));
} }
/** /**
@@ -3,8 +3,8 @@
namespace Tests\Feature\Notifications; namespace Tests\Feature\Notifications;
use App\Actions\Notifications\RenderDiscordMessageTemplate; use App\Actions\Notifications\RenderDiscordMessageTemplate;
use App\Actions\Notifications\TicketStatusChanged;
use App\Actions\Notifications\TicketStatusChangedPayload; use App\Actions\Notifications\TicketStatusChangedPayload;
use App\Enums\NotificationEventType;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase; use Tests\TestCase;
@@ -54,7 +54,7 @@ class RenderDiscordMessageTemplateTest extends TestCase
#[DataProvider('supportedVariableProvider')] #[DataProvider('supportedVariableProvider')]
public function test_it_replaces_supported_template_variables(string $template, string $expected): void public function test_it_replaces_supported_template_variables(string $template, string $expected): void
{ {
$renderedMessage = app(RenderDiscordMessageTemplate::class)->handle($template, $this->payload()); $renderedMessage = app(RenderDiscordMessageTemplate::class)->handle($template, $this->event());
$this->assertSame($expected, $renderedMessage); $this->assertSame($expected, $renderedMessage);
} }
@@ -66,16 +66,15 @@ class RenderDiscordMessageTemplateTest extends TestCase
{ {
$renderedMessage = app(RenderDiscordMessageTemplate::class)->handle( $renderedMessage = app(RenderDiscordMessageTemplate::class)->handle(
'[$ticket_key] $unknown moved to $status_to', '[$ticket_key] $unknown moved to $status_to',
$this->payload(), $this->event(),
); );
$this->assertSame('[CORE-42] $unknown moved to Doing', $renderedMessage); $this->assertSame('[CORE-42] $unknown moved to Doing', $renderedMessage);
} }
private function payload(): TicketStatusChangedPayload private function event(): TicketStatusChanged
{ {
return new TicketStatusChangedPayload( return new TicketStatusChanged(new TicketStatusChangedPayload(
eventType: NotificationEventType::TicketStatusChanged,
projectId: 10, projectId: 10,
projectKey: 'CORE', projectKey: 'CORE',
projectName: 'Core Platform', projectName: 'Core Platform',
@@ -90,6 +89,6 @@ class RenderDiscordMessageTemplateTest extends TestCase
toStatusId: 2, toStatusId: 2,
toStatusLabel: 'Doing', toStatusLabel: 'Doing',
occurredAt: CarbonImmutable::parse('2026-04-24T09:15:30+00:00'), occurredAt: CarbonImmutable::parse('2026-04-24T09:15:30+00:00'),
); ));
} }
} }
@@ -131,27 +131,27 @@ class TicketCreatedNotificationDispatchTest extends TestCase
Queue::assertPushed(DeliverNotificationAction::class, 3); Queue::assertPushed(DeliverNotificationAction::class, 3);
Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($webhookAction, $project, $ticket, $user, $backlogStatus): bool { Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($webhookAction, $project, $ticket, $user, $backlogStatus): bool {
return $job->notificationActionId === $webhookAction->id return $job->notificationActionId === $webhookAction->id
&& $job->payload->projectId === $project->id && $job->event->payload()->projectId === $project->id
&& $job->payload->projectKey === 'CORE' && $job->event->payload()->projectKey === 'CORE'
&& $job->payload->projectName === 'Core Platform' && $job->event->payload()->projectName === 'Core Platform'
&& $job->payload->ticketId === $ticket->id && $job->event->payload()->ticketId === $ticket->id
&& $job->payload->ticketKey === $ticket->ticket_key && $job->event->payload()->ticketKey === $ticket->ticket_key
&& $job->payload->ticketTitle === 'Trigger ticket created notification' && $job->event->payload()->ticketTitle === 'Trigger ticket created notification'
&& $job->payload->ticketUrl === route('projects.tickets.show', [$project, $ticket]) && $job->event->payload()->ticketUrl === route('projects.tickets.show', [$project, $ticket])
&& $job->payload->actorId === $user->id && $job->event->payload()->actorId === $user->id
&& $job->payload->actorName === 'Erica Example' && $job->event->payload()->actorName === 'Erica Example'
&& $job->payload->fromStatusId === null && $job->event->payload()->fromStatusId === null
&& $job->payload->fromStatusLabel === null && $job->event->payload()->fromStatusLabel === null
&& $job->payload->toStatusId === $backlogStatus->id && $job->event->payload()->toStatusId === $backlogStatus->id
&& $job->payload->toStatusLabel === 'Backlog' && $job->event->payload()->toStatusLabel === 'Backlog'
&& $job->payload->eventType === NotificationEventType::TicketCreate && $job->event->eventType() === NotificationEventType::TicketCreate
&& $job->notificationDeliveryLogId !== null; && $job->notificationDeliveryLogId !== null;
}); });
Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $discordAction->id Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $discordAction->id
&& $job->payload->eventType === NotificationEventType::TicketCreate && $job->event->eventType() === NotificationEventType::TicketCreate
&& $job->notificationDeliveryLogId !== null); && $job->notificationDeliveryLogId !== null);
Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $filterNotExistsAction->id Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $filterNotExistsAction->id
&& $job->payload->eventType === NotificationEventType::TicketCreate && $job->event->eventType() === NotificationEventType::TicketCreate
&& $job->notificationDeliveryLogId !== null); && $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 === $disabledAction->id);
Queue::assertNotPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $statusChangedAction->id); Queue::assertNotPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $statusChangedAction->id);
@@ -147,7 +147,7 @@ class TicketStatusChangedNotificationDispatchTest extends TestCase
'project_id' => $project->id, 'project_id' => $project->id,
'name' => 'Wrong event', 'name' => 'Wrong event',
'enabled' => true, 'enabled' => true,
'event_type' => 'ticket_created', 'event_type' => NotificationEventType::TicketCreate->value,
'channel' => NotificationChannel::Webhook->value, 'channel' => NotificationChannel::Webhook->value,
'channel_configuration' => json_encode([]), 'channel_configuration' => json_encode([]),
'message_template' => null, 'message_template' => null,
@@ -169,20 +169,20 @@ class TicketStatusChangedNotificationDispatchTest extends TestCase
Queue::assertPushed(DeliverNotificationAction::class, 5); Queue::assertPushed(DeliverNotificationAction::class, 5);
Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($webhookAction, $project, $ticket, $user, $backlogStatus, $doingStatus): bool { Queue::assertPushed(DeliverNotificationAction::class, function (DeliverNotificationAction $job) use ($webhookAction, $project, $ticket, $user, $backlogStatus, $doingStatus): bool {
return $job->notificationActionId === $webhookAction->id return $job->notificationActionId === $webhookAction->id
&& $job->payload->projectId === $project->id && $job->event->payload()->projectId === $project->id
&& $job->payload->projectKey === 'CORE' && $job->event->payload()->projectKey === 'CORE'
&& $job->payload->projectName === 'Core Platform' && $job->event->payload()->projectName === 'Core Platform'
&& $job->payload->ticketId === $ticket->id && $job->event->payload()->ticketId === $ticket->id
&& $job->payload->ticketKey === 'CORE-1' && $job->event->payload()->ticketKey === 'CORE-1'
&& $job->payload->ticketTitle === 'Fix webhook dispatch' && $job->event->payload()->ticketTitle === 'Fix webhook dispatch'
&& $job->payload->ticketUrl === route('projects.tickets.show', [$project, $ticket]) && $job->event->payload()->ticketUrl === route('projects.tickets.show', [$project, $ticket])
&& $job->payload->actorId === $user->id && $job->event->payload()->actorId === $user->id
&& $job->payload->actorName === 'Erica Example' && $job->event->payload()->actorName === 'Erica Example'
&& $job->payload->fromStatusId === $backlogStatus->id && $job->event->payload()->fromStatusId === $backlogStatus->id
&& $job->payload->fromStatusLabel === 'Backlog' && $job->event->payload()->fromStatusLabel === 'Backlog'
&& $job->payload->toStatusId === $doingStatus->id && $job->event->payload()->toStatusId === $doingStatus->id
&& $job->payload->toStatusLabel === 'Doing' && $job->event->payload()->toStatusLabel === 'Doing'
&& $job->payload->eventType === NotificationEventType::TicketStatusChanged && $job->event->eventType() === NotificationEventType::TicketStatusChanged
&& $job->notificationDeliveryLogId !== null; && $job->notificationDeliveryLogId !== null;
}); });
Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $discordAction->id Queue::assertPushed(DeliverNotificationAction::class, fn (DeliverNotificationAction $job): bool => $job->notificationActionId === $discordAction->id
@@ -36,6 +36,9 @@ class ProjectNotificationSettingsControllerTest extends TestCase
'value' => 'Doing', 'value' => 'Doing',
], ],
], ],
'channel_configuration' => [
'allowed_mentions' => ['users', 'roles'],
],
]); ]);
$this->syncProjectPermissions($project, $user, ['edit']); $this->syncProjectPermissions($project, $user, ['edit']);
@@ -48,6 +51,8 @@ class ProjectNotificationSettingsControllerTest extends TestCase
->where('project.id', $project->id) ->where('project.id', $project->id)
->where('notificationActions.0.name', 'Discord alerts') ->where('notificationActions.0.name', 'Discord alerts')
->where('notificationActions.0.channel', NotificationChannel::Discord->value) ->where('notificationActions.0.channel', NotificationChannel::Discord->value)
->where('notificationActions.0.channel_configuration.allowed_mentions.0', 'users')
->where('notificationActions.0.channel_configuration.allowed_mentions.1', 'roles')
->where('notificationActions.0.event_type', NotificationEventType::TicketStatusChanged->value) ->where('notificationActions.0.event_type', NotificationEventType::TicketStatusChanged->value)
->where('notificationActions.0.enabled', true) ->where('notificationActions.0.enabled', true)
->where('notificationActions.0.has_delivery_url', true) ->where('notificationActions.0.has_delivery_url', true)
@@ -58,6 +63,8 @@ class ProjectNotificationSettingsControllerTest extends TestCase
->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('eventTypeOptions.1.value', NotificationEventType::TicketCreate->value)
->where('discordAllowedMentionOptions.0.value', 'everyone')
->where('discordAllowedMentionOptions.2.value', 'users')
->where('filterAttributeOptions.0.value', 'project.id') ->where('filterAttributeOptions.0.value', 'project.id')
->where('filterOperatorOptions.0.value', 'equals') ->where('filterOperatorOptions.0.value', 'equals')
->where('templateVariables.0.value', '$url') ->where('templateVariables.0.value', '$url')
@@ -96,6 +103,9 @@ class ProjectNotificationSettingsControllerTest extends TestCase
'name' => 'Discord alerts', 'name' => 'Discord alerts',
'event_type' => NotificationEventType::TicketStatusChanged->value, 'event_type' => NotificationEventType::TicketStatusChanged->value,
'channel' => NotificationChannel::Discord->value, 'channel' => NotificationChannel::Discord->value,
'channel_configuration' => [
'allowed_mentions' => ['users', 'roles'],
],
'enabled' => '1', 'enabled' => '1',
'delivery_url' => 'https://discord.com/api/webhooks/123456/discord-alerts', 'delivery_url' => 'https://discord.com/api/webhooks/123456/discord-alerts',
'filters' => json_encode([ 'filters' => json_encode([
@@ -115,6 +125,10 @@ class ProjectNotificationSettingsControllerTest extends TestCase
$this->assertSame($project->id, $notificationAction->project_id); $this->assertSame($project->id, $notificationAction->project_id);
$this->assertSame(NotificationChannel::Discord, $notificationAction->channel); $this->assertSame(NotificationChannel::Discord, $notificationAction->channel);
$this->assertSame(NotificationEventType::TicketStatusChanged, $notificationAction->event_type); $this->assertSame(NotificationEventType::TicketStatusChanged, $notificationAction->event_type);
$this->assertSame(
['allowed_mentions' => ['users', 'roles']],
$notificationAction->channel_configuration,
);
$this->assertTrue($notificationAction->enabled); $this->assertTrue($notificationAction->enabled);
$this->assertSame( $this->assertSame(
'https://discord.com/api/webhooks/123456/discord-alerts', 'https://discord.com/api/webhooks/123456/discord-alerts',
@@ -151,6 +165,9 @@ class ProjectNotificationSettingsControllerTest extends TestCase
'name' => 'Ops escalation alerts', 'name' => 'Ops escalation alerts',
'event_type' => NotificationEventType::TicketStatusChanged->value, 'event_type' => NotificationEventType::TicketStatusChanged->value,
'channel' => NotificationChannel::Discord->value, 'channel' => NotificationChannel::Discord->value,
'channel_configuration' => [
'allowed_mentions' => ['users', 'everyone'],
],
'enabled' => '1', 'enabled' => '1',
'delivery_url' => '', 'delivery_url' => '',
'filters' => json_encode([ 'filters' => json_encode([
@@ -179,6 +196,17 @@ class ProjectNotificationSettingsControllerTest extends TestCase
'value' => ['CORE-1', 'CORE-2'], 'value' => ['CORE-1', 'CORE-2'],
], ],
], $notificationAction->filters); ], $notificationAction->filters);
$this->assertSame(
['allowed_mentions' => ['users', 'everyone']],
$notificationAction->channel_configuration,
);
$this->assertSame([
[
'attribute' => 'ticket.key',
'operator' => 'in',
'value' => ['CORE-1', 'CORE-2'],
],
], $notificationAction->filters);
$this->assertSame('$ticket_key moved to $status_to: $url', $notificationAction->message_template); $this->assertSame('$ticket_key moved to $status_to: $url', $notificationAction->message_template);
} }
@@ -305,6 +333,9 @@ class ProjectNotificationSettingsControllerTest extends TestCase
'value' => [], 'value' => [],
], ],
], JSON_THROW_ON_ERROR), ], JSON_THROW_ON_ERROR),
'channel_configuration' => [
'allowed_mentions' => ['not-valid'],
],
'message_template' => '', 'message_template' => '',
]) ])
->assertRedirect(route('projects.settings.notifications', $project)) ->assertRedirect(route('projects.settings.notifications', $project))
@@ -314,6 +345,9 @@ class ProjectNotificationSettingsControllerTest extends TestCase
'enabled', 'enabled',
'delivery_url', 'delivery_url',
'filters.0.value', 'filters.0.value',
'channel_configuration.allowed_mentions.0',
'channel_configuration.allowed_mentions.0',
'filters.0.value',
'message_template', 'message_template',
]); ]);
} }