first commit

This commit is contained in:
KodekaTeam committed 2026-06-02 00:17:50 +07:00
1 parent abb09fbea8
commit 72f6d49818
355 files changed
+121239 -3

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,123 @@
export const NOTIFICATION_ACTION_OPTIONS = [
{
value: "server_down",
label: "Server down",
description: "Trigger the action when a server stops responding.",
},
{
value: "high_cpu_over_80",
label: "High CPU (>80%)",
description: "Trigger the action when CPU usage passes 80%.",
},
{
value: "high_ram_over_90",
label: "High RAM (>90%)",
description: "Trigger the action when RAM usage passes 90%.",
},
{
value: "ssl_expiring",
label: "SSL expiring",
description: "Trigger the action when an SSL certificate is near expiry.",
},
{
value: "container_crash",
label: "Container crash",
description: "Trigger the action when a container stops unexpectedly.",
},
{
value: "security_breach",
label: "Security breach",
description: "Trigger the action when a security incident is detected.",
},
{
value: "app_deploy",
label: "App Deploy",
description: "Trigger the action when an app is deployed.",
},
{
value: "app_build_error",
label: "App Build Error",
description: "Trigger the action when the build fails.",
},
{
value: "database_backup",
label: "Database Backup",
description: "Trigger the action for database backup lifecycle updates.",
},
{
value: "doktainer_backup",
label: "Doktainer Backup",
description: "Reserved for Doktainer app database backup notifications.",
},
{
value: "volume_backup",
label: "Volume Backup",
description: "Trigger the action when a volume backup is created.",
},
{
value: "docker_cleanup",
label: "Docker Cleanup",
description: "Trigger the action when Docker cleanup is performed.",
},
{
value: "server_threshold",
label: "Server Threshold",
description: "Trigger the action when the server threshold is reached.",
},
] as const;
const NOTIFICATION_ACTION_ALIASES: Record<string, string> = {
backup_database: "database_backup",
backup_doktainer: "doktainer_backup",
};
const NOTIFICATION_ACTION_LABELS = new Map<string, string>(
NOTIFICATION_ACTION_OPTIONS.map((action) => [action.value, action.label]),
);
export function normalizeNotificationActionKey(value: string) {
const trimmed = value.trim();
if (!trimmed) {
return "";
}
const normalizedAlias = trimmed
.toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "");
if (NOTIFICATION_ACTION_ALIASES[normalizedAlias]) {
return NOTIFICATION_ACTION_ALIASES[normalizedAlias];
}
const matchedOption = NOTIFICATION_ACTION_OPTIONS.find(
(action) => action.value === trimmed || action.label === trimmed,
);
if (matchedOption) {
return matchedOption.value;
}
return trimmed
.toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "");
}
export function normalizeNotificationActionKeys(values: string[]) {
return [
...new Set(values.map(normalizeNotificationActionKey).filter(Boolean)),
];
}
export function getNotificationActionLabel(value: string) {
const normalizedValue = normalizeNotificationActionKey(value);
return (
NOTIFICATION_ACTION_LABELS.get(normalizedValue) ||
normalizedValue
.split("_")
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(" ")
);
}
@@ -0,0 +1,25 @@
import type {
NotificationProviderRecord,
NotificationProviderType,
SettingsRecord,
} from "@/lib/api";
export type NotificationProviderItem = NotificationProviderRecord;
export type NotificationProviderKind = NotificationProviderType;
export type EditableNotificationSettings = SettingsRecord & {
integrations: {
cloudflare: SettingsRecord["integrations"]["cloudflare"] & {
apiToken: string;
};
awsS3: SettingsRecord["integrations"]["awsS3"] & {
secretAccessKey: string;
};
github: SettingsRecord["integrations"]["github"] & {
token: string;
};
gitlab: SettingsRecord["integrations"]["gitlab"] & {
token: string;
};
};
};
@@ -0,0 +1,121 @@
import type { SettingsRecord, UpdateSettingsBody } from "@/lib/api";
import { normalizeNotificationActionKeys } from "@/app/notifications/components/notification-actions";
import type { EditableNotificationSettings } from "@/app/notifications/components/notification-settings.types";
import { resolvePublicAppOrigin } from "@/server/lib/public-url";
function normalizeProviders(
providers: SettingsRecord["notifications"]["providers"],
) {
return providers.map((provider) => ({
...provider,
actions: normalizeNotificationActionKeys(provider.actions),
}));
}
export const emptyNotificationSettings = (): EditableNotificationSettings => ({
general: {
panelName: process.env.NEXT_PUBLIC_PANEL_NAME || "DOKTAINER",
panelUrl: resolvePublicAppOrigin(),
timezone: process.env.NEXT_PUBLIC_PANEL_TIMEZONE || "Asia/Jakarta",
theme: "dark",
sessionTimeoutMinutes: 30,
},
notifications: {
providers: [],
},
security: {
twoFactorEnabled: false,
twoFactorPendingSetup: false,
ipWhitelistEnabled: false,
ipWhitelist: [],
},
integrations: {
cloudflare: {
connected: false,
zoneId: "",
hasApiToken: false,
apiToken: "",
},
awsS3: {
connected: false,
accessKeyId: "",
region: "",
bucket: "",
hasSecretAccessKey: false,
secretAccessKey: "",
},
github: {
connected: false,
hasToken: false,
token: "",
},
gitlab: {
connected: false,
hasToken: false,
token: "",
},
},
});
export function toEditableNotificationSettings(
source: SettingsRecord,
): EditableNotificationSettings {
return {
...source,
notifications: {
providers: normalizeProviders(source.notifications.providers),
},
integrations: {
cloudflare: {
...source.integrations.cloudflare,
apiToken: "",
},
awsS3: {
...source.integrations.awsS3,
secretAccessKey: "",
},
github: {
...source.integrations.github,
token: "",
},
gitlab: {
...source.integrations.gitlab,
token: "",
},
},
};
}
export function toNotificationSettingsPayload(
source: EditableNotificationSettings,
): UpdateSettingsBody {
return {
general: source.general,
notifications: {
providers: normalizeProviders(source.notifications.providers),
},
security: source.security,
integrations: {
cloudflare: {
connected: source.integrations.cloudflare.connected,
zoneId: source.integrations.cloudflare.zoneId,
apiToken: source.integrations.cloudflare.apiToken,
},
awsS3: {
connected: source.integrations.awsS3.connected,
accessKeyId: source.integrations.awsS3.accessKeyId,
secretAccessKey: source.integrations.awsS3.secretAccessKey,
region: source.integrations.awsS3.region,
bucket: source.integrations.awsS3.bucket,
},
github: {
connected: source.integrations.github.connected,
token: source.integrations.github.token,
},
gitlab: {
connected: source.integrations.gitlab.connected,
token: source.integrations.gitlab.token,
},
},
};
}
+338
View File
@@ -0,0 +1,338 @@
"use client";
import { useEffect, useState } from "react";
import ConfirmActionDialog from "@/components/ConfirmActionDialog";
import ToastViewport from "@/components/ToastViewport";
import GuardedPage from "@/components/GuardedPage";
import { settingsApi, type SettingsRecord } from "@/lib/api";
import NotificationsSettingsPanel from "@/app/notifications/components/NotificationsSettingsPanel";
import type {
EditableNotificationSettings,
NotificationProviderItem,
} from "@/app/notifications/components/notification-settings.types";
import {
emptyNotificationSettings,
toEditableNotificationSettings,
toNotificationSettingsPayload,
} from "@/app/notifications/components/notification-settings.utils";
import {
Banner,
SettingsLoadingPanel,
} from "@/app/settings/components/SettingsPrimitives";
import { useToastManager } from "@/lib/use-toast-manager";
type PendingConfirmAction = {
title: string;
description: string;
confirmLabel: string;
tone?: "danger" | "warning" | "info";
note?: string;
onConfirm: () => void;
};
export default function NotificationsPage() {
const [settings, setSettings] = useState<EditableNotificationSettings>(
emptyNotificationSettings,
);
const [loading, setLoading] = useState(true);
const [actionLoading, setActionLoading] = useState<string | null>(null);
const [savingProviderId, setSavingProviderId] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [confirmDialog, setConfirmDialog] =
useState<PendingConfirmAction | null>(null);
const { toasts, pushToast, dismissToast } = useToastManager();
const syncSettingsFromServer = (source: SettingsRecord) => {
setSettings(toEditableNotificationSettings(source));
};
useEffect(() => {
let mounted = true;
const loadSettings = async () => {
setLoading(true);
setLoadError(null);
try {
const response = await settingsApi.get();
if (!mounted) return;
syncSettingsFromServer(response.data);
} catch (err) {
if (!mounted) return;
setLoadError(
err instanceof Error ? err.message : "Failed to load settings",
);
} finally {
if (mounted) setLoading(false);
}
};
void loadSettings();
return () => {
mounted = false;
};
}, []);
const persistSettings = async (
nextSettings: EditableNotificationSettings,
options?: { providerId?: string | null; successMessage?: string },
) => {
setSavingProviderId(options?.providerId ?? null);
try {
const response = await settingsApi.update(
toNotificationSettingsPayload(nextSettings),
);
syncSettingsFromServer(response.data);
pushToast({
tone: "success",
title: "Notification Updated",
message:
options?.successMessage ||
response.message ||
"Notification settings saved",
});
} catch (err) {
pushToast({
tone: "error",
title: "Save Failed",
message:
err instanceof Error ? err.message : "Failed to save notifications",
});
} finally {
setSavingProviderId(null);
}
};
const applyProviderChange = (
recipe: (
current: EditableNotificationSettings,
) => EditableNotificationSettings,
options?: { providerId?: string | null; successMessage?: string },
) => {
let nextState: EditableNotificationSettings | null = null;
setSettings((current) => {
nextState = recipe(current);
return nextState;
});
queueMicrotask(() => {
if (nextState) {
void persistSettings(nextState, options);
}
});
};
const upsertProvider = async (
provider: EditableNotificationSettings["notifications"]["providers"][number],
) => {
const isExisting = settings.notifications.providers.some(
(item) => item.id === provider.id,
);
applyProviderChange(
(current) => ({
...current,
notifications: {
...current.notifications,
providers: isExisting
? current.notifications.providers.map((item) =>
item.id === provider.id ? provider : item,
)
: [...current.notifications.providers, provider],
},
}),
{
providerId: provider.id,
successMessage: isExisting
? "Notification provider updated"
: "Notification provider created",
},
);
};
const toggleProvider = async (providerId: string) => {
applyProviderChange(
(current) => ({
...current,
notifications: {
...current.notifications,
providers: current.notifications.providers.map((item) =>
item.id === providerId ? { ...item, enabled: !item.enabled } : item,
),
},
}),
{
providerId,
successMessage: "Provider status updated",
},
);
};
const performDeleteProvider = async (provider: NotificationProviderItem) => {
const providerId = provider.id;
applyProviderChange(
(current) => ({
...current,
notifications: {
...current.notifications,
providers: current.notifications.providers.filter(
(item) => item.id !== providerId,
),
},
}),
{
providerId,
successMessage: "Notification provider deleted",
},
);
};
const handleDeleteProvider = (provider: NotificationProviderItem) => {
setConfirmDialog({
title: "Delete Notification Provider",
description: `Delete notification provider "${provider.name}"?`,
confirmLabel: "Delete Provider",
tone: "danger",
note: "This removes the saved notification provider configuration and credentials from Doktainer.",
onConfirm: () => {
void performDeleteProvider(provider);
},
});
};
const testNotification = async (providerId: string) => {
const selected = settings.notifications.providers.find(
(item) => item.id === providerId,
);
if (!selected) {
pushToast({
tone: "error",
title: "Provider Not Found",
message: "Notification provider tidak ditemukan.",
});
return;
}
if (
selected.type !== "email" &&
selected.type !== "telegram" &&
selected.type !== "discord" &&
selected.type !== "custom"
) {
pushToast({
tone: "warning",
title: "Live Test Unavailable",
message:
"Live test saat ini hanya tersedia untuk Email, Telegram, Discord, dan Custom Webhook.",
});
return;
}
const payloadMap: Record<
"email" | "telegram" | "discord" | "custom",
Record<string, unknown>
> = {
email: {
id: selected.id,
name: selected.name,
enabled: selected.enabled,
smtpHost: selected.smtpHost,
smtpPort: selected.smtpPort,
smtpSecure: selected.smtpSecure,
smtpUsername: selected.smtpUsername,
smtpPassword: selected.smtpPassword,
smtpFromEmail: selected.smtpFromEmail,
smtpFromName: selected.smtpFromName,
},
telegram: {
id: selected.id,
name: selected.name,
enabled: selected.enabled,
telegramBotToken: selected.telegramBotToken,
telegramChatId: selected.telegramChatId,
},
discord: {
id: selected.id,
name: selected.name,
enabled: selected.enabled,
webhookUrl: selected.webhookUrl,
},
custom: {
id: selected.id,
name: selected.name,
enabled: selected.enabled,
webhookUrl: selected.webhookUrl,
},
};
setActionLoading(`notify-${selected.type}-${selected.id}`);
try {
const response = await settingsApi.testNotification(
selected.type,
payloadMap[selected.type],
);
pushToast({
tone: "success",
title: "Test Notification Sent",
message: response.message || "Test notification sent successfully",
});
} catch (err) {
pushToast({
tone: "error",
title: "Test Failed",
message: err instanceof Error ? err.message : "Action failed",
});
} finally {
setActionLoading(null);
}
};
return (
<GuardedPage
route="/notifications"
title="Notifications"
subtitle="Manage notification providers and select which events will trigger notifications."
redirectSubtitle="Redirecting to a page allowed for your role"
>
<ConfirmActionDialog
open={confirmDialog !== null}
title={confirmDialog?.title ?? ""}
description={confirmDialog?.description ?? ""}
confirmLabel={confirmDialog?.confirmLabel ?? "Confirm"}
tone={confirmDialog?.tone ?? "danger"}
note={confirmDialog?.note}
onClose={() => setConfirmDialog(null)}
onConfirm={() => {
const current = confirmDialog;
setConfirmDialog(null);
current?.onConfirm();
}}
/>
<div
className="animate-slide-in"
style={{ display: "flex", flexDirection: "column", gap: 16 }}
>
{loadError ? <Banner message={loadError} tone="error" /> : null}
{loading ? (
<SettingsLoadingPanel />
) : (
<NotificationsSettingsPanel
settings={settings}
actionLoading={actionLoading}
savingProviderId={savingProviderId}
testNotification={testNotification}
onUpsertProvider={upsertProvider}
onToggleProvider={toggleProvider}
onDeleteProvider={handleDeleteProvider}
/>
)}
</div>
<ToastViewport toasts={toasts} onClose={dismissToast} />
</GuardedPage>
);
}