feat(subscribe): Move subscription configuration and application to subscription module

This commit is contained in:
web@ppanel
2025-01-14 14:12:26 +07:00
parent 18b07c750d
commit f90d4d2ce6
51 changed files with 1284 additions and 943 deletions
@@ -3,6 +3,8 @@ import { getTranslations } from 'next-intl/server';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import GroupTable from './group-table';
import SubscribeApp from './subscribe-app';
import SubscribeConfig from './subscribe-config';
import SubscribeTable from './subscribe-table';
export default async function Page() {
@@ -13,6 +15,8 @@ export default async function Page() {
<TabsList>
<TabsTrigger value='subscribe'>{t('tabs.subscribe')}</TabsTrigger>
<TabsTrigger value='group'>{t('tabs.subscribeGroup')}</TabsTrigger>
<TabsTrigger value='config'>{t('tabs.subscribeConfig')}</TabsTrigger>
<TabsTrigger value='app'>{t('tabs.subscribeApp')}</TabsTrigger>
</TabsList>
<TabsContent value='subscribe'>
<SubscribeTable />
@@ -20,6 +24,12 @@ export default async function Page() {
<TabsContent value='group'>
<GroupTable />
</TabsContent>
<TabsContent value='config'>
<SubscribeConfig />
</TabsContent>
<TabsContent value='app'>
<SubscribeApp />
</TabsContent>
</Tabs>
);
}
@@ -0,0 +1,386 @@
'use client';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
createApplication,
deleteApplication,
getApplication,
getSubscribeType,
updateApplication,
} from '@/services/admin/system';
import { zodResolver } from '@hookform/resolvers/zod';
import { Icon } from '@iconify/react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@workspace/ui/components/select';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { useTranslations } from 'next-intl';
import Image from 'next/legacy/image';
import { assign, shake } from 'radash';
import { useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const defaultValues = {
platform: 'windows',
subscribe_type: 'Clash',
name: '',
icon: '',
url: '',
};
interface FormProps<T> {
trigger: React.ReactNode | string;
title: string;
initialValues?: Partial<T>;
onSubmit: (values: T) => Promise<boolean>;
loading?: boolean;
}
function SubscribeAppForm<T extends API.CreateApplicationRequest | API.UpdateApplicationRequest>({
trigger,
title,
loading,
initialValues,
onSubmit,
}: FormProps<T>) {
const t = useTranslations('subscribe.app');
const [open, setOpen] = useState(false);
const formSchema = z.object({
platform: z.enum(['windows', 'macos', 'linux', 'android', 'ios']),
name: z.string(),
subscribe_type: z.string(),
icon: z.string(),
url: z.string(),
});
type FormSchema = z.infer<typeof formSchema>;
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
defaultValues: assign(
defaultValues,
shake(initialValues, (value) => value === null),
),
});
useEffect(() => {
form.reset(
assign(
defaultValues,
shake(initialValues, (value) => value === null),
),
);
}, [form, initialValues]);
const { data: subscribe_types } = useQuery<string[]>({
queryKey: ['getSubscribeType'],
queryFn: async () => {
const { data } = await getSubscribeType();
return data.data?.subscribe_types || [];
},
});
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
{typeof trigger === 'string' ? <Button>{trigger}</Button> : trigger}
</SheetTrigger>
<SheetContent className='w-[600px] max-w-full'>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
<Form {...form}>
<form className='space-y-4 py-4'>
<FormField
control={form.control}
name='platform'
render={({ field }) => (
<FormItem>
<FormLabel>{t('platform')}</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder={t('platform')} />
</SelectTrigger>
<SelectContent>
{['windows', 'macos', 'linux', 'android', 'ios'].map((platform) => (
<SelectItem key={platform} value={platform}>
{platform.toUpperCase()}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='subscribe_type'
render={({ field }) => (
<FormItem>
<FormLabel>{t('subscriptionProtocol')}</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder={t('subscriptionProtocol')} />
</SelectTrigger>
<SelectContent>
{subscribe_types?.map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='name'
render={({ field }) => (
<FormItem>
<FormLabel>{t('appName')}</FormLabel>
<FormControl>
<EnhancedInput {...field} required />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='icon'
render={({ field }) => (
<FormItem>
<FormLabel>{t('appIcon')}</FormLabel>
<FormControl>
<EnhancedInput {...field} required />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='url'
render={({ field }) => (
<FormItem>
<FormLabel>{t('appDownloadURL')}</FormLabel>
<FormControl>
<EnhancedInput {...field} required />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' onClick={() => setOpen(false)}>
{t('cancel')}
</Button>
<Button
onClick={form.handleSubmit(async (values) => {
const success = await onSubmit(values as T);
if (success) setOpen(false);
})}
disabled={loading}
>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
{t('confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}
export default function SubscribeApp() {
const t = useTranslations('subscribe.app');
const [loading, setLoading] = useState(false);
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.Application, { platform: string }>
action={ref}
header={{
toolbar: (
<SubscribeAppForm<API.CreateApplicationRequest>
trigger={t('add')}
title={t('createApp')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
await createApplication(values);
toast.success(t('createSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>
),
}}
params={[
{
key: 'platform',
placeholder: t('platform'),
options: [
{ label: 'Windows', value: 'windows' },
{ label: 'MacOS', value: 'mac' },
{ label: 'Linux', value: 'linux' },
{ label: 'Android', value: 'android' },
{ label: 'iOS', value: 'ios' },
],
},
]}
request={async (_pagination, filters) => {
const { data } = await getApplication();
const flatApps = Object.entries(data.data || {}).flatMap(([platform, apps]) =>
(apps as API.Application[]).map((app) => ({
...app,
platform,
})),
);
return {
list: filters.platform
? flatApps.filter((app) => app.platform === filters.platform)
: flatApps,
total: 0,
};
}}
columns={[
{
accessorKey: 'platform',
header: t('platform'),
cell: ({ row }) => row.getValue('platform'),
},
{
accessorKey: 'subscribe_type',
header: t('subscriptionProtocol'),
cell: ({ row }) => row.getValue('subscribe_type'),
},
{
accessorKey: 'name',
header: t('appName'),
},
{
accessorKey: 'icon',
header: t('appIcon'),
cell: ({ row }) => (
<Image
src={row.getValue('icon')}
alt={row.getValue('name')}
className='h-8 w-8 rounded-md'
width={32}
height={32}
/>
),
},
{
accessorKey: 'url',
header: t('appDownloadURL'),
},
]}
actions={{
render: (row) => [
<SubscribeAppForm<API.UpdateApplicationRequest>
key='edit'
trigger={<Button>{t('edit')}</Button>}
title={t('editApp')}
loading={loading}
initialValues={{
...row,
}}
onSubmit={async (values) => {
setLoading(true);
try {
await updateApplication({
...values,
id: row.id,
});
toast.success(t('updateSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
title={t('confirmDelete')}
description={t('deleteWarning')}
onConfirm={async () => {
await deleteApplication({ id: row.id! });
toast.success(t('deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
],
batchRender: (rows) => [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('batchDelete')}</Button>}
title={t('confirmDelete')}
description={t('deleteWarning')}
onConfirm={async () => {
await Promise.all(rows.map((row) => deleteApplication({ id: row.id! })));
toast.success(t('deleteSuccess'));
ref.current?.reset();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
],
}}
/>
);
}
@@ -0,0 +1,106 @@
'use client';
import { useQuery } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { getSubscribeConfig, updateSubscribeConfig } from '@/services/admin/system';
import { Label } from '@workspace/ui/components/label';
import { Switch } from '@workspace/ui/components/switch';
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
import { Textarea } from '@workspace/ui/components/textarea';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
export default function SubscribeConfig() {
const t = useTranslations('subscribe.config');
const { data, refetch } = useQuery({
queryKey: ['getSubscribeConfig'],
queryFn: async () => {
const { data } = await getSubscribeConfig();
return data.data;
},
});
async function updateConfig(key: string, value: unknown) {
if (data?.[key] === value) return;
try {
await updateSubscribeConfig({
...data,
[key]: value,
} as API.SubscribeConfig);
toast.success(t('saveSuccess'));
refetch();
} catch (error) {
/* empty */
}
}
return (
<Table>
<TableBody>
<TableRow>
<TableCell>
<Label>{t('singleSubscriptionMode')}</Label>
<p className='text-muted-foreground text-xs'>
{t('singleSubscriptionModeDescription')}
</p>
</TableCell>
<TableCell className='text-right'>
<Switch
checked={data?.single_model}
onCheckedChange={(checked) => {
updateConfig('single_model', checked);
}}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('wildcardResolution')}</Label>
<p className='text-muted-foreground text-xs'>{t('wildcardResolutionDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<Switch
checked={data?.pan_domain}
onCheckedChange={(checked) => {
updateConfig('pan_domain', checked);
}}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('subscriptionPath')}</Label>
<p className='text-muted-foreground text-xs'>{t('subscriptionPathDescription')}</p>
</TableCell>
<TableCell className='flex items-center gap-2 text-right'>
<EnhancedInput
placeholder={t('subscriptionPathPlaceholder')}
value={data?.subscribe_path}
onValueBlur={(value) => updateConfig('subscribe_path', value)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell className='align-top'>
<Label>{t('subscriptionDomain')}</Label>
<p className='text-muted-foreground text-xs'>{t('subscriptionDomainDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<Textarea
className='h-52'
placeholder={t('subscriptionDomainPlaceholder')}
defaultValue={data?.subscribe_domain}
onBlur={(e) => {
updateConfig('subscribe_domain', e.target.value);
}}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
);
}
-5
View File
@@ -5,7 +5,6 @@ import Currency from './currency';
import Invite from './invite';
import Node from './node';
import Site from './site';
import Subscription from './subscription';
import Telegram from './telegram';
import Tos from './tos';
import Verify from './verify';
@@ -18,7 +17,6 @@ export default async function Page() {
<TabsList className='h-full flex-wrap'>
<TabsTrigger value='site'>{t('tabs.site')}</TabsTrigger>
<TabsTrigger value='currency'>{t('tabs.currency')}</TabsTrigger>
<TabsTrigger value='subscription'>{t('tabs.subscription')}</TabsTrigger>
<TabsTrigger value='verify'>{t('tabs.verify')}</TabsTrigger>
<TabsTrigger value='node'>{t('tabs.node')}</TabsTrigger>
<TabsTrigger value='invite'>{t('tabs.invite')}</TabsTrigger>
@@ -31,9 +29,6 @@ export default async function Page() {
<TabsContent value='currency'>
<Currency />
</TabsContent>
<TabsContent value='subscription'>
<Subscription />
</TabsContent>
<TabsContent value='verify'>
<Verify />
</TabsContent>
@@ -1,340 +0,0 @@
'use client';
import { useQuery } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import {
createApplication,
deleteApplication,
getApplication,
getSubscribeConfig,
getSubscribeType,
updateApplication,
updateSubscribeConfig,
} from '@/services/admin/system';
import { Button } from '@workspace/ui/components/button';
import { Label } from '@workspace/ui/components/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@workspace/ui/components/select';
import { Switch } from '@workspace/ui/components/switch';
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import { Textarea } from '@workspace/ui/components/textarea';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
function compareData(
originalData: API.ApplicationResponse,
modifiedData: API.ApplicationResponse,
): {
added: API.Application[];
deleted: API.Application[];
updated: API.Application[];
} {
const added: API.Application[] = [];
const deleted: API.Application[] = [];
const updated: API.Application[] = [];
const findById = (array: API.Application[], id: number): API.Application | undefined => {
return array.find((item) => item.id === id);
};
const isUpdated = (original: API.Application, modified: API.Application): boolean => {
return (
original.name !== modified.name ||
original.platform !== modified.platform ||
original.subscribe_type !== modified.subscribe_type ||
original.url !== modified.url ||
original.icon !== modified.icon
);
};
Object.values(originalData).forEach((platformData) => {
platformData.forEach((originalApp) => {
const modifiedApp = findById(
modifiedData[originalApp.platform as API.CreateApplicationRequest['platform']],
originalApp.id,
);
if (!modifiedApp) {
deleted.push(originalApp);
} else if (isUpdated(originalApp, modifiedApp)) {
updated.push(modifiedApp);
}
});
});
Object.values(modifiedData).forEach((platformData) => {
platformData.forEach((modifiedApp) => {
if (
!findById(
originalData[modifiedApp.platform as API.CreateApplicationRequest['platform']],
modifiedApp.id,
)
) {
added.push(modifiedApp);
}
});
});
return { added, deleted, updated };
}
export default function Subscription() {
const t = useTranslations('system.subscription');
const { data, refetch } = useQuery({
queryKey: ['getSubscribeConfig'],
queryFn: async () => {
const { data } = await getSubscribeConfig();
return data.data;
},
});
const { data: apps, refetch: appsRefetch } = useQuery({
queryKey: ['getApplication'],
queryFn: async () => {
const { data } = await getApplication();
return data.data;
},
});
async function updateConfig(key: string, value: unknown) {
if (data?.[key] === value) return;
try {
await updateSubscribeConfig({
...data,
[key]: value,
} as API.SubscribeConfig);
toast.success(t('saveSuccess'));
refetch();
} catch (error) {
/* empty */
}
}
const { data: subscribe_types } = useQuery<string[]>({
queryKey: ['getSubscribeType'],
queryFn: async () => {
const { data } = await getSubscribeType();
return data.data?.subscribe_types || [];
},
});
const [app, setApp] = useState<API.ApplicationResponse>();
const appTypes = Object.keys(apps || {}) as (keyof API.ApplicationResponse)[];
useEffect(() => {
if (!app) setApp(apps);
}, [app, apps]);
return (
<>
<Table>
<TableBody>
<TableRow>
<TableCell>
<Label>{t('singleSubscriptionMode')}</Label>
<p className='text-muted-foreground text-xs'>
{t('singleSubscriptionModeDescription')}
</p>
</TableCell>
<TableCell className='text-right'>
<Switch
checked={data?.single_model}
onCheckedChange={(checked) => {
updateConfig('single_model', checked);
}}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('wildcardResolution')}</Label>
<p className='text-muted-foreground text-xs'>{t('wildcardResolutionDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<Switch
checked={data?.pan_domain}
onCheckedChange={(checked) => {
updateConfig('pan_domain', checked);
}}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('subscriptionPath')}</Label>
<p className='text-muted-foreground text-xs'>{t('subscriptionPathDescription')}</p>
</TableCell>
<TableCell className='flex items-center gap-2 text-right'>
<EnhancedInput
placeholder={t('subscriptionPathPlaceholder')}
value={data?.subscribe_path}
onValueBlur={(value) => updateConfig('subscribe_path', value)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell className='align-top'>
<Label>{t('subscriptionDomain')}</Label>
<p className='text-muted-foreground text-xs'>{t('subscriptionDomainDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<Textarea
className='h-52'
placeholder={t('subscriptionDomainPlaceholder')}
defaultValue={data?.subscribe_domain}
onBlur={(e) => {
updateConfig('subscribe_domain', e.target.value);
}}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('app')}</Label>
<p className='text-muted-foreground text-xs'>{t('appDescription')}</p>
</TableCell>
<TableCell className='flex justify-end gap-2'>
<Button
size='sm'
variant='outline'
onClick={() => {
setApp(apps);
}}
>
{t('reset')}
</Button>
<Button
size='sm'
onClick={() => {
const { added, deleted, updated } = compareData(apps!, app!);
added.forEach(async (item) => {
await createApplication(item as API.CreateApplicationRequest);
});
deleted.forEach(async (item) => {
await deleteApplication({
id: item.id,
});
});
updated.forEach(async (item) => {
await updateApplication(item);
});
toast.success(t('saveSuccess'));
appsRefetch();
}}
>
{t('save')}
</Button>
</TableCell>
</TableRow>
</TableBody>
</Table>
<Tabs defaultValue='windows'>
<TabsList className='h-full flex-wrap'>
{appTypes.map((type) => {
return (
<TabsTrigger value={type} key={type} className='uppercase'>
{type}
</TabsTrigger>
);
})}
</TabsList>
{appTypes.map((type) => {
const list = (app?.[type] || []) as API.Application[];
const updatedList = (key: string, value: string, index: number) => {
const newList = list.map((item, i) => (i === index ? { ...item, [key]: value } : item));
setApp({
...app,
[type]: newList,
} as API.ApplicationResponse);
};
return (
<TabsContent value={type} key={type} className='mt-4 space-y-4'>
{list.map((item, index) => {
return (
<div className='flex flex-col items-center gap-2 lg:flex-row' key={index}>
<Select
value={item.subscribe_type}
onValueChange={(value) => {
updatedList('subscribe_type', value, index);
}}
>
<SelectTrigger>
<SelectValue placeholder={t('subscriptionProtocol')} />
</SelectTrigger>
<SelectContent>
{subscribe_types?.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
<EnhancedInput
placeholder={t('appName')}
value={item.name}
onValueChange={(value) => updatedList('name', value as string, index)}
/>
<EnhancedInput
placeholder={t('appIcon')}
value={item.icon}
onValueChange={(value) => updatedList('icon', value as string, index)}
/>
<EnhancedInput
placeholder={t('appDownloadURL')}
value={item.url}
onValueChange={(value) => updatedList('url', value as string, index)}
/>
<Button
variant='destructive'
size='sm'
onClick={() => {
setApp({
...app,
[type]: list.filter((l, i) => i !== index),
} as API.ApplicationResponse);
}}
>
{t('delete')}
</Button>
</div>
);
})}
<Button
className='w-full'
variant='outline'
onClick={() => {
setApp({
...app,
[type]: [
...list,
{
platform: type,
},
],
} as API.ApplicationResponse);
}}
>
{t('add')}
</Button>
</TabsContent>
);
})}
</Tabs>
</>
);
}