mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(notifications): let a plugin register a notification channel
TREK's four channels (in-app, email, webhook, ntfy) were a closed set: notificationService.send() dispatched with four copy-pasted `if` blocks and no provider abstraction, so a fifth channel meant editing eight files by hand. A plugin could produce a notification via ctx.notify.send(), but never deliver one. A plugin now registers a channel with `hooks.notificationChannel` + `hook:notification-channel` on a plain `type: 'integration'` — not a new manifest type, so the TREK-Plugins registry schema and both its CI gates are untouched. Core refactor - New channel registry (services/notifications/): email/webhook/ntfy become ExternalChannel providers wrapping the EXISTING send functions — no delivery logic is rewritten, only relocated. In-app deliberately stays out: it writes typed rows with scope/target/callbacks, not a rendered title+body, the same line shared/ already draws with i18n/externalNotifications. - The event text is now rendered once per recipient instead of once per channel. - The channel set is open: NotifChannel becomes a string, the matrix is registry-derived, and the UI columns are server-driven. The DB column was already bare TEXT and the Zod contract already a string record — only the TypeScript and the two UIs were ever closed. The hook runs USERLESS. Every other hook is user-initiated, so actingUserId falls out of the request; a notification is host-initiated for an ARBITRARY recipient, so ctx.settings.get() would return undefined. The host resolves the recipient's decrypted scope:'user' settings itself and passes them as an argument. That is what lets a channel plugin be handed someone's push token WITHOUT being handed the right to read their trips as them. Enabling the plugin is the opt-in: a plugin channel is not gated on the admin's `notification_channels` list. A built-in always exists in code and needs an explicit switch; a plugin channel only exists because an admin enabled that plugin. (Nothing could write a `plugin:` id into that CSV anyway, and the admin toggle rebuilt it from three booleans, silently dropping anything else — so requiring a second opt-in meant the channel could never be turned on at all.) Also fixed, found while building this: - Plugin settings keys were unvalidated, so a field named `__proto__` or `constructor` resolved off Object.prototype: a REQUIRED field with such a name reported as configured for every user who had configured nothing — enough, for a channel, to be dispatched to everyone with no credentials. Keys are now constrained at install and the config blob is parsed null-prototype, so it is impossible even for an already-installed plugin. - A `select` field's options were cast straight through, so the obvious `["1","5"]` form rendered every dropdown entry BLANK (the client reads value/label). Now coerced, and malformed options are rejected. Also adds: operator-supplied egress hosts (a plugin talking to a self-hosted service can't name the operator's host at publish time, so an admin adds it post-install and the runtime re-spawns the child with the widened allow-list — only for a plugin that DECLARED operatorEgress, and only an admin, never a user); settings-page actions (a "Test connection" button, user-initiated so ctx.settings.get() returns the clicking user's own value); and a Gotify-shaped notification-channel template in the SDK. Verified end to end against a real Gotify container, not just in tests.
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import AdminPluginsPanel from './AdminPluginsPanel'
|
||||
|
||||
/**
|
||||
* The "allowed hosts" chip. A plugin that talks to a SELF-HOSTED service (a Gotify) can't
|
||||
* name the operator's host in its manifest, so the admin adds it — but they'd never know
|
||||
* that unless the card says so. Until a host exists the plugin can reach NOTHING and looks
|
||||
* silently broken, which is why the chip is warning-toned and actionable in that state.
|
||||
*/
|
||||
function plugin(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'trek-gotify', name: 'Gotify', description: 'Push notifications', type: 'integration',
|
||||
icon: 'Bell', version: '1.0.0', status: 'active', enabled: 1,
|
||||
last_error: null, reviewed_at: null, source_repo: null,
|
||||
permissions: JSON.stringify(['hook:notification-channel', 'http:outbound:gotify.net']),
|
||||
capabilities: '{}',
|
||||
operatorEgress: true,
|
||||
egressHostCount: 0,
|
||||
dependencyStatus: 'ok',
|
||||
dependencyIssues: { disabledAddons: [], missing: [], versionMismatch: [] },
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function mockList(p: Record<string, unknown>) {
|
||||
server.use(
|
||||
http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [p] })),
|
||||
http.get('*/api/admin/plugins/registry', () => HttpResponse.json({ plugins: [] })),
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => resetAllStores())
|
||||
|
||||
describe('AdminPluginsPanel — allowed-hosts chip', () => {
|
||||
it('FE-COMP-PLUGINS-EGRESS-001: invites the admin to add a host when none is set', async () => {
|
||||
mockList(plugin({ egressHostCount: 0 }))
|
||||
render(<AdminPluginsPanel />)
|
||||
// The plugin can't reach anything yet — the card must say so, not stay silent.
|
||||
expect(await screen.findByRole('button', { name: /add allowed host/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-PLUGINS-EGRESS-002: shows the count once hosts exist', async () => {
|
||||
mockList(plugin({ egressHostCount: 2 }))
|
||||
render(<AdminPluginsPanel />)
|
||||
expect(await screen.findByRole('button', { name: /2 allowed host/i })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /add allowed host/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-PLUGINS-EGRESS-003: a plugin that never declared operatorEgress gets NO chip', async () => {
|
||||
mockList(plugin({ operatorEgress: false }))
|
||||
render(<AdminPluginsPanel />)
|
||||
await screen.findByText('Gotify')
|
||||
// An admin must never be invited to widen egress for a plugin that didn't ask for it.
|
||||
expect(screen.queryByRole('button', { name: /allowed host/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-PLUGINS-EGRESS-004: clicking the chip opens the allowed-hosts dialog', async () => {
|
||||
mockList(plugin({ egressHostCount: 1 }))
|
||||
server.use(
|
||||
http.get('*/api/admin/plugins/trek-gotify/egress-hosts', () =>
|
||||
HttpResponse.json({ supported: true, hosts: ['gotify.mydomain.com'] })),
|
||||
)
|
||||
render(<AdminPluginsPanel />)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 allowed host/i }))
|
||||
await waitFor(() => expect(screen.getByText('gotify.mydomain.com')).toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The Discover (pre-install) modal. Its "Connects to" list is what a reviewer reads to
|
||||
* judge a plugin's network reach — so for an operatorEgress plugin that list is NOT the
|
||||
* whole story, and saying nothing would actively mislead them.
|
||||
*/
|
||||
function mockDetail(manifest: Record<string, unknown> | null) {
|
||||
server.use(
|
||||
http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [] })),
|
||||
// pluginBrowse returns the ARRAY itself, not { plugins: [...] }.
|
||||
http.get('*/api/admin/plugins/registry', () =>
|
||||
HttpResponse.json([{ id: 'trek-gotify', name: 'Gotify', author: 'jubnl', description: 'Push', repo: 'jubnl/trek-gotify', type: 'integration', tags: [] }])),
|
||||
http.get('*/api/admin/plugins/registry/trek-gotify', () =>
|
||||
HttpResponse.json({
|
||||
id: 'trek-gotify', name: 'Gotify', author: 'jubnl', description: 'Push', repo: 'jubnl/trek-gotify',
|
||||
type: 'integration', tags: [], size: 1024, publishedAt: null, latest: '1.0.0', manifest,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
describe('AdminPluginsPanel — Discover modal, operator-egress pill', () => {
|
||||
const base = { permissions: ['hook:notification-channel', 'http:outbound:gotify.net'], egress: ['gotify.net'], settings: [], license: 'MIT', icon: null }
|
||||
|
||||
/** The panel opens on Installed — switch to Discover, then open the plugin's card. */
|
||||
async function openDetail() {
|
||||
render(<AdminPluginsPanel />)
|
||||
fireEvent.click(await screen.findByRole('button', { name: /discover/i }))
|
||||
fireEvent.click(await screen.findByText('Gotify'))
|
||||
}
|
||||
|
||||
it('FE-COMP-PLUGINS-EGRESS-005: warns that the host list is not the whole story', async () => {
|
||||
mockDetail({ ...base, operatorEgress: true })
|
||||
await openDetail()
|
||||
|
||||
// The declared host is still listed…
|
||||
expect(await screen.findByText('gotify.net')).toBeInTheDocument()
|
||||
// …alongside the pill saying an admin adds more.
|
||||
expect(screen.getByText(/hosts you add/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-PLUGINS-EGRESS-006: an ordinary plugin gets NO such pill', async () => {
|
||||
mockDetail({ ...base, operatorEgress: false })
|
||||
await openDetail()
|
||||
|
||||
expect(await screen.findByText('gotify.net')).toBeInTheDocument()
|
||||
// Its egress list IS the whole story — claiming otherwise would be a lie.
|
||||
expect(screen.queryByText(/hosts you add/i)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -42,6 +42,10 @@ interface PluginRow {
|
||||
source_repo: string | null
|
||||
permissions: string
|
||||
capabilities: string
|
||||
/** The plugin needs OPERATOR-supplied egress hosts (a self-hosted target). */
|
||||
operatorEgress?: boolean
|
||||
/** How many hosts the admin has added — 0 means the plugin can't reach anything yet. */
|
||||
egressHostCount?: number
|
||||
dependencies?: PluginDependencies
|
||||
dependencyStatus?: DependencyStatus
|
||||
dependencyIssues?: DependencyIssues
|
||||
@@ -68,6 +72,8 @@ interface RegistryDetail extends RegistryItem {
|
||||
manifest: {
|
||||
permissions: string[]
|
||||
egress: string[]
|
||||
/** The plugin needs OPERATOR-supplied hosts — its egress list is not the whole story. */
|
||||
operatorEgress?: boolean
|
||||
settings: Array<{ key: string; label: string; inputType: string; scope: string; required: boolean }>
|
||||
license: string | null
|
||||
icon: string | null
|
||||
@@ -118,7 +124,7 @@ const PERM_KEYS = [
|
||||
'events:subscribe', 'jobs:run',
|
||||
'ws:broadcast:trip', 'ws:broadcast:user',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'hook:table-contributor', 'hook:map-marker-provider',
|
||||
'hook:pdf-section-provider', 'hook:atlas-layer-provider', 'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:user-data', 'http:outbound',
|
||||
'hook:pdf-section-provider', 'hook:atlas-layer-provider', 'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:notification-channel', 'hook:user-data', 'http:outbound',
|
||||
]
|
||||
|
||||
const KNOWN_TYPES = ['widget', 'page', 'integration', 'trip-page']
|
||||
@@ -169,6 +175,7 @@ function deriveCaps(perms: string[], caps: { widget?: { slot?: string }; tripPag
|
||||
if (perms.includes('hook:calendar-source')) out.push({ icon: CalendarDays, label: t('admin.plugins.cap.calendar') })
|
||||
if (perms.includes('hook:place-detail-provider')) out.push({ icon: MapPin, label: t('admin.plugins.cap.placeDetails') })
|
||||
if (perms.includes('hook:trip-warning-provider')) out.push({ icon: AlertTriangle, label: t('admin.plugins.cap.warnings') })
|
||||
if (perms.includes('hook:notification-channel')) out.push({ icon: Bell, label: t('admin.plugins.cap.notificationChannel') })
|
||||
if (perms.includes('events:subscribe')) out.push({ icon: Radio, label: t('admin.plugins.cap.events') })
|
||||
for (const h of perms.filter(p => p.startsWith('http:outbound:')).map(p => p.slice('http:outbound:'.length)).filter(Boolean)) {
|
||||
out.push({ icon: ArrowRight, label: h, net: true })
|
||||
@@ -250,6 +257,10 @@ export default function AdminPluginsPanel() {
|
||||
const [latest, setLatest] = useState<Record<string, string>>({})
|
||||
const [detailFor, setDetailFor] = useState<RegistryItem | null>(null)
|
||||
const [errorsFor, setErrorsFor] = useState<{ id: string; rows: Array<{ ts: string; level: string; message: string }> } | null>(null)
|
||||
const [egressFor, setEgressFor] = useState<{ id: string; supported: boolean; hosts: string[] } | null>(null)
|
||||
const [egressDraft, setEgressDraft] = useState('')
|
||||
const [egressSaving, setEgressSaving] = useState(false)
|
||||
const [egressError, setEgressError] = useState('')
|
||||
const [confirmUninstall, setConfirmUninstall] = useState<PluginRow | null>(null)
|
||||
// A QUEUE, not one slot: "Update All" can produce several re-consent prompts —
|
||||
// each must be shown, not silently overwritten by the last one.
|
||||
@@ -349,6 +360,31 @@ export default function AdminPluginsPanel() {
|
||||
const f = e.dataTransfer.files?.[0]
|
||||
if (f) void uploadPlugin(f)
|
||||
}
|
||||
const openEgress = (id: string) => {
|
||||
setMenu(null)
|
||||
setEgressDraft(''); setEgressError('')
|
||||
adminApi.pluginEgressHosts(id)
|
||||
.then(d => setEgressFor({ id, supported: d.supported, hosts: d.hosts }))
|
||||
.catch(() => setEgressFor({ id, supported: false, hosts: [] }))
|
||||
}
|
||||
|
||||
// Saving RE-SPAWNS the plugin: the child's egress guard is installed once at init and
|
||||
// a second init is refused, so a live child's allow-list can never be widened in place.
|
||||
const saveEgress = async (hosts: string[]) => {
|
||||
if (!egressFor) return
|
||||
setEgressSaving(true); setEgressError('')
|
||||
try {
|
||||
const d = await adminApi.pluginSetEgressHosts(egressFor.id, hosts)
|
||||
setEgressFor({ ...egressFor, hosts: d.hosts })
|
||||
setEgressDraft('')
|
||||
} catch (e) {
|
||||
const err = e as { response?: { data?: { error?: string } } }
|
||||
setEgressError(err.response?.data?.error || t('common.error'))
|
||||
} finally {
|
||||
setEgressSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openErrors = (id: string) => {
|
||||
setMenu(null)
|
||||
adminApi.pluginErrors(id)
|
||||
@@ -657,7 +693,8 @@ export default function AdminPluginsPanel() {
|
||||
hasUpdate={updateAvailable(p)} latestVer={latest[p.id]}
|
||||
onToggle={() => toggle(p)}
|
||||
onUpdate={() => runUpdate(p)} onRestart={() => restart(p.id)}
|
||||
onErrors={() => openErrors(p.id)} onUninstall={() => { setMenu(null); setConfirmUninstall(p) }} />
|
||||
onErrors={() => openErrors(p.id)} onEgress={() => openEgress(p.id)}
|
||||
onUninstall={() => { setMenu(null); setConfirmUninstall(p) }} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -693,6 +730,56 @@ export default function AdminPluginsPanel() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Operator-supplied egress hosts */}
|
||||
{egressFor && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setEgressFor(null)}>
|
||||
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-lg shadow-modal" onClick={e => e.stopPropagation()}>
|
||||
<div className="px-5 py-3.5 border-b border-edge-secondary flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-content flex items-center gap-2"><Globe size={15} /> {egressFor.id} — {t('admin.plugins.allowedHosts')}</span>
|
||||
<button onClick={() => setEgressFor(null)} className="text-content-faint hover:text-content"><X size={16} /></button>
|
||||
</div>
|
||||
<div className="p-5 space-y-3">
|
||||
{!egressFor.supported ? (
|
||||
<p className="text-sm text-content-faint">{t('admin.plugins.allowedHosts.unsupported')}</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-content-faint">{t('admin.plugins.allowedHosts.hint')}</p>
|
||||
{egressFor.hosts.length === 0 && (
|
||||
<p className="text-sm text-content-faint italic">{t('admin.plugins.allowedHosts.none')}</p>
|
||||
)}
|
||||
{egressFor.hosts.map(h => (
|
||||
<div key={h} className="flex items-center justify-between gap-2 rounded-lg border border-edge-secondary px-3 py-2">
|
||||
<span className="text-sm font-mono text-content break-all">{h}</span>
|
||||
<button
|
||||
disabled={egressSaving}
|
||||
onClick={() => saveEgress(egressFor.hosts.filter(x => x !== h))}
|
||||
className="text-content-faint hover:text-danger disabled:opacity-50"
|
||||
aria-label={t('common.delete')}
|
||||
><Trash2 size={14} /></button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={egressDraft}
|
||||
onChange={e => setEgressDraft(e.target.value)}
|
||||
placeholder="gotify.example.com"
|
||||
className="flex-1 rounded-lg border border-edge bg-surface px-3 py-2 text-sm text-content"
|
||||
/>
|
||||
<button
|
||||
disabled={egressSaving || !egressDraft.trim()}
|
||||
onClick={() => saveEgress([...egressFor.hosts, egressDraft.trim()])}
|
||||
className="rounded-lg bg-content px-3 py-2 text-sm text-surface disabled:opacity-50"
|
||||
>{t('common.add')}</button>
|
||||
</div>
|
||||
{egressError && <p className="text-xs text-danger">{egressError}</p>}
|
||||
<p className="text-xs text-content-faint">{t('admin.plugins.allowedHosts.restartNote')}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={!!confirmUninstall}
|
||||
onClose={() => setConfirmUninstall(null)}
|
||||
@@ -799,10 +886,10 @@ function EmptyState({ t, onDiscover }: { t: T; onDiscover: () => void }) {
|
||||
)
|
||||
}
|
||||
|
||||
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggle, onUpdate, onRestart, onErrors, onUninstall }: {
|
||||
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggle, onUpdate, onRestart, onErrors, onEgress, onUninstall }: {
|
||||
p: PluginRow; t: T; busy: string | null; menu: string | null; setMenu: (v: string | null) => void
|
||||
hasUpdate: boolean; latestVer?: string
|
||||
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onErrors: () => void; onUninstall: () => void
|
||||
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onErrors: () => void; onEgress: () => void; onUninstall: () => void
|
||||
}) {
|
||||
const caps = deriveCaps(parseJson<string[]>(p.permissions, []), parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}), t)
|
||||
const deps = deriveDeps(p, t)
|
||||
@@ -830,7 +917,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
|
||||
<div className="flex items-center gap-1.5 mt-1.5 text-[11.5px] text-danger">
|
||||
<AlertTriangle size={13} className="shrink-0" /><span className="truncate">{p.last_error}</span>
|
||||
</div>
|
||||
) : caps.length > 0 && (
|
||||
) : (caps.length > 0 || p.operatorEgress) && (
|
||||
<div className="hidden sm:flex items-center gap-1.5 flex-wrap mt-2">
|
||||
{caps.map((c, i) => (
|
||||
<span key={i} className={`inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-[3px] rounded-md border ${
|
||||
@@ -838,6 +925,25 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
|
||||
<c.icon size={12} className={c.net ? 'text-info' : 'text-content-muted'} />{c.label}
|
||||
</span>
|
||||
))}
|
||||
{/* This plugin talks to a service only the OPERATOR can name (a self-hosted
|
||||
Gotify/ntfy), so its manifest can't list the host — the admin adds it.
|
||||
Actionable, and warning-toned until at least one host exists, because
|
||||
until then the plugin cannot reach anything and looks silently broken. */}
|
||||
{p.operatorEgress && (
|
||||
<button
|
||||
onClick={onEgress}
|
||||
title={t('admin.plugins.allowedHosts.hint')}
|
||||
className={`inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-[3px] rounded-md border transition-colors ${
|
||||
p.egressHostCount > 0
|
||||
? 'text-info border-info/25 bg-info-soft hover:border-info/50'
|
||||
: 'text-warning border-warning/30 bg-warning-soft hover:border-warning/60'}`}
|
||||
>
|
||||
<Globe size={12} className={p.egressHostCount > 0 ? 'text-info' : 'text-warning'} />
|
||||
{p.egressHostCount > 0
|
||||
? t('admin.plugins.allowedHosts.count').replace('{n}', String(p.egressHostCount))
|
||||
: t('admin.plugins.allowedHosts.add')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{deps.length > 0 && (
|
||||
@@ -874,6 +980,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
|
||||
<MenuItem icon={<RotateCw size={14} />} label={t('admin.plugins.restart')} onClick={onRestart} />
|
||||
)}
|
||||
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={onErrors} />
|
||||
<MenuItem icon={<Globe size={14} />} label={t('admin.plugins.allowedHosts')} onClick={onEgress} />
|
||||
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
|
||||
<>
|
||||
<a href={`https://github.com/${p.source_repo}`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
|
||||
@@ -1070,14 +1177,26 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
</div>
|
||||
)}
|
||||
|
||||
{manifest && manifest.egress.length > 0 && (
|
||||
{manifest && (manifest.egress.length > 0 || manifest.operatorEgress) && (
|
||||
<div className="mt-5">
|
||||
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.connectsTitle')}</h4>
|
||||
<div className="flex flex-wrap gap-1.5 mt-2">
|
||||
<div className="flex flex-wrap items-center gap-1.5 mt-2">
|
||||
{manifest.egress.map(h => (
|
||||
<code key={h} className="text-[12px] font-mono text-info bg-info-soft rounded-md px-2 py-1">{h}</code>
|
||||
))}
|
||||
{/* The hosts above are NOT the whole story for this plugin: it talks to a
|
||||
service only the operator can name, so its reach is whatever an admin
|
||||
adds after install. Say so HERE — this is the pre-install review, and a
|
||||
reviewer who reads only the host list would otherwise be misled. */}
|
||||
{manifest.operatorEgress && (
|
||||
<span className="inline-flex items-center gap-1.5 text-[12px] font-medium text-warning bg-warning-soft border border-warning/30 rounded-md px-2 py-1">
|
||||
<Globe size={12} />{t('admin.plugins.operatorEgressPill')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{manifest.operatorEgress && (
|
||||
<p className="text-[11.5px] text-content-faint mt-2">{t('admin.plugins.operatorEgressHint')}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import NotificationsTab from './NotificationsTab';
|
||||
|
||||
@@ -13,7 +12,29 @@ const minimalMatrix = {
|
||||
preferences: {
|
||||
trip_invite: { inapp: true, email: false },
|
||||
},
|
||||
available_channels: { email: true, webhook: false, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'email'] },
|
||||
};
|
||||
@@ -25,15 +46,13 @@ beforeEach(() => {
|
||||
server.use(
|
||||
http.get('/api/notifications/preferences', () => HttpResponse.json(minimalMatrix)),
|
||||
http.get('/api/settings', () => HttpResponse.json({ settings: { webhook_url: '' } })),
|
||||
http.put('/api/notifications/preferences', () => HttpResponse.json({ success: true })),
|
||||
http.put('/api/notifications/preferences', () => HttpResponse.json({ success: true }))
|
||||
);
|
||||
});
|
||||
|
||||
describe('NotificationsTab', () => {
|
||||
it('FE-COMP-NOTIFICATIONS-001: shows loading state initially', () => {
|
||||
server.use(
|
||||
http.get('/api/notifications/preferences', () => new Promise(() => {})),
|
||||
);
|
||||
server.use(http.get('/api/notifications/preferences', () => new Promise(() => {})));
|
||||
render(<NotificationsTab />);
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
@@ -64,11 +83,33 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: {},
|
||||
available_channels: { email: false, webhook: false, inapp: false },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'email'] },
|
||||
}),
|
||||
),
|
||||
})
|
||||
)
|
||||
);
|
||||
render(<NotificationsTab />);
|
||||
await waitFor(() => {
|
||||
@@ -86,14 +127,36 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true }, booking_change: { email: true } },
|
||||
available_channels: { email: true, webhook: false, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite', 'booking_change'],
|
||||
implemented_combos: {
|
||||
trip_invite: ['inapp'], // no email → dash in email column
|
||||
booking_change: ['email'], // no inapp → dash in inapp column
|
||||
trip_invite: ['inapp'], // no email → dash in email column
|
||||
booking_change: ['email'], // no inapp → dash in inapp column
|
||||
},
|
||||
}),
|
||||
),
|
||||
})
|
||||
)
|
||||
);
|
||||
render(<NotificationsTab />);
|
||||
await waitFor(() => {
|
||||
@@ -111,7 +174,7 @@ describe('NotificationsTab', () => {
|
||||
http.put('/api/notifications/preferences', async ({ request }) => {
|
||||
capturedBody = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -138,9 +201,7 @@ describe('NotificationsTab', () => {
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-007: toggle rolls back on API error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.put('/api/notifications/preferences', () => HttpResponse.json({ error: 'fail' }, { status: 500 })),
|
||||
);
|
||||
server.use(http.put('/api/notifications/preferences', () => HttpResponse.json({ error: 'fail' }, { status: 500 })));
|
||||
|
||||
render(<NotificationsTab />);
|
||||
await waitFor(() => {
|
||||
@@ -169,11 +230,13 @@ describe('NotificationsTab', () => {
|
||||
const user = userEvent.setup();
|
||||
let resolveRequest!: () => void;
|
||||
server.use(
|
||||
http.put('/api/notifications/preferences', () =>
|
||||
new Promise<Response>(resolve => {
|
||||
resolveRequest = () => resolve(HttpResponse.json({ success: true }) as unknown as Response);
|
||||
}),
|
||||
),
|
||||
http.put(
|
||||
'/api/notifications/preferences',
|
||||
() =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveRequest = () => resolve(HttpResponse.json({ success: true }) as unknown as Response);
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -200,11 +263,33 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, webhook: false } },
|
||||
available_channels: { email: false, webhook: true, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
}),
|
||||
),
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -218,7 +303,7 @@ describe('NotificationsTab', () => {
|
||||
|
||||
// Save button should be present
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.some(b => /save/i.test(b.textContent || ''))).toBe(true);
|
||||
expect(buttons.some((b) => /save/i.test(b.textContent || ''))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-010: webhook URL input shows masked placeholder when webhook is already set', async () => {
|
||||
@@ -226,14 +311,34 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, webhook: false } },
|
||||
available_channels: { email: false, webhook: true, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
}),
|
||||
),
|
||||
http.get('/api/settings', () =>
|
||||
HttpResponse.json({ settings: { webhook_url: '••••••••' } }),
|
||||
})
|
||||
),
|
||||
http.get('/api/settings', () => HttpResponse.json({ settings: { webhook_url: '••••••••' } }))
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -252,15 +357,37 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, webhook: false } },
|
||||
available_channels: { email: false, webhook: true, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
}),
|
||||
})
|
||||
),
|
||||
http.put('/api/settings', async ({ request }) => {
|
||||
capturedBody = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -271,7 +398,7 @@ describe('NotificationsTab', () => {
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.type(input, 'https://example.com/hook');
|
||||
|
||||
const saveBtn = screen.getAllByRole('button').find(b => /save/i.test(b.textContent || ''));
|
||||
const saveBtn = screen.getAllByRole('button').find((b) => /save/i.test(b.textContent || ''));
|
||||
expect(saveBtn).toBeDefined();
|
||||
await user.click(saveBtn!);
|
||||
|
||||
@@ -285,14 +412,34 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, webhook: false } },
|
||||
available_channels: { email: false, webhook: true, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
}),
|
||||
),
|
||||
http.get('/api/settings', () =>
|
||||
HttpResponse.json({ settings: { webhook_url: '' } }),
|
||||
})
|
||||
),
|
||||
http.get('/api/settings', () => HttpResponse.json({ settings: { webhook_url: '' } }))
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -301,7 +448,7 @@ describe('NotificationsTab', () => {
|
||||
});
|
||||
|
||||
await screen.findByRole('textbox');
|
||||
const testBtn = screen.getAllByRole('button').find(b => /test/i.test(b.textContent || ''));
|
||||
const testBtn = screen.getAllByRole('button').find((b) => /test/i.test(b.textContent || ''));
|
||||
expect(testBtn).toBeDefined();
|
||||
expect(testBtn).toBeDisabled();
|
||||
});
|
||||
@@ -312,21 +459,41 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, webhook: false } },
|
||||
available_channels: { email: false, webhook: true, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
}),
|
||||
),
|
||||
http.post('/api/notifications/test-webhook', () =>
|
||||
HttpResponse.json({ success: true }),
|
||||
})
|
||||
),
|
||||
http.post('/api/notifications/test-webhook', () => HttpResponse.json({ success: true }))
|
||||
);
|
||||
|
||||
render(
|
||||
<>
|
||||
<NotificationsTab />
|
||||
<ToastContainer />
|
||||
</>,
|
||||
</>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -336,7 +503,7 @@ describe('NotificationsTab', () => {
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.type(input, 'https://example.com/hook');
|
||||
|
||||
const testBtn = screen.getAllByRole('button').find(b => /test/i.test(b.textContent || ''));
|
||||
const testBtn = screen.getAllByRole('button').find((b) => /test/i.test(b.textContent || ''));
|
||||
expect(testBtn).toBeDefined();
|
||||
await user.click(testBtn!);
|
||||
|
||||
@@ -352,11 +519,40 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, ntfy: false } },
|
||||
available_channels: { email: false, webhook: false, inapp: true, ntfy: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'ntfy',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.ntfy',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
|
||||
}),
|
||||
),
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -374,12 +570,41 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, ntfy: false } },
|
||||
available_channels: { email: false, webhook: false, inapp: true, ntfy: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'ntfy',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.ntfy',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
|
||||
}),
|
||||
})
|
||||
),
|
||||
http.get('/api/settings', () => HttpResponse.json({ settings: { ntfy_topic: '' } })),
|
||||
http.get('/api/settings', () => HttpResponse.json({ settings: { ntfy_topic: '' } }))
|
||||
);
|
||||
|
||||
render(<NotificationsTab />);
|
||||
@@ -389,7 +614,7 @@ describe('NotificationsTab', () => {
|
||||
|
||||
// Test button should be disabled when topic is empty
|
||||
const allButtons = await screen.findAllByRole('button');
|
||||
const testBtn = allButtons.find(b => /test/i.test(b.textContent || ''));
|
||||
const testBtn = allButtons.find((b) => /test/i.test(b.textContent || ''));
|
||||
expect(testBtn).toBeDefined();
|
||||
expect(testBtn).toBeDisabled();
|
||||
});
|
||||
@@ -401,22 +626,51 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, ntfy: false } },
|
||||
available_channels: { email: false, webhook: false, inapp: true, ntfy: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'ntfy',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.ntfy',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
|
||||
}),
|
||||
})
|
||||
),
|
||||
http.post('/api/notifications/test-ntfy', () => {
|
||||
ntfyCalled = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
render(
|
||||
<>
|
||||
<NotificationsTab />
|
||||
<ToastContainer />
|
||||
</>,
|
||||
</>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -429,7 +683,7 @@ describe('NotificationsTab', () => {
|
||||
|
||||
// Test button should now be enabled
|
||||
const allButtons = screen.getAllByRole('button');
|
||||
const testBtn = allButtons.find(b => /test/i.test(b.textContent || ''));
|
||||
const testBtn = allButtons.find((b) => /test/i.test(b.textContent || ''));
|
||||
expect(testBtn).toBeDefined();
|
||||
expect(testBtn).not.toBeDisabled();
|
||||
|
||||
@@ -446,21 +700,43 @@ describe('NotificationsTab', () => {
|
||||
http.get('/api/notifications/preferences', () =>
|
||||
HttpResponse.json({
|
||||
preferences: { trip_invite: { inapp: true, webhook: false } },
|
||||
available_channels: { email: false, webhook: true, inapp: true },
|
||||
channels: [
|
||||
{
|
||||
id: 'email',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.email',
|
||||
active: false,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'webhook',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.webhook',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
{
|
||||
id: 'inapp',
|
||||
source: 'builtin',
|
||||
labelKey: 'settings.notificationPreferences.inapp',
|
||||
active: true,
|
||||
configured: true,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
}),
|
||||
})
|
||||
),
|
||||
http.post('/api/notifications/test-webhook', () =>
|
||||
HttpResponse.json({ success: false, error: 'Connection refused' }),
|
||||
),
|
||||
HttpResponse.json({ success: false, error: 'Connection refused' })
|
||||
)
|
||||
);
|
||||
|
||||
render(
|
||||
<>
|
||||
<NotificationsTab />
|
||||
<ToastContainer />
|
||||
</>,
|
||||
</>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -470,7 +746,7 @@ describe('NotificationsTab', () => {
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.type(input, 'https://example.com/hook');
|
||||
|
||||
const testBtn = screen.getAllByRole('button').find(b => /test/i.test(b.textContent || ''));
|
||||
const testBtn = screen.getAllByRole('button').find((b) => /test/i.test(b.textContent || ''));
|
||||
expect(testBtn).toBeDefined();
|
||||
await user.click(testBtn!);
|
||||
|
||||
@@ -480,3 +756,98 @@ describe('NotificationsTab', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Plugin notification channels (e.g. a Gotify plugin)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// A plugin channel must be a first-class citizen here alongside in-app/email/ntfy:
|
||||
// its own column in the matrix, its state visible, and a way to act on it. The
|
||||
// credentials themselves live on the plugin's settings page, so an UNconfigured
|
||||
// channel links there rather than just naming the place.
|
||||
|
||||
const pluginMatrix = (over: Record<string, unknown> = {}) => ({
|
||||
preferences: { trip_invite: { inapp: true, 'plugin:trek-gotify': true } },
|
||||
channels: [
|
||||
{ id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },
|
||||
{
|
||||
id: 'plugin:trek-gotify',
|
||||
source: 'plugin',
|
||||
label: 'Gotify',
|
||||
settingsPath: '/settings?tab=plugins',
|
||||
active: true,
|
||||
configured: true,
|
||||
...over,
|
||||
},
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'plugin:trek-gotify'] },
|
||||
});
|
||||
|
||||
function mockMatrix(matrix: unknown) {
|
||||
server.use(
|
||||
http.get('*/api/notifications/preferences', () => HttpResponse.json(matrix)),
|
||||
http.get('*/api/settings', () => HttpResponse.json({ settings: {} })),
|
||||
);
|
||||
}
|
||||
|
||||
describe('NotificationsTab — plugin channels', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PLUGIN-001: a configured plugin channel gets its own column, by its own name', async () => {
|
||||
mockMatrix(pluginMatrix());
|
||||
render(<NotificationsTab />);
|
||||
// The server sends the display name outright — plugin channels have no i18n key.
|
||||
// It appears TWICE by design: once as the channel's own card, once as the matrix
|
||||
// column header — i.e. it really is a first-class column, not just a side panel.
|
||||
const shown = await screen.findAllByText('Gotify');
|
||||
expect(shown.length).toBe(2);
|
||||
// …and it is togglable per event, exactly like a built-in.
|
||||
await waitFor(() => expect(screen.getAllByRole('button').length).toBeGreaterThan(0));
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PLUGIN-002: configured → offers a test send, no Configure link', async () => {
|
||||
mockMatrix(pluginMatrix({ configured: true }));
|
||||
render(<NotificationsTab />);
|
||||
|
||||
const test = await screen.findByRole('button', { name: /send test/i });
|
||||
expect(test).toBeEnabled();
|
||||
expect(screen.queryByRole('link', { name: /configure/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PLUGIN-003: NOT configured → links to the plugin settings tab, test disabled', async () => {
|
||||
mockMatrix(pluginMatrix({ configured: false }));
|
||||
render(<NotificationsTab />);
|
||||
|
||||
const link = await screen.findByRole('link', { name: /configure/i });
|
||||
// A real route — settings is one page with a ?tab= param, not a route per plugin.
|
||||
expect(link).toHaveAttribute('href', '/settings?tab=plugins');
|
||||
expect(screen.getByRole('button', { name: /send test/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PLUGIN-004: Send test calls the generic channel-test route', async () => {
|
||||
mockMatrix(pluginMatrix());
|
||||
let called = '';
|
||||
server.use(
|
||||
http.post('*/api/notifications/test/:channelId', ({ params }) => {
|
||||
called = String(params.channelId);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await userEvent.click(await screen.findByRole('button', { name: /send test/i }));
|
||||
await waitFor(() => expect(called).toBe('plugin:trek-gotify'));
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PLUGIN-005: an INACTIVE plugin channel is not shown at all', async () => {
|
||||
mockMatrix(pluginMatrix({ active: false }));
|
||||
render(<NotificationsTab />);
|
||||
await screen.findByText(/in-app/i);
|
||||
// The admin hasn't enabled the channel — it must not appear as an option.
|
||||
expect(screen.queryByText('Gotify')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Lock } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { notificationsApi, settingsApi } from '../../api/client'
|
||||
@@ -6,19 +7,30 @@ import { useToast } from '../shared/Toast'
|
||||
import ToggleSwitch from './ToggleSwitch'
|
||||
import Section from './Section'
|
||||
|
||||
interface ChannelDescriptor {
|
||||
id: string
|
||||
source: 'builtin' | 'plugin'
|
||||
/** Built-ins: an i18n key. */
|
||||
labelKey?: string
|
||||
/** Plugin channels: a literal name, already resolved by the server. */
|
||||
label?: string
|
||||
settingsPath?: string
|
||||
active: boolean
|
||||
configured: boolean
|
||||
}
|
||||
|
||||
interface PreferencesMatrix {
|
||||
preferences: Record<string, Record<string, boolean>>
|
||||
available_channels: { email: boolean; webhook: boolean; inapp: boolean; ntfy: boolean }
|
||||
channels: ChannelDescriptor[]
|
||||
event_types: string[]
|
||||
implemented_combos: Record<string, string[]>
|
||||
defaults?: { ntfyServer: string | null }
|
||||
}
|
||||
|
||||
const CHANNEL_LABEL_KEYS: Record<string, string> = {
|
||||
email: 'settings.notificationPreferences.email',
|
||||
webhook: 'settings.notificationPreferences.webhook',
|
||||
inapp: 'settings.notificationPreferences.inapp',
|
||||
ntfy: 'settings.notificationPreferences.ntfy',
|
||||
/** Plugin channels have no i18n — the server sends their display name outright. */
|
||||
function channelLabel(ch: ChannelDescriptor, t: (k: string) => string): string {
|
||||
if (ch.labelKey) return t(ch.labelKey) || ch.id
|
||||
return ch.label || ch.id
|
||||
}
|
||||
|
||||
const EVENT_LABEL_KEYS: Record<string, string> = {
|
||||
@@ -48,6 +60,7 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
const [ntfyTokenIsSet, setNtfyTokenIsSet] = useState(false)
|
||||
const [ntfySaving, setNtfySaving] = useState(false)
|
||||
const [ntfyTesting, setNtfyTesting] = useState(false)
|
||||
const [channelTesting, setChannelTesting] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
notificationsApi.getPreferences().then((data: PreferencesMatrix) => setMatrix(data)).catch(() => {})
|
||||
@@ -71,13 +84,34 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Columns are whatever the server says exists and the admin turned on — so a
|
||||
// plugin channel gets a column here with no client change.
|
||||
const visibleChannels = matrix
|
||||
? (['email', 'webhook', 'ntfy', 'inapp'] as const).filter(ch => {
|
||||
if (!matrix.available_channels[ch as keyof typeof matrix.available_channels]) return false
|
||||
return matrix.event_types.some(evt => matrix.implemented_combos[evt]?.includes(ch))
|
||||
? matrix.channels.filter(ch => {
|
||||
if (!ch.active) return false
|
||||
return matrix.event_types.some(evt => matrix.implemented_combos[evt]?.includes(ch.id))
|
||||
})
|
||||
: []
|
||||
|
||||
const hasChannel = (id: string) => matrix?.channels.some(ch => ch.id === id && ch.active) ?? false
|
||||
|
||||
// Plugin channels have no bespoke credential form here — the user fills those in on the
|
||||
// plugin's own settings page. What they DO get is a test send, through the generic route.
|
||||
const pluginChannels = matrix?.channels.filter(ch => ch.source === 'plugin' && ch.active) ?? []
|
||||
|
||||
const testChannel = async (ch: ChannelDescriptor) => {
|
||||
setChannelTesting(ch.id)
|
||||
try {
|
||||
const result = await notificationsApi.testChannel(ch.id)
|
||||
if (result.success) toast.success(t('settings.notificationPreferences.testSuccess'))
|
||||
else toast.error(result.error || t('settings.notificationPreferences.testFailed'))
|
||||
} catch {
|
||||
toast.error(t('settings.notificationPreferences.testFailed'))
|
||||
} finally {
|
||||
setChannelTesting(null)
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = async (eventType: string, channel: string) => {
|
||||
if (!matrix) return
|
||||
const current = matrix.preferences[eventType]?.[channel] ?? true
|
||||
@@ -184,7 +218,7 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
|
||||
{saving && <p style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginBottom: 8 }}>{t('common.saving')}</p>}
|
||||
{matrix.available_channels.webhook && (
|
||||
{hasChannel('webhook') && (
|
||||
<div style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
|
||||
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
|
||||
{t('settings.webhookUrl.label')}
|
||||
@@ -215,7 +249,7 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{matrix.available_channels.ntfy && (
|
||||
{hasChannel('ntfy') && (
|
||||
<div style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
|
||||
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
|
||||
{t('settings.ntfyUrl.topicLabel')}
|
||||
@@ -275,19 +309,50 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{pluginChannels.map(ch => (
|
||||
<div key={ch.id} style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
|
||||
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
|
||||
{channelLabel(ch, t)}
|
||||
</label>
|
||||
<p style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginBottom: 8 }}>
|
||||
{ch.configured
|
||||
? t('settings.notificationPreferences.pluginConfigured')
|
||||
: t('settings.notificationPreferences.notConfigured')}
|
||||
</p>
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
{/* Unconfigured is the common case on first use — send them to where the
|
||||
credentials actually live rather than just naming the place. */}
|
||||
{!ch.configured && ch.settingsPath && (
|
||||
<Link
|
||||
to={ch.settingsPath}
|
||||
style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', padding: '6px 12px', background: 'var(--text-primary)', color: 'var(--bg-primary)', border: 'none', borderRadius: 6, textDecoration: 'none' }}
|
||||
>
|
||||
{t('settings.notificationPreferences.configure')}
|
||||
</Link>
|
||||
)}
|
||||
<button
|
||||
onClick={() => testChannel(ch)}
|
||||
disabled={!ch.configured || channelTesting === ch.id}
|
||||
style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', padding: '6px 12px', background: 'transparent', color: 'var(--text-secondary)', border: '1px solid var(--border-primary)', borderRadius: 6, cursor: (!ch.configured || channelTesting === ch.id) ? 'not-allowed' : 'pointer', opacity: (!ch.configured || channelTesting === ch.id) ? 0.5 : 1 }}
|
||||
>
|
||||
{t('settings.notificationPreferences.sendTest')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{/* Header row */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: `1fr ${visibleChannels.map(() => '64px').join(' ')}`, gap: 4, paddingBottom: 6, marginBottom: 4, borderBottom: '1px solid var(--border-primary)' }}>
|
||||
<span />
|
||||
{visibleChannels.map(ch => (
|
||||
<span key={ch} style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', textAlign: 'center', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
|
||||
{t(CHANNEL_LABEL_KEYS[ch]) || ch}
|
||||
<span key={ch.id} title={!ch.configured ? t('settings.notificationPreferences.notConfigured') : undefined} style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, color: ch.configured ? 'var(--text-faint)' : 'var(--color-warning, #d69e2e)', textAlign: 'center', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
|
||||
{channelLabel(ch, t)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{/* Event rows */}
|
||||
{matrix.event_types.map(eventType => {
|
||||
const implementedForEvent = matrix.implemented_combos[eventType] ?? []
|
||||
const relevantChannels = visibleChannels.filter(ch => implementedForEvent.includes(ch))
|
||||
const relevantChannels = visibleChannels.filter(ch => implementedForEvent.includes(ch.id))
|
||||
if (relevantChannels.length === 0) return null
|
||||
return (
|
||||
<div key={eventType} style={{ display: 'grid', gridTemplateColumns: `1fr ${visibleChannels.map(() => '64px').join(' ')}`, gap: 4, alignItems: 'center', padding: '6px 0', borderBottom: '1px solid var(--border-primary)' }}>
|
||||
@@ -295,13 +360,13 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
{t(EVENT_LABEL_KEYS[eventType]) || eventType}
|
||||
</span>
|
||||
{visibleChannels.map(ch => {
|
||||
if (!implementedForEvent.includes(ch)) {
|
||||
return <span key={ch} style={{ textAlign: 'center', color: 'var(--text-faint)', fontSize: 'calc(14px * var(--fs-scale-body, 1))' }}>—</span>
|
||||
if (!implementedForEvent.includes(ch.id)) {
|
||||
return <span key={ch.id} style={{ textAlign: 'center', color: 'var(--text-faint)', fontSize: 'calc(14px * var(--fs-scale-body, 1))' }}>—</span>
|
||||
}
|
||||
const isOn = matrix.preferences[eventType]?.[ch] ?? true
|
||||
const isOn = matrix.preferences[eventType]?.[ch.id] ?? true
|
||||
return (
|
||||
<div key={ch} style={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<ToggleSwitch on={isOn} onToggle={() => toggle(eventType, ch)} />
|
||||
<div key={ch.id} style={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<ToggleSwitch on={isOn} onToggle={() => toggle(eventType, ch.id)} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Blocks, Save, Loader2, Link2, Unlink, CheckCircle } from 'lucide-react'
|
||||
import { pluginsApi, type PluginUserSettingField } from '../../api/client'
|
||||
import { pluginsApi, type PluginUserSettingField, type PluginAction } from '../../api/client'
|
||||
import { usePluginStore } from '../../store/pluginStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -64,6 +64,9 @@ function PluginSettingsForm({ id, name }: { id: string; name: string }) {
|
||||
const [values, setValues] = useState<Record<string, string | boolean>>({})
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [oauth, setOauth] = useState<{ configured: boolean; connected: boolean } | null>(null)
|
||||
const [actions, setActions] = useState<PluginAction[]>([])
|
||||
const [running, setRunning] = useState<string | null>(null)
|
||||
const [actionResult, setActionResult] = useState<Record<string, { ok: boolean; message?: string }>>({})
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
@@ -71,6 +74,7 @@ function PluginSettingsForm({ id, name }: { id: string; name: string }) {
|
||||
.then(r => {
|
||||
if (!alive) return
|
||||
setFields(r.fields)
|
||||
setActions(r.actions ?? [])
|
||||
const init: Record<string, string | boolean> = {}
|
||||
for (const f of r.fields) {
|
||||
const v = r.config[f.key]
|
||||
@@ -84,8 +88,23 @@ function PluginSettingsForm({ id, name }: { id: string; name: string }) {
|
||||
}, [id])
|
||||
|
||||
const hasFields = (fields?.length ?? 0) > 0
|
||||
// Show the card if the plugin has user fields OR an OAuth connection to offer.
|
||||
if (fields === null || (!hasFields && !oauth?.configured)) return null
|
||||
// Show the card if the plugin has user fields, actions, OR an OAuth connection to offer.
|
||||
if (fields === null || (!hasFields && actions.length === 0 && !oauth?.configured)) return null
|
||||
|
||||
// An action runs AS the caller, so it sees the values they just saved — run the save
|
||||
// first if the form is dirty would be nicer, but keeping it explicit is less surprising.
|
||||
const runAction = async (a: PluginAction) => {
|
||||
if (a.danger && !window.confirm(t('settings.plugins.actions.confirm'))) return
|
||||
setRunning(a.key)
|
||||
try {
|
||||
const res = await pluginsApi.runAction(id, a.key)
|
||||
setActionResult(prev => ({ ...prev, [a.key]: res }))
|
||||
} catch {
|
||||
setActionResult(prev => ({ ...prev, [a.key]: { ok: false, message: t('common.error') } }))
|
||||
} finally {
|
||||
setRunning(null)
|
||||
}
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
@@ -164,6 +183,38 @@ function PluginSettingsForm({ id, name }: { id: string; name: string }) {
|
||||
{t('common.save')}
|
||||
</button>
|
||||
)}
|
||||
{actions.length > 0 && (
|
||||
<div className="mt-4 border-t border-border pt-4">
|
||||
<span className="block text-xs font-semibold uppercase tracking-wide text-content-muted mb-2">
|
||||
{t('settings.plugins.actions')}
|
||||
</span>
|
||||
<div className="flex flex-col gap-2">
|
||||
{actions.map(a => {
|
||||
const res = actionResult[a.key]
|
||||
return (
|
||||
<div key={a.key} className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={() => runAction(a)}
|
||||
disabled={running !== null}
|
||||
className={`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-semibold disabled:opacity-60 ${
|
||||
a.danger ? 'border-danger text-danger' : 'border-border text-content'
|
||||
}`}
|
||||
>
|
||||
{running === a.key && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{a.label}
|
||||
</button>
|
||||
{a.hint && <span className="text-xs text-content-muted">{a.hint}</span>}
|
||||
{res && (
|
||||
<span className={`text-xs font-medium ${res.ok ? 'text-success' : 'text-danger'}`}>
|
||||
{res.message || (res.ok ? t('common.success') : t('common.error'))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<PluginOAuthSection id={id} state={oauth} setState={setOauth} />
|
||||
</div>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user