Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 75 additions & 29 deletions app/(dashboard)/events-target/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ import { useDataTable } from "@/hooks/use-data-table"
import { useEventTarget } from "@/hooks/use-event-target"
import { useModuleSwitches } from "@/hooks/use-module-switches"
import { EventsTargetNewForm } from "@/components/events-target/new-form"
import { canManageEventDestinations } from "@/lib/event-destinations-access"
import {
applyEventDestinationsLoadResult,
canManageEventDestinations,
initialEventDestinationsState,
resolveEventDestinationsNotifyState,
type EventDestinationsLoadState,
} from "@/lib/event-destinations-state"
import { useDialog } from "@/lib/feedback/dialog"
import { useMessage } from "@/lib/feedback/message"
import type { ColumnDef } from "@tanstack/react-table"
Expand All @@ -38,41 +44,60 @@ export default function EventsTargetPage() {
const { getEventsTargetList, deleteEventTarget } = useEventTarget()
const { getModuleSwitches } = useModuleSwitches()

const [data, setData] = useState<RowData[]>([])
const [loading, setLoading] = useState(false)
const [loadState, setLoadState] = useState<EventDestinationsLoadState<RowData>>({
...initialEventDestinationsState,
})
const [loading, setLoading] = useState(true)
const [searchTerm, setSearchTerm] = useState("")
const [newFormOpen, setNewFormOpen] = useState(false)
const [notifyEnabled, setNotifyEnabled] = useState<boolean | undefined>(undefined)
const loadingRef = React.useRef(false)
const requestVersionRef = React.useRef(0)

const canManageDestinations = canManageEventDestinations(notifyEnabled)
const { data, loadFailed, notifyEnabled, notifyFailed } = loadState
const canManageDestinations = canManageEventDestinations({
notifyEnabled,
loading,
loadFailed,
notifyFailed,
})

const loadData = useCallback(async () => {
if (loadingRef.current) return
loadingRef.current = true
const requestVersion = ++requestVersionRef.current
setLoading(true)
try {
const [response, switches] = await Promise.allSettled([
getEventsTargetList(),
const response = await getEventsTargetList()
const nextNotifyEnabled = await resolveEventDestinationsNotifyState(response, () =>
getModuleSwitches({ suppress403Redirect: true }),
])

if (switches.status === "fulfilled" && switches.value) {
setNotifyEnabled(switches.value.notify_enabled)
}
)

if (response.status === "rejected") {
throw response.reason
}

const list = (response.value?.notification_endpoints ?? []) as RowData[]
setData(list)
if (requestVersion !== requestVersionRef.current) return
const list = (response.notification_endpoints ?? []) as RowData[]
setLoadState((current) =>
applyEventDestinationsLoadResult(current, {
ok: true,
data: list,
notifyEnabled: nextNotifyEnabled,
}),
)
} catch {
setData([])
if (requestVersion !== requestVersionRef.current) return
setLoadState((current) => applyEventDestinationsLoadResult(current, { ok: false }))
} finally {
setLoading(false)
if (requestVersion === requestVersionRef.current) {
loadingRef.current = false
setLoading(false)
}
}
}, [getEventsTargetList, getModuleSwitches])

useEffect(() => {
loadData()
return () => {
requestVersionRef.current += 1
loadingRef.current = false
}
}, [loadData])

const filteredData = useMemo(() => {
Expand Down Expand Up @@ -209,9 +234,9 @@ export default function EventsTargetPage() {
<RiAddLine className="size-4" aria-hidden />
<span>{t("Add Event Destination")}</span>
</Button>
<Button variant="outline" className="h-11 w-full sm:h-8 sm:w-auto" onClick={loadData}>
<Button variant="outline" className="h-11 w-full sm:h-8 sm:w-auto" onClick={loadData} disabled={loading}>
<RiRefreshLine className="size-4" aria-hidden />
<span>{t("Refresh")}</span>
<span>{loading ? t("Refreshing…") : t("Refresh")}</span>
</Button>
</div>
</div>
Expand All @@ -220,19 +245,40 @@ export default function EventsTargetPage() {
<h1 className="text-2xl font-bold">{t("Event Destinations")}</h1>
</PageHeader>

{!canManageDestinations ? (
{notifyEnabled === false ? (
<Alert>
<AlertTitle>{t("Notify is disabled")}</AlertTitle>
<AlertDescription>{t("Enable notify in Settings before managing event destinations.")}</AlertDescription>
</Alert>
) : null}

<DataTable
table={table}
isLoading={loading}
emptyTitle={t("No Destinations")}
emptyDescription={t("Create an event destination to forward notifications.")}
/>
{notifyFailed ? (
<Alert variant="destructive">
<AlertTitle>{t("Notify status unavailable")}</AlertTitle>
<AlertDescription>
{t("Unable to verify whether notify is enabled. Refresh before making changes.")}
</AlertDescription>
</Alert>
) : null}

{loadFailed ? (
<Alert variant="destructive">
<AlertTitle>{t("Load Failed")}</AlertTitle>
<AlertDescription>
{data.length > 0 ? t("Previously loaded values may be stale.") : t("Refresh to try again.")}
</AlertDescription>
</Alert>
) : null}

{data.length > 0 || !loadFailed ? (
<DataTable
table={table}
isLoading={loading && data.length === 0}
emptyTitle={t("No Destinations")}
emptyDescription={t("Create an event destination to forward notifications.")}
caption={t("Event Destinations")}
/>
) : null}

<EventsTargetNewForm open={newFormOpen} onOpenChange={setNewFormOpen} onSuccess={loadData} />
</Page>
Expand Down
1 change: 1 addition & 0 deletions hooks/use-event-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function useEventTarget() {

const getEventsTargetList = useCallback(async () => {
return api.get("/target/list") as Promise<{
notify_enabled?: unknown
notification_endpoints?: Array<{
account_id: string
service: string
Expand Down
3 changes: 0 additions & 3 deletions lib/event-destinations-access.js

This file was deleted.

3 changes: 0 additions & 3 deletions lib/event-destinations-access.ts

This file was deleted.

80 changes: 80 additions & 0 deletions lib/event-destinations-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
export interface EventDestinationsLoadState<T> {
data: T[]
loadFailed: boolean
notifyEnabled: boolean | undefined
notifyFailed: boolean
}

export const initialEventDestinationsState: EventDestinationsLoadState<never> = {
data: [],
loadFailed: false,
notifyEnabled: undefined,
notifyFailed: false,
}

export function readTargetListNotifyState(payload: unknown): {
present: boolean
value: boolean | undefined
} {
if (!payload || typeof payload !== "object" || !Object.hasOwn(payload, "notify_enabled")) {
return { present: false, value: undefined }
}

const value = (payload as { notify_enabled?: unknown }).notify_enabled
return { present: true, value: typeof value === "boolean" ? value : undefined }
}

export function readModuleNotifyState(payload: unknown) {
if (!payload || typeof payload !== "object") return undefined
const value = (payload as { notify_enabled?: unknown }).notify_enabled
return typeof value === "boolean" ? value : undefined
}

export async function resolveEventDestinationsNotifyState(
targetListPayload: unknown,
loadModuleSwitches: () => Promise<unknown>,
) {
const targetListState = readTargetListNotifyState(targetListPayload)
if (targetListState.present) return targetListState.value

try {
return readModuleNotifyState(await loadModuleSwitches())
} catch {
return undefined
}
}

export function applyEventDestinationsLoadResult<T>(
current: EventDestinationsLoadState<T>,
result: { ok: true; data: T[]; notifyEnabled: boolean | undefined } | { ok: false },
): EventDestinationsLoadState<T> {
if (!result.ok) {
return {
...current,
loadFailed: true,
notifyEnabled: undefined,
notifyFailed: false,
}
}

return {
data: result.data,
loadFailed: false,
notifyEnabled: result.notifyEnabled,
notifyFailed: result.notifyEnabled === undefined,
}
}

export function canManageEventDestinations({
notifyEnabled,
loading,
loadFailed,
notifyFailed,
}: {
notifyEnabled: boolean | undefined
loading: boolean
loadFailed: boolean
notifyFailed: boolean
}) {
return notifyEnabled === true && !loading && !loadFailed && !notifyFailed
}
2 changes: 1 addition & 1 deletion lib/notify-module-access.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export function canManageNotifyBackedFeature(notifyEnabled) {
return notifyEnabled !== false
return notifyEnabled === true
}
2 changes: 1 addition & 1 deletion lib/notify-module-access.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export function canManageNotifyBackedFeature(notifyEnabled: boolean | undefined) {
return notifyEnabled !== false
return notifyEnabled === true
}
10 changes: 0 additions & 10 deletions tests/lib/event-destinations-access.test.js

This file was deleted.

Loading