feat(config): Add application selection and encryption settings to configuration form

This commit is contained in:
web@ppanel 2025-01-20 20:17:49 +07:00
parent 28f8c78963
commit 88b3504735
5 changed files with 148 additions and 19 deletions

View File

@ -1,6 +1,10 @@
'use client'; 'use client';
import { getApplicationConfig, updateApplicationConfig } from '@/services/admin/system'; import {
getApplication,
getApplicationConfig,
updateApplicationConfig,
} from '@/services/admin/system';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
@ -24,18 +28,24 @@ import {
SheetTrigger, SheetTrigger,
} from '@workspace/ui/components/sheet'; } from '@workspace/ui/components/sheet';
import { Textarea } from '@workspace/ui/components/textarea'; import { Textarea } from '@workspace/ui/components/textarea';
import { Combobox } from '@workspace/ui/custom-components/combobox';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input'; import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { UploadImage } from '@workspace/ui/custom-components/upload-image'; import { UploadImage } from '@workspace/ui/custom-components/upload-image';
import { DicesIcon } from 'lucide-react';
import { useTranslations } from 'next-intl'; import { useTranslations } from 'next-intl';
import { uid } from 'radash';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { z } from 'zod'; import { z } from 'zod';
const formSchema = z.object({ const formSchema = z.object({
startup_picture: z.string(), app_id: z.number().optional(),
startup_picture_skip_time: z.number(), app_key: z.string().optional(),
domains: z.array(z.string()), encryption: z.string().optional(),
startup_picture: z.string().optional(),
startup_picture_skip_time: z.number().optional(),
domains: z.array(z.string()).optional(),
}); });
type FormSchema = z.infer<typeof formSchema>; type FormSchema = z.infer<typeof formSchema>;
@ -48,6 +58,9 @@ export default function ConfigForm() {
const form = useForm<FormSchema>({ const form = useForm<FormSchema>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
defaultValues: { defaultValues: {
app_id: 0,
app_key: '',
encryption: '',
startup_picture: '', startup_picture: '',
startup_picture_skip_time: 0, startup_picture_skip_time: 0,
domains: [], domains: [],
@ -62,6 +75,14 @@ export default function ConfigForm() {
}, },
}); });
const { data: applications } = useQuery({
queryKey: ['getApplication'],
queryFn: async () => {
const { data } = await getApplication();
return data.data?.applications || [];
},
});
useEffect(() => { useEffect(() => {
if (data) { if (data) {
form.reset({ form.reset({
@ -100,6 +121,80 @@ export default function ConfigForm() {
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'> <ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
<Form {...form}> <Form {...form}>
<form className='space-y-4 py-4'> <form className='space-y-4 py-4'>
<FormField
control={form.control}
name='app_id'
render={({ field }) => (
<FormItem>
<FormLabel>{t('selectApp')}</FormLabel>
<FormDescription>{t('selectAppDescription')}</FormDescription>
<FormControl>
<Combobox
{...field}
options={
applications?.map((app) => ({
label: app.name,
value: app.id,
})) || []
}
value={field.value}
onChange={(value) => form.setValue(field.name, value)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='app_key'
render={({ field }) => (
<FormItem>
<FormLabel>{t('communicationKey')}</FormLabel>
<FormDescription>{t('communicationKeyDescription')}</FormDescription>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={(value) => form.setValue(field.name, value as string)}
suffix={
<div className='bg-muted flex h-9 items-center text-nowrap px-3'>
<DicesIcon
onClick={() => {
const id = uid(32).toLowerCase();
const formatted = `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;
form.setValue(field.name, formatted);
}}
className='cursor-pointer'
/>
</div>
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='encryption'
render={({ field }) => (
<FormItem>
<FormLabel>{t('encryption')}</FormLabel>
<FormDescription>{t('encryptionDescription')}</FormDescription>
<FormControl>
<Combobox
options={[
{ label: 'none', value: 'none' },
{ label: 'AES', value: 'aes' },
]}
value={field.value}
onChange={(value) => form.setValue(field.name, value)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField <FormField
control={form.control} control={form.control}
name='startup_picture' name='startup_picture'
@ -109,7 +204,8 @@ export default function ConfigForm() {
<FormDescription>{t('startupPictureDescription')}</FormDescription> <FormDescription>{t('startupPictureDescription')}</FormDescription>
<FormControl> <FormControl>
<EnhancedInput <EnhancedInput
{...field} value={field.value}
onValueChange={(value) => form.setValue(field.name, value as string)}
suffix={ suffix={
<UploadImage <UploadImage
className='bg-muted h-9 rounded-none border-none px-2' className='bg-muted h-9 rounded-none border-none px-2'
@ -158,7 +254,7 @@ export default function ConfigForm() {
<Textarea <Textarea
className='h-52' className='h-52'
placeholder='example.com' placeholder='example.com'
value={field.value.join('\n')} value={field.value?.join('\n')}
onChange={(e) => onChange={(e) =>
form.setValue( form.setValue(
'domains', 'domains',

View File

@ -3,8 +3,6 @@ import { Card, CardDescription, CardHeader, CardTitle } from '@workspace/ui/comp
import { getTranslations } from 'next-intl/server'; import { getTranslations } from 'next-intl/server';
import Link from 'next/link'; import Link from 'next/link';
const BASE_URL = 'https://cdn.jsdelivr.net/gh/perfect-panel/ppanel-assets/billing/index.json';
interface BillingProps { interface BillingProps {
type: 'dashboard' | 'payment'; type: 'dashboard' | 'payment';
} }
@ -17,23 +15,48 @@ interface ItemType {
href: string; href: string;
} }
async function getBillingURL() {
try {
const response = await fetch(
'https://api.github.com/repos/perfect-panel/ppanel-assets/commits',
);
const json = await response.json();
const version = json[0]?.sha;
const url = new URL('https://cdn.jsdelivr.net/gh/perfect-panel/ppanel-assets');
url.pathname += `@${version}/billing/index.json`;
return url.toString();
} catch (error) {
return 'https://cdn.jsdelivr.net/gh/perfect-panel/ppanel-assets/billing/index.json';
}
}
export default async function Billing({ type }: BillingProps) { export default async function Billing({ type }: BillingProps) {
const t = await getTranslations('common.billing'); const t = await getTranslations('common.billing');
let list: ItemType[] = []; let list: ItemType[] = [];
try { try {
const response = await fetch(BASE_URL, { cache: 'no-store' }); const url = await getBillingURL();
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const response = await fetch(url, {
const data = await response.json(); headers: {
const now = new Date().getTime(); Accept: 'application/json',
list = data[type].filter((item: { expiryDate: string }) => { },
const expiryDate = Date.parse(item.expiryDate);
return !isNaN(expiryDate) && expiryDate > now;
}); });
const data = await response.json();
const now = Date.now();
list = Array.isArray(data[type])
? data[type].filter((item: { expiryDate: string }) => {
const expiryDate = Date.parse(item.expiryDate);
return !isNaN(expiryDate) && expiryDate > now;
})
: [];
} catch (error) { } catch (error) {
console.log('Error fetching billing data:', error); console.log(error);
return null; return null;
} }
if (list && list.length === 0) return null;
if (!list?.length) return null;
return ( return (
<> <>
<h1 className='text mt-2 font-bold'> <h1 className='text mt-2 font-bold'>

View File

@ -26,6 +26,12 @@
"editApp": "Edit App", "editApp": "Edit App",
"nameDescription": "Application name, displayed in the app list", "nameDescription": "Application name, displayed in the app list",
"platform": "Platform", "platform": "Platform",
"selectApp": "Select App",
"selectAppDescription": "Select the app to configure, all settings will apply to the selected app",
"communicationKey": "Communication Key",
"communicationKeyDescription": "Key used for client communication",
"encryption": "Encryption Method",
"encryptionDescription": "Choose the encryption method for client communication. If selected, the client will use this method to communicate with the server",
"startupPicture": "Startup Picture", "startupPicture": "Startup Picture",
"startupPictureDescription": "Startup picture, supports network and local images. For network images, please enter the complete image URL", "startupPictureDescription": "Startup picture, supports network and local images. For network images, please enter the complete image URL",
"startupPicturePreview": "Startup Picture Preview", "startupPicturePreview": "Startup Picture Preview",

View File

@ -27,7 +27,9 @@ declare namespace API {
}; };
type ApplicationConfig = { type ApplicationConfig = {
encryption: boolean; app_id: number;
encryption_key: string;
encryption_method: string;
domains: string[]; domains: string[];
startup_picture: string; startup_picture: string;
startup_picture_skip_time: number; startup_picture_skip_time: number;

View File

@ -19,7 +19,9 @@ declare namespace API {
}; };
type ApplicationConfig = { type ApplicationConfig = {
encryption: boolean; app_id: number;
encryption_key: string;
encryption_method: string;
domains: string[]; domains: string[];
startup_picture: string; startup_picture: string;
startup_picture_skip_time: number; startup_picture_skip_time: number;