mirror of
https://github.com/Portabase/portabase.git
synced 2026-07-14 11:16:13 +02:00
fix: feature-base-refactoring (#297)
* docs: add AGENTS.md with feature-based architecture conventions Defines the target src/ structure, feature list, naming conventions (kebab-case, file type patterns), import direction rules, and feature boundary guidelines for the planned big-bang refactor. * docs: add features/channel/ to architecture conventions Generic channel UI (card, modal, form) goes to features/channel/. Provider-specific sub-folders: channel/notifications/ and channel/storages/. * refactor: move event emitter to lib/, project service to db/services/, dedup use-mobile hook * fix: remove unused auth import in db/services/project.ts * refactor: migrate wrappers/common to components/common (flat) * fix: remove dead commented-out code from button-with-loading.tsx * refactor: merge features/browser into features/theme, flatten upload/updates, migrate statistics * refactor: migrate wrappers/auth to features/auth Move all auth components and forms from src/components/wrappers/auth/ into src/features/auth/ with flat kebab-case naming. Handle extra reset-password-form.tsx and differing reset-password-schema.ts by copying them as reset-password-page-form.tsx and reset-password-page.schema.ts. * refactor: remove dead auth files and fix zPassword schema Delete reset-password-section.tsx and reset-password-page-form.tsx (zero consumers). Fix reset-password-page.schema.ts to import zPassword from @/lib/zod. * refactor: migrate wrappers/dashboard/common to features/layout, rename Header.tsx to header.tsx * fix: decouple layout from theme/updates cross-feature imports Use slot props (actions, updateNotification) so app/ composes ModeToggle and UpdateNotification into Header and AppSidebar. Delete dead side-bar-logo.tsx (zero consumers). * refactor: merge features/keys into features/agents, flatten sub-dirs, migrate agent wrappers - Merge src/features/keys/keys.action.ts into src/features/agents/ - Flatten src/features/agents/components/ and hooks/ into feature root - Migrate all src/components/wrappers/dashboard/agent/ files into src/features/agents/ - Update all import paths across app/ and src/ accordingly - Fix broken code-snippet import in agent-key-modal.tsx (was pointing to non-existent wrappers path) * fix: move github-releases to lib/, remove dead code and unused imports Move GitHub release fetch logic from features/updates/github.ts to lib/github-releases.ts so both features/updates and features/agents can import it without cross-feature imports. Remove commented-out impersonation block from agent-database-card.tsx. Remove unused imports (CopyButton, Terminal, Key, Info). * refactor: flatten features/projects/components, migrate project wrappers Move project.dialog/form out of sub-dir, migrate project-card, project-database-card, and delete-project button/action from wrappers into features/projects/. Update all import paths across src/ and app/. Leave wrappers/dashboard/projects/database/ untouched for Task 10. * fix: extract DatabaseCard to components/common, remove cross-feature import DatabaseCard was imported by both features/projects and features/agents, violating the no-cross-feature-import rule. Extract to components/common/ database-card.tsx so both features import from the shared layer. Also tighten extendedProps type and remove commented-out maxCount prop. * refactor: migrate all database/backup/restore/health UI to features/database Consolidates ~40 files from 5 source locations (features/dashboard/backup, features/dashboard/restore, wrappers/dashboard/backup, wrappers/dashboard/database, wrappers/dashboard/health, wrappers/dashboard/projects/database) into the new flat features/database directory with kebab-case filenames and updated @/ imports. * fix: remove dead restore-form files and console.log from health-grid Delete restore-form.tsx (186 lines all commented-out, zero consumers) and restore-form.schema.ts (only a commented import). Remove console.log(logs) from getOldestLog helper in health-grid.tsx. Cross-feature imports (database→storages for dispatchStorage/storeBackupFiles) are accepted as known architectural coupling — storage dispatch is called from database server actions at runtime and cannot route through app/ props. * refactor: migrate wrappers/admin/users to features/users, fix table-colums typo * fix: fix relative imports, string interpolation, and console.error in users feature Replace relative imports with @/ aliases in user-actions-cell.tsx and admin-user-edit-modal.tsx. Fix string interpolation bug in dialog title (was regular string, now template literal). Remove console.error from admin-user-change-role-modal.tsx. * refactor: migrate wrappers/profile to features/profile, fix profile-apperance typo * fix: remove console.error calls and ts-ignore in profile feature Remove console.error from profile-account.tsx, 2fa-form.tsx (x2). Replace @ts-ignore on fileInput.onchange with typed cast in avatar-with-upload.tsx. * refactor: rename features/organization to features/organizations, migrate all org wrappers Moves 37 org-related files from features/organization/, features/dashboard/, hooks/, wrappers/admin/organizations/, wrappers/admin/channels/organization/, and wrappers/dashboard/organization/ into a flat features/organizations/ feature directory. Updates all import paths codebase-wide. Fixes @ts-ignore and removes unused @better-fetch/fetch import in admin-organization-form. * fix: remove console.error, @ts-ignore, and unused destructures in features/organizations * refactor: migrate wrappers/organization/migration to features/migration Move all 5 migration files to src/features/migration/, update internal imports to @/features/migration/ absolute paths, remove console.log, and delete src/components/wrappers/dashboard/organization/ entirely. * refactor: migrate wrappers/admin/settings to features/settings Move all 14 settings files (email, notification, storage, s3) from wrappers/dashboard/admin/settings/ into features/settings/, rewriting imports, replacing @ts-ignore with @ts-expect-error, and renaming error params to _error where applicable. * refactor: rename notifications files to kebab convention, migrate notification logs - Rename dispatch.ts/helpers.ts/types.ts to notifications.*.ts - Migrate notification logs components from wrappers/dashboard/admin/notifications/logs/ to features/notifications/ - Fix all import paths across codebase and in providers/ - Remove unused useRouter import, replace @ts-ignore with @ts-expect-error - Delete src/components/wrappers/dashboard/admin/notifications/ * refactor: rename storages dispatch/helpers/types to kebab convention - Rename dispatch.ts/helpers.ts/types.ts to storages.*.ts - Fix all import paths across codebase and in providers/ - Fix relative ../types and ../../types imports in all storage providers to absolute @/ paths - Replace @ts-ignore with @ts-expect-error, remove console.debug/console.error * refactor: create features/channel with generic UI and notifications/storages provider sub-folders Consolidates 4 source locations into src/features/channel/: - components/wrappers/dashboard/admin/channels/ → features/channel/ (11 generic UI files) - features/notifications/providers/ → features/channel/notifications/ (9 backend + 18 form files) - features/storages/providers/ → features/channel/storages/ (backend + forms) The two conflicting google-drive/helpers.ts files (client helpers vs OAuth action) are kept separate: helpers.ts and google-drive-refresh.action.ts. Rewrites all imports codebase-wide to point to new locations. Removes console.log/console.error calls, upgrades @ts-ignore to @ts-expect-error. * fix: remove console.error from local storage provider * fix: multi-select.tsx scroll issue * fix: multi-select.tsx scroll issue
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
"use server";
|
||||
import { z } from "zod";
|
||||
import { EmailFormSchema } from "@/features/settings/email-form.schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import * as drizzleDb from "@/db";
|
||||
import {userAction} from "@/lib/safe-actions/actions";
|
||||
import {withUpdatedAt} from "@/db/utils";
|
||||
|
||||
export const updateEmailSettingsAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
data: EmailFormSchema,
|
||||
})
|
||||
)
|
||||
.action(async ({ parsedInput }) => {
|
||||
const { name, data } = parsedInput;
|
||||
|
||||
const [updatedSettings] = await db
|
||||
.update(drizzleDb.schemas.setting)
|
||||
.set(withUpdatedAt({
|
||||
...data,
|
||||
}))
|
||||
.where(eq(drizzleDb.schemas.setting.name, name))
|
||||
.returning();
|
||||
|
||||
return {
|
||||
data: updatedSettings,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const EmailFormSchema = z.object({
|
||||
smtpPassword: z.string(),
|
||||
smtpFrom: z.string(),
|
||||
smtpHost: z.string(),
|
||||
smtpPort: z.string(),
|
||||
smtpUser: z.string(),
|
||||
smtpSecure: z.boolean()
|
||||
});
|
||||
|
||||
export type EmailFormType = z.infer<typeof EmailFormSchema>;
|
||||
@@ -0,0 +1,236 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
useZodForm
|
||||
} from "@/components/ui/form";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Form} from "@/components/ui/form";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {useMutation} from "@tanstack/react-query";
|
||||
import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from "@/components/ui/tooltip";
|
||||
|
||||
import {
|
||||
EmailFormSchema,
|
||||
EmailFormType
|
||||
} from "@/features/settings/email-form.schema";
|
||||
import {PasswordInput} from "@/components/ui/password-input";
|
||||
import {
|
||||
updateEmailSettingsAction
|
||||
} from "@/features/settings/email-form.action";
|
||||
import {toast} from "sonner";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {sendEmail} from "@/lib/email";
|
||||
import {render} from "@react-email/components";
|
||||
import EmailSettingsTest from "@/components/emails/email-settings-test";
|
||||
import {ButtonWithLoading} from "@/components/common/button-with-loading";
|
||||
import {Send} from "lucide-react";
|
||||
import {Switch} from "@/components/ui/switch";
|
||||
|
||||
export type EmailFormProps = {
|
||||
defaultValues?: EmailFormType;
|
||||
};
|
||||
|
||||
export const EmailForm = (props: EmailFormProps) => {
|
||||
const form = useZodForm({
|
||||
schema: EmailFormSchema,
|
||||
defaultValues: props.defaultValues,
|
||||
});
|
||||
const isDirty = form.formState.isDirty;
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (values: EmailFormType) => {
|
||||
const updateEmailSettings = await updateEmailSettingsAction({name: "system", data: values});
|
||||
const data = updateEmailSettings?.data?.data;
|
||||
if (updateEmailSettings?.serverError || !data) {
|
||||
toast.error(updateEmailSettings?.serverError);
|
||||
return;
|
||||
}
|
||||
toast.success(`Success updating email informations`);
|
||||
form.reset(data);
|
||||
router.refresh();
|
||||
},
|
||||
});
|
||||
|
||||
const mutationSendEmailTest = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!props.defaultValues?.smtpUser || !props.defaultValues?.smtpFrom) {
|
||||
toast.error("SMTP is not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const email = await sendEmail({
|
||||
to: props.defaultValues.smtpUser,
|
||||
subject: "Portabase",
|
||||
html: await render(EmailSettingsTest(), {}),
|
||||
from: props.defaultValues.smtpFrom,
|
||||
});
|
||||
|
||||
if (email?.response) {
|
||||
toast.success("Test Email successfully sent!");
|
||||
}
|
||||
|
||||
return email;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(`Email sending failed: ${error.message}`);
|
||||
} else {
|
||||
toast.error("Unknown error while sending test email");
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Form
|
||||
form={form}
|
||||
className="flex flex-col gap-4 mt-3"
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="smtpFrom"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>From Email *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"example@portabase.com"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"The email from where the email will be send"}</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="smtpHost"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Server Host *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"ssl0.ovh.net"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"Your email server host"}</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="smtpPort"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Server Port *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"465"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"Your email server port (send)"}</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="smtpPassword"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput placeholder="Password" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"Your email server password"}</FormDescription>
|
||||
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="smtpUser"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>User Email *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"example@portabase.com"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"The email server user"}</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="smtpSecure"
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Secure</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex justify-between gap-4">
|
||||
{props.defaultValues?.smtpFrom && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div>
|
||||
<ButtonWithLoading
|
||||
type="button"
|
||||
disabled={isDirty || mutationSendEmailTest.isPending}
|
||||
isPending={mutationSendEmailTest.isPending}
|
||||
onClick={async () => {
|
||||
await mutationSendEmailTest.mutateAsync();
|
||||
}}
|
||||
icon={<Send />}
|
||||
size="default"
|
||||
className="bg-green-600 hover:bg-green-700 text-white font-medium shadow-sm transition-all"
|
||||
|
||||
>
|
||||
Send email test
|
||||
</ButtonWithLoading>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
|
||||
{isDirty && (
|
||||
<TooltipContent>
|
||||
You must save changes before testing the email settings.
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit">
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client"
|
||||
import {EmailForm} from "@/features/settings/email-form";
|
||||
import {Setting} from "@/db/schema/01_setting";
|
||||
import {EmailFormType} from "@/features/settings/email-form.schema";
|
||||
|
||||
|
||||
export type SettingsEmailSectionProps = {
|
||||
settings: Setting;
|
||||
};
|
||||
|
||||
export const SettingsEmailSection = (props: SettingsEmailSectionProps) => {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col h-full ">
|
||||
<EmailForm defaultValues={props.settings.smtpFrom ? props.settings as EmailFormType : undefined}/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
"use client"
|
||||
import {Alert, AlertDescription, AlertTitle} from "@/components/ui/alert";
|
||||
import {Info} from "lucide-react";
|
||||
import {ButtonWithLoading} from "@/components/common/button-with-loading";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {Setting} from "@/db/schema/01_setting";
|
||||
import {
|
||||
Form,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
useZodForm
|
||||
} from "@/components/ui/form";
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
|
||||
import {useMutation} from "@tanstack/react-query";
|
||||
import {getChannelIcon} from "@/features/channel/channels-helpers";
|
||||
import {NotificationChannelWith} from "@/db/schema/09_notification-channel";
|
||||
import {
|
||||
DefaultNotificationSchema, DefaultNotificationType
|
||||
} from "@/features/settings/notification.schema";
|
||||
import {
|
||||
updateNotificationSettingsAction
|
||||
} from "@/features/settings/notification.action";
|
||||
import {toast} from "sonner";
|
||||
import {Badge} from "@/components/ui/badge";
|
||||
|
||||
export type SettingsNotificationSectionProps = {
|
||||
settings: Setting;
|
||||
notificationChannels: NotificationChannelWith[];
|
||||
};
|
||||
|
||||
export const SettingsNotificationSection = ({settings, notificationChannels}: SettingsNotificationSectionProps) => {
|
||||
const router = useRouter();
|
||||
|
||||
const form = useZodForm({
|
||||
schema: DefaultNotificationSchema,
|
||||
defaultValues: {
|
||||
notificationChannelId: settings.defaultNotificationChannelId ?? "",
|
||||
}
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (values: DefaultNotificationType) => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<Alert className="mt-3 flex items-start gap-2">
|
||||
<Info className="h-4 w-4 mt-1"/>
|
||||
<div>
|
||||
<AlertTitle>Informations</AlertTitle>
|
||||
<AlertDescription className="flex flex-wrap items-center gap-1">
|
||||
The default notification channel will be used to send
|
||||
<Badge>error_health_agent</Badge>
|
||||
<Badge>error_health_database</Badge>
|
||||
<Badge>error_backup</Badge>
|
||||
<Badge>error_restore</Badge>
|
||||
events. For more options like notify when success, please set policy at database level
|
||||
</AlertDescription>
|
||||
</div>
|
||||
</Alert>
|
||||
<div className="flex flex-col h-full py-4 gap-3">
|
||||
<Form
|
||||
className="space-y-4"
|
||||
form={form}
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notificationChannelId"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-grow ">
|
||||
<FormLabel>Default Notification Provider</FormLabel>
|
||||
{notificationChannels.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground">No channel available</div>
|
||||
) : (
|
||||
<Select
|
||||
value={field.value ?? ""}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
>
|
||||
<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>
|
||||
|
||||
|
||||
<div className="flex justify-between gap-4">
|
||||
|
||||
{notificationChannels.length > 0 && (
|
||||
<ButtonWithLoading
|
||||
type="submit"
|
||||
>
|
||||
Confirm
|
||||
</ButtonWithLoading>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end">
|
||||
{notificationChannels.length > 0 && form.getValues("notificationChannelId") ? (
|
||||
<ButtonWithLoading
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
form.setValue("notificationChannelId", "");
|
||||
await mutation.mutateAsync({
|
||||
notificationChannelId: null,
|
||||
});
|
||||
}}
|
||||
className="flex-shrink-0 w-full sm:w-auto"
|
||||
>
|
||||
Reset
|
||||
</ButtonWithLoading>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
"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 "@/features/settings/notification.schema";
|
||||
import {withUpdatedAt} from "@/db/utils";
|
||||
|
||||
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(withUpdatedAt({
|
||||
defaultNotificationChannelId: data.notificationChannelId ?? null,
|
||||
}))
|
||||
.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",
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import {z} from "zod";
|
||||
|
||||
export const DefaultNotificationSchema = z.object({
|
||||
notificationChannelId: z.string().optional().nullable()
|
||||
});
|
||||
|
||||
export type DefaultNotificationType = z.infer<typeof DefaultNotificationSchema>;
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs";
|
||||
import {useEffect, useState} from "react";
|
||||
import {useRouter, useSearchParams} from "next/navigation";
|
||||
import {Setting} from "@/db/schema/01_setting";
|
||||
import {SettingsEmailSection} from "@/features/settings/email-section";
|
||||
import {SettingsStorageSection} from "@/features/settings/storage-section";
|
||||
import {StorageChannelWith} from "@/db/schema/12_storage-channel";
|
||||
import {AlarmClock, MailboxIcon, Save} from "lucide-react";
|
||||
import {
|
||||
SettingsNotificationSection
|
||||
} from "@/features/settings/notification-section";
|
||||
import {NotificationChannelWith} from "@/db/schema/09_notification-channel";
|
||||
|
||||
export type SettingsTabsProps = {
|
||||
settings: Setting
|
||||
storageChannels: StorageChannelWith[],
|
||||
notificationChannels: NotificationChannelWith[];
|
||||
|
||||
};
|
||||
|
||||
export const SettingsTabs = ({settings, storageChannels, notificationChannels}: SettingsTabsProps) => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [tab, setTab] = useState<string>(() => searchParams.get("tab") ?? "email");
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const newTab = searchParams.get("tab") ?? "email";
|
||||
setTab(newTab);
|
||||
}, [searchParams]);
|
||||
|
||||
const handleChangeTab = (value: string) => {
|
||||
router.push(`?tab=${value}`);
|
||||
};
|
||||
|
||||
|
||||
const tabs = [
|
||||
{
|
||||
name: 'System Email',
|
||||
value: 'email',
|
||||
icon: MailboxIcon,
|
||||
content: (
|
||||
<SettingsEmailSection settings={settings}/>
|
||||
)
|
||||
},
|
||||
{
|
||||
name: 'Storage',
|
||||
value: 'storage',
|
||||
icon: Save,
|
||||
content: (
|
||||
<SettingsStorageSection storageChannels={storageChannels} settings={settings}/>
|
||||
|
||||
)
|
||||
},
|
||||
{
|
||||
name: 'Notification',
|
||||
value: 'notification',
|
||||
icon: AlarmClock,
|
||||
content: (
|
||||
<SettingsNotificationSection notificationChannels={notificationChannels} settings={settings}/>
|
||||
|
||||
)
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
return (
|
||||
<div className="h-full mt-3">
|
||||
<Tabs className="h-full gap-4" value={tab} onValueChange={handleChangeTab}>
|
||||
<TabsList>
|
||||
{tabs.map(({icon: Icon, name, value}) => (
|
||||
<TabsTrigger key={value} value={value} className='flex items-center gap-1 px-2.5 sm:px-3'>
|
||||
<Icon/>
|
||||
{name}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
{tabs.map(tab => (
|
||||
<TabsContent key={tab.value} value={tab.value} className="h-full">
|
||||
{tab.content}
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useZodForm } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
|
||||
import { S3FormSchema, S3FormType } from "@/features/settings/storage-s3.schema";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { updateS3SettingsAction } from "@/features/settings/storage-s3.action";
|
||||
import {PasswordInput} from "@/components/ui/password-input";
|
||||
|
||||
export type S3FormProps = {
|
||||
defaultValues?: S3FormType;
|
||||
};
|
||||
|
||||
export const StorageS3Form = (props: S3FormProps) => {
|
||||
const form = useZodForm({
|
||||
schema: S3FormSchema,
|
||||
defaultValues: props.defaultValues,
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (values: S3FormType) => {
|
||||
const updateS3Settings = await updateS3SettingsAction({ name: "system", data: values });
|
||||
const data = updateS3Settings?.data?.data;
|
||||
if (updateS3Settings?.serverError || !data) {
|
||||
toast.error(updateS3Settings?.serverError);
|
||||
return;
|
||||
}
|
||||
toast.success(`Success updating storage informations`);
|
||||
router.refresh();
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Form
|
||||
form={form}
|
||||
className="flex flex-col gap-4 mt-3"
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="s3EndPointUrl"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Endpoint Url *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"s3.eu-west-3.amazonaws.com"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"Your s3 compatible url"}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="s3AccessKeyId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Access Key *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"The access key token"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"Add your access key"}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="s3SecretAccessKey"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Secret Key *</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput placeholder={"The secret key token"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"Add your secret key"}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="S3BucketName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Bucket name *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={"my-bucket"} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{"The bucket name where you want to store your data"}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex justify-end gap-4">
|
||||
<Button>Save</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
"use server";
|
||||
|
||||
import { z } from "zod";
|
||||
import { db } from "@/db";
|
||||
import { S3FormSchema, StorageSwitchSchema } from "@/features/settings/storage-s3.schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import * as drizzleDb from "@/db";
|
||||
import {userAction} from "@/lib/safe-actions/actions";
|
||||
import {withUpdatedAt} from "@/db/utils";
|
||||
|
||||
export const updateS3SettingsAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
data: S3FormSchema,
|
||||
})
|
||||
)
|
||||
.action(async ({ parsedInput }) => {
|
||||
const { name, data } = parsedInput;
|
||||
|
||||
const [updatedSettings] = await db
|
||||
.update(drizzleDb.schemas.setting)
|
||||
.set(withUpdatedAt({ ...data }))
|
||||
.where(eq(drizzleDb.schemas.setting.name, name))
|
||||
.returning();
|
||||
|
||||
return {
|
||||
data: updatedSettings,
|
||||
};
|
||||
});
|
||||
|
||||
export const updateStorageSettingsAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
data: StorageSwitchSchema,
|
||||
})
|
||||
)
|
||||
.action(async ({ parsedInput }) => {
|
||||
const { name, data } = parsedInput;
|
||||
|
||||
const [updatedSettings] = await db
|
||||
.update(drizzleDb.schemas.setting)
|
||||
// @ts-expect-error — StorageSwitchSchema fields not fully typed in drizzle schema
|
||||
.set({ ...data })
|
||||
.where(eq(drizzleDb.schemas.setting.name, name))
|
||||
.returning();
|
||||
|
||||
return {
|
||||
data: updatedSettings,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const S3FormSchema = z.object({
|
||||
s3EndPointUrl: z.string(),
|
||||
s3AccessKeyId: z.string(),
|
||||
s3SecretAccessKey: z.string(),
|
||||
S3BucketName: z.string(),
|
||||
});
|
||||
|
||||
export type S3FormType = z.infer<typeof S3FormSchema>;
|
||||
|
||||
export const StorageSwitchSchema = z.object({
|
||||
storage: z.enum(["local", "s3"]),
|
||||
});
|
||||
|
||||
export type StorageType = z.infer<typeof StorageSwitchSchema>;
|
||||
@@ -0,0 +1,173 @@
|
||||
"use client"
|
||||
import {Alert, AlertDescription, AlertTitle} from "@/components/ui/alert";
|
||||
import {Info} from "lucide-react";
|
||||
import {ButtonWithLoading} from "@/components/common/button-with-loading";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {Setting} from "@/db/schema/01_setting";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
useZodForm
|
||||
} from "@/components/ui/form";
|
||||
import {StorageChannelWith} from "@/db/schema/12_storage-channel";
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
|
||||
import {useMutation} from "@tanstack/react-query";
|
||||
import {
|
||||
DefaultStorageSchema,
|
||||
DefaultStorageType
|
||||
} from "@/features/settings/storage.schema";
|
||||
import {getChannelIcon} from "@/features/channel/channels-helpers";
|
||||
import {
|
||||
updateStorageSettingsAction
|
||||
} from "@/features/settings/storage.action";
|
||||
import {toast} from "sonner";
|
||||
import {Switch} from "@/components/ui/switch";
|
||||
import {downloadMasterKeyAction} from "@/features/agents/keys.action";
|
||||
|
||||
export type SettingsStorageSectionProps = {
|
||||
settings: Setting;
|
||||
storageChannels: StorageChannelWith[];
|
||||
};
|
||||
|
||||
export const SettingsStorageSection = ({settings, storageChannels}: SettingsStorageSectionProps) => {
|
||||
const router = useRouter();
|
||||
|
||||
const form = useZodForm({
|
||||
schema: DefaultStorageSchema,
|
||||
defaultValues: {
|
||||
storageChannelId: settings.defaultStorageChannelId ?? undefined,
|
||||
encryption: settings.encryption ?? false
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (values: DefaultStorageType) => {
|
||||
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 handleDownload = async () => {
|
||||
const result = await downloadMasterKeyAction();
|
||||
|
||||
if (!result?.success) {
|
||||
toast.error(result?.message ?? "Download failed");
|
||||
return;
|
||||
}
|
||||
|
||||
const byteCharacters = atob(result.data as string);
|
||||
const byteNumbers = new Array(byteCharacters.length)
|
||||
.fill(null)
|
||||
.map((_, i) => byteCharacters.charCodeAt(i));
|
||||
|
||||
const blob = new Blob([new Uint8Array(byteNumbers)], {
|
||||
type: "application/octet-stream",
|
||||
});
|
||||
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "master_key.bin";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<Alert className="mt-3">
|
||||
<Info className="h-4 w-4"/>
|
||||
<AlertTitle>Informations</AlertTitle>
|
||||
<AlertDescription>
|
||||
The default storage channel will be used by default to store your backups if no storage policy is
|
||||
configured at the database level. </AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex flex-col h-full py-4 gap-3">
|
||||
<Form
|
||||
className="space-y-4"
|
||||
form={form}
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="storageChannelId"
|
||||
render={({field}) => (
|
||||
<FormItem className="flex-grow">
|
||||
<FormLabel>Default Storage Provider</FormLabel>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger className="w-full h-full mb-0">
|
||||
<SelectValue placeholder="Select a default storage channel"/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{storageChannels.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>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="encryption"
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Backups Encryption</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ButtonWithLoading className="flex-shrink-0 w-full sm:w-auto" type="submit">
|
||||
Confirm
|
||||
</ButtonWithLoading>
|
||||
</Form>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm font-medium ">
|
||||
Download instance <button
|
||||
type="button"
|
||||
onClick={handleDownload}
|
||||
className="text-sm hover:text-muted-foreground underline underline-offset-4 transition-colors w-fit"
|
||||
>
|
||||
Master Key
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
"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 {DefaultStorageSchema} from "@/features/settings/storage.schema";
|
||||
import {withUpdatedAt} from "@/db/utils";
|
||||
|
||||
export const updateStorageSettingsAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
data: DefaultStorageSchema,
|
||||
})
|
||||
)
|
||||
.action(async ({parsedInput}): Promise<ServerActionResult<Setting>> => {
|
||||
const {name, data} = parsedInput;
|
||||
|
||||
try {
|
||||
const [updatedSettings] = await db
|
||||
.update(drizzleDb.schemas.setting)
|
||||
.set(withUpdatedAt({
|
||||
defaultStorageChannelId: data.storageChannelId,
|
||||
encryption: data.encryption,
|
||||
}))
|
||||
.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",
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import {z} from "zod";
|
||||
|
||||
export const DefaultStorageSchema = z.object({
|
||||
storageChannelId: z.string(),
|
||||
encryption: z.boolean(),
|
||||
});
|
||||
|
||||
export type DefaultStorageType = z.infer<typeof DefaultStorageSchema>;
|
||||
Reference in New Issue
Block a user