feat(KAN-45): rebuild project notification settings
CI/CD / preconditions (pull_request) Canceled after 0s
CI/CD / test_and_check_app (pull_request) Canceled after 0s
CI/CD / Publish immutable image (pull_request) Canceled after 0s

This commit is contained in:
2026-09-16 09:32:05 +02:00
parent b2789b4670
commit 538b17b9b8
11 changed files with 1752 additions and 1190 deletions
@@ -0,0 +1,632 @@
<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { computed, watch } from 'vue';
import {
destroy,
store,
update,
} from '@/actions/App/Http/Controllers/ProjectNotificationSettingsController';
import FormFeedback from '@/components/FormFeedback.vue';
import InputError from '@/components/InputError.vue';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useFormProtection } from '@/composables/useFormProtection';
import { notificationLabel } from '@/lib/notification-labels';
import { useLocalization } from '@/composables/useLocalization';
import {
serializeNotificationFilters,
supportsFilterValue,
} from '@/lib/notification-filters';
import type { ProjectNotificationSettingsPageProps } from '@/types';
import type {
NotificationEditorTarget,
NotificationFilterFormState,
} from '@/types/project-notifications';
const props = defineProps<{
target: NotificationEditorTarget | null;
settings: ProjectNotificationSettingsPageProps;
}>();
const emit = defineEmits<{ close: [] }>();
const { t } = useLocalization();
const form = useForm({
name: '',
event_type: '',
channel: '',
enabled: true,
delivery_url: '',
message_template: '',
allowed_mentions: [] as string[],
filters: [] as NotificationFilterFormState[],
});
const protection = useFormProtection(form, {
isDirty: () => props.target !== null && form.isDirty,
});
const deleting = computed(() => props.target?.action === 'delete');
const title = computed(() =>
t(
deleting.value
? 'notifications.delete'
: props.target?.action === 'edit'
? 'notifications.edit'
: 'notifications.create',
),
);
const inputClass =
'border-input bg-background focus-visible:ring-ring min-h-11 w-full min-w-0 rounded-md border px-3 py-2 text-sm focus-visible:ring-2';
let nextFilterId = 0;
watch(
() => props.target,
(target) => {
if (!target) {
return;
}
const entry = target.entry;
const mentions = entry?.channel_configuration.allowed_mentions;
form.defaults({
name: entry?.name ?? '',
event_type:
entry?.event_type ??
props.settings.eventTypeOptions[0]?.value ??
'',
channel:
entry?.channel ??
props.settings.channelOptions.find(
(option) => option.value === 'webhook',
)?.value ??
props.settings.channelOptions[0]?.value ??
'',
enabled: entry?.enabled ?? true,
delivery_url: '',
message_template: entry?.message_template ?? '',
allowed_mentions: Array.isArray(mentions)
? mentions.filter(
(value): value is string => typeof value === 'string',
)
: [],
filters: (entry?.filters ?? []).map((filter) => ({
id: nextFilterId++,
attribute: filter.attribute,
operator: filter.operator,
value: Array.isArray(filter.value)
? filter.value.join(', ')
: (filter.value ?? ''),
})),
});
form.resetAndClearErrors();
protection.clearFeedback();
},
{ immediate: true },
);
function close(open: boolean): void {
if (open || form.processing || !protection.confirmLeave()) {
return;
}
form.resetAndClearErrors();
protection.clearFeedback();
emit('close');
}
function addFilter(): void {
form.filters.push({
id: nextFilterId++,
attribute: props.settings.filterAttributeOptions[0]?.value ?? '',
operator: 'equals',
value: '',
});
}
function removeFilter(index: number): void {
form.filters.splice(index, 1);
form.clearErrors(
...(Object.keys(form.errors).filter((key) =>
key.startsWith('filters'),
) as (keyof typeof form.errors)[]),
);
}
function errorFor(prefix: string): string | undefined {
return Object.entries(form.errors).find(
([key]) => key === prefix || key.startsWith(`${prefix}.`),
)?.[1];
}
function submit(): void {
const target = props.target;
if (!target || form.processing) {
return;
}
const project = props.settings.project.id;
const route =
target.action === 'create'
? store(project)
: target.action === 'edit'
? update([project, target.entry.id])
: destroy([project, target.entry.id]);
form.transform((data) =>
deleting.value
? {}
: {
name: data.name,
event_type: data.event_type,
channel: data.channel,
enabled: data.enabled,
delivery_url: data.delivery_url || null,
channel_configuration:
data.channel === 'discord'
? { allowed_mentions: data.allowed_mentions }
: {},
message_template:
data.channel === 'discord' ? data.message_template : null,
filters: serializeNotificationFilters(data.filters),
},
);
protection.submit(route, {
preserveScroll: true,
onSuccess: () => {
form.resetAndClearErrors();
emit('close');
},
});
}
</script>
<template>
<Dialog :open="target !== null" @update:open="close">
<DialogContent
class="sm:max-w-2xl"
:show-close-button="!form.processing"
@escape-key-down="form.processing && $event.preventDefault()"
@interact-outside="form.processing && $event.preventDefault()"
>
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
<DialogDescription>{{
deleting
? t('notifications.deleteHelp', {
name: target?.entry?.name ?? '',
})
: t('notifications.editorHelp')
}}</DialogDescription>
</DialogHeader>
<form
class="grid min-w-0 gap-5"
:aria-busy="form.processing"
@submit.prevent="submit"
>
<FormFeedback :state="protection.state.value" @retry="submit" />
<fieldset
v-if="!deleting"
:disabled="form.processing"
class="grid min-w-0 gap-5"
>
<div class="grid gap-2">
<Label for="notification-name">{{
t('notifications.name')
}}</Label>
<Input
id="notification-name"
v-model="form.name"
name="name"
required
maxlength="255"
:aria-invalid="!!form.errors.name"
aria-describedby="notification-name-error"
/>
<InputError
id="notification-name-error"
:message="form.errors.name"
/>
</div>
<div class="grid min-w-0 gap-4 sm:grid-cols-2">
<div class="grid min-w-0 gap-2">
<Label for="notification-event">{{
t('notifications.event')
}}</Label>
<select
id="notification-event"
v-model="form.event_type"
name="event_type"
:class="inputClass"
:aria-invalid="!!form.errors.event_type"
aria-describedby="notification-event-error"
>
<option
v-for="option in settings.eventTypeOptions"
:key="option.value"
:value="option.value"
>
{{
notificationLabel(
t,
'event',
option.value,
option.label,
)
}}
</option>
</select>
<InputError
id="notification-event-error"
:message="form.errors.event_type"
/>
</div>
<div class="grid min-w-0 gap-2">
<Label for="notification-channel">{{
t('notifications.channel')
}}</Label>
<select
id="notification-channel"
v-model="form.channel"
name="channel"
:class="inputClass"
:aria-invalid="!!form.errors.channel"
aria-describedby="notification-channel-error"
>
<option
v-for="option in settings.channelOptions"
:key="option.value"
:value="option.value"
>
{{
notificationLabel(
t,
'channel',
option.value,
option.label,
)
}}
</option>
</select>
<InputError
id="notification-channel-error"
:message="form.errors.channel"
/>
</div>
</div>
<section
class="bg-muted/25 grid min-w-0 gap-3 rounded-lg border p-4"
aria-labelledby="notification-delivery-title"
>
<h3
id="notification-delivery-title"
class="font-semibold"
>
{{ t('notifications.delivery') }}
</h3>
<p v-if="target?.action === 'edit'" class="text-sm">
{{
t(
target.entry.has_delivery_url
? 'notifications.keepUrl'
: 'notifications.urlMissing',
)
}}
</p>
<Label for="notification-url">{{
t(
target?.action === 'edit'
? 'notifications.replaceUrl'
: 'notifications.url',
)
}}</Label>
<Input
id="notification-url"
v-model="form.delivery_url"
name="delivery_url"
type="password"
autocomplete="new-password"
:spellcheck="false"
:required="target?.action === 'create'"
maxlength="2048"
:aria-invalid="!!form.errors.delivery_url"
aria-describedby="notification-url-help notification-url-error"
/>
<p
id="notification-url-help"
class="text-caption text-muted-foreground"
>
{{ t('notifications.secretHelp') }}
</p>
<InputError
id="notification-url-error"
:message="form.errors.delivery_url"
/>
</section>
<section
v-if="form.channel === 'discord'"
class="grid min-w-0 gap-4"
aria-labelledby="notification-message-title"
>
<div class="grid gap-2">
<Label
id="notification-message-title"
for="notification-message"
>{{ t('notifications.message') }}</Label
>
<textarea
id="notification-message"
v-model="form.message_template"
name="message_template"
rows="4"
required
maxlength="2000"
:class="inputClass"
:aria-invalid="!!form.errors.message_template"
aria-describedby="notification-message-help notification-message-error"
/>
<p
id="notification-message-help"
class="text-caption text-muted-foreground"
>
{{ t('notifications.messageHelp') }}
</p>
<InputError
id="notification-message-error"
:message="form.errors.message_template"
/>
</div>
<details class="rounded-lg border p-3">
<summary
class="focus-visible:ring-ring cursor-pointer rounded font-medium focus-visible:ring-2"
>
{{ t('notifications.variables') }}
</summary>
<dl class="mt-3 grid min-w-0 gap-3 text-sm">
<div
v-for="variable in settings.templateVariables"
:key="variable.value"
class="grid min-w-0 gap-1"
>
<dt class="break-all font-mono">
{{ variable.value }}
</dt>
<dd class="text-muted-foreground">
{{
notificationLabel(
t,
'variable',
variable.value.slice(1),
variable.description,
)
}}
</dd>
</div>
</dl>
</details>
<fieldset
class="grid gap-2"
aria-describedby="notification-mentions-help notification-mentions-error"
>
<legend class="mb-2 text-sm font-medium">
{{ t('notifications.mentions') }}
</legend>
<label
v-for="option in settings.discordAllowedMentionOptions"
:key="option.value"
class="flex min-h-11 items-center gap-3 rounded-lg border px-3 py-2 text-sm"
>
<input
v-model="form.allowed_mentions"
type="checkbox"
:value="option.value"
:aria-invalid="
!!errorFor('channel_configuration')
"
class="accent-primary size-4"
/>{{
notificationLabel(
t,
'mention',
option.value,
option.label,
)
}}
</label>
<p
id="notification-mentions-help"
class="text-caption text-muted-foreground"
>
{{ t('notifications.mentionsHelp') }}
</p>
<InputError
id="notification-mentions-error"
:message="errorFor('channel_configuration')"
/>
</fieldset>
</section>
<section
class="grid min-w-0 gap-3 border-t pt-4"
aria-labelledby="notification-filters-title"
>
<h3
id="notification-filters-title"
class="font-semibold"
>
{{ t('notifications.filters') }}
</h3>
<p class="text-caption text-muted-foreground">
{{ t('notifications.filtersHelp') }}
</p>
<p v-if="!form.filters.length" class="text-sm">
{{ t('notifications.noFilters') }}
</p>
<fieldset
v-for="(filter, index) in form.filters"
:key="filter.id"
class="bg-muted/25 grid min-w-0 gap-3 rounded-lg border p-3"
>
<legend class="px-1 text-sm font-medium">
{{
t('notifications.filterNumber', {
number: index + 1,
})
}}
</legend>
<div class="grid min-w-0 gap-3 sm:grid-cols-2">
<div class="grid min-w-0 gap-2">
<Label
:for="`filter-attribute-${filter.id}`"
>{{
t('notifications.attribute')
}}</Label
>
<select
:id="`filter-attribute-${filter.id}`"
v-model="filter.attribute"
:class="inputClass"
:aria-invalid="
!!errorFor(`filters.${index}`)
"
:aria-describedby="`filter-error-${filter.id}`"
>
<option
v-for="option in settings.filterAttributeOptions"
:key="option.value"
:value="option.value"
>
{{
notificationLabel(
t,
'attribute',
option.value,
option.label,
)
}}
</option>
</select>
</div>
<div class="grid min-w-0 gap-2">
<Label
:for="`filter-operator-${filter.id}`"
>{{
t('notifications.operator')
}}</Label
>
<select
:id="`filter-operator-${filter.id}`"
v-model="filter.operator"
:class="inputClass"
:aria-invalid="
!!errorFor(`filters.${index}`)
"
:aria-describedby="`filter-error-${filter.id}`"
>
<option
v-for="option in settings.filterOperatorOptions"
:key="option.value"
:value="option.value"
>
{{
notificationLabel(
t,
'operator',
option.value,
option.label,
)
}}
</option>
</select>
</div>
</div>
<div
v-if="supportsFilterValue(filter.operator)"
class="grid gap-2"
>
<Label :for="`filter-value-${filter.id}`">{{
t(
filter.operator === 'in'
? 'notifications.values'
: 'notifications.value',
)
}}</Label>
<textarea
:id="`filter-value-${filter.id}`"
v-model="filter.value"
rows="2"
:class="inputClass"
:aria-invalid="
!!errorFor(`filters.${index}`)
"
:aria-describedby="`filter-error-${filter.id}`"
/>
</div>
<InputError
:id="`filter-error-${filter.id}`"
:message="errorFor(`filters.${index}`)"
/>
<Button
type="button"
variant="outline"
class="justify-self-end"
:aria-label="
t('notifications.removeFilterNumber', {
number: index + 1,
})
"
@click="removeFilter(index)"
>{{ t('notifications.removeFilter') }}</Button
>
</fieldset>
<InputError :message="form.errors.filters" />
<Button
type="button"
variant="outline"
class="justify-self-start"
@click="addFilter"
>{{ t('notifications.addFilter') }}</Button
>
</section>
<div class="grid gap-2 border-t pt-4">
<Label
for="notification-enabled"
class="flex min-h-11 items-center gap-3"
><Checkbox
id="notification-enabled"
v-model="form.enabled"
:invalid="!!form.errors.enabled"
aria-describedby="notification-enabled-help notification-enabled-error"
/>{{ t('notifications.enabled') }}</Label
>
<p
id="notification-enabled-help"
class="text-caption text-muted-foreground"
>
{{ t('notifications.enabledHelp') }}
</p>
<InputError
id="notification-enabled-error"
:message="form.errors.enabled"
/>
</div>
</fieldset>
<InputError v-else :message="errorFor('notificationAction')" />
<DialogFooter>
<Button
type="button"
variant="outline"
:disabled="form.processing"
@click="close(false)"
>{{ t('common.cancel') }}</Button
>
<Button
type="submit"
:variant="deleting ? 'destructive' : 'default'"
:loading="form.processing"
>{{
deleting
? t('notifications.confirmDelete')
: t('common.save')
}}</Button
>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>
+23
View File
@@ -0,0 +1,23 @@
import type { NotificationActionFilterModel } from '@/types/models/notification-action-filter-model';
import type { NotificationFilterFormState } from '@/types/project-notifications';
export const supportsFilterValue = (operator: string): boolean =>
!['exists', 'not_exists'].includes(operator);
export function serializeNotificationFilters(
filters: NotificationFilterFormState[],
): NotificationActionFilterModel[] {
return filters.map(({ attribute, operator, value }) => ({
attribute,
operator,
value:
operator === 'in'
? value
.split(/[\n,]/)
.map((entry) => entry.trim())
.filter(Boolean)
: supportsFilterValue(operator)
? value.trim()
: null,
}));
}
+13
View File
@@ -0,0 +1,13 @@
import type { Localization } from '@/lib/localization';
import { en } from '@/locales/en';
import type { TranslationKey } from '@/types/localization';
export function notificationLabel(
t: Localization['t'],
group: string,
value: string,
fallback: string,
): string {
const key = `notifications.${group}.${value}`;
return Object.hasOwn(en, key) ? t(key as TranslationKey) : fallback;
}
+109
View File
@@ -1,4 +1,113 @@
export const en = {
'notifications.title': 'Notifications',
'notifications.pageTitle': '{project} · Notifications',
'notifications.description':
'Send ticket updates to your team with webhook and Discord actions.',
'notifications.saved': 'Notification settings saved.',
'notifications.actions': 'Notification actions',
'notifications.create': 'Add notification',
'notifications.edit': 'Edit notification',
'notifications.delete': 'Delete notification?',
'notifications.editNamed': 'Edit {name}',
'notifications.deleteNamed': 'Delete {name}',
'notifications.empty': 'No notifications yet',
'notifications.emptyHelp':
'Add an action to send updates when a ticket event matches your rules.',
'notifications.enabled': 'Enabled',
'notifications.disabled': 'Disabled',
'notifications.delivery': 'Delivery',
'notifications.urlSaved': 'Secret URL saved',
'notifications.urlMissing': 'No delivery URL saved',
'notifications.filterCount': {
one: '{count} filter · all must match',
other: '{count} filters · all must match',
},
'notifications.noFiltersShort': 'All matching events',
'notifications.noChanges': 'No saved changes yet',
'notifications.createdAt': 'Created {date}',
'notifications.updatedAt': 'Updated {date}',
'notifications.deleteHelp':
'Delete “{name}”? This action will stop sending notifications. This cannot be undone.',
'notifications.editorHelp':
'Choose a ticket event, a delivery channel and optional filters.',
'notifications.name': 'Name',
'notifications.event': 'Trigger',
'notifications.channel': 'Channel',
'notifications.keepUrl':
'A secret URL is saved. Leave the field blank to keep it.',
'notifications.replaceUrl': 'Replace delivery URL (optional)',
'notifications.url': 'Delivery URL',
'notifications.secretHelp':
'URLs are stored encrypted and never shown again after saving. Enter the complete webhook URL.',
'notifications.message': 'Discord message template',
'notifications.messageHelp':
'Use the variables below to include ticket details. Maximum 2,000 characters.',
'notifications.variables': 'Available template variables',
'notifications.mentions': 'Allowed mentions',
'notifications.mentionsHelp':
'Leave all unchecked to disable mentions. Only the selected mention types may notify people.',
'notifications.filters': 'Filters',
'notifications.filtersHelp':
'All filters must match before this action sends a notification.',
'notifications.noFilters':
'No filters. This action runs for every matching event.',
'notifications.filterNumber': 'Filter {number}',
'notifications.attribute': 'Attribute',
'notifications.operator': 'Operator',
'notifications.value': 'Value',
'notifications.values': 'Values (comma or newline separated)',
'notifications.removeFilter': 'Remove filter',
'notifications.removeFilterNumber': 'Remove filter {number}',
'notifications.addFilter': 'Add filter',
'notifications.enabledHelp':
'Turn off this action to pause delivery while keeping its configuration.',
'notifications.confirmDelete': 'Delete notification',
'notifications.channel.discord': 'Discord',
'notifications.channel.webhook': 'Webhook',
'notifications.event.ticket_status_changed': 'Ticket status changed',
'notifications.event.ticket_create': 'Ticket create',
'notifications.event.ticket_assignee_changed': 'Assignee changed',
'notifications.attribute.project.id': 'Project ID',
'notifications.attribute.project.key': 'Project key',
'notifications.attribute.project.name': 'Project name',
'notifications.attribute.ticket.id': 'Ticket ID',
'notifications.attribute.ticket.key': 'Ticket key',
'notifications.attribute.ticket.title': 'Ticket title',
'notifications.attribute.ticket.url': 'Ticket URL',
'notifications.attribute.actor.id': 'Actor ID',
'notifications.attribute.actor.name': 'Actor name',
'notifications.attribute.assignee.from.id': 'From assignee ID',
'notifications.attribute.assignee.from.name': 'From assignee name',
'notifications.attribute.assignee.to.id': 'To assignee ID',
'notifications.attribute.assignee.to.name': 'To assignee name',
'notifications.attribute.status.from.id': 'From status ID',
'notifications.attribute.status.from.label': 'From status label',
'notifications.attribute.status.to.id': 'To status ID',
'notifications.attribute.status.to.label': 'To status label',
'notifications.operator.equals': 'Equals',
'notifications.operator.not_equals': 'Not equals',
'notifications.operator.exists': 'Exists',
'notifications.operator.not_exists': 'Not exists',
'notifications.operator.in': 'In list',
'notifications.mention.everyone': '@everyone and @here',
'notifications.mention.roles': 'Role mentions (@role)',
'notifications.mention.users': 'User mentions (@username)',
'notifications.variable.url':
'Absolute ticket URL for the notification event.',
'notifications.variable.ticket_key': 'Project ticket key such as CORE-42.',
'notifications.variable.ticket_title':
'Ticket title for the notification event.',
'notifications.variable.project_name': 'Project name that owns the ticket.',
'notifications.variable.status_from':
'Origin status label for status moves; blank for ticket create and assignee changes.',
'notifications.variable.status_to':
'Destination or initial status label for the ticket event.',
'notifications.variable.actor_name':
'Actor name when the event has a known user.',
'notifications.variable.assignee_from':
'Previous assignee name when the event updates assignment; blank otherwise.',
'notifications.variable.assignee_to':
'New assignee name when the event updates assignment; blank when unassigned.',
'templates.description':
'Reuse a proven project setup. Manage published templates and see which projects inherit their configuration.',
'templates.updated': 'Project templates updated.',
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
import type { NotificationActionModel } from '@/types/models/notification-action-model';
export type NotificationEditorTarget =
| { action: 'create'; entry?: never }
| { action: 'edit' | 'delete'; entry: NotificationActionModel };
export type NotificationFilterFormState = {
id: number;
attribute: string;
operator: string;
value: string;
};
@@ -430,4 +430,66 @@ class ProjectNotificationSettingsControllerTest extends TestCase
->missing('notificationActions.0.delivery_url'),
);
}
public function test_editor_accepts_array_filters_and_can_clear_discord_mentions(): void
{
$user = User::factory()->create();
$project = Project::factory()->create();
$notificationAction = NotificationAction::factory()->discord()->for($project)->create([
'channel_configuration' => ['allowed_mentions' => ['users']],
'delivery_url' => 'https://discord.com/api/webhooks/123456/original-secret',
]);
$this->syncProjectPermissions($project, $user, ['edit']);
$this->actingAs($user)
->patch(route('projects.settings.notifications.update', [$project, $notificationAction]), [
'name' => 'Paused alerts',
'event_type' => NotificationEventType::TicketAssigneeChanged->value,
'channel' => NotificationChannel::Discord->value,
'enabled' => false,
'delivery_url' => null,
'message_template' => '$ticket_key: $url',
'channel_configuration' => ['allowed_mentions' => []],
'filters' => [
['attribute' => 'ticket.key', 'operator' => 'in', 'value' => ['CORE-1', 'CORE-2']],
['attribute' => 'actor.name', 'operator' => 'exists', 'value' => null],
],
])
->assertSessionHasNoErrors()
->assertRedirect(route('projects.settings.notifications', $project));
$notificationAction->refresh();
$this->assertFalse($notificationAction->enabled);
$this->assertSame(['allowed_mentions' => []], $notificationAction->channel_configuration);
$this->assertSame('https://discord.com/api/webhooks/123456/original-secret', $notificationAction->delivery_url);
$this->assertSame([
['attribute' => 'ticket.key', 'operator' => 'in', 'value' => ['CORE-1', 'CORE-2']],
['attribute' => 'actor.name', 'operator' => 'exists', 'value' => null],
], $notificationAction->filters);
}
public function test_invalid_editor_update_does_not_change_saved_configuration(): void
{
$user = User::factory()->create();
$project = Project::factory()->create();
$notificationAction = NotificationAction::factory()->discord()->for($project)->create();
$original = $notificationAction->fresh()->getRawOriginal();
$this->syncProjectPermissions($project, $user, ['edit']);
$this->actingAs($user)
->from(route('projects.settings.notifications', $project))
->patch(route('projects.settings.notifications.update', [$project, $notificationAction]), [
'name' => 'Invalid update',
'event_type' => NotificationEventType::TicketCreate->value,
'channel' => NotificationChannel::Discord->value,
'enabled' => false,
'delivery_url' => 'invalid-url',
'message_template' => '',
'channel_configuration' => ['allowed_mentions' => ['unsupported']],
'filters' => [['attribute' => 'ticket.key', 'operator' => 'in', 'value' => []]],
])
->assertSessionHasErrors(['delivery_url', 'message_template', 'channel_configuration.allowed_mentions.0', 'filters.0.value']);
$this->assertSame($original, $notificationAction->fresh()->getRawOriginal());
}
}
@@ -0,0 +1,19 @@
<?php
namespace Tests\Feature\Projects;
use Symfony\Component\Process\Process;
use Tests\TestCase;
class ProjectNotificationSettingsUiTest extends TestCase
{
public function test_notification_settings_render_actions_and_serialize_filter_values(): void
{
$process = new Process(['node', 'tests/Fixtures/project-notification-settings.mjs'], base_path());
$process->setTimeout(60);
$process->run();
$this->assertTrue($process->isSuccessful(), $process->getOutput().$process->getErrorOutput());
$this->assertStringContainsString('Notification settings checks passed.', $process->getOutput());
}
}
@@ -0,0 +1,310 @@
import assert from 'node:assert/strict';
import process from 'node:process';
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? 'playwright'
);
const browser = await chromium.launch({ channel: 'chrome', headless: true });
const base = 'http://127.0.0.1:4195';
const context = await browser.newContext({
viewport: { width: 1440, height: 1000 },
});
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const requests = [];
page.on('request', (request) => {
if (['POST', 'PATCH', 'DELETE'].includes(request.method())) {
requests.push(request);
}
});
const button = (name) => page.getByRole('button', { name, exact: true });
const dialog = () => page.getByRole('dialog');
const result = (value) =>
context.addCookies([
{ name: 'notification_test_result', value, url: base },
]);
const visit = async (query = '?reset') => {
await result('success');
await page.goto(base + '/projects/1/settings/notifications' + query);
await page
.getByRole('heading', { name: 'Notifications', exact: true })
.waitFor();
};
const closed = () => dialog().waitFor({ state: 'hidden' });
const state = (value) =>
dialog().locator(`[data-form-state="${value}"]`).waitFor();
const noOverflow = async () =>
assert.equal(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth,
),
true,
);
const submit = async (label, method, path, expected) => {
const sent = page.waitForRequest((request) => request.method() === method);
await dialog().getByRole('button', { name: label, exact: true }).click();
const request = await sent;
assert.equal(new URL(request.url()).pathname, path);
assert.deepEqual(request.postDataJSON(), expected);
};
try {
for (const width of [1440, 768, 390, 320]) {
await page.setViewportSize({ width, height: 1000 });
for (const theme of ['light', 'dark']) {
await page.emulateMedia({ colorScheme: theme });
await visit();
await noOverflow();
const trigger = button('Edit Release alerts');
await trigger.focus();
await page.keyboard.press('Enter');
await dialog().waitFor();
assert.equal(
await page.getByLabel('Name', { exact: true }).inputValue(),
'Release alerts',
);
const secret = page.getByLabel('Replace delivery URL (optional)');
assert.equal(await secret.inputValue(), '');
assert.equal(await secret.getAttribute('type'), 'password');
assert.equal(
await page
.getByLabel('Values (comma or newline separated)')
.inputValue(),
'CORE-1, CORE-2',
);
assert.equal(
await page
.getByLabel('User mentions (@username)', { exact: true })
.isChecked(),
true,
);
await page
.getByText('Available template variables', { exact: true })
.click();
await dialog().getByText('$url', { exact: true }).waitFor();
await noOverflow();
assert.equal(
await dialog().evaluate(
(el) => el.scrollWidth <= el.clientWidth + 1,
),
true,
);
if (
process.env.NOTIFICATION_SCREENSHOTS &&
[1440, 390].includes(width)
) {
await page.screenshot({
path: `${process.env.NOTIFICATION_SCREENSHOTS}/kan45-${width}-${theme}.png`,
});
}
await page.keyboard.press('Escape');
await closed();
assert.equal(
await trigger.evaluate((el) => el === document.activeElement),
true,
);
}
}
await page.setViewportSize({ width: 1280, height: 1000 });
await visit();
await button('Add notification').click();
assert.equal(
await page.getByLabel('Channel', { exact: true }).inputValue(),
'webhook',
);
assert.equal(
await page
.getByLabel('Discord message template', { exact: true })
.count(),
0,
);
await page.getByLabel('Name', { exact: true }).fill('New webhook');
await page
.getByLabel('Delivery URL', { exact: true })
.fill('https://hooks.example.test/new-secret');
await page
.getByLabel('Trigger', { exact: true })
.selectOption('ticket_assignee_changed');
await page.getByLabel('Enabled', { exact: true }).uncheck();
await button('Add filter').click();
await page
.getByLabel('Attribute', { exact: true })
.selectOption('actor.name');
await page.getByLabel('Operator', { exact: true }).selectOption('exists');
assert.equal(await page.getByLabel('Value', { exact: true }).count(), 0);
const payload = {
name: 'New webhook',
event_type: 'ticket_assignee_changed',
channel: 'webhook',
enabled: false,
delivery_url: 'https://hooks.example.test/new-secret',
channel_configuration: {},
message_template: null,
filters: [{ attribute: 'actor.name', operator: 'exists', value: null }],
};
await submit('Save', 'POST', '/projects/1/settings/notifications', payload);
await closed();
await button('Edit New webhook').waitFor();
assert.equal(
await page
.locator('body')
.textContent()
.then((text) => text.includes('new-secret')),
false,
);
await button('Edit New webhook').click();
assert.equal(
await page.getByLabel('Replace delivery URL (optional)').inputValue(),
'',
);
await button('Remove filter 1').click();
await page.getByLabel('Channel', { exact: true }).selectOption('discord');
await page
.getByRole('textbox', { name: 'Discord message template', exact: true })
.fill('$ticket_key: $url');
await page.getByLabel('Role mentions (@role)', { exact: true }).check();
await button('Add filter').click();
await page
.getByLabel('Attribute', { exact: true })
.selectOption('ticket.key');
await page.getByLabel('Operator', { exact: true }).selectOption('in');
await page
.getByLabel('Values (comma or newline separated)')
.fill(' CORE-1,\n CORE-3, ');
const edited = {
...payload,
channel: 'discord',
delivery_url: null,
channel_configuration: { allowed_mentions: ['roles'] },
message_template: '$ticket_key: $url',
filters: [
{
attribute: 'ticket.key',
operator: 'in',
value: ['CORE-1', 'CORE-3'],
},
],
};
await result('validation');
await submit(
'Save',
'PATCH',
'/projects/1/settings/notifications/100',
edited,
);
await state('validation');
await page.getByText('Enter a valid URL.', { exact: true }).waitFor();
await page
.getByText('Choose at least one ticket.', { exact: true })
.waitFor();
await page
.getByText('This mention type is not supported.', { exact: true })
.waitFor();
assert.equal(
await page.getByLabel('Name', { exact: true }).inputValue(),
'New webhook',
);
await result('server');
await submit(
'Save',
'PATCH',
'/projects/1/settings/notifications/100',
edited,
);
await state('server');
await result('forbidden');
await submit(
'Try again',
'PATCH',
'/projects/1/settings/notifications/100',
edited,
);
await state('server');
await result('success');
await submit(
'Try again',
'PATCH',
'/projects/1/settings/notifications/100',
edited,
);
await closed();
await button('Edit New webhook').click();
await page.getByLabel('Role mentions (@role)', { exact: true }).uncheck();
await button('Remove filter 1').click();
await page
.getByLabel('Replace delivery URL (optional)')
.fill('https://hooks.example.test/replacement');
await page.route('**/notifications/100', (route) => route.abort('failed'));
await button('Save').click();
await state('network');
await page.unroute('**/notifications/100');
await submit(
'Try again',
'PATCH',
'/projects/1/settings/notifications/100',
{
...edited,
delivery_url: 'https://hooks.example.test/replacement',
channel_configuration: { allowed_mentions: [] },
filters: [],
},
);
await closed();
await button('Edit New webhook').click();
await page.getByLabel('Channel', { exact: true }).selectOption('webhook');
await submit('Save', 'PATCH', '/projects/1/settings/notifications/100', {
...edited,
channel: 'webhook',
channel_configuration: {},
message_template: null,
filters: [],
});
await closed();
// Dismissing a dirty dialog asks before clearing a secret; reopening starts clean.
await button('Edit New webhook').click();
await page
.getByLabel('Replace delivery URL (optional)')
.fill('discard-this-secret');
page.once('dialog', (prompt) => prompt.dismiss());
await button('Cancel').click();
assert.equal(await dialog().isVisible(), true);
page.once('dialog', (prompt) => prompt.accept());
await button('Cancel').click();
await closed();
await button('Edit Release alerts').click();
assert.equal(
await page.getByLabel('Replace delivery URL (optional)').inputValue(),
'',
);
assert.equal(
await page.getByLabel('Name', { exact: true }).inputValue(),
'Release alerts',
);
await button('Cancel').click();
await closed();
const before = requests.length;
await button('Delete New webhook').click();
await dialog()
.getByText(/This cannot be undone/)
.waitFor();
await button('Cancel').click();
await closed();
assert.equal(requests.length, before);
await button('Delete New webhook').click();
await submit(
'Delete notification',
'DELETE',
'/projects/1/settings/notifications/100',
{},
);
await closed();
assert.equal(await button('Edit New webhook').count(), 0);
await visit('?reset&empty');
await page.getByRole('heading', { name: 'No notifications yet' }).waitFor();
assert.deepEqual(errors, []);
console.log(
'Notification browser checks passed: CRUD, filters, channels, secrets, validation, retries, keyboard, responsive layouts and themes.',
);
} finally {
await browser.close();
}
@@ -0,0 +1,19 @@
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import '../../resources/css/app.css';
import Notifications from '../../resources/js/pages/projects/settings/Notifications.vue';
import { createAppearance } from '../../resources/js/composables/useAppearance';
import { createLocalization } from '../../resources/js/lib/localization';
createInertiaApp({
resolve: (name) =>
name === 'Notifications'
? Notifications
: { render: () => h('h1', 'Destination reached') },
setup: ({ el, App, props, plugin }) =>
createApp({ render: () => h(App, props) })
.use(plugin)
.use(createLocalization())
.use(createAppearance())
.mount(el),
});
@@ -0,0 +1,363 @@
import assert from 'node:assert/strict';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import vue from '@vitejs/plugin-vue';
import tailwind from '@tailwindcss/vite';
import { createServer } from 'vite';
import { createSSRApp, h } from 'vue';
import { renderToString } from 'vue/server-renderer';
import { createInertiaApp } from '@inertiajs/vue3';
const serve = process.argv.includes('--serve');
const server = await createServer({
configFile: false,
cacheDir: 'node_modules/.vite/project-notification-settings-fixture',
plugins: [vue(), ...(serve ? [tailwind()] : [])],
resolve: {
alias: {
'@': fileURLToPath(new URL('../../resources/js', import.meta.url)),
},
},
server: serve
? { host: '127.0.0.1', port: 4195, strictPort: true, hmr: false }
: { middlewareMode: true, hmr: false, watch: null },
appType: 'custom',
});
const options = (values) => values.map((value) => ({ value, label: value }));
function initial() {
return {
project: { id: 1, key: 'CORE', name: 'Core platform' },
status: null,
templateState: null,
channelOptions: options(['discord', 'webhook']),
eventTypeOptions: options([
'ticket_status_changed',
'ticket_create',
'ticket_assignee_changed',
]),
filterAttributeOptions: options([
'project.id',
'ticket.key',
'status.to.label',
'actor.name',
]),
filterOperatorOptions: options([
'equals',
'not_equals',
'exists',
'not_exists',
'in',
]),
discordAllowedMentionOptions: options(['everyone', 'roles', 'users']),
templateVariables: [
{ value: '$ticket_key', description: 'Ticket key' },
{ value: '$url', description: 'Ticket URL' },
],
notificationActions: [
{
id: 10,
project_id: 1,
name: 'Release alerts',
enabled: true,
event_type: 'ticket_status_changed',
event_type_label: 'Ticket status changed',
channel: 'discord',
channel_label: 'Discord',
channel_configuration: { allowed_mentions: ['users'] },
has_delivery_url: true,
message_template: '$ticket_key moved to $status_to: $url',
filters: [
{
attribute: 'ticket.key',
operator: 'in',
value: ['CORE-1', 'CORE-2'],
},
],
created_at: '2026-09-01T09:00:00Z',
updated_at: '2026-09-02T12:00:00Z',
},
{
id: 20,
project_id: 1,
name: 'Audit webhook',
enabled: false,
event_type: 'ticket_create',
event_type_label: 'Ticket create',
channel: 'webhook',
channel_label: 'Webhook',
channel_configuration: {},
has_delivery_url: false,
message_template: null,
filters: [],
created_at: null,
updated_at: null,
},
],
};
}
function makePage(
extra = {},
url = '/projects/1/settings/notifications',
component = 'Notifications',
) {
return {
component,
url,
version: null,
clearHistory: false,
encryptHistory: false,
props: {
name: 'KanbanGit',
errors: {},
sidebarOpen: true,
appearance: 'system',
auth: {
user: {
id: 1,
name: 'Alex Morgan',
email: 'alex@example.test',
avatar: null,
avatar_color: '#10B981',
avatar_is_generated: true,
},
permissions: {
globalAdmin: false,
projectCreate: false,
canManageTeams: false,
},
},
navigation: {
project: {
id: 1,
name: 'Core platform',
key: 'CORE',
canManage: true,
},
},
...initial(),
...extra,
},
};
}
if (serve) {
let data = initial();
let nextId = 100;
server.middlewares.use(async (request, response, next) => {
if (!request.url.startsWith('/projects')) {
return next();
}
const url = new URL(request.url, 'http://localhost');
const mutation = request.method !== 'GET';
if (!mutation && url.searchParams.has('reset')) {
data = initial();
nextId = 100;
}
let errors = {};
if (mutation) {
let body = '';
for await (const chunk of request) {
body += chunk;
}
const submitted = JSON.parse(body || '{}');
const result =
request.headers.cookie?.match(
/notification_test_result=(\w+)/,
)?.[1] ?? 'success';
if (result === 'server' || result === 'forbidden') {
response.statusCode = result === 'server' ? 500 : 403;
response.end('Unavailable');
return;
}
if (result === 'validation') {
errors = {
delivery_url: 'Enter a valid URL.',
'filters.0.value': 'Choose at least one ticket.',
'channel_configuration.allowed_mentions.0':
'This mention type is not supported.',
};
} else {
const id = Number(url.pathname.split('/').at(-1));
if (request.method === 'DELETE') {
data.notificationActions = data.notificationActions.filter(
(entry) => entry.id !== id,
);
} else {
const { delivery_url, ...safe } = submitted;
if (request.method === 'POST') {
data.notificationActions.push({
id: nextId++,
project_id: 1,
...safe,
has_delivery_url: !!delivery_url,
created_at: '2026-09-15T10:00:00Z',
updated_at: null,
});
} else {
const entry = data.notificationActions.find(
(entry) => entry.id === id,
);
Object.assign(entry, safe, {
has_delivery_url:
entry.has_delivery_url || !!delivery_url,
});
}
}
}
data.status = Object.keys(errors).length ? null : 'Updated';
}
if (url.searchParams.has('empty')) {
data.notificationActions = [];
}
const page = makePage({ ...data, errors });
response.setHeader('Vary', 'X-Inertia');
if (request.headers['x-inertia']) {
response.setHeader('X-Inertia', 'true');
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(page));
return;
}
const escaped = JSON.stringify(page)
.replaceAll('&', '&amp;')
.replaceAll('"', '&quot;')
.replaceAll('<', '&lt;');
response.setHeader('Content-Type', 'text/html');
response.end(
await server.transformIndexHtml(
request.url,
'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><div id="app" data-page="' +
escaped +
'"></div><script type="module" src="/tests/Fixtures/project-notification-settings-preview.mjs"></script></body></html>',
),
);
});
await server.listen();
console.log('Notification settings fixture ready.');
} else {
try {
const { createLocalization } = await server.ssrLoadModule(
'/resources/js/lib/localization.ts',
);
const { createAppearance } = await server.ssrLoadModule(
'/resources/js/composables/useAppearance.ts',
);
const { en } = await server.ssrLoadModule(
'/resources/js/locales/en.ts',
);
const component = (
await server.ssrLoadModule(
'/resources/js/pages/projects/settings/Notifications.vue',
)
).default;
const render = async (extra = {}, locale = createLocalization()) =>
(
await createInertiaApp({
page: makePage(extra),
resolve: () => component,
render: renderToString,
setup: ({ App, props, plugin }) =>
createSSRApp({ render: () => h(App, props) })
.use(plugin)
.use(locale)
.use(createAppearance()),
})
).body;
const html = await render();
assert.match(html, /Notifications/);
assert.match(html, /aria-current="page"/);
assert.match(html, /Release alerts/);
assert.match(html, /Audit webhook/);
assert.match(html, /Secret URL saved/);
assert.match(html, /No delivery URL saved/);
assert.match(html, /1 filter · all must match/);
assert.match(html, /Disabled/);
assert.match(html, /Ticket status changed/);
assert.match(html, /No saved changes yet/);
assert.match(
await render({ notificationActions: [] }),
/No notifications yet/,
);
assert.match(
await render({ status: 'Saved' }),
/Notification settings saved/,
);
assert.match(
await render(
{},
createLocalization(
{ locale: 'de' },
{
de: {
...en,
'notifications.title': 'Benachrichtigungen',
},
},
),
),
/Benachrichtigungen/,
);
const { serializeNotificationFilters } = await server.ssrLoadModule(
'/resources/js/lib/notification-filters.ts',
);
assert.deepEqual(
serializeNotificationFilters([
{
id: 1,
attribute: 'ticket.key',
operator: 'in',
value: ' CORE-1, \nCORE-2, ',
},
{
id: 2,
attribute: 'actor.name',
operator: 'exists',
value: 'ignored',
},
{
id: 3,
attribute: 'actor.name',
operator: 'not_exists',
value: 'ignored',
},
{
id: 4,
attribute: 'status.to.label',
operator: 'equals',
value: ' Done ',
},
{
id: 5,
attribute: 'status.to.label',
operator: 'not_equals',
value: ' Doing ',
},
]),
[
{
attribute: 'ticket.key',
operator: 'in',
value: ['CORE-1', 'CORE-2'],
},
{ attribute: 'actor.name', operator: 'exists', value: null },
{
attribute: 'actor.name',
operator: 'not_exists',
value: null,
},
{
attribute: 'status.to.label',
operator: 'equals',
value: 'Done',
},
{
attribute: 'status.to.label',
operator: 'not_equals',
value: 'Doing',
},
],
);
assert.deepEqual(serializeNotificationFilters([]), []);
console.log('Notification settings checks passed.');
} finally {
await server.close();
}
}