feat: set default notification channel

This commit is contained in:
charles-gauthereau
2026-03-25 22:07:20 +01:00
parent 7a4af4e1e0
commit 61b1a2e724
7 changed files with 2804 additions and 33 deletions
@@ -18,6 +18,10 @@ import {NotificationChannelWith} from "@/db/schema/09_notification-channel";
import {
DefaultNotificationSchema, DefaultNotificationType
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification.schema";
import {
updateNotificationSettingsAction
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification.action";
import {toast} from "sonner";
export type SettingsNotificationSectionProps = {
settings: Setting;
@@ -30,22 +34,22 @@ export const SettingsNotificationSection = ({settings, notificationChannels}: Se
const form = useZodForm({
schema: DefaultNotificationSchema,
defaultValues: {
// notificationChannels: settings.defaultNotificationChannelId ?? undefined,
notificationChannelId: settings.defaultNotificationChannelId ?? undefined,
}
});
const mutation = useMutation({
mutationFn: async (values: DefaultNotificationType) => {
// const result = await updateStorageSettingsAction({name: "system", data: values})
// const inner = result?.data;
//
// if (inner?.success) {
// toast.success(inner.actionSuccess?.message);
// router.refresh();
// } else {
// toast.error(inner?.actionError?.message);
// }
const result = await updateNotificationSettingsAction({name: "system", data: values})
const inner = result?.data;
if (inner?.success) {
toast.success(inner.actionSuccess?.message);
router.refresh();
} else {
toast.error(inner?.actionError?.message);
}
}
});
@@ -69,36 +73,41 @@ export const SettingsNotificationSection = ({settings, notificationChannels}: Se
<div className="flex flex-wrap items-center gap-3">
<FormField
control={form.control}
name="storageChannelId"
render={({field}) => (
name="notificationChannelId"
render={({ field }) => (
<FormItem className="flex-grow min-w-[200px] sm:flex-grow-0 sm:w-64">
<FormLabel>Default Notification Provider</FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-full mb-0">
<SelectValue placeholder="Select a default channel"/>
</SelectTrigger>
<SelectContent>
{notificationChannels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
<div className="flex items-center gap-2">
{getChannelIcon(channel.provider)}
<span className="font-medium">{channel.name}</span>
<span
className="text-[9px] uppercase bg-secondary px-1.5 py-0.5 rounded">
{channel.provider}
</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
{notificationChannels.length === 0 ? (
<div className="text-sm text-muted-foreground">No channel available</div>
) : (
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-full mb-0">
<SelectValue placeholder="Select a default channel" />
</SelectTrigger>
<SelectContent>
{notificationChannels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
<div className="flex items-center gap-2">
{getChannelIcon(channel.provider)}
<span className="font-medium">{channel.name}</span>
<span className="text-[9px] uppercase bg-secondary px-1.5 py-0.5 rounded">
{channel.provider}
</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)}
</FormItem>
)}
/>
</div>
{notificationChannels.length >0 && (
<ButtonWithLoading className="flex-shrink-0 w-full sm:w-auto" type="submit">
Confirm
</ButtonWithLoading>
)}
</Form>
</div>
</div>
@@ -0,0 +1,51 @@
"use server"
import {userAction} from "@/lib/safe-actions/actions";
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {eq} from "drizzle-orm";
import {ServerActionResult} from "@/types/action-type";
import {Setting} from "@/db/schema/01_setting";
import {z} from "zod";
import {
DefaultNotificationSchema
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification.schema";
export const updateNotificationSettingsAction = userAction
.schema(
z.object({
name: z.string(),
data: DefaultNotificationSchema,
})
)
.action(async ({parsedInput}): Promise<ServerActionResult<Setting>> => {
const {name, data} = parsedInput;
try {
const [updatedSettings] = await db
.update(drizzleDb.schemas.setting)
.set({
defaultNotificationChannelId: data.notificationChannelId,
})
.where(eq(drizzleDb.schemas.setting.name, name))
.returning();
return {
success: true,
value: updatedSettings,
actionSuccess: {
message: "Settings successfully updated",
},
};
} catch (error) {
return {
success: false,
actionError: {
message: "Failed update settings.",
status: 500,
cause: error instanceof Error ? error.message : "Unknown error",
},
};
}
});
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE "settings" ADD COLUMN "default_notification_channel_id" uuid;--> statement-breakpoint
ALTER TABLE "settings" ADD CONSTRAINT "settings_default_notification_channel_id_notification_channel_id_fk" FOREIGN KEY ("default_notification_channel_id") REFERENCES "public"."notification_channel"("id") ON DELETE set null ON UPDATE no action;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -295,6 +295,13 @@
"when": 1774378412843,
"tag": "0041_spooky_radioactive_man",
"breakpoints": true
},
{
"idx": 42,
"version": "7",
"when": 1774472168308,
"tag": "0042_breezy_namora",
"breakpoints": true
}
]
}
+3
View File
@@ -4,6 +4,7 @@ import {z} from "zod";
import {timestamps} from "@/db/schema/00_common";
import {storageChannel} from "@/db/schema/12_storage-channel";
import {relations} from "drizzle-orm";
import {notificationChannel} from "@/db/schema/09_notification-channel";
export const setting = pgTable("settings", {
@@ -15,6 +16,8 @@ export const setting = pgTable("settings", {
smtpPort: varchar("smtp_port", {length: 255}),
smtpUser: varchar("smtp_user", {length: 255}),
smtpSecure: boolean("smtp_secure"),
defaultNotificationChannelId: uuid('default_notification_channel_id')
.references(() => notificationChannel.id, {onDelete: "set null"}),
defaultStorageChannelId: uuid('default_storage_channel_id')
.references(() => storageChannel.id, {onDelete: "set null"}),
encryption: boolean("encryption").default(false),
+169 -2
View File
@@ -1,6 +1,10 @@
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {and, eq, gte, lt} from "drizzle-orm";
import {and, eq, gte, isNotNull, lt} from "drizzle-orm";
import {enforceRetention} from "@/lib/tasks/database";
import {dispatchNotification} from "@/features/notifications/dispatch";
import {EventKind, EventPayload} from "@/features/notifications/types";
import {DatabaseWith} from "@/db/schema/07_database";
export async function getHealthLast12hLogs({id}: { id: string }) {
const now = new Date()
@@ -38,4 +42,167 @@ export async function deleteHealthLogsOlderThan12h() {
)
return logsToDelete.length
}
}
//
//
// export async function sendNotificationsHealthCheck(event: EventKind) {
//
//
//
// const date = new Date();
// let level: "info" | "critical" = "info";
// let message = "";
// let error: string | null = null;
//
// switch (event) {
// case "error_backup":
// case "error_restore":
// level = "critical";
// message = `An error occurred during ${event.includes("backup") ? "backup" : "restore"} on ${date.toISOString()}.`;
// error = "Check database connection or agent";
// break;
// case "success_backup":
// case "success_restore":
// level = "info";
// message = `${event.includes("backup") ? "Backup" : "Restore"} completed successfully at ${date.toISOString()}.`;
// break;
// case "weekly_report":
// level = "info";
// message = `Weekly report generated at ${date.toISOString()}.`;
// break;
// }
//
//
//
//
//
//
//
//
//
//
// const activePolicies = database.alertPolicies.filter(policy =>
// policy.enabled && policy.eventKinds.includes(event)
// );
//
// const promises = activePolicies.map(alertPolicy => {
// const date = new Date();
// let level: "info" | "critical" = "info";
// let message = "";
// let error: string | null = null;
//
// switch (event) {
// case "error_backup":
// case "error_restore":
// level = "critical";
// message = `An error occurred during ${event.includes("backup") ? "backup" : "restore"} on ${date.toISOString()}.`;
// error = "Check database connection or agent";
// break;
// case "success_backup":
// case "success_restore":
// level = "info";
// message = `${event.includes("backup") ? "Backup" : "Restore"} completed successfully at ${date.toISOString()}.`;
// break;
// case "weekly_report":
// level = "info";
// message = `Weekly report generated at ${date.toISOString()}.`;
// break;
// }
//
// const titleMap: Record<EventKind, string> = {
// error_backup: `Backup Notification`,
// error_restore: `Restore Notification`,
// success_backup: `Backup Notification`,
// success_restore: `Restore Notification`,
// weekly_report: `Weekly Report Notification`,
// };
//
// const payload: EventPayload = {
// title: titleMap[event],
// message,
// level: level,
// event: event,
// data: {
// host: database.name,
// id: database.id,
// agentDatabaseId: database.agentDatabaseId,
// error,
// },
// };
//
// return dispatchNotification(payload, alertPolicy.id, undefined, undefined);
// });
//
//
// return Promise.all(promises);
// }
//
//
//
// export async function checkAgentsHealthError() {
//
// const agents = await db.query.agent.findMany({
// where: isNotNull(drizzleDb.schemas.agent.lastContact),
// });
//
// for (const agent of agents) {
// const now = new Date()
// if (agent.lastContact - now > 10min) {
//
// if (agent.health_error_count < 4) {
// // peux pas depasser 3 count
// alors
// // update agent field health_error_count +1
//
// // send notifcations health_ping_fail
//
//
// const payload: EventPayload = {
// title: titleMap[event],
// message,
// level: level,
// event: event,
// data: {
// host: database.name,
// id: database.id,
// agentDatabaseId: database.agentDatabaseId,
// error,
// },
// };
//
//
// await dispatchNotification(payload, alertPolicy.id, undefined, undefined);
// }else {
// pass
// }
// }
//
//
// if (!db.retentionPolicy) continue;
// await enforceRetention(db.id, db.retentionPolicy);
// }
//
//
//
// const now = new Date()
// const threshold = new Date(now.getTime() - 12 * 60 * 60 * 1000)
//
// const logsToDelete = await db
// .select()
// .from(drizzleDb.schemas.healthcheckLog)
// .where(
// lt(drizzleDb.schemas.healthcheckLog.date, threshold)
// )
//
// console.log(`Number of logs found to delete: ${logsToDelete.length}`)
//
// await db
// .delete(drizzleDb.schemas.healthcheckLog)
// .where(
// lt(drizzleDb.schemas.healthcheckLog.date, threshold)
// )
//
// return logsToDelete.length
// }