Compare commits
88 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d3999c640c | |||
| d8fa13bebc | |||
| f700be095a | |||
| 461fdb1219 | |||
| 6ca24333da | |||
| 8dffd69b48 | |||
| 1d526b5973 | |||
| 1c8d4afad0 | |||
| e4429a5c4d | |||
| fe699809a4 | |||
| 3e5402f2fc | |||
| c4a47a47dd | |||
| 6376ec1a79 | |||
| a988cb3c50 | |||
| f9a7ece9bf | |||
| 39d746f0a1 | |||
| fce627ba11 | |||
| e2d83ec9e6 | |||
| ab6f6a64c2 | |||
| ac36075e7b | |||
| a4de9df1fc | |||
| d7f8b3b707 | |||
| 88ce8d7f85 | |||
| 2bcd4cf30c | |||
| 351fffcc78 | |||
| 4da59609b4 | |||
| e4fbd5c754 | |||
| fd48856019 | |||
| 1ab9b39e8a | |||
| 4563c570ac | |||
| 9e01f4f590 | |||
| 7c0a312163 | |||
| 10250d9e34 | |||
| 6a3bb7016e | |||
| b6e778d482 | |||
| e63f823b0b | |||
| c4f536eb05 | |||
| f4a1237619 | |||
| 5272360c77 | |||
| 6d81bfdaeb | |||
| 59faeab34a | |||
| 6ccf9b8bdc | |||
| d4b37e4997 | |||
| ba2b50e972 | |||
| e37ae49960 | |||
| 973c06f0fa | |||
| 2f20ac95da | |||
| 551135de77 | |||
| ee98e7e513 | |||
| 38dda842c0 | |||
| d85af491aa | |||
| 4f7cc807af | |||
| 327f98cfa7 | |||
| 01ff6ec908 | |||
| b41296eb44 | |||
| 217ddce60c | |||
| 26176a7afa | |||
| 0c43844a6f | |||
| a7936de6dc | |||
| 72a4106022 | |||
| 6ab2ba92a0 | |||
| e5d4deb346 | |||
| 0448d213a3 | |||
| f190c68eb0 | |||
| 7a279e6e30 | |||
| 641ed5ec36 | |||
| 5b21d8a7bc | |||
| fce9119567 | |||
| 292efdf1d8 | |||
| 9d9c3cd7b3 | |||
| 296a6c10a3 | |||
| 822416d22d | |||
| bbcd018aeb | |||
| 0e6ba5b081 | |||
| 33daa1fb73 | |||
| 1d9b0a4e06 | |||
| ea08de0aa2 | |||
| 65c9b9f64f | |||
| 48415e9a30 | |||
| 42671a5974 | |||
| b2b4a95250 | |||
| b4d4f59c71 | |||
| 7f3cac3c1c | |||
| 32253e3717 | |||
| a76471a806 | |||
| d53a00611e | |||
| 2fb98be591 | |||
| 634be371b1 |
+143
-6
@@ -1,21 +1,158 @@
|
||||
<a name="readme-top"></a>
|
||||
# Changelog
|
||||
|
||||
## [1.1.3](https://github.com/perfect-panel/ppanel-web/compare/v1.1.2...v1.1.3) (2025-07-24)
|
||||
# [1.4.0](https://github.com/perfect-panel/ppanel-web/compare/v1.3.0...v1.4.0) (2025-09-14)
|
||||
|
||||
|
||||
### ♻ Code Refactoring
|
||||
|
||||
* **logs**: Add localization files and update existing translations for multiple languages ([2f20ac9](https://github.com/perfect-panel/ppanel-web/commit/2f20ac9))
|
||||
* **subscribe-form**: Replace server_group and server with node_tags and nodes in default values and form schema ([38dda84](https://github.com/perfect-panel/ppanel-web/commit/38dda84))
|
||||
* Add localization updates for log and server files across multiple languages ([2bcd4cf](https://github.com/perfect-panel/ppanel-web/commit/2bcd4cf))
|
||||
* Clean up NodeForm and ServerForm components by removing unused functions and optimizing state management ([10250d9](https://github.com/perfect-panel/ppanel-web/commit/10250d9))
|
||||
* Enhance log pages with Badge component and update translations ([a4de9df](https://github.com/perfect-panel/ppanel-web/commit/a4de9df))
|
||||
* Make 'scheme' field optional in client form schema ([f4a1237](https://github.com/perfect-panel/ppanel-web/commit/f4a1237))
|
||||
* Refactor server management API endpoints and typings ([4f7cc80](https://github.com/perfect-panel/ppanel-web/commit/4f7cc80))
|
||||
* Remove application management forms and related configurations ([0c43844](https://github.com/perfect-panel/ppanel-web/commit/0c43844))
|
||||
* Remove default options from TagInput component for improved flexibility ([6a3bb70](https://github.com/perfect-panel/ppanel-web/commit/6a3bb70))
|
||||
* Remove unused preview state variables and add sort order to node properties ([e63f823](https://github.com/perfect-panel/ppanel-web/commit/e63f823))
|
||||
* Rename buildScheme to buildSchema and update imports in server form components ([ee98e7e](https://github.com/perfect-panel/ppanel-web/commit/ee98e7e))
|
||||
* Simplify node display in subscribe form and remove unused Badge import ([551135d](https://github.com/perfect-panel/ppanel-web/commit/551135d))
|
||||
* Update bun.lockb to reflect dependency changes ([ba2b50e](https://github.com/perfect-panel/ppanel-web/commit/ba2b50e))
|
||||
* Update component imports and improve code consistency ([59faeab](https://github.com/perfect-panel/ppanel-web/commit/59faeab))
|
||||
* Update dependencies and improve code consistency across multiple files ([e37ae49](https://github.com/perfect-panel/ppanel-web/commit/e37ae49))
|
||||
* Update localization files and service imports ([d4b37e4](https://github.com/perfect-panel/ppanel-web/commit/d4b37e4))
|
||||
|
||||
|
||||
### ✨ Features
|
||||
|
||||
* **config**: Add translations for server configuration in multiple languages ([f9a7ece](https://github.com/perfect-panel/ppanel-web/commit/f9a7ece))
|
||||
* **logs**: Add various log pages for tracking user activities and system events ([d85af49](https://github.com/perfect-panel/ppanel-web/commit/d85af49))
|
||||
* Add bandwidth fields and placeholders for upload and download in server configuration forms; update localization files for multiple languages ([3e5402f](https://github.com/perfect-panel/ppanel-web/commit/3e5402f))
|
||||
* Add batch delete functionality and enhance chart tooltips in statistics cards ([c4f536e](https://github.com/perfect-panel/ppanel-web/commit/c4f536e))
|
||||
* Add language support and descriptions in product localization files ([fd48856](https://github.com/perfect-panel/ppanel-web/commit/fd48856))
|
||||
* Add log cleanup settings and update localization files ([6ccf9b8](https://github.com/perfect-panel/ppanel-web/commit/6ccf9b8))
|
||||
* Add queryNodeTag function and integrate tag retrieval in NodeForm and SubscribeForm components ([4563c57](https://github.com/perfect-panel/ppanel-web/commit/4563c57))
|
||||
* Add quota management features and localization updates ([fce627b](https://github.com/perfect-panel/ppanel-web/commit/fce627b))
|
||||
* Add server form component with protocol configuration and localization support ([217ddce](https://github.com/perfect-panel/ppanel-web/commit/217ddce))
|
||||
* Enhance TagInput component with option handling and improved tag addition logic ([b6e778d](https://github.com/perfect-panel/ppanel-web/commit/b6e778d))
|
||||
* Implement data migration functionality and update localization files ([6d81bfd](https://github.com/perfect-panel/ppanel-web/commit/6d81bfd))
|
||||
* Refactor user detail and subscription management components ([973c06f](https://github.com/perfect-panel/ppanel-web/commit/973c06f))
|
||||
* Update server list fetching logic and adjust query parameters ([5272360](https://github.com/perfect-panel/ppanel-web/commit/5272360))
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **auth**: Implement user redirection to dashboard upon authentication ([f84f98c](https://github.com/perfect-panel/ppanel-web/commit/f84f98c))
|
||||
* **page**: Refine version checking logic and remove unnecessary comments for clarity ([26176a7](https://github.com/perfect-panel/ppanel-web/commit/26176a7))
|
||||
* Add localization updates and new utility functions ([4da5960](https://github.com/perfect-panel/ppanel-web/commit/4da5960))
|
||||
* Add user_subscribe_id filter to SubscribeLogPage and update typings; disable eslint in service index files ([ab6f6a6](https://github.com/perfect-panel/ppanel-web/commit/ab6f6a6))
|
||||
* Added system version card and system log dialog components; updated statistics page to include total server and user statistics ([fe69980](https://github.com/perfect-panel/ppanel-web/commit/fe69980))
|
||||
* Adjust timestamp calculations to use milliseconds instead of seconds in quota broadcast form submission ([8dffd69](https://github.com/perfect-panel/ppanel-web/commit/8dffd69))
|
||||
* Correct cookie key format for sidebar state retrieval ([9e01f4f](https://github.com/perfect-panel/ppanel-web/commit/9e01f4f))
|
||||
* Improve UI for protocol status display in server form component ([461fdb1](https://github.com/perfect-panel/ppanel-web/commit/461fdb1))
|
||||
* Increase pagination size limit for server and node lists to improve data retrieval ([7c0a312](https://github.com/perfect-panel/ppanel-web/commit/7c0a312))
|
||||
* Optimize Task Manager to use milliseconds to calculate timers, and simplify import statements ([d8fa13b](https://github.com/perfect-panel/ppanel-web/commit/d8fa13b))
|
||||
* Refactor protocol status display for improved readability in server form component ([f700be0](https://github.com/perfect-panel/ppanel-web/commit/f700be0))
|
||||
* Remove GroupTable and related components, simplify SubscribeTable and update language handling in subscription forms ([1ab9b39](https://github.com/perfect-panel/ppanel-web/commit/1ab9b39))
|
||||
* Remove redundant transport label from localization files ([88ce8d7](https://github.com/perfect-panel/ppanel-web/commit/88ce8d7))
|
||||
* Remove unnecessary comments and improve variable handling in GoTemplateEditor; ensure zero value displays as empty in EnhancedInput ([c4a47a4](https://github.com/perfect-panel/ppanel-web/commit/c4a47a4))
|
||||
* Remove unnecessary comments to simplify code readability ([a988cb3](https://github.com/perfect-panel/ppanel-web/commit/a988cb3))
|
||||
* Replace MarkdownEditor with HTMLEditor in EmailBroadcastForm; simplify content rendering in EmailTaskManager; disable eslint in service index files ([e2d83ec](https://github.com/perfect-panel/ppanel-web/commit/e2d83ec))
|
||||
* Replace redundant icon rendering with a single instance in system version card component ([e4429a5](https://github.com/perfect-panel/ppanel-web/commit/e4429a5))
|
||||
* Update billing URL fetching logic and improve version handling in system version card component ([1c8d4af](https://github.com/perfect-panel/ppanel-web/commit/1c8d4af))
|
||||
* Update condition for plugin field in PROTOCOL_FIELDS to include specific plugins ([6376ec1](https://github.com/perfect-panel/ppanel-web/commit/6376ec1))
|
||||
* Update getAppSubLink function to improve URL handling and encoding logic ([351fffc](https://github.com/perfect-panel/ppanel-web/commit/351fffc))
|
||||
* Update order_id to order_no in BalanceLogPage and related typings; enhance timezone switch component with additional features and localization updates ([ac36075](https://github.com/perfect-panel/ppanel-web/commit/ac36075))
|
||||
* Update protocol plugin handling and add new options in typings ([6ca2433](https://github.com/perfect-panel/ppanel-web/commit/6ca2433))
|
||||
* Update release URLs to include 'v' prefix for versioning in system version card component ([1d526b5](https://github.com/perfect-panel/ppanel-web/commit/1d526b5))
|
||||
* Update SidebarLeft component styles to enhance hover effects ([e4fbd5c](https://github.com/perfect-panel/ppanel-web/commit/e4fbd5c))
|
||||
* Update validation for days and gift_value fields in QuotaBroadcastForm; set default values to avoid errors ([39d746f](https://github.com/perfect-panel/ppanel-web/commit/39d746f))
|
||||
|
||||
|
||||
### 📝 Documentation
|
||||
|
||||
* Merge branch 'main' into develop ([d7f8b3b](https://github.com/perfect-panel/ppanel-web/commit/d7f8b3b))
|
||||
|
||||
<a name="readme-top"></a>
|
||||
|
||||
# Changelog
|
||||
|
||||
# [1.3.0](https://github.com/perfect-panel/ppanel-web/compare/v1.2.0...v1.3.0) (2025-08-15)
|
||||
|
||||
### ♻ Code Refactoring
|
||||
|
||||
- Refactoring and adding multiple features ([65c9b9f](https://github.com/perfect-panel/ppanel-web/commit/65c9b9f))
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- **api**: Add getClient API endpoint to retrieve subscription applications ([7a279e6](https://github.com/perfect-panel/ppanel-web/commit/7a279e6))
|
||||
- **marketing**: Add marketing management features and localization updates ([ea08de0](https://github.com/perfect-panel/ppanel-web/commit/ea08de0))
|
||||
- **protocol**: Add template preview functionality with localization support ([0448d21](https://github.com/perfect-panel/ppanel-web/commit/0448d21))
|
||||
- **subscribe**: Update subscription management localization and add new fields ([1d9b0a4](https://github.com/perfect-panel/ppanel-web/commit/1d9b0a4))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **bun**: Update bun.lockb to reflect dependency changes ([bbcd018](https://github.com/perfect-panel/ppanel-web/commit/bbcd018))
|
||||
- **editor**: Add Go template editor component and update related schemas ([9d9c3cd](https://github.com/perfect-panel/ppanel-web/commit/9d9c3cd))
|
||||
- **editor**: Enhance Go Template Editor to support trimmed template tags and improve range/end matching ([641ed5e](https://github.com/perfect-panel/ppanel-web/commit/641ed5e))
|
||||
- **editor**: Enhance Go Template Editor with schema support and improved completion ([5b21d8a](https://github.com/perfect-panel/ppanel-web/commit/5b21d8a))
|
||||
- **enhaced-input**: Disable autocomplete for EnhancedInput component ([f190c68](https://github.com/perfect-panel/ppanel-web/commit/f190c68))
|
||||
- **global**: Add user agent limit settings to subscription configuration ([822416d](https://github.com/perfect-panel/ppanel-web/commit/822416d))
|
||||
- **locales**: Update 'conf' output format to use uppercase 'CONF' ([fce9119](https://github.com/perfect-panel/ppanel-web/commit/fce9119))
|
||||
- **locales**: Update "userAccount" label to "user" in multiple localization files ([48415e9](https://github.com/perfect-panel/ppanel-web/commit/48415e9))
|
||||
- **protocol-form**: Swap 'description' and 'user_agent' columns for improved clarity in the table ([72a4106](https://github.com/perfect-panel/ppanel-web/commit/72a4106))
|
||||
- **protocol-form**: Update protocol options descriptions for clarity and add new security and transport options ([e5d4deb](https://github.com/perfect-panel/ppanel-web/commit/e5d4deb))
|
||||
- **protocol**: Add 'conf' output format option and update translations ([292efdf](https://github.com/perfect-panel/ppanel-web/commit/292efdf))
|
||||
- **protpcp-form**: Rename 'schema' to 'scheme' for consistency across the application ([6ab2ba9](https://github.com/perfect-panel/ppanel-web/commit/6ab2ba9))
|
||||
- **register**: Update localization files to include trial subscription settings and descriptions ([33daa1f](https://github.com/perfect-panel/ppanel-web/commit/33daa1f))
|
||||
- **system**: Add time unit translations for user registration settings in multiple languages ([296a6c1](https://github.com/perfect-panel/ppanel-web/commit/296a6c1))
|
||||
- Update privacy policy and terms of service schemas to use correct field names ([0e6ba5b](https://github.com/perfect-panel/ppanel-web/commit/0e6ba5b))
|
||||
|
||||
<a name="readme-top"></a>
|
||||
|
||||
# Changelog
|
||||
|
||||
# [1.2.0](https://github.com/perfect-panel/ppanel-web/compare/v1.1.5...v1.2.0) (2025-08-04)
|
||||
|
||||
### ♻ Code Refactoring
|
||||
|
||||
- **view**: System and Auth Control ([b2b4a95](https://github.com/perfect-panel/ppanel-web/commit/b2b4a95))
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- **netlify**: Add Netlify configuration for admin and user apps with Next.js plugin ([b4d4f59](https://github.com/perfect-panel/ppanel-web/commit/b4d4f59))
|
||||
|
||||
<a name="readme-top"></a>
|
||||
|
||||
# Changelog
|
||||
|
||||
## [1.1.5](https://github.com/perfect-panel/ppanel-web/compare/v1.1.4...v1.1.5) (2025-07-26)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **subscribe**: Filter out items that are not marked as visible in subscription list ([32253e3](https://github.com/perfect-panel/ppanel-web/commit/32253e3))
|
||||
|
||||
## [1.1.4](https://github.com/perfect-panel/ppanel-web/compare/v1.1.3...v1.1.4) (2025-07-25)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **locales**: Simplify "show" label in subscription localization files ([d53a006](https://github.com/perfect-panel/ppanel-web/commit/d53a006))
|
||||
- **order**: Preserve last successful order on error during order creation ([2fb98be](https://github.com/perfect-panel/ppanel-web/commit/2fb98be))
|
||||
- **subscribe**: Filter out hidden items in subscription list display ([634be37](https://github.com/perfect-panel/ppanel-web/commit/634be37))
|
||||
|
||||
## [1.1.3](https://github.com/perfect-panel/ppanel-web/compare/v1.1.2...v1.1.3) (2025-07-24)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **auth**: Implement user redirection to dashboard upon authentication ([f84f98c](https://github.com/perfect-panel/ppanel-web/commit/f84f98c))
|
||||
|
||||
## [1.1.2](https://github.com/perfect-panel/ppanel-web/compare/v1.1.1...v1.1.2) (2025-07-24)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **billing**: Add display for gift amount in subscription billing ([04af2f9](https://github.com/perfect-panel/ppanel-web/commit/04af2f9))
|
||||
* **order**: Update subscription cell to display name and quantity ([96eba17](https://github.com/perfect-panel/ppanel-web/commit/96eba17))
|
||||
* **tool**: Added API for obtaining version, updated version information display logic ([2675034](https://github.com/perfect-panel/ppanel-web/commit/2675034))
|
||||
- **billing**: Add display for gift amount in subscription billing ([04af2f9](https://github.com/perfect-panel/ppanel-web/commit/04af2f9))
|
||||
- **order**: Update subscription cell to display name and quantity ([96eba17](https://github.com/perfect-panel/ppanel-web/commit/96eba17))
|
||||
- **tool**: Added API for obtaining version, updated version information display logic ([2675034](https://github.com/perfect-panel/ppanel-web/commit/2675034))
|
||||
|
||||
<a name="readme-top"></a>
|
||||
|
||||
|
||||
@@ -34,6 +34,19 @@ English
|
||||
|
||||
</div>
|
||||
|
||||
> **Article 1.**
|
||||
> All human beings are born free and equal in dignity and rights.
|
||||
> They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.
|
||||
>
|
||||
> **Article 12.**
|
||||
> No one shall be subjected to arbitrary interference with his privacy, family, home or correspondence, nor to attacks upon his honour and reputation.
|
||||
> Everyone has the right to the protection of the law against such interference or attacks.
|
||||
>
|
||||
> **Article 19.**
|
||||
> Everyone has the right to freedom of opinion and expression; this right includes freedom to hold opinions without interference and to seek, receive and impart information and ideas through any media and regardless of frontiers.
|
||||
>
|
||||
> _Source: [United Nations – Universal Declaration of Human Rights (UN.org)](https://www.un.org/sites/un2.un.org/files/2021/03/udhr.pdf)_
|
||||
|
||||
## 📦 Application List
|
||||
|
||||
| 📦 Application | 🖼️ Preview |
|
||||
|
||||
@@ -34,6 +34,19 @@
|
||||
|
||||
</div>
|
||||
|
||||
> **第一条**
|
||||
> 人人生而自由,在尊严与权利上一律平等。
|
||||
> 他们赋有理性与良知,应当以兄弟般的精神彼此相待。
|
||||
>
|
||||
> **第十二条**
|
||||
> 任何人的隐私、家庭、住宅和通信不得任意干涉,其名誉与荣誉不得加以攻击。
|
||||
> 人人有权受到法律的保护,以免遭受这种干涉或攻击。
|
||||
>
|
||||
> **第十九条**
|
||||
> 人人有思想与表达的自由;此项自由包括持有主张而不受干预,以及通过任何媒介、无论国界,自由寻求、接受和传播信息与思想。
|
||||
>
|
||||
> _来源: [United Nations – Universal Declaration of Human Rights (UN.org)](https://www.un.org/sites/un2.un.org/files/2021/03/udhr.pdf)_
|
||||
|
||||
## 📦 Application List
|
||||
|
||||
| 📦 Application | 🖼️ Preview |
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import { createAds, deleteAds, getAdsList, updateAds } from '@/services/admin/ads';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -46,9 +46,6 @@ export default function Page() {
|
||||
),
|
||||
}}
|
||||
params={[
|
||||
{
|
||||
key: 'search',
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
placeholder: t('status'),
|
||||
@@ -57,6 +54,9 @@ export default function Page() {
|
||||
{ label: t('disabled'), value: '0' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'search',
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getAdsList({
|
||||
|
||||
@@ -81,9 +81,13 @@ export default function AnnouncementForm<T extends Record<string, any>>({
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<ScrollArea className='-mx-6 h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 px-6 pt-4'>
|
||||
<form
|
||||
id='notice-form'
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className='space-y-4 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='title'
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getApplication,
|
||||
getApplicationConfig,
|
||||
updateApplicationConfig,
|
||||
} 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,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
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 { UploadImage } from '@workspace/ui/custom-components/upload-image';
|
||||
import { DicesIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const formSchema = z.object({
|
||||
app_id: z.number().optional(),
|
||||
encryption_key: z.string().optional(),
|
||||
encryption_method: 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>;
|
||||
|
||||
export default function ConfigForm() {
|
||||
const t = useTranslations('subscribe.app');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const form = useForm<FormSchema>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
app_id: 0,
|
||||
encryption_key: '',
|
||||
encryption_method: '',
|
||||
startup_picture: '',
|
||||
startup_picture_skip_time: 0,
|
||||
domains: [],
|
||||
},
|
||||
});
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getApplicationConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getApplicationConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const { data: applications } = useQuery({
|
||||
queryKey: ['getApplication'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getApplication();
|
||||
return data.data?.applications || [];
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: FormSchema) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateApplicationConfig({
|
||||
...values,
|
||||
domains: values.domains?.filter((domain) => domain),
|
||||
} as API.ApplicationConfig);
|
||||
toast.success(t('updateSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant='outline'>
|
||||
<Icon icon='mdi:cog' className='mr-2' />
|
||||
{t('config')}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[520px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('configApp')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
|
||||
<Form {...form}>
|
||||
<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='encryption_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_method'
|
||||
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
|
||||
control={form.control}
|
||||
name='startup_picture'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('startupPicture')}</FormLabel>
|
||||
<FormDescription>{t('startupPictureDescription')}</FormDescription>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
value={field.value}
|
||||
onValueChange={(value) => form.setValue(field.name, value as string)}
|
||||
suffix={
|
||||
<UploadImage
|
||||
className='bg-muted h-9 rounded-none border-none px-2'
|
||||
onChange={(value) => form.setValue('startup_picture', value as string)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='startup_picture_skip_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('startupPictureSkip')}</FormLabel>
|
||||
<FormDescription>{t('startupPictureSkipDescription')}</FormDescription>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
min={0}
|
||||
suffix='S'
|
||||
value={field.value}
|
||||
onValueChange={(value) =>
|
||||
form.setValue('startup_picture_skip_time', Number(value))
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='domains'
|
||||
render={({ field }) => (
|
||||
<FormItem className='px-1'>
|
||||
<FormLabel>{t('backupDomains')}</FormLabel>
|
||||
<FormDescription>{t('backupDomainsDescription')}</FormDescription>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-28'
|
||||
placeholder='example.com'
|
||||
value={field.value?.join('\n')}
|
||||
onChange={(e) => {
|
||||
form.setValue(field.name, e.target.value.split('\n'));
|
||||
}}
|
||||
/>
|
||||
</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(onSubmit)} disabled={loading}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getSubscribeType } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { assign, shake } from 'radash';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const platforms = ['windows', 'macos', 'linux', 'android', 'ios', 'harmony'];
|
||||
|
||||
const defaultValues = {
|
||||
subscribe_type: 'Clash',
|
||||
name: '',
|
||||
icon: '',
|
||||
url: '',
|
||||
};
|
||||
|
||||
const versionSchema = z.object({
|
||||
url: z.string(),
|
||||
version: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
is_default: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const formSchema = z.object({
|
||||
icon: z.string(),
|
||||
name: z.string(),
|
||||
subscribe_type: z.string(),
|
||||
platform: z.object({
|
||||
windows: z.array(versionSchema).optional(),
|
||||
macos: z.array(versionSchema).optional(),
|
||||
linux: z.array(versionSchema).optional(),
|
||||
android: z.array(versionSchema).optional(),
|
||||
ios: z.array(versionSchema).optional(),
|
||||
harmony: z.array(versionSchema).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
interface FormProps<T> {
|
||||
trigger: React.ReactNode | string;
|
||||
title: string;
|
||||
initialValues?: Partial<T>;
|
||||
onSubmit: (values: T) => Promise<boolean>;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export default 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);
|
||||
|
||||
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-[520px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
|
||||
<Form {...form}>
|
||||
<form className='space-y-4 py-4'>
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='icon'
|
||||
render={({ field }) => (
|
||||
<FormItem className='col-span-2'>
|
||||
<FormLabel>{t('appIcon')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
required
|
||||
suffix={
|
||||
<UploadImage
|
||||
className='bg-muted h-9 rounded-none border-none px-2'
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value as string);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value as string);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('appName')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
required
|
||||
type='text'
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value as string);
|
||||
}}
|
||||
/>
|
||||
</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>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormItem>
|
||||
<FormLabel>{t('platform')}</FormLabel>
|
||||
<Tabs defaultValue={platforms[0]}>
|
||||
<TabsList>
|
||||
{platforms.map((platform) => (
|
||||
<TabsTrigger key={platform} value={platform} className='uppercase'>
|
||||
{platform}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
{platforms.map((platform) => (
|
||||
<TabsContent key={platform} value={platform}>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`platform.${platform as keyof FormSchema['platform']}`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<ArrayInput
|
||||
isReverse
|
||||
className='grid grid-cols-3 gap-4'
|
||||
fields={[
|
||||
{
|
||||
name: 'version',
|
||||
type: 'text',
|
||||
placeholder: t('version'),
|
||||
defaultValue: '1.0.0',
|
||||
},
|
||||
{
|
||||
name: 'description',
|
||||
type: 'text',
|
||||
placeholder: t('description'),
|
||||
},
|
||||
{
|
||||
name: 'is_default',
|
||||
type: 'boolean',
|
||||
placeholder: t('defaultVersion'),
|
||||
},
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
placeholder: t('downloadLink'),
|
||||
className: 'col-span-3',
|
||||
},
|
||||
]}
|
||||
value={field.value}
|
||||
onChange={(value) => {
|
||||
const filteredValue = value.filter((item) => item.url);
|
||||
|
||||
const newDefaultIndex = value.findIndex(
|
||||
(item, idx) =>
|
||||
item.is_default &&
|
||||
(!field.value?.[idx] || !field.value[idx].is_default),
|
||||
);
|
||||
|
||||
let finalValue = filteredValue;
|
||||
|
||||
if (newDefaultIndex >= 0 && filteredValue[newDefaultIndex]) {
|
||||
finalValue = filteredValue.map((item, index) => ({
|
||||
...item,
|
||||
is_default: index === newDefaultIndex,
|
||||
}));
|
||||
} else if (
|
||||
!filteredValue.some((item) => item.is_default) &&
|
||||
filteredValue.length > 0
|
||||
) {
|
||||
finalValue = filteredValue.map((item, index) => ({
|
||||
...item,
|
||||
is_default: index === 0,
|
||||
}));
|
||||
}
|
||||
|
||||
form.setValue(field.name, finalValue as any);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</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 unknown as T);
|
||||
if (success) setOpen(false);
|
||||
})}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
createApplication,
|
||||
deleteApplication,
|
||||
getApplication,
|
||||
updateApplication,
|
||||
} from '@/services/admin/system';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/legacy/image';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import ConfigForm from './config';
|
||||
import SubscribeAppForm from './form';
|
||||
|
||||
export default function SubscribeApp() {
|
||||
const t = useTranslations('subscribe.app');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<API.ApplicationResponseInfo, Record<string, unknown>>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t('appList'),
|
||||
toolbar: (
|
||||
<div className='flex items-center gap-2'>
|
||||
<ConfigForm />
|
||||
<SubscribeAppForm<API.CreateApplicationRequest>
|
||||
trigger={t('create')}
|
||||
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;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
request={async (_pagination, filters) => {
|
||||
const { data } = await getApplication();
|
||||
return {
|
||||
list: data.data?.applications || [],
|
||||
total: 0,
|
||||
};
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
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: 'name',
|
||||
header: t('appName'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscribe_type',
|
||||
header: t('subscriptionProtocol'),
|
||||
cell: ({ row }) => row.getValue('subscribe_type'),
|
||||
},
|
||||
]}
|
||||
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')}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('apple');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'apple'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'apple',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: keyof API.UpdateAuthMethodConfigRequest, value: unknown) {
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('teamId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('teamIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='ABCDE1FGHI'
|
||||
value={data?.config?.team_id}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
team_id: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('keyId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('keyIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='ABC1234567'
|
||||
value={data?.config?.key_id}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
key_id: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('clientId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='com.your.app.service'
|
||||
value={data?.config?.client_id}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_id: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('clientSecret')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientSecretDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Textarea
|
||||
className='h-20'
|
||||
placeholder={`-----BEGIN PRIVATE KEY-----\nMIGTAgEA...\n-----END PRIVATE KEY-----`}
|
||||
defaultValue={data?.config?.client_secret}
|
||||
onBlur={(e) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_secret: e.target.value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('redirectUri')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('redirectUriDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='https://your-domain.com'
|
||||
value={data?.config.redirect_url}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
redirect_url: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { DicesIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('device');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'device'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'device',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: keyof API.UpdateAuthMethodConfigRequest, value: unknown) {
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('showAds')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('showAdsDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.config?.show_ads}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
show_ads: checked,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('blockVirtualMachine')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('blockVirtualMachineDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.config?.only_real_device}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
only_real_device: checked,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enableSecurity')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableSecurityDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.config?.enable_security}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
enable_security: checked,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('communicationKey')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('communicationKeyDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.security_secret}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
security_secret: value,
|
||||
});
|
||||
}}
|
||||
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)}`;
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
security_secret: formatted,
|
||||
});
|
||||
}}
|
||||
className='cursor-pointer'
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getAuthMethodConfig,
|
||||
testEmailSend,
|
||||
updateAuthMethodConfig,
|
||||
} from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@workspace/ui/components/card';
|
||||
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { HTMLEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { LogsTable } from '../log';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('email');
|
||||
const ref = useRef<Partial<API.AuthMethodConfig>>({});
|
||||
const [email, setEmail] = useState<string>();
|
||||
|
||||
const { data, refetch, isFetching } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'email'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'email',
|
||||
});
|
||||
ref.current = data.data as API.AuthMethodConfig;
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...ref.current,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs defaultValue='settings'>
|
||||
<TabsList className='h-full flex-wrap'>
|
||||
<TabsTrigger value='settings'>{t('settings')}</TabsTrigger>
|
||||
<TabsTrigger value='template'>{t('template')}</TabsTrigger>
|
||||
<TabsTrigger value='logs'>{t('logs')}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value='settings'>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('emailVerification')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('emailVerificationDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.config?.enable_verify}
|
||||
onCheckedChange={(checked) =>
|
||||
updateConfig('config', { ...data?.config, enable_verify: checked })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('emailSuffixWhitelist')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('emailSuffixWhitelistDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.config?.enable_domain_suffix}
|
||||
onCheckedChange={(checked) =>
|
||||
updateConfig('config', { ...data?.config, enable_domain_suffix: checked })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('whitelistSuffixes')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('whitelistSuffixesDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Textarea
|
||||
className='h-32'
|
||||
placeholder={t('whitelistSuffixesPlaceholder')}
|
||||
defaultValue={data?.config?.domain_suffix_list}
|
||||
onBlur={(e) =>
|
||||
updateConfig('config', { ...data?.config, domain_suffix_list: e.target.value })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('smtpServerAddress')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('smtpServerAddressDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.config?.platform_config?.host}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.platform_config,
|
||||
host: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('smtpServerPort')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('smtpServerPortDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.config?.platform_config?.port}
|
||||
type='number'
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...ref.current?.config?.platform_config,
|
||||
port: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('smtpEncryptionMethod')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('smtpEncryptionMethodDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.config?.platform_config?.ssl}
|
||||
onCheckedChange={(checked) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...ref.current?.config?.platform_config,
|
||||
ssl: checked,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('smtpAccount')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('smtpAccountDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.config?.platform_config?.user}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...ref.current?.config?.platform_config,
|
||||
user: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('smtpPassword')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('smtpPasswordDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.config?.platform_config?.pass}
|
||||
type='password'
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...ref.current?.config?.platform_config,
|
||||
pass: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('senderAddress')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('senderAddressDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.config?.platform_config?.from}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...ref.current?.config?.platform_config,
|
||||
from: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('sendTestEmail')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('sendTestEmailDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='flex items-center gap-2 text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='test@example.com'
|
||||
value={email}
|
||||
type='email'
|
||||
onValueChange={(value) => setEmail(value as string)}
|
||||
/>
|
||||
<Button
|
||||
disabled={!email || isFetching}
|
||||
onClick={async () => {
|
||||
if (!email) return;
|
||||
try {
|
||||
await testEmailSend({ email });
|
||||
toast.success(t('sendSuccess'));
|
||||
} catch {
|
||||
toast.error(t('sendFailure'));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('sendTestEmail')}
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='template'>
|
||||
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
|
||||
{[
|
||||
'verify_email_template',
|
||||
'expiration_email_template',
|
||||
'maintenance_email_template',
|
||||
'traffic_exceed_email_template',
|
||||
].map((templateKey) => (
|
||||
<Card key={templateKey}>
|
||||
<CardHeader>
|
||||
<CardTitle>{t(`${templateKey}`)}</CardTitle>
|
||||
<CardDescription>
|
||||
{t(`${templateKey}Description`, { after: '{{', before: '}}' })}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<HTMLEditor
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.config?.[templateKey] as string}
|
||||
onBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
[templateKey]: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='logs'>
|
||||
<LogsTable type='email' />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('facebook');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'facebook'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'facebook',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: keyof API.UpdateAuthMethodConfigRequest, value: unknown) {
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('clientId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='1234567890123456'
|
||||
value={data?.config?.client_id}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_id: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('clientSecret')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientSecretDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='1234567890abcdef1234567890abcdef'
|
||||
value={data?.config?.client_secret}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_secret: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const appleSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
config: z
|
||||
.object({
|
||||
team_id: z.string().optional(),
|
||||
key_id: z.string().optional(),
|
||||
client_id: z.string().optional(),
|
||||
client_secret: z.string().optional(),
|
||||
redirect_url: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type AppleFormData = z.infer<typeof appleSchema>;
|
||||
|
||||
export default function AppleForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'apple'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'apple',
|
||||
});
|
||||
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<AppleFormData>({
|
||||
resolver: zodResolver(appleSchema),
|
||||
defaultValues: {
|
||||
enabled: false,
|
||||
config: {
|
||||
team_id: '',
|
||||
key_id: '',
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
redirect_url: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset({
|
||||
enabled: data.enabled || false,
|
||||
config: {
|
||||
team_id: data.config?.team_id || '',
|
||||
key_id: data.config?.key_id || '',
|
||||
client_id: data.config?.client_id || '',
|
||||
client_secret: data.config?.client_secret || '',
|
||||
redirect_url: data.config?.redirect_url || '',
|
||||
},
|
||||
});
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: AppleFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
enabled: values.enabled,
|
||||
config: {
|
||||
...data?.config,
|
||||
...values.config,
|
||||
},
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:apple' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('apple.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('apple.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('apple.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form id='apple-form' onSubmit={form.handleSubmit(onSubmit)} className='space-y-2 pt-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('apple.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('apple.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.team_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('apple.teamId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='ABCDE1FGHI'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('apple.teamIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.key_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('apple.keyId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='ABC1234567'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('apple.keyIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.client_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('apple.clientId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='com.your.app.service'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('apple.clientIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.client_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('apple.clientSecret')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-20'
|
||||
placeholder={`-----BEGIN PRIVATE KEY-----\nMIGTAgEA...\n-----END PRIVATE KEY-----`}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('apple.clientSecretDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.redirect_url'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('apple.redirectUri')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='https://your-domain.com'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('apple.redirectUriDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='apple-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const deviceSchema = z.object({
|
||||
id: z.number(),
|
||||
method: z.string(),
|
||||
enabled: z.boolean(),
|
||||
config: z
|
||||
.object({
|
||||
show_ads: z.boolean().optional(),
|
||||
only_real_device: z.boolean().optional(),
|
||||
enable_security: z.boolean().optional(),
|
||||
security_secret: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type DeviceFormData = z.infer<typeof deviceSchema>;
|
||||
|
||||
export default function DeviceForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'device'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'device',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<DeviceFormData>({
|
||||
resolver: zodResolver(deviceSchema),
|
||||
defaultValues: {
|
||||
id: 0,
|
||||
method: 'device',
|
||||
enabled: false,
|
||||
config: {
|
||||
show_ads: false,
|
||||
only_real_device: false,
|
||||
enable_security: false,
|
||||
security_secret: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: DeviceFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig(values as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function generateSecurityKey() {
|
||||
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('config.security_secret', formatted);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:devices' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('device.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('device.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('device.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='device-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('device.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('device.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.show_ads'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('device.showAds')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('device.showAdsDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.only_real_device'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('device.blockVirtualMachine')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('device.blockVirtualMachineDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.enable_security'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('device.enableSecurity')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('device.enableSecurityDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.security_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('device.communicationKey')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='e.g., 12345678-1234-1234-1234-123456789abc'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
suffix={
|
||||
<div className='bg-muted flex h-9 items-center text-nowrap px-3'>
|
||||
<Icon
|
||||
icon='mdi:dice-multiple'
|
||||
onClick={generateSecurityKey}
|
||||
className='size-4 cursor-pointer'
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('device.communicationKeyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='device-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getAuthMethodConfig,
|
||||
testEmailSend,
|
||||
updateAuthMethodConfig,
|
||||
} from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { HTMLEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const emailSettingsSchema = z.object({
|
||||
id: z.number(),
|
||||
method: z.string(),
|
||||
enabled: z.boolean(),
|
||||
config: z
|
||||
.object({
|
||||
enable_verify: z.boolean(),
|
||||
enable_domain_suffix: z.boolean(),
|
||||
domain_suffix_list: z.string().optional(),
|
||||
verify_email_template: z.string().optional(),
|
||||
expiration_email_template: z.string().optional(),
|
||||
maintenance_email_template: z.string().optional(),
|
||||
traffic_exceed_email_template: z.string().optional(),
|
||||
platform: z.string(),
|
||||
platform_config: z
|
||||
.object({
|
||||
host: z.string().optional(),
|
||||
port: z.number().optional(),
|
||||
ssl: z.boolean(),
|
||||
user: z.string().optional(),
|
||||
pass: z.string().optional(),
|
||||
from: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type EmailSettingsFormData = z.infer<typeof emailSettingsSchema>;
|
||||
|
||||
export default function EmailSettingsForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [testEmail, setTestEmail] = useState<string>();
|
||||
|
||||
const { data, refetch, isFetching } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'email'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'email',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<EmailSettingsFormData>({
|
||||
resolver: zodResolver(emailSettingsSchema),
|
||||
defaultValues: {
|
||||
id: 0,
|
||||
method: 'email',
|
||||
enabled: false,
|
||||
config: {
|
||||
enable_verify: false,
|
||||
enable_domain_suffix: false,
|
||||
domain_suffix_list: '',
|
||||
verify_email_template: '',
|
||||
expiration_email_template: '',
|
||||
maintenance_email_template: '',
|
||||
traffic_exceed_email_template: '',
|
||||
platform: 'smtp',
|
||||
platform_config: {
|
||||
host: '',
|
||||
port: 587,
|
||||
ssl: false,
|
||||
user: '',
|
||||
pass: '',
|
||||
from: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: EmailSettingsFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...values,
|
||||
config: {
|
||||
...values.config,
|
||||
platform: 'smtp',
|
||||
},
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:email-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('email.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('email.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('email.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='email-settings-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<Tabs defaultValue='basic' className='space-y-2'>
|
||||
<TabsList className='flex h-full w-full flex-wrap *:flex-auto md:flex-nowrap'>
|
||||
<TabsTrigger value='basic'>{t('email.basicSettings')}</TabsTrigger>
|
||||
<TabsTrigger value='smtp'>{t('email.smtpSettings')}</TabsTrigger>
|
||||
<TabsTrigger value='verify'>{t('email.verifyTemplate')}</TabsTrigger>
|
||||
<TabsTrigger value='expiration'>{t('email.expirationTemplate')}</TabsTrigger>
|
||||
<TabsTrigger value='maintenance'>{t('email.maintenanceTemplate')}</TabsTrigger>
|
||||
<TabsTrigger value='traffic'>{t('email.trafficTemplate')}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value='basic' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.enable_verify'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.emailVerification')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.emailVerificationDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.enable_domain_suffix'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.emailSuffixWhitelist')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('email.emailSuffixWhitelistDescription')}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.domain_suffix_list'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.whitelistSuffixes')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-32'
|
||||
placeholder={t('email.whitelistSuffixesPlaceholder')}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.whitelistSuffixesDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='smtp' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.host'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.smtpServerAddress')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.smtpServerAddressDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.port'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.smtpServerPort')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
placeholder='587'
|
||||
value={field.value?.toString()}
|
||||
onValueChange={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.smtpServerPortDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.ssl'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.smtpEncryptionMethod')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('email.smtpEncryptionMethodDescription')}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.user'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.smtpAccount')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.smtpAccountDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.pass'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.smtpPassword')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='password'
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.smtpPasswordDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.from'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.senderAddress')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('email.senderAddressDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className='space-y-2 border-t pt-4'>
|
||||
<FormLabel>{t('email.sendTestEmail')}</FormLabel>
|
||||
<div className='flex items-center gap-2'>
|
||||
<EnhancedInput
|
||||
placeholder='test@example.com'
|
||||
type='email'
|
||||
value={testEmail}
|
||||
onValueChange={(value) => setTestEmail(value as string)}
|
||||
/>
|
||||
<Button
|
||||
type='button'
|
||||
disabled={!testEmail || isFetching}
|
||||
onClick={async () => {
|
||||
if (!testEmail) return;
|
||||
try {
|
||||
await testEmailSend({ email: testEmail });
|
||||
toast.success(t('email.sendSuccess'));
|
||||
} catch {
|
||||
toast.error(t('email.sendFailure'));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('email.sendTestEmail')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('email.sendTestEmailDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='verify' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.verify_email_template'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.verifyEmailTemplate')}</FormLabel>
|
||||
<FormControl>
|
||||
<HTMLEditor
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onBlur={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className='mt-4 space-y-2 border-t pt-4'>
|
||||
<p className='text-muted-foreground text-sm font-medium'>
|
||||
{t('email.templateVariables.title')}
|
||||
</p>
|
||||
<div className='text-muted-foreground space-y-2 text-xs'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.Type}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.type.description')}</span>
|
||||
</div>
|
||||
<div className='pl-6 text-orange-600 dark:text-orange-400'>
|
||||
💡 {t('email.templateVariables.type.conditionalSyntax')}
|
||||
<br />
|
||||
<code className='rounded bg-orange-50 px-1 text-xs dark:bg-orange-900/20'>
|
||||
{'{{if eq .Type 1}}...{{else}}...{{end}}'}
|
||||
</code>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteLogo}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteLogo.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteName}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteName.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.Expire}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.expire.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.Code}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.code.description')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='expiration' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.expiration_email_template'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.expirationEmailTemplate')}</FormLabel>
|
||||
<FormControl>
|
||||
<HTMLEditor
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onBlur={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className='mt-4 space-y-2 border-t pt-4'>
|
||||
<p className='text-muted-foreground text-sm font-medium'>
|
||||
{t('email.templateVariables.title')}
|
||||
</p>
|
||||
<div className='text-muted-foreground space-y-2 text-xs'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteLogo}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteLogo.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteName}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteName.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.ExpireDate}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.expireDate.description')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='maintenance' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.maintenance_email_template'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.maintenanceEmailTemplate')}</FormLabel>
|
||||
<FormControl>
|
||||
<HTMLEditor
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onBlur={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className='mt-4 space-y-2 border-t pt-4'>
|
||||
<p className='text-muted-foreground text-sm font-medium'>
|
||||
{t('email.templateVariables.title')}
|
||||
</p>
|
||||
<div className='text-muted-foreground space-y-2 text-xs'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteLogo}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteLogo.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteName}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteName.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.MaintenanceDate}}'}
|
||||
</code>
|
||||
<span>
|
||||
{t('email.templateVariables.maintenanceDate.description')}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.MaintenanceTime}}'}
|
||||
</code>
|
||||
<span>
|
||||
{t('email.templateVariables.maintenanceTime.description')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='traffic' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.traffic_exceed_email_template'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('email.trafficExceedEmailTemplate')}</FormLabel>
|
||||
<FormControl>
|
||||
<HTMLEditor
|
||||
placeholder={t('email.inputPlaceholder')}
|
||||
value={field.value}
|
||||
onBlur={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className='mt-4 space-y-2 border-t pt-4'>
|
||||
<p className='text-muted-foreground text-sm font-medium'>
|
||||
{t('email.templateVariables.title')}
|
||||
</p>
|
||||
<div className='text-muted-foreground space-y-2 text-xs'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteLogo}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteLogo.description')}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<code className='bg-muted text-foreground rounded px-1.5 py-0.5 font-mono'>
|
||||
{'{{.SiteName}}'}
|
||||
</code>
|
||||
<span>{t('email.templateVariables.siteName.description')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='email-settings-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const facebookSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
client_id: z.string().optional(),
|
||||
client_secret: z.string().optional(),
|
||||
});
|
||||
|
||||
type FacebookFormData = z.infer<typeof facebookSchema>;
|
||||
|
||||
export default function FacebookForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch, isFetching } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'facebook'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'facebook',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<FacebookFormData>({
|
||||
resolver: zodResolver(facebookSchema),
|
||||
defaultValues: {
|
||||
enabled: false,
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset({
|
||||
enabled: data.enabled || false,
|
||||
client_id: data.config?.client_id || '',
|
||||
client_secret: data.config?.client_secret || '',
|
||||
});
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: FacebookFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
enabled: values.enabled,
|
||||
config: {
|
||||
...data?.config,
|
||||
client_id: values.client_id,
|
||||
client_secret: values.client_secret,
|
||||
},
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:facebook' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('facebook.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('facebook.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('facebook.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='facebook-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('facebook.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('facebook.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='client_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('facebook.clientId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='1234567890123456'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('facebook.clientIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='client_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('facebook.clientSecret')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='1234567890abcdef1234567890abcdef'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
type='password'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('facebook.clientSecretDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='facebook-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const githubSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
client_id: z.string().optional(),
|
||||
client_secret: z.string().optional(),
|
||||
});
|
||||
|
||||
type GithubFormData = z.infer<typeof githubSchema>;
|
||||
|
||||
export default function GithubForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'github'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'github',
|
||||
});
|
||||
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<GithubFormData>({
|
||||
resolver: zodResolver(githubSchema),
|
||||
defaultValues: {
|
||||
enabled: false,
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset({
|
||||
enabled: data.enabled || false,
|
||||
client_id: data.config?.client_id || '',
|
||||
client_secret: data.config?.client_secret || '',
|
||||
});
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: GithubFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
enabled: values.enabled,
|
||||
config: {
|
||||
...data?.config,
|
||||
client_id: values.client_id,
|
||||
client_secret: values.client_secret,
|
||||
},
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:github' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('github.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('github.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('github.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='github-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('github.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('github.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='client_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('github.clientId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='e.g., Iv1.1234567890abcdef'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('github.clientIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='client_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('github.clientSecret')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='e.g., 1234567890abcdef1234567890abcdef12345678'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
type='password'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('github.clientSecretDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='github-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const googleSchema = z.object({
|
||||
id: z.number(),
|
||||
method: z.string().default('google').optional(),
|
||||
enabled: z.boolean().default(false).optional(),
|
||||
config: z
|
||||
.object({
|
||||
client_id: z.string().optional(),
|
||||
client_secret: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type GoogleFormData = z.infer<typeof googleSchema>;
|
||||
|
||||
export default function GoogleForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch, isFetching } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'google'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'google',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<GoogleFormData>({
|
||||
resolver: zodResolver(googleSchema),
|
||||
defaultValues: {
|
||||
id: 0,
|
||||
method: 'google',
|
||||
enabled: false,
|
||||
config: {
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: GoogleFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig(values as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:google' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('google.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('google.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('google.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='google-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('google.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('google.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.client_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('google.clientId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='123456789-abc123def456.apps.googleusercontent.com'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('google.clientIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.client_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('google.clientSecret')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='GOCSPX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
type='password'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('google.clientSecretDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='google-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getAuthMethodConfig,
|
||||
getSmsPlatform,
|
||||
testSmsSend,
|
||||
updateAuthMethodConfig,
|
||||
} from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
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 { Switch } from '@workspace/ui/components/switch';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { AreaCodeSelect } from '@workspace/ui/custom-components/area-code-select';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import TagInput from '@workspace/ui/custom-components/tag-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const phoneSettingsSchema = z.object({
|
||||
id: z.number(),
|
||||
method: z.string(),
|
||||
enabled: z.boolean(),
|
||||
config: z
|
||||
.object({
|
||||
enable_whitelist: z.boolean().optional(),
|
||||
whitelist: z.array(z.string()).optional(),
|
||||
platform: z.string().optional(),
|
||||
platform_config: z
|
||||
.object({
|
||||
access: z.string().optional(),
|
||||
endpoint: z.string().optional(),
|
||||
secret: z.string().optional(),
|
||||
template_code: z.string().optional(),
|
||||
sign_name: z.string().optional(),
|
||||
phone_number: z.string().optional(),
|
||||
template: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type PhoneSettingsFormData = z.infer<typeof phoneSettingsSchema>;
|
||||
|
||||
export default function PhoneSettingsForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [testParams, setTestParams] = useState<API.TestSmsSendRequest>({
|
||||
telephone: '',
|
||||
area_code: '1',
|
||||
});
|
||||
|
||||
const { data, refetch, isFetching } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'mobile'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'mobile',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const { data: platforms } = useQuery({
|
||||
queryKey: ['getSmsPlatform'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSmsPlatform();
|
||||
return data.data?.list;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<PhoneSettingsFormData>({
|
||||
resolver: zodResolver(phoneSettingsSchema),
|
||||
defaultValues: {
|
||||
id: 0,
|
||||
method: 'mobile',
|
||||
enabled: false,
|
||||
config: {
|
||||
enable_whitelist: false,
|
||||
whitelist: [],
|
||||
platform: '',
|
||||
platform_config: {
|
||||
access: '',
|
||||
endpoint: '',
|
||||
secret: '',
|
||||
template_code: 'code',
|
||||
sign_name: '',
|
||||
phone_number: '',
|
||||
template: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const selectedPlatform = platforms?.find(
|
||||
(platform) => platform.platform === form.watch('config.platform'),
|
||||
);
|
||||
const { platform_url, platform_field_description: platformConfig } = selectedPlatform ?? {};
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: PhoneSettingsFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig(values as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:phone-settings' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('phone.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('phone.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('phone.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='phone-settings-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('phone.enableTip')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.enable_whitelist'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.whitelistValidation')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('phone.whitelistValidationTip')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.whitelist'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.whitelistAreaCode')}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
placeholder='1, 852, 886, 888'
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('phone.whitelistAreaCodeTip')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.platform')}</FormLabel>
|
||||
<div className='flex items-center gap-1'>
|
||||
<FormControl>
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{platforms?.map((item) => (
|
||||
<SelectItem key={item.platform} value={item.platform}>
|
||||
{item.platform}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
{platform_url && (
|
||||
<Button size='sm' asChild>
|
||||
<Link href={platform_url} target='_blank'>
|
||||
{t('phone.applyPlatform')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<FormDescription>{t('phone.platformTip')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.access'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.accessLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.platformConfigTip', { key: platformConfig?.access })}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.platformConfigTip', { key: platformConfig?.access })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{platformConfig?.endpoint && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.endpoint'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.endpointLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.platformConfigTip', {
|
||||
key: platformConfig?.endpoint,
|
||||
})}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.platformConfigTip', { key: platformConfig?.endpoint })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.secretLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='password'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.platformConfigTip', { key: platformConfig?.secret })}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.platformConfigTip', { key: platformConfig?.secret })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{platformConfig?.template_code && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.template_code'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.templateCodeLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.platformConfigTip', {
|
||||
key: platformConfig?.template_code,
|
||||
})}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.platformConfigTip', { key: platformConfig?.template_code })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{platformConfig?.sign_name && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.sign_name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.signNameLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.platformConfigTip', {
|
||||
key: platformConfig?.sign_name,
|
||||
})}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.platformConfigTip', { key: platformConfig?.sign_name })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{platformConfig?.phone_number && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.phone_number'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.phoneNumberLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.platformConfigTip', {
|
||||
key: platformConfig?.phone_number,
|
||||
})}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.platformConfigTip', { key: platformConfig?.phone_number })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{platformConfig?.code_variable && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='config.platform_config.template'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('phone.template')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
disabled={isFetching}
|
||||
placeholder={t('phone.placeholders.template', {
|
||||
code: platformConfig?.code_variable,
|
||||
})}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('phone.templateTip', { code: platformConfig?.code_variable })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className='space-y-4 border-t pt-4'>
|
||||
<div>
|
||||
<FormLabel>{t('phone.testSms')}</FormLabel>
|
||||
<p className='text-muted-foreground mb-3 text-sm'>{t('phone.testSmsTip')}</p>
|
||||
<div className='flex items-center gap-2'>
|
||||
<AreaCodeSelect
|
||||
value={testParams.area_code}
|
||||
onChange={(value) => {
|
||||
if (value.phone) {
|
||||
setTestParams((prev) => ({ ...prev, area_code: value.phone! }));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<EnhancedInput
|
||||
placeholder={t('phone.testSmsPhone')}
|
||||
value={testParams.telephone}
|
||||
onValueChange={(value) => {
|
||||
setTestParams((prev) => ({ ...prev, telephone: value as string }));
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type='button'
|
||||
disabled={!testParams.telephone || !testParams.area_code || isFetching}
|
||||
onClick={async () => {
|
||||
if (isFetching || !testParams.telephone || !testParams.area_code) return;
|
||||
try {
|
||||
await testSmsSend(testParams);
|
||||
toast.success(t('phone.sendSuccess'));
|
||||
} catch {
|
||||
toast.error(t('phone.sendFailed'));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('phone.testSms')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='phone-settings-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const telegramSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
bot: z.string().optional(),
|
||||
bot_token: z.string().optional(),
|
||||
});
|
||||
|
||||
type TelegramFormData = z.infer<typeof telegramSchema>;
|
||||
|
||||
export default function TelegramForm() {
|
||||
const t = useTranslations('auth-control');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'telegram'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'telegram',
|
||||
});
|
||||
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<TelegramFormData>({
|
||||
resolver: zodResolver(telegramSchema),
|
||||
defaultValues: {
|
||||
enabled: false,
|
||||
bot: '',
|
||||
bot_token: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset({
|
||||
enabled: data.enabled || false,
|
||||
bot: data.config?.bot || '',
|
||||
bot_token: data.config?.bot_token || '',
|
||||
});
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: TelegramFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
enabled: values.enabled,
|
||||
config: {
|
||||
...data?.config,
|
||||
bot: values.bot,
|
||||
bot_token: values.bot_token,
|
||||
},
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:telegram' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('telegram.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('telegram.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('telegram.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='telegram-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enabled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('telegram.enable')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('telegram.enableDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='bot'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('telegram.clientId')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='6123456789'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('telegram.clientIdDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='bot_token'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('telegram.clientSecret')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder='6123456789:AAHn_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
type='password'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('telegram.clientSecretDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='telegram-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getInviteConfig, updateInviteConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@workspace/ui/components/card';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export function Invite() {
|
||||
const t = useTranslations('auth-control.invite');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getInviteConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getInviteConfig();
|
||||
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateInviteConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.InviteConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('inviteSettings')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enableForcedInvite')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('enableForcedInviteDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.forced_invite}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('forced_invite', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('inviteCommissionPercentage')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('inviteCommissionPercentageDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.referral_percentage}
|
||||
type='number'
|
||||
min={0}
|
||||
max={100}
|
||||
suffix='%'
|
||||
onValueBlur={(value) => updateConfig('referral_percentage', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('commissionFirstTimeOnly')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('commissionFirstTimeOnlyDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.only_first_purchase}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('only_first_purchase', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Invite } from './invite';
|
||||
import { Register } from './register';
|
||||
import { Verify } from './verify';
|
||||
import { VerifyCode } from './verify-code';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div className='space-y-3'>
|
||||
<Invite />
|
||||
<Register />
|
||||
<VerifyCode />
|
||||
<Verify />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getSubscribeList } from '@/services/admin/subscribe';
|
||||
import { getRegisterConfig, updateRegisterConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@workspace/ui/components/card';
|
||||
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 { Combobox } from '@workspace/ui/custom-components/combobox';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export function Register() {
|
||||
const t = useTranslations('auth-control.register');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getRegisterConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getRegisterConfig();
|
||||
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
await updateRegisterConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.RegisterConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
}
|
||||
|
||||
const { data: subscribe } = useQuery({
|
||||
queryKey: ['getSubscribeList', 'all'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeList({
|
||||
page: 1,
|
||||
size: 9999,
|
||||
});
|
||||
return data.data?.list as API.Subscribe[];
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('registerSettings')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('stopNewUserRegistration')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('stopNewUserRegistrationDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.stop_register}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('stop_register', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('ipRegistrationLimit')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('ipRegistrationLimitDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enable_ip_register_limit}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('enable_ip_register_limit', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('registrationLimitCount')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('registrationLimitCountDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
value={data?.ip_register_limit}
|
||||
onValueBlur={(value) => updateConfig('ip_register_limit', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('penaltyTime')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('penaltyTimeDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
value={data?.ip_register_limit_duration}
|
||||
onValueBlur={(value) => updateConfig('ip_register_limit_duration', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('trialRegistration')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('trialRegistrationDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enable_trial}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('enable_trial', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow className='flex flex-col'>
|
||||
<TableCell className='w-full'>
|
||||
<Label>{t('trialSubscribePlan')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('trialSubscribePlanDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='max-w-96'>
|
||||
<EnhancedInput
|
||||
placeholder={t('trialDuration')}
|
||||
type='number'
|
||||
min={0}
|
||||
value={data?.trial_time}
|
||||
onValueBlur={(value) => updateConfig('trial_time', value)}
|
||||
prefix={
|
||||
<Select
|
||||
value={String(data?.trial_subscribe)}
|
||||
onValueChange={(value) => updateConfig('trial_subscribe', Number(value))}
|
||||
>
|
||||
<SelectTrigger className='bg-secondary rounded-r-none'>
|
||||
{data?.trial_subscribe ? (
|
||||
<SelectValue placeholder='Select Subscribe' />
|
||||
) : (
|
||||
'Select Subscribe'
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{subscribe?.map((item) => (
|
||||
<SelectItem key={item.id} value={String(item.id)}>
|
||||
{item.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
}
|
||||
suffix={
|
||||
<Combobox
|
||||
className='bg-secondary rounded-l-none'
|
||||
value={data?.trial_time_unit}
|
||||
onChange={(value) => {
|
||||
if (value) {
|
||||
updateConfig('trial_time_unit', value);
|
||||
}
|
||||
}}
|
||||
options={[
|
||||
{ label: t('noLimit'), value: 'NoLimit' },
|
||||
{ label: t('year'), value: 'Year' },
|
||||
{ label: t('month'), value: 'Month' },
|
||||
{ label: t('day'), value: 'Day' },
|
||||
{ label: t('hour'), value: 'Hour' },
|
||||
{ label: t('minute'), value: 'Minute' },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getVerifyCodeConfig, updateVerifyCodeConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@workspace/ui/components/card';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export function VerifyCode() {
|
||||
const t = useTranslations('auth-control.verify-code');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getVerifyCodeConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getVerifyCodeConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateVerifyCodeConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.VerifyCodeConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className='mb-6'>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('verifyCodeSettings')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('expireTime')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('expireTimeDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
placeholder='300'
|
||||
value={data?.verify_code_expire_time}
|
||||
onValueBlur={(value) => updateConfig('verify_code_expire_time', Number(value))}
|
||||
suffix={t('second')}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('interval')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('intervalDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
placeholder='60'
|
||||
value={data?.verify_code_interval}
|
||||
onValueBlur={(value) => updateConfig('verify_code_interval', Number(value))}
|
||||
suffix={t('second')}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('dailyLimit')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('dailyLimitDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
placeholder='15'
|
||||
value={data?.verify_code_limit}
|
||||
onValueBlur={(value) => updateConfig('verify_code_limit', Number(value))}
|
||||
suffix={t('times')}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getVerifyConfig, updateVerifyConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@workspace/ui/components/card';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export function Verify() {
|
||||
const t = useTranslations('auth-control.verify');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getVerifyConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getVerifyConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateVerifyConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.VerifyConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className='mb-6'>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('verifySettings')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>Turnstile Site Key</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('turnstileSiteKeyDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.turnstile_site_key}
|
||||
onValueBlur={(value) => updateConfig('turnstile_site_key', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>Turnstile Site Secret</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('turnstileSecretDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.turnstile_secret}
|
||||
onValueBlur={(value) => updateConfig('turnstile_secret', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('registrationVerificationCode')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('registrationVerificationCodeDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enable_register_verify}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('enable_register_verify', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('loginVerificationCode')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('loginVerificationCodeDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enable_login_verify}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('enable_login_verify', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('resetPasswordVerificationCode')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('resetPasswordVerificationCodeDescription')}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enable_reset_password_verify}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig('enable_reset_password_verify', checked);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('github');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'github'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'github',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: keyof API.UpdateAuthMethodConfigRequest, value: unknown) {
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('clientId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='e.g., Iv1.1234567890abcdef'
|
||||
value={data?.config?.client_id}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_id: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('clientSecret')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientSecretDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='e.g., 1234567890abcdef1234567890abcdef12345678'
|
||||
value={data?.config?.client_secret}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_secret: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('google');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'google'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'google',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: keyof API.UpdateAuthMethodConfigRequest, value: unknown) {
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('clientId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='123456789-abc123def456.apps.googleusercontent.com'
|
||||
value={data?.config?.client_id}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_id: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('clientSecret')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientSecretDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='GOCSPX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
|
||||
value={data?.config?.client_secret}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
client_secret: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { AuthControl } from '@/config/navs';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
interface AuthControlLayoutProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function AuthControlLayout({ children }: Readonly<AuthControlLayoutProps>) {
|
||||
const pathname = usePathname();
|
||||
const t = useTranslations('menu');
|
||||
if (!pathname) return null;
|
||||
return (
|
||||
<Tabs value={pathname}>
|
||||
<TabsList className='h-full flex-wrap'>
|
||||
{AuthControl.map((item) => (
|
||||
<TabsTrigger key={item.url} value={item.url} asChild>
|
||||
<Link href={item.url}>{t(item.title)}</Link>
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
<TabsContent value={pathname}>{children}</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import { getMessageLogList } from '@/services/admin/log';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef } from 'react';
|
||||
|
||||
export function LogsTable({ type }: { type: 'email' | 'mobile' }) {
|
||||
const t = useTranslations('auth-control.log');
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<
|
||||
API.MessageLog,
|
||||
{
|
||||
platform?: string;
|
||||
to?: string;
|
||||
subject?: string;
|
||||
content?: string;
|
||||
status?: number;
|
||||
}
|
||||
>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t(`${type}Log`),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: 'ID',
|
||||
},
|
||||
{
|
||||
accessorKey: 'platform',
|
||||
header: t('platform'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'to',
|
||||
header: t('to'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'subject',
|
||||
header: t('subject'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'content',
|
||||
header: t('content'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: t('status'),
|
||||
cell: ({ row }) => {
|
||||
const status = row.getValue('status');
|
||||
const text = status === 1 ? t('sendSuccess') : t('sendFailed');
|
||||
return <Badge variant={status === 1 ? 'default' : 'destructive'}>{text}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('createdAt'),
|
||||
cell: ({ row }) => formatDate(row.getValue('created_at')),
|
||||
},
|
||||
{
|
||||
accessorKey: 'updated_at',
|
||||
header: t('updatedAt'),
|
||||
cell: ({ row }) => formatDate(row.getValue('updated_at')),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
// {
|
||||
// key: 'platform',
|
||||
// placeholder: t('platform'),
|
||||
// },
|
||||
{
|
||||
key: 'to',
|
||||
placeholder: t('to'),
|
||||
},
|
||||
{
|
||||
key: 'subject',
|
||||
placeholder: t('subject'),
|
||||
},
|
||||
{
|
||||
key: 'content',
|
||||
placeholder: t('content'),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
placeholder: t('status'),
|
||||
options: [
|
||||
{ label: t('sendSuccess'), value: '1' },
|
||||
{ label: t('sendFailed'), value: '0' },
|
||||
],
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await getMessageLogList({
|
||||
...pagination,
|
||||
...filter,
|
||||
status: filter.status === undefined ? undefined : Number(filter.status),
|
||||
type: type,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,61 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
'use client';
|
||||
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import AppleForm from './forms/apple-form';
|
||||
import DeviceForm from './forms/device-form';
|
||||
import EmailSettingsForm from './forms/email-settings-form';
|
||||
import FacebookForm from './forms/facebook-form';
|
||||
import GithubForm from './forms/github-form';
|
||||
import GoogleForm from './forms/google-form';
|
||||
import PhoneSettingsForm from './forms/phone-settings-form';
|
||||
import TelegramForm from './forms/telegram-form';
|
||||
|
||||
export default function Page() {
|
||||
return redirect('/dashboard/auth-control/general');
|
||||
const t = useTranslations('auth-control');
|
||||
|
||||
const formSections = [
|
||||
{
|
||||
title: t('communicationMethods'),
|
||||
forms: [{ component: EmailSettingsForm }, { component: PhoneSettingsForm }],
|
||||
},
|
||||
{
|
||||
title: t('socialAuthMethods'),
|
||||
forms: [
|
||||
{ component: AppleForm },
|
||||
{ component: GoogleForm },
|
||||
{ component: FacebookForm },
|
||||
{ component: GithubForm },
|
||||
{ component: TelegramForm },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('deviceAuthMethods'),
|
||||
forms: [{ component: DeviceForm }],
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='space-y-8'>
|
||||
{formSections.map((section, sectionIndex) => (
|
||||
<div key={sectionIndex}>
|
||||
<h2 className='mb-4 text-lg font-semibold'>{section.title}</h2>
|
||||
<Table>
|
||||
<TableBody>
|
||||
{section.forms.map((form, formIndex) => {
|
||||
const FormComponent = form.component;
|
||||
return (
|
||||
<TableRow key={formIndex}>
|
||||
<TableCell>
|
||||
<FormComponent />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,395 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getAuthMethodConfig,
|
||||
getSmsPlatform,
|
||||
testSmsSend,
|
||||
updateAuthMethodConfig,
|
||||
} from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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 { AreaCodeSelect } from '@workspace/ui/custom-components/area-code-select';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import TagInput from '@workspace/ui/custom-components/tag-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Link from 'next/link';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { LogsTable } from '../log';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('phone');
|
||||
const { data, refetch, isFetching } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'mobile'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'mobile',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const { data: platforms } = useQuery({
|
||||
queryKey: ['getSmsPlatform'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSmsPlatform();
|
||||
return data.data?.list;
|
||||
},
|
||||
});
|
||||
|
||||
const selectedPlatform = platforms?.find(
|
||||
(platform) => platform.platform === data?.config?.platform,
|
||||
);
|
||||
const { platform_url, platform_field_description: platformConfig } = selectedPlatform ?? {};
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('updateSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
const [params, setParams] = useState<API.TestSmsSendRequest>({
|
||||
telephone: '',
|
||||
area_code: '1',
|
||||
});
|
||||
|
||||
return (
|
||||
<Tabs defaultValue='settings' className='w-full'>
|
||||
<TabsList>
|
||||
<TabsTrigger value='settings'>{t('settings')}</TabsTrigger>
|
||||
<TabsTrigger value='logs'>{t('logs')}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value='settings'>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableTip')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
disabled={isFetching}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('whitelistValidation')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('whitelistValidationTip')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
defaultValue={data?.config?.enable_whitelist}
|
||||
onCheckedChange={(checked) =>
|
||||
updateConfig('config', { ...data?.config, enable_whitelist: checked })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('whitelistAreaCode')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('whitelistAreaCodeTip')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='w-1/2 text-right'>
|
||||
<TagInput
|
||||
placeholder='1, 852, 886, 888'
|
||||
value={data?.config?.whitelist || []}
|
||||
onChange={(value) =>
|
||||
updateConfig('config', { ...data?.config, whitelist: value })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('platform')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('platformTip')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='flex items-center gap-1 text-right'>
|
||||
<Select
|
||||
value={data?.config?.platform}
|
||||
onValueChange={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform: value,
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{platforms?.map((item) => (
|
||||
<SelectItem key={item.platform} value={item.platform}>
|
||||
{item.platform}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{platform_url && (
|
||||
<Button size='sm' asChild>
|
||||
<Link href={platform_url} target='_blank'>
|
||||
{t('applyPlatform')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('accessLabel')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('platformConfigTip', { key: platformConfig?.access })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.platform_config.access ?? ''}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
access: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
placeholder={t('platformConfigTip', { key: platformConfig?.access })}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{platformConfig?.endpoint && (
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('endpointLabel')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('platformConfigTip', { key: platformConfig?.endpoint })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.platform_config.endpoint ?? ''}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
endpoint: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
placeholder={t('platformConfigTip', { key: platformConfig?.endpoint })}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('secretLabel')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('platformConfigTip', { key: platformConfig?.secret })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.platform_config?.secret ?? ''}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
secret: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
type='password'
|
||||
placeholder={t('platformConfigTip', { key: platformConfig?.secret })}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{platformConfig?.template_code && (
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('templateCodeLabel')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('platformConfigTip', { key: platformConfig?.template_code })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.platform_config?.template_code ?? 'code'}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
template_code: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
placeholder={t('platformConfigTip', { key: platformConfig?.template_code })}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{platformConfig?.sign_name && (
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('signNameLabel')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('platformConfigTip', { key: platformConfig?.sign_name })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.platform_config?.sign_name ?? ''}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
sign_name: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
placeholder={t('platformConfigTip', {
|
||||
key: platformConfig?.sign_name,
|
||||
})}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{platformConfig?.phone_number && (
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('phoneNumberLabel')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('platformConfigTip', { key: platformConfig?.phone_number })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.config?.platform_config?.phone_number ?? ''}
|
||||
onValueBlur={(value) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
phone_number: value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
placeholder={t('platformConfigTip', {
|
||||
key: platformConfig?.phone_number,
|
||||
})}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{platformConfig?.code_variable && (
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('template')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('templateTip', { code: platformConfig?.code_variable })}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Textarea
|
||||
defaultValue={data?.config?.platform_config?.template ?? ''}
|
||||
onBlur={(e) =>
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
platform_config: {
|
||||
...data?.config?.platform_config,
|
||||
template: e.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={isFetching}
|
||||
placeholder={t('placeholders.template', {
|
||||
code: platformConfig?.code_variable,
|
||||
})}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('testSms')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('testSmsTip')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='flex items-center gap-2 text-right'>
|
||||
<AreaCodeSelect
|
||||
value={params.area_code}
|
||||
onChange={(value) => {
|
||||
if (value.phone) {
|
||||
setParams((prev) => ({ ...prev, area_code: value.phone! }));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<EnhancedInput
|
||||
placeholder={t('testSmsPhone')}
|
||||
value={params.telephone}
|
||||
onValueChange={(value) => {
|
||||
setParams((prev) => ({ ...prev, telephone: value as string }));
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
disabled={!params.telephone || !params.area_code}
|
||||
onClick={async () => {
|
||||
if (isFetching || !params.telephone || !params.area_code) return;
|
||||
try {
|
||||
await testSmsSend(params);
|
||||
toast.success(t('sendSuccess'));
|
||||
} catch {
|
||||
toast.error(t('sendFailed'));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('testSms')}
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='logs'>
|
||||
<LogsTable type='mobile' />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getAuthMethodConfig, updateAuthMethodConfig } from '@/services/admin/authMethod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
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 { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('telegram');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getAuthMethodConfig', 'telegram'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getAuthMethodConfig({
|
||||
method: 'telegram',
|
||||
});
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: keyof API.UpdateAuthMethodConfigRequest, value: unknown) {
|
||||
try {
|
||||
await updateAuthMethodConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.UpdateAuthMethodConfigRequest);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('enable')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('enableDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Switch
|
||||
checked={data?.enabled}
|
||||
onCheckedChange={(checked) => updateConfig('enabled', checked)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('clientId')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientIdDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='6123456789'
|
||||
value={data?.config?.bot}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
bot: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('clientSecret')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('clientSecretDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='6123456789:AAHn_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
|
||||
value={data?.config?.bot_token}
|
||||
onValueBlur={(value) => {
|
||||
updateConfig('config', {
|
||||
...data?.config,
|
||||
bot_token: value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -267,7 +267,7 @@ export default function CouponForm<T extends Record<string, any>>({
|
||||
<DatePicker
|
||||
placeholder={t('form.enterValue')}
|
||||
value={field.value}
|
||||
disabled={(date) => date < new Date(Date.now() - 24 * 60 * 60 * 1000)}
|
||||
disabled={(date: Date) => date < new Date(Date.now() - 24 * 60 * 60 * 1000)}
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
|
||||
@@ -10,12 +10,12 @@ import {
|
||||
updateCoupon,
|
||||
} from '@/services/admin/coupon';
|
||||
import { getSubscribeList } from '@/services/admin/subscribe';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -64,9 +64,6 @@ export default function Page() {
|
||||
),
|
||||
}}
|
||||
params={[
|
||||
{
|
||||
key: 'search',
|
||||
},
|
||||
{
|
||||
key: 'subscribe',
|
||||
placeholder: t('subscribe'),
|
||||
@@ -75,6 +72,9 @@ export default function Page() {
|
||||
value: String(item.id),
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'search',
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getCouponList({
|
||||
|
||||
@@ -8,10 +8,10 @@ import {
|
||||
getDocumentList,
|
||||
updateDocument,
|
||||
} from '@/services/admin/document';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
@@ -5,7 +5,7 @@ import { cookies } from 'next/headers';
|
||||
|
||||
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const cookieStore = await cookies();
|
||||
const defaultOpen = cookieStore.get('sidebar:state')?.value === 'true';
|
||||
const defaultOpen = cookieStore.get('sidebar_state')?.value === 'true';
|
||||
return (
|
||||
<SidebarProvider defaultOpen={defaultOpen}>
|
||||
<SidebarLeft />
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { Display } from '@/components/display';
|
||||
import { OrderLink } from '@/components/order-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterBalanceLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function BalanceLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const getBalanceTypeText = (type: number) => {
|
||||
const typeText = t(`type.${type}`);
|
||||
if (typeText === `log.type.${type}`) {
|
||||
return `${t('unknown')} (${type})`;
|
||||
}
|
||||
return typeText;
|
||||
};
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.BalanceLog, { search?: string }>
|
||||
header={{ title: t('title.balance') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount',
|
||||
header: t('column.amount'),
|
||||
cell: ({ row }) => <Display type='currency' value={row.original.amount} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'order_no',
|
||||
header: t('column.orderNo'),
|
||||
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'balance',
|
||||
header: t('column.balance'),
|
||||
cell: ({ row }) => <Display type='currency' value={row.original.balance} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'type',
|
||||
header: t('column.type'),
|
||||
cell: ({ row }) => <Badge>{getBalanceTypeText(row.original.type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterBalanceLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { Display } from '@/components/display';
|
||||
import { OrderLink } from '@/components/order-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterCommissionLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function CommissionLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const getCommissionTypeText = (type: number) => {
|
||||
const typeText = t(`type.${type}`);
|
||||
if (typeText === `log.type.${type}`) {
|
||||
return `${t('unknown')} (${type})`;
|
||||
}
|
||||
return typeText;
|
||||
};
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.CommissionLog, { search?: string }>
|
||||
header={{ title: t('title.commission') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount',
|
||||
header: t('column.amount'),
|
||||
cell: ({ row }) => <Display type='currency' value={row.original.amount} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'order_no',
|
||||
header: t('column.orderNo'),
|
||||
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'type',
|
||||
header: t('column.type'),
|
||||
cell: ({ row }) => <Badge>{getCommissionTypeText(row.original.type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterCommissionLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterEmailLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function EmailLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const initialFilters = {
|
||||
search: sp.get('search') || undefined,
|
||||
date: sp.get('date') || today,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.MessageLog, { search?: string }>
|
||||
header={{ title: t('title.email') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'platform',
|
||||
header: t('column.platform'),
|
||||
cell: ({ row }) => <Badge>{row.getValue('platform')}</Badge>,
|
||||
},
|
||||
{ accessorKey: 'to', header: t('column.to') },
|
||||
{ accessorKey: 'subject', header: t('column.subject') },
|
||||
{
|
||||
accessorKey: 'content',
|
||||
header: t('column.content'),
|
||||
cell: ({ row }) => (
|
||||
<pre className='max-w-[480px] overflow-auto whitespace-pre-wrap break-words text-xs'>
|
||||
{JSON.stringify(row.original.content || {}, null, 2)}
|
||||
</pre>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: t('column.status'),
|
||||
cell: ({ row }) => {
|
||||
const status = row.original.status;
|
||||
const getStatusVariant = (status: any) => {
|
||||
if (status === 1) {
|
||||
return 'default';
|
||||
} else if (status === 0) {
|
||||
return 'destructive';
|
||||
}
|
||||
return 'outline';
|
||||
};
|
||||
|
||||
const getStatusText = (status: any) => {
|
||||
if (status === 1) return t('sent');
|
||||
if (status === 0) return t('failed');
|
||||
return t('unknown');
|
||||
};
|
||||
|
||||
return <Badge variant={getStatusVariant(status)}>{getStatusText(status)}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
]}
|
||||
params={[{ key: 'search' }, { key: 'date', type: 'date' }]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterEmailLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
search: filter?.search,
|
||||
date: (filter as any)?.date,
|
||||
});
|
||||
const list = ((data?.data?.list || []) as API.MessageLog[]) || [];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { Display } from '@/components/display';
|
||||
import { OrderLink } from '@/components/order-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterGiftLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function GiftLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const getGiftTypeText = (type: number) => {
|
||||
const typeText = t(`type.${type}`);
|
||||
if (typeText === `log.type.${type}`) {
|
||||
return `${t('unknown')} (${type})`;
|
||||
}
|
||||
return typeText;
|
||||
};
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.GiftLog, { search?: string }>
|
||||
header={{ title: t('title.gift') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscribe_id',
|
||||
header: t('column.subscribe'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeDetail id={Number(row.original.subscribe_id)} enabled hoverCard />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'order_no',
|
||||
header: t('column.orderNo'),
|
||||
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount',
|
||||
header: t('column.amount'),
|
||||
cell: ({ row }) => <Display type='currency' value={row.original.amount} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'balance',
|
||||
header: t('column.balance'),
|
||||
cell: ({ row }) => <Display type='currency' value={row.original.balance} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'type',
|
||||
header: t('column.type'),
|
||||
cell: ({ row }) => <Badge>{getGiftTypeText(row.original.type)}</Badge>,
|
||||
},
|
||||
{ accessorKey: 'remark', header: t('column.remark') },
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterGiftLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { IpLink } from '@/components/ip-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterLoginLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function LoginLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.LoginLog, { date?: string; user_id?: number }>
|
||||
header={{ title: t('title.login') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<Badge className='capitalize'>{row.original.method}</Badge>{' '}
|
||||
<UserDetail id={Number(row.original.user_id)} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
|
||||
{
|
||||
accessorKey: 'login_ip',
|
||||
header: t('column.ip'),
|
||||
cell: ({ row }) => <IpLink ip={String((row.original as any).login_ip || '')} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_agent',
|
||||
header: t('column.userAgent'),
|
||||
cell: ({ row }) => {
|
||||
const userAgent = String(row.original.user_agent || '');
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className='max-w-48 cursor-help truncate'>{userAgent}</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className='max-w-md break-words'>{userAgent}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'success',
|
||||
header: t('column.success'),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.success ? 'default' : 'destructive'}>
|
||||
{row.original.success ? t('success') : t('failed')}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterLoginLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
});
|
||||
const list = ((data?.data?.list || []) as API.LoginLog[]) || [];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterMobileLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
export default function MobileLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const initialFilters = {
|
||||
search: sp.get('search') || undefined,
|
||||
date: sp.get('date') || today,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.MessageLog, { search?: string }>
|
||||
header={{ title: t('title.mobile') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'platform',
|
||||
header: t('column.platform'),
|
||||
cell: ({ row }) => <Badge>{row.getValue('platform')}</Badge>,
|
||||
},
|
||||
{ accessorKey: 'to', header: t('column.to') },
|
||||
{ accessorKey: 'subject', header: t('column.subject') },
|
||||
{
|
||||
accessorKey: 'content',
|
||||
header: t('column.content'),
|
||||
cell: ({ row }) => (
|
||||
<pre className='max-w-[480px] overflow-auto whitespace-pre-wrap break-words text-xs'>
|
||||
{JSON.stringify(row.original.content || {}, null, 2)}
|
||||
</pre>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: t('column.status'),
|
||||
cell: ({ row }) => {
|
||||
const status = row.original.status;
|
||||
const getStatusVariant = (status: any) => {
|
||||
if (status === 1) {
|
||||
return 'default';
|
||||
} else if (status === 0) {
|
||||
return 'destructive';
|
||||
}
|
||||
return 'outline';
|
||||
};
|
||||
|
||||
const getStatusText = (status: any) => {
|
||||
if (status === 1) return t('sent');
|
||||
if (status === 0) return t('failed');
|
||||
return t('unknown');
|
||||
};
|
||||
|
||||
return <Badge variant={getStatusVariant(status)}>{getStatusText(status)}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
]}
|
||||
params={[{ key: 'search' }, { key: 'date', type: 'date' }]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterMobileLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
search: filter?.search,
|
||||
date: (filter as any)?.date,
|
||||
});
|
||||
const list = ((data?.data?.list || []) as API.MessageLog[]) || [];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { IpLink } from '@/components/ip-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterRegisterLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function RegisterLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.RegisterLog, { date?: string; user_id?: number }>
|
||||
header={{ title: t('title.register') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'auth_method',
|
||||
header: t('column.identifier'),
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<Badge className='capitalize'>{row.original.auth_method}</Badge>
|
||||
<span className='ml-1 text-sm'>{row.original.identifier}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'register_ip',
|
||||
header: t('column.ip'),
|
||||
cell: ({ row }) => <IpLink ip={String((row.original as any).register_ip || '')} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_agent',
|
||||
header: t('column.userAgent'),
|
||||
cell: ({ row }) => {
|
||||
const userAgent = String(row.original.user_agent || '');
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className='max-w-48 cursor-help truncate'>{userAgent}</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className='max-w-md break-words'>{userAgent}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterRegisterLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { OrderLink } from '@/components/order-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterResetSubscribeLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function ResetSubscribeLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const getResetSubscribeTypeText = (type: number) => {
|
||||
const typeText = t(`type.${type}`);
|
||||
if (typeText === `log.type.${type}`) {
|
||||
return `${t('unknown')} (${type})`;
|
||||
}
|
||||
return typeText;
|
||||
};
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_subscribe_id: sp.get('user_subscribe_id')
|
||||
? Number(sp.get('user_subscribe_id'))
|
||||
: undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.ResetSubscribeLog, { date?: string; user_subscribe_id?: number }>
|
||||
header={{ title: t('title.resetSubscribe') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_subscribe_id',
|
||||
header: t('column.subscribeId'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeDetail id={Number(row.original.user_subscribe_id)} enabled hoverCard />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'type',
|
||||
header: t('column.type'),
|
||||
cell: ({ row }) => <Badge>{getResetSubscribeTypeText(row.original.type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'order_no',
|
||||
header: t('column.orderNo'),
|
||||
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_subscribe_id', placeholder: t('column.subscribeId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterResetSubscribeLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterServerTrafficLog } from '@/services/admin/log';
|
||||
import { filterServerList } from '@/services/admin/server';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { formatBytes } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Link from 'next/link';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function ServerTrafficLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const { data: servers = [] } = useQuery({
|
||||
queryKey: ['filterServerListAll'],
|
||||
queryFn: async () => {
|
||||
const { data } = await filterServerList({ page: 1, size: 999999999 });
|
||||
return data?.data?.list || [];
|
||||
},
|
||||
});
|
||||
|
||||
const getServerName = (id?: number) =>
|
||||
id ? (servers.find((s) => s.id === id)?.name ?? `Server ${id}`) : 'Unknown';
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
server_id: sp.get('server_id') ? Number(sp.get('server_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.ServerTrafficLog, { date?: string; server_id?: number }>
|
||||
header={{ title: t('title.serverTraffic') }}
|
||||
initialFilters={initialFilters}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<Button key='detail' asChild>
|
||||
<Link
|
||||
href={`/dashboard/log/traffic-details?date=${row.date}&server_id=${row.server_id}`}
|
||||
>
|
||||
{t('detail')}
|
||||
</Link>
|
||||
</Button>,
|
||||
],
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'server_id',
|
||||
header: t('column.server'),
|
||||
cell: ({ row }) => (
|
||||
<span>
|
||||
{getServerName(row.original.server_id)} ({row.original.server_id})
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'upload',
|
||||
header: t('column.upload'),
|
||||
cell: ({ row }) => formatBytes(row.original.upload),
|
||||
},
|
||||
{
|
||||
accessorKey: 'download',
|
||||
header: t('column.download'),
|
||||
cell: ({ row }) => formatBytes(row.original.download),
|
||||
},
|
||||
{
|
||||
accessorKey: 'total',
|
||||
header: t('column.total'),
|
||||
cell: ({ row }) => formatBytes(row.original.total),
|
||||
},
|
||||
{ accessorKey: 'date', header: t('column.date') },
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'server_id', placeholder: t('column.serverId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterServerTrafficLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
server_id: (filter as any)?.server_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterUserSubscribeTrafficLog } from '@/services/admin/log';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { formatBytes } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Link from 'next/link';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function SubscribeTrafficLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
user_subscribe_id: sp.get('user_subscribe_id')
|
||||
? Number(sp.get('user_subscribe_id'))
|
||||
: undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<
|
||||
API.UserSubscribeTrafficLog,
|
||||
{ date?: string; user_id?: number; user_subscribe_id?: number }
|
||||
>
|
||||
header={{ title: t('title.subscribeTraffic') }}
|
||||
initialFilters={initialFilters}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<Button key='detail' asChild>
|
||||
<Link
|
||||
href={`/dashboard/log/traffic-details?date=${row.date}&user_id=${row.user_id}&subscribe_id=${row.subscribe_id}`}
|
||||
>
|
||||
{t('detail')}
|
||||
</Link>
|
||||
</Button>,
|
||||
],
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscribe_id',
|
||||
header: t('column.subscribe'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeDetail id={Number(row.original.subscribe_id)} enabled hoverCard />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'upload',
|
||||
header: t('column.upload'),
|
||||
cell: ({ row }) => formatBytes(row.original.upload),
|
||||
},
|
||||
{
|
||||
accessorKey: 'download',
|
||||
header: t('column.download'),
|
||||
cell: ({ row }) => formatBytes(row.original.download),
|
||||
},
|
||||
{
|
||||
accessorKey: 'total',
|
||||
header: t('column.total'),
|
||||
cell: ({ row }) => formatBytes(row.original.total),
|
||||
},
|
||||
{
|
||||
accessorKey: 'date',
|
||||
header: t('column.date'),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
{ key: 'user_subscribe_id', placeholder: t('column.subscribeId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterUserSubscribeTrafficLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id,
|
||||
});
|
||||
const list = ((data?.data?.list || []) as API.UserSubscribeTrafficLog[]) || [];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { IpLink } from '@/components/ip-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterSubscribeLog } from '@/services/admin/log';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function SubscribeLogPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
user_subscribe_id: sp.get('user_subscribe_id')
|
||||
? Number(sp.get('user_subscribe_id'))
|
||||
: undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.SubscribeLog, { date?: string; user_id?: number }>
|
||||
header={{ title: t('title.subscribe') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_subscribe_id',
|
||||
header: t('column.subscribe'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeDetail id={Number(row.original.user_subscribe_id)} enabled hoverCard />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'client_ip',
|
||||
header: t('column.ip'),
|
||||
cell: ({ row }) => <IpLink ip={String((row.original as any).client_ip || '')} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_agent',
|
||||
header: t('column.userAgent'),
|
||||
cell: ({ row }) => {
|
||||
const userAgent = String(row.original.user_agent || '');
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className='max-w-48 cursor-help truncate'>{userAgent}</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className='max-w-md break-words'>{userAgent}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
{ key: 'user_subscribe_id', placeholder: t('column.subscribeId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterSubscribeLog({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { filterTrafficLogDetails } from '@/services/admin/log';
|
||||
import { filterServerList } from '@/services/admin/server';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { formatBytes } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function TrafficDetailsPage() {
|
||||
const t = useTranslations('log');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const { data: servers = [] } = useQuery({
|
||||
queryKey: ['filterServerListAll'],
|
||||
queryFn: async () => {
|
||||
const { data } = await filterServerList({ page: 1, size: 999999999 });
|
||||
return data?.data?.list || [];
|
||||
},
|
||||
});
|
||||
|
||||
const getServerName = (id?: number) =>
|
||||
id ? (servers.find((s) => s.id === id)?.name ?? `Server ${id}`) : 'Unknown';
|
||||
|
||||
const initialFilters = {
|
||||
date: sp.get('date') || today,
|
||||
server_id: sp.get('server_id') ? Number(sp.get('server_id')) : undefined,
|
||||
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
|
||||
subscribe_id: sp.get('subscribe_id') ? Number(sp.get('subscribe_id')) : undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.TrafficLogDetails, { search?: string }>
|
||||
header={{ title: t('title.trafficDetails') }}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'server_id',
|
||||
header: t('column.server'),
|
||||
cell: ({ row }) => (
|
||||
<span>
|
||||
{getServerName(row.original.server_id)} ({row.original.server_id})
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_id',
|
||||
header: t('column.user'),
|
||||
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscribe_id',
|
||||
header: t('column.subscribe'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeDetail id={Number(row.original.subscribe_id)} enabled hoverCard />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'upload',
|
||||
header: t('column.upload'),
|
||||
cell: ({ row }) => formatBytes(row.original.upload),
|
||||
},
|
||||
{
|
||||
accessorKey: 'download',
|
||||
header: t('column.download'),
|
||||
cell: ({ row }) => formatBytes(row.original.download),
|
||||
},
|
||||
{
|
||||
accessorKey: 'timestamp',
|
||||
header: t('column.time'),
|
||||
cell: ({ row }) => formatDate(row.original.timestamp),
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'date', type: 'date' },
|
||||
{ key: 'server_id', placeholder: t('column.serverId') },
|
||||
{ key: 'user_id', placeholder: t('column.userId') },
|
||||
{ key: 'subscribe_id', placeholder: t('column.subscribeId') },
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterTrafficLogDetails({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
server_id: (filter as any)?.server_id,
|
||||
user_id: (filter as any)?.user_id,
|
||||
subscribe_id: (filter as any)?.subscribe_id,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
'use client';
|
||||
|
||||
import { createBatchSendEmailTask, getPreSendEmailCount } from '@/services/admin/marketing';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { Input } from '@workspace/ui/components/input';
|
||||
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { HTMLEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
export default function EmailBroadcastForm() {
|
||||
const t = useTranslations('marketing');
|
||||
|
||||
// Define schema with internationalized error messages
|
||||
const emailBroadcastSchema = z.object({
|
||||
subject: z.string().min(1, t('subject') + ' ' + t('cannotBeEmpty')),
|
||||
content: z.string().min(1, t('content') + ' ' + t('cannotBeEmpty')),
|
||||
scope: z.number(),
|
||||
register_start_time: z.string().optional(),
|
||||
register_end_time: z.string().optional(),
|
||||
additional: z
|
||||
.string()
|
||||
.optional()
|
||||
.refine(
|
||||
(value) => {
|
||||
if (!value || value.trim() === '') return true;
|
||||
const emails = value.split('\n').filter((email) => email.trim() !== '');
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emails.every((email) => emailRegex.test(email.trim()));
|
||||
},
|
||||
{
|
||||
message: t('pleaseEnterValidEmailAddresses'),
|
||||
},
|
||||
),
|
||||
scheduled: z.string().optional(),
|
||||
interval: z.number().min(0.1, t('emailIntervalMinimum')).optional(),
|
||||
limit: z.number().min(1, t('dailyLimit')).optional(),
|
||||
});
|
||||
|
||||
type EmailBroadcastFormData = z.infer<typeof emailBroadcastSchema>;
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [estimatedRecipients, setEstimatedRecipients] = useState<{
|
||||
users: number;
|
||||
additional: number;
|
||||
total: number;
|
||||
}>({ users: 0, additional: 0, total: 0 });
|
||||
|
||||
const form = useForm<EmailBroadcastFormData>({
|
||||
resolver: zodResolver(emailBroadcastSchema),
|
||||
defaultValues: {
|
||||
subject: '',
|
||||
content: '',
|
||||
scope: 1, // ScopeAll
|
||||
register_start_time: '',
|
||||
register_end_time: '',
|
||||
additional: '',
|
||||
scheduled: '',
|
||||
interval: 1,
|
||||
limit: 1000,
|
||||
},
|
||||
});
|
||||
|
||||
// Calculate recipient count
|
||||
const calculateRecipients = async () => {
|
||||
const formData = form.getValues();
|
||||
|
||||
try {
|
||||
// Call API to get actual recipient count
|
||||
const scope = formData.scope || 1; // Default to ScopeAll
|
||||
|
||||
// Convert dates to timestamps if they exist
|
||||
let register_start_time: number = 0;
|
||||
let register_end_time: number = 0;
|
||||
|
||||
if (formData.register_start_time) {
|
||||
register_start_time = Math.floor(new Date(formData.register_start_time).getTime());
|
||||
}
|
||||
|
||||
if (formData.register_end_time) {
|
||||
register_end_time = Math.floor(new Date(formData.register_end_time).getTime());
|
||||
}
|
||||
|
||||
const response = await getPreSendEmailCount({
|
||||
scope,
|
||||
register_start_time,
|
||||
register_end_time,
|
||||
});
|
||||
|
||||
const userCount = response.data?.data?.count || 0;
|
||||
|
||||
// Calculate additional email count
|
||||
const additionalEmails = formData.additional || '';
|
||||
const additionalCount = additionalEmails
|
||||
.split('\n')
|
||||
.filter((email: string) => email.trim() !== '').length;
|
||||
|
||||
const total = userCount + additionalCount;
|
||||
|
||||
setEstimatedRecipients({
|
||||
users: userCount,
|
||||
additional: additionalCount,
|
||||
total,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to get recipient count:', error);
|
||||
// Set to 0 if API fails, don't use fallback simulation
|
||||
const additionalEmails = formData.additional || '';
|
||||
const additionalCount = additionalEmails
|
||||
.split('\n')
|
||||
.filter((email: string) => email.trim() !== '').length;
|
||||
|
||||
setEstimatedRecipients({
|
||||
users: 0,
|
||||
additional: additionalCount,
|
||||
total: additionalCount,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Listen to form changes
|
||||
const watchedValues = form.watch();
|
||||
|
||||
// Use useEffect to respond to form changes, but only when sheet is open
|
||||
useEffect(() => {
|
||||
if (!open) return; // Only calculate when sheet is open
|
||||
|
||||
const debounceTimer = setTimeout(() => {
|
||||
calculateRecipients();
|
||||
}, 500); // Add debounce to avoid too frequent API calls
|
||||
|
||||
return () => clearTimeout(debounceTimer);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
open, // Add open dependency
|
||||
watchedValues.scope,
|
||||
watchedValues.register_start_time,
|
||||
watchedValues.register_end_time,
|
||||
watchedValues.additional,
|
||||
]);
|
||||
|
||||
const onSubmit = async (data: EmailBroadcastFormData) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// Validate scheduled send time
|
||||
let scheduled: number | undefined;
|
||||
if (data.scheduled && data.scheduled.trim() !== '') {
|
||||
const scheduledDate = new Date(data.scheduled);
|
||||
const now = new Date();
|
||||
if (scheduledDate <= now) {
|
||||
toast.error(t('scheduledSendTimeMustBeLater'));
|
||||
return;
|
||||
}
|
||||
scheduled = Math.floor(scheduledDate.getTime());
|
||||
}
|
||||
|
||||
let register_start_time: number = 0;
|
||||
let register_end_time: number = 0;
|
||||
|
||||
if (data.register_start_time) {
|
||||
register_start_time = Math.floor(new Date(data.register_start_time).getTime());
|
||||
}
|
||||
|
||||
if (data.register_end_time) {
|
||||
register_end_time = Math.floor(new Date(data.register_end_time).getTime());
|
||||
}
|
||||
|
||||
// Prepare API request data
|
||||
const requestData: API.CreateBatchSendEmailTaskRequest = {
|
||||
subject: data.subject,
|
||||
content: data.content,
|
||||
scope: data.scope,
|
||||
register_start_time,
|
||||
register_end_time,
|
||||
additional: data.additional || undefined,
|
||||
scheduled,
|
||||
interval: data.interval ? data.interval * 1000 : undefined, // Convert seconds to milliseconds
|
||||
limit: data.limit,
|
||||
};
|
||||
|
||||
// Call API to create batch send email task
|
||||
await createBatchSendEmailTask(requestData);
|
||||
|
||||
if (!data.scheduled || data.scheduled.trim() === '') {
|
||||
toast.success(t('emailBroadcastTaskCreatedSuccessfully'));
|
||||
} else {
|
||||
toast.success(t('emailAddedToScheduledQueue'));
|
||||
}
|
||||
|
||||
form.reset();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
console.error('Email broadcast failed:', error);
|
||||
toast.error(t('sendFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:email-send' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('emailBroadcast')}</p>
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t('createNewEmailBroadcastCampaign')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[700px] max-w-full md:max-w-screen-lg'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('createBroadcast')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='broadcast-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<Tabs defaultValue='content' className='space-y-2'>
|
||||
<TabsList className='grid w-full grid-cols-2'>
|
||||
<TabsTrigger value='content'>{t('content')}</TabsTrigger>
|
||||
<TabsTrigger value='settings'>{t('sendSettings')}</TabsTrigger>
|
||||
</TabsList>
|
||||
{/* Email Content Tab */}
|
||||
<TabsContent value='content' className='space-y-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='subject'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('subject')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder={`${t('pleaseEnter')} ${t('subject').toLowerCase()}`}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='content'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('content')}</FormLabel>
|
||||
<FormControl>
|
||||
<HTMLEditor
|
||||
value={field.value}
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value || '');
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('useMarkdownEditor')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* Send Settings Tab */}
|
||||
<TabsContent value='settings' className='space-y-2'>
|
||||
{/* Send scope and estimated recipients */}
|
||||
<div className='grid grid-cols-2 items-center gap-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='scope'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('sendScope')}</FormLabel>
|
||||
<Select
|
||||
onValueChange={(value) => field.onChange(parseInt(value))}
|
||||
value={field.value?.toString() || '1'}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('selectSendScope')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='1'>{t('allUsers')}</SelectItem> {/* ScopeAll */}
|
||||
<SelectItem value='2'>{t('subscribedUsersOnly')}</SelectItem>{' '}
|
||||
{/* ScopeActive */}
|
||||
<SelectItem value='3'>
|
||||
{t('expiredSubscriptionUsersOnly')}
|
||||
</SelectItem>{' '}
|
||||
{/* ScopeExpired */}
|
||||
<SelectItem value='4'>{t('noSubscriptionUsersOnly')}</SelectItem>{' '}
|
||||
{/* ScopeNone */}
|
||||
<SelectItem value='5'>{t('specificUsersOnly')}</SelectItem>{' '}
|
||||
{/* ScopeSkip */}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>{t('sendScopeDescription')}</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Estimated recipients info */}
|
||||
<div className='flex justify-end'>
|
||||
<div className='border-l-primary bg-primary/10 border-l-4 px-4 py-3 text-sm'>
|
||||
<span className='text-muted-foreground'>{t('estimatedRecipients')}: </span>
|
||||
<span className='text-primary text-lg font-medium'>
|
||||
{estimatedRecipients.total}
|
||||
</span>
|
||||
<span className='text-muted-foreground ml-2 text-xs'>
|
||||
({t('users')}: {estimatedRecipients.users}, {t('additional')}:{' '}
|
||||
{estimatedRecipients.additional})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='register_start_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('registrationStartDate')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='datetime-local'
|
||||
disabled={form.watch('scope') === 5} // ScopeSkip
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('includeUsersRegisteredAfter')}</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='register_end_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('registrationEndDate')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='datetime-local'
|
||||
disabled={form.watch('scope') === 5} // ScopeSkip
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('includeUsersRegisteredBefore')}</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Additional recipients */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='additional'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('additionalRecipientEmails')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder={`${t('pleaseEnter')}${t('additionalRecipientEmails').toLowerCase()},${t('onePerLine')},for example:\nexample1@domain.com\nexample2@domain.com\nexample3@domain.com`}
|
||||
className='min-h-[120px] font-mono text-sm'
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('additionalRecipientsDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Send time settings */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='scheduled'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('scheduledSend')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='datetime-local'
|
||||
placeholder={t('leaveEmptyForImmediateSend')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('selectSendTime')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Send rate control */}
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='interval'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('emailInterval')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type='number'
|
||||
min={1}
|
||||
step={0.1}
|
||||
placeholder='1'
|
||||
{...field}
|
||||
onChange={(e) => field.onChange(parseFloat(e.target.value) || 1)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('intervalTimeBetweenEmails')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='limit'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('dailySendLimit')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type='number'
|
||||
min={1}
|
||||
step={1}
|
||||
placeholder='1000'
|
||||
{...field}
|
||||
onChange={(e) => field.onChange(parseInt(e.target.value) || 1000)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('maximumNumberPerDay')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex flex-row items-center justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' onClick={() => setOpen(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button type='submit' form='broadcast-form' disabled={loading}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 h-4 w-4 animate-spin' />}
|
||||
{loading
|
||||
? t('processing')
|
||||
: !form.watch('scheduled') || form.watch('scheduled')?.trim() === ''
|
||||
? t('sendNow')
|
||||
: t('scheduleSend')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import { getBatchSendEmailTaskList, stopBatchSendEmailTask } from '@/services/admin/marketing';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@workspace/ui/components/dialog';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function EmailTaskManager() {
|
||||
const t = useTranslations('marketing');
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
const [selectedTask, setSelectedTask] = useState<API.BatchSendEmailTask | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const stopTask = async (taskId: number) => {
|
||||
try {
|
||||
await stopBatchSendEmailTask({
|
||||
id: taskId,
|
||||
});
|
||||
toast.success(t('taskStoppedSuccessfully'));
|
||||
ref.current?.refresh();
|
||||
} catch (error) {
|
||||
console.error('Failed to stop task:', error);
|
||||
toast.error(t('failedToStopTask'));
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: number) => {
|
||||
const statusConfig = {
|
||||
0: { label: t('notStarted'), variant: 'secondary' as const },
|
||||
1: { label: t('inProgress'), variant: 'default' as const },
|
||||
2: { label: t('completed'), variant: 'default' as const },
|
||||
};
|
||||
|
||||
const config = statusConfig[status as keyof typeof statusConfig] || {
|
||||
label: `${t('status')} ${status}`,
|
||||
variant: 'secondary' as const,
|
||||
};
|
||||
|
||||
return <Badge variant={config.variant}>{config.label}</Badge>;
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:email-multiple' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('emailTaskManager')}</p>
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t('viewAndManageEmailBroadcastTasks')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[1000px] max-w-full md:max-w-screen-lg'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('emailBroadcastTasks')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<div className='mt-4 space-y-4'>
|
||||
<ProTable<API.BatchSendEmailTask, API.GetBatchSendEmailTaskListParams>
|
||||
action={ref}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'subject',
|
||||
header: t('subject'),
|
||||
cell: ({ row }) => (
|
||||
<div
|
||||
className='max-w-[200px] truncate font-medium'
|
||||
title={row.getValue('subject') as string}
|
||||
>
|
||||
{row.getValue('subject') as string}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'scope',
|
||||
header: t('recipientType'),
|
||||
cell: ({ row }) => {
|
||||
const scope = row.original.scope;
|
||||
const scopeLabels = {
|
||||
1: t('allUsers'), // ScopeAll
|
||||
2: t('subscribedUsers'), // ScopeActive
|
||||
3: t('expiredUsers'), // ScopeExpired
|
||||
4: t('nonSubscribers'), // ScopeNone
|
||||
5: t('specificUsers'), // ScopeSkip
|
||||
};
|
||||
return (
|
||||
scopeLabels[scope as keyof typeof scopeLabels] || `${t('scope')} ${scope}`
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: t('status'),
|
||||
cell: ({ row }) => getStatusBadge(row.getValue('status') as number),
|
||||
},
|
||||
{
|
||||
accessorKey: 'progress',
|
||||
header: t('progress'),
|
||||
cell: ({ row }) => {
|
||||
const task = row.original as API.BatchSendEmailTask;
|
||||
const progress = task.total > 0 ? (task.current / task.total) * 100 : 0;
|
||||
return (
|
||||
<div className='space-y-1'>
|
||||
<div className='flex justify-between text-sm'>
|
||||
<span>
|
||||
{task.current} / {task.total}
|
||||
</span>
|
||||
<span>{progress.toFixed(1)}%</span>
|
||||
</div>
|
||||
<div className='bg-muted h-2 overflow-hidden rounded-full'>
|
||||
<div
|
||||
className='bg-primary h-full transition-all duration-300'
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'scheduled',
|
||||
header: t('sendTime'),
|
||||
cell: ({ row }) => {
|
||||
const scheduled = row.getValue('scheduled') as number;
|
||||
return scheduled && scheduled > 0 ? formatDate(scheduled) : '--';
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('createdAt'),
|
||||
cell: ({ row }) => {
|
||||
const createdAt = row.getValue('created_at') as number;
|
||||
return formatDate(createdAt);
|
||||
},
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const response = await getBatchSendEmailTaskList({
|
||||
...filters,
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
});
|
||||
return {
|
||||
list: response.data?.data?.list || [],
|
||||
total: response.data?.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
params={[
|
||||
{
|
||||
key: 'status',
|
||||
placeholder: t('status'),
|
||||
options: [
|
||||
{ label: t('notStarted'), value: '0' },
|
||||
{ label: t('inProgress'), value: '1' },
|
||||
{ label: t('completed'), value: '2' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'scope',
|
||||
placeholder: t('sendScope'),
|
||||
options: [
|
||||
{ label: t('allUsers'), value: '1' },
|
||||
{ label: t('subscribedUsers'), value: '2' },
|
||||
{ label: t('expiredUsers'), value: '3' },
|
||||
{ label: t('nonSubscribers'), value: '4' },
|
||||
{ label: t('specificUsers'), value: '5' },
|
||||
],
|
||||
},
|
||||
]}
|
||||
actions={{
|
||||
render: (row) => {
|
||||
return [
|
||||
<Dialog key='view-content'>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='icon'
|
||||
onClick={() => setSelectedTask(row as API.BatchSendEmailTask)}
|
||||
>
|
||||
<Icon icon='mdi:eye' />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className='max-h-[80vh] max-w-4xl'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('emailContent')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className='h-[60vh] pr-4'>
|
||||
{selectedTask && (
|
||||
<div className='space-y-4'>
|
||||
<div>
|
||||
<h4 className='text-muted-foreground mb-2 text-sm font-medium'>
|
||||
{t('subject')}
|
||||
</h4>
|
||||
<p className='font-medium'>{selectedTask.subject}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className='text-muted-foreground mb-2 text-sm font-medium'>
|
||||
{t('content')}
|
||||
</h4>
|
||||
<div dangerouslySetInnerHTML={{ __html: selectedTask.content }} />
|
||||
</div>
|
||||
{selectedTask.additional && (
|
||||
<div>
|
||||
<h4 className='text-muted-foreground mb-2 text-sm font-medium'>
|
||||
{t('additionalRecipients')}
|
||||
</h4>
|
||||
<p className='text-sm'>{selectedTask.additional}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>,
|
||||
...([0, 1].includes(row.status)
|
||||
? [
|
||||
<Button key='stop' variant='destructive' onClick={() => stopTask(row.id)}>
|
||||
{t('stop')}
|
||||
</Button>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import EmailBroadcastForm from './email/broadcast-form';
|
||||
import EmailTaskManager from './email/task-manager';
|
||||
import QuotaBroadcastForm from './quota/broadcast-form';
|
||||
import QuotaTaskManager from './quota/task-manager';
|
||||
|
||||
export default function MarketingPage() {
|
||||
const t = useTranslations('marketing');
|
||||
|
||||
const formSections = [
|
||||
{
|
||||
title: t('emailMarketing'),
|
||||
forms: [{ component: EmailBroadcastForm }, { component: EmailTaskManager }],
|
||||
},
|
||||
{
|
||||
title: t('quotaService'),
|
||||
forms: [{ component: QuotaBroadcastForm }, { component: QuotaTaskManager }],
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='space-y-8'>
|
||||
{formSections.map((section, sectionIndex) => (
|
||||
<div key={sectionIndex}>
|
||||
<h2 className='mb-4 text-lg font-semibold'>{section.title}</h2>
|
||||
<Table>
|
||||
<TableBody>
|
||||
{section.forms.map((form, formIndex) => {
|
||||
const FormComponent = form.component;
|
||||
return (
|
||||
<TableRow key={formIndex}>
|
||||
<TableCell>
|
||||
<FormComponent />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
'use client';
|
||||
|
||||
import { Display } from '@/components/display';
|
||||
import { createQuotaTask, queryQuotaTaskPreCount } from '@/services/admin/marketing';
|
||||
import { getSubscribeList } from '@/services/admin/subscribe';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { RadioGroup, RadioGroupItem } from '@workspace/ui/components/radio-group';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Combobox } from '@workspace/ui/custom-components/combobox';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { unitConversion } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
export default function QuotaBroadcastForm() {
|
||||
const t = useTranslations('marketing');
|
||||
|
||||
// Define schema with internationalized error messages
|
||||
const quotaBroadcastSchema = z.object({
|
||||
subscribers: z.array(z.number()).min(1, t('pleaseSelectSubscribers')),
|
||||
is_active: z.boolean(),
|
||||
start_time: z.string().optional(),
|
||||
end_time: z.string().optional(),
|
||||
reset_traffic: z.boolean(),
|
||||
days: z.number().optional(),
|
||||
gift_type: z.number(),
|
||||
gift_value: z.number().optional(),
|
||||
});
|
||||
|
||||
type QuotaBroadcastFormData = z.infer<typeof quotaBroadcastSchema>;
|
||||
|
||||
const form = useForm<QuotaBroadcastFormData>({
|
||||
resolver: zodResolver(quotaBroadcastSchema),
|
||||
mode: 'onChange', // Enable real-time validation
|
||||
defaultValues: {
|
||||
subscribers: [],
|
||||
is_active: true,
|
||||
start_time: '',
|
||||
end_time: '',
|
||||
reset_traffic: false,
|
||||
days: 0,
|
||||
gift_type: 1,
|
||||
gift_value: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const [recipients, setRecipients] = useState<number>(0);
|
||||
const [isCalculating, setIsCalculating] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// Get subscribe list
|
||||
const { data: subscribeList } = useQuery({
|
||||
queryKey: ['getSubscribeList', 'all'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeList({
|
||||
page: 1,
|
||||
size: 999999999,
|
||||
});
|
||||
return data.data?.list as API.SubscribeItem[];
|
||||
},
|
||||
});
|
||||
|
||||
// Calculate recipient count
|
||||
const calculateRecipients = async () => {
|
||||
setIsCalculating(true);
|
||||
try {
|
||||
const formData = form.getValues();
|
||||
let start_time: number = 0;
|
||||
let end_time: number = 0;
|
||||
|
||||
if (formData.start_time) {
|
||||
start_time = new Date(formData.start_time).getTime();
|
||||
}
|
||||
|
||||
if (formData.end_time) {
|
||||
end_time = new Date(formData.end_time).getTime();
|
||||
}
|
||||
|
||||
const response = await queryQuotaTaskPreCount({
|
||||
subscribers: formData.subscribers,
|
||||
is_active: formData.is_active,
|
||||
start_time,
|
||||
end_time,
|
||||
});
|
||||
|
||||
if (response.data?.data?.count !== undefined) {
|
||||
setRecipients(response.data.data.count);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to calculate recipients:', error);
|
||||
toast.error(t('failedToCalculateRecipients'));
|
||||
setRecipients(0);
|
||||
} finally {
|
||||
setIsCalculating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Watch form values and recalculate recipients only when sheet is open
|
||||
const watchedValues = form.watch();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return; // Only calculate when sheet is open
|
||||
|
||||
const debounceTimer = setTimeout(() => {
|
||||
calculateRecipients();
|
||||
}, 500); // Add debounce to avoid too frequent API calls
|
||||
|
||||
return () => clearTimeout(debounceTimer);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
open,
|
||||
watchedValues.subscribers,
|
||||
watchedValues.is_active,
|
||||
watchedValues.start_time,
|
||||
watchedValues.end_time,
|
||||
]);
|
||||
|
||||
const onSubmit = async (data: QuotaBroadcastFormData) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
let start_time: number = 0;
|
||||
let end_time: number = 0;
|
||||
|
||||
if (data.start_time) {
|
||||
start_time = Math.floor(new Date(data.start_time).getTime());
|
||||
}
|
||||
|
||||
if (data.end_time) {
|
||||
end_time = Math.floor(new Date(data.end_time).getTime());
|
||||
}
|
||||
|
||||
await createQuotaTask({
|
||||
subscribers: data.subscribers,
|
||||
is_active: data.is_active,
|
||||
start_time,
|
||||
end_time,
|
||||
reset_traffic: data.reset_traffic,
|
||||
days: data.days || 0,
|
||||
gift_type: data.gift_type,
|
||||
gift_value: data.gift_value || 0,
|
||||
});
|
||||
|
||||
toast.success(t('quotaTaskCreatedSuccessfully'));
|
||||
form.reset();
|
||||
setRecipients(0);
|
||||
setOpen(false); // Close the sheet after successful submission
|
||||
} catch (error) {
|
||||
console.error('Failed to create quota task:', error);
|
||||
toast.error(t('failedToCreateQuotaTask'));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:gift' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('quotaBroadcast')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('createAndSendQuotaTasks')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('createQuotaTask')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-32px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='quota-broadcast-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='mt-4 space-y-6'
|
||||
>
|
||||
{/* Subscribers selection */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='subscribers'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('subscribers')}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox
|
||||
multiple={true}
|
||||
value={field.value || []}
|
||||
onChange={field.onChange}
|
||||
placeholder={t('pleaseSelectSubscribers')}
|
||||
options={
|
||||
subscribeList?.map((subscribe) => ({
|
||||
value: subscribe.id!,
|
||||
label: subscribe.name!,
|
||||
children: (
|
||||
<div>
|
||||
<div>{subscribe.name}</div>
|
||||
<div className='text-muted-foreground text-xs'>
|
||||
<Display type='traffic' value={subscribe.traffic || 0} /> /{' '}
|
||||
<Display type='currency' value={subscribe.unit_price || 0} />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
})) || []
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Subscription count info and active status */}
|
||||
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='is_active'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('validOnly')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('selectValidSubscriptionsOnly')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className='border-l-primary bg-primary/10 flex items-center border-l-4 px-4 py-3 text-sm'>
|
||||
<span className='text-muted-foreground'>{t('subscriptionCount')}: </span>
|
||||
<span className='text-primary text-lg font-medium'>
|
||||
{isCalculating ? (
|
||||
<Icon icon='mdi:loading' className='ml-2 h-4 w-4 animate-spin' />
|
||||
) : (
|
||||
recipients.toLocaleString()
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Subscription validity period range */}
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='start_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('subscriptionValidityStartDate')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='datetime-local'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('includeSubscriptionsValidAfter')}</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='end_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('subscriptionValidityEndDate')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='datetime-local'
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('includeSubscriptionsValidBefore')}</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Reset traffic */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='reset_traffic'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('resetTraffic')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('resetTrafficDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Quota days */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='days'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('quotaDays')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={1}
|
||||
value={field.value?.toString()}
|
||||
onValueChange={(value) => field.onChange(parseInt(value, 10))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('numberOfDaysForTheQuota')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Gift configuration */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='gift_type'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('giftType')}</FormLabel>
|
||||
<FormControl>
|
||||
<RadioGroup
|
||||
defaultValue={String(field.value)}
|
||||
onValueChange={(value) => {
|
||||
field.onChange(Number(value));
|
||||
form.setValue('gift_value', 0);
|
||||
}}
|
||||
className='flex gap-4'
|
||||
>
|
||||
<FormItem className='flex items-center space-x-3 space-y-0'>
|
||||
<FormControl>
|
||||
<RadioGroupItem value='1' />
|
||||
</FormControl>
|
||||
<FormLabel className='font-normal'>{t('fixedAmount')}</FormLabel>
|
||||
</FormItem>
|
||||
<FormItem className='flex items-center space-x-3 space-y-0'>
|
||||
<FormControl>
|
||||
<RadioGroupItem value='2' />
|
||||
</FormControl>
|
||||
<FormLabel className='font-normal'>{t('percentageAmount')}</FormLabel>
|
||||
</FormItem>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Gift amount based on type */}
|
||||
{form.watch('gift_type') === 1 && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='gift_value'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('giftAmount')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput<number>
|
||||
placeholder={t('enterAmount')}
|
||||
type='number'
|
||||
value={field.value}
|
||||
formatInput={(value) => unitConversion('centsToDollars', value)}
|
||||
formatOutput={(value) => unitConversion('dollarsToCents', value)}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
min={1}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{form.watch('gift_type') === 2 && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='gift_value'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('giftAmount')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('enterPercentage')}
|
||||
type='number'
|
||||
suffix='%'
|
||||
value={field.value}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
min={1}
|
||||
max={100}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('percentageAmountDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex flex-row items-center justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' onClick={() => setOpen(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
form='quota-broadcast-form'
|
||||
disabled={
|
||||
isSubmitting || !form.formState.isValid || form.watch('subscribers').length === 0
|
||||
}
|
||||
>
|
||||
{isSubmitting && <Icon icon='mdi:loading' className='mr-2 h-4 w-4 animate-spin' />}
|
||||
{t('createQuotaTask')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
'use client';
|
||||
|
||||
import { Display } from '@/components/display';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { queryQuotaTaskList } from '@/services/admin/marketing';
|
||||
import { getSubscribeList } from '@/services/admin/subscribe';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function QuotaTaskManager() {
|
||||
const t = useTranslations('marketing');
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// Get subscribe list to show subscription names
|
||||
const { data: subscribeList } = useQuery({
|
||||
queryKey: ['getSubscribeList', 'all'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeList({
|
||||
page: 1,
|
||||
size: 999999999,
|
||||
});
|
||||
return data.data?.list as API.SubscribeItem[];
|
||||
},
|
||||
});
|
||||
|
||||
// Create a map for quick lookup of subscription names
|
||||
const subscribeMap =
|
||||
subscribeList?.reduce(
|
||||
(acc, subscribe) => {
|
||||
acc[subscribe.id!] = subscribe.name!;
|
||||
return acc;
|
||||
},
|
||||
{} as Record<number, string>,
|
||||
) || {};
|
||||
|
||||
const getStatusBadge = (status: number) => {
|
||||
const statusConfig = {
|
||||
0: { label: t('notStarted'), variant: 'secondary' as const },
|
||||
1: { label: t('inProgress'), variant: 'default' as const },
|
||||
2: { label: t('completed'), variant: 'default' as const },
|
||||
};
|
||||
|
||||
const config = statusConfig[status as keyof typeof statusConfig] || {
|
||||
label: `${t('status')} ${status}`,
|
||||
variant: 'secondary' as const,
|
||||
};
|
||||
|
||||
return <Badge variant={config.variant}>{config.label}</Badge>;
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:database-plus' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('quotaTaskManager')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('viewAndManageQuotaTasks')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[1000px] max-w-full md:max-w-screen-lg'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('quotaTasks')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<div className='mt-4 space-y-4'>
|
||||
{open && (
|
||||
<ProTable<API.QuotaTask, API.QueryQuotaTaskListParams>
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'subscribers',
|
||||
header: t('subscribers'),
|
||||
size: 200,
|
||||
cell: ({ row }) => {
|
||||
const subscribers = row.getValue('subscribers') as number[];
|
||||
const subscriptionNames =
|
||||
subscribers?.map((id) => subscribeMap[id]).filter(Boolean) || [];
|
||||
|
||||
if (subscriptionNames.length === 0) {
|
||||
return (
|
||||
<span className='text-muted-foreground text-sm'>
|
||||
{t('noSubscriptions')}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='flex flex-wrap gap-1'>
|
||||
{subscriptionNames.map((name, index) => (
|
||||
<span key={index} className='bg-muted rounded px-2 py-1 text-xs'>
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'is_active',
|
||||
header: t('validOnly'),
|
||||
size: 120,
|
||||
cell: ({ row }) => {
|
||||
const isActive = row.getValue('is_active') as boolean;
|
||||
return <span className='text-sm'>{isActive ? t('yes') : t('no')}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'reset_traffic',
|
||||
header: t('resetTraffic'),
|
||||
size: 120,
|
||||
cell: ({ row }) => {
|
||||
const resetTraffic = row.getValue('reset_traffic') as boolean;
|
||||
return <span className='text-sm'>{resetTraffic ? t('yes') : t('no')}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'gift_value',
|
||||
header: t('giftAmount'),
|
||||
size: 120,
|
||||
cell: ({ row }) => {
|
||||
const giftValue = row.getValue('gift_value') as number;
|
||||
const task = row.original as API.QuotaTask;
|
||||
const giftType = task.gift_type;
|
||||
|
||||
return (
|
||||
<div className='text-sm font-medium'>
|
||||
{giftType === 1 ? (
|
||||
<Display type='currency' value={giftValue} />
|
||||
) : (
|
||||
`${giftValue}%`
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'days',
|
||||
header: t('quotaDays'),
|
||||
size: 100,
|
||||
cell: ({ row }) => {
|
||||
const days = row.getValue('days') as number;
|
||||
return (
|
||||
<span className='font-medium'>
|
||||
{days} {t('days')}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'time_range',
|
||||
header: t('timeRange'),
|
||||
size: 180,
|
||||
cell: ({ row }) => {
|
||||
const task = row.original as API.QuotaTask;
|
||||
const startTime = task.start_time;
|
||||
const endTime = task.end_time;
|
||||
|
||||
if (!startTime && !endTime) {
|
||||
return (
|
||||
<span className='text-muted-foreground text-sm'>{t('noTimeLimit')}</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='space-y-1 text-xs'>
|
||||
{startTime && (
|
||||
<div>
|
||||
{t('startTime')}: {formatDate(startTime)}
|
||||
</div>
|
||||
)}
|
||||
{endTime && (
|
||||
<div>
|
||||
{t('endTime')}: {formatDate(endTime)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: t('status'),
|
||||
size: 100,
|
||||
cell: ({ row }) => getStatusBadge(row.getValue('status') as number),
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('createdAt'),
|
||||
size: 150,
|
||||
cell: ({ row }) => {
|
||||
const createdAt = row.getValue('created_at') as number;
|
||||
return formatDate(createdAt);
|
||||
},
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const response = await queryQuotaTaskList({
|
||||
...filters,
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
});
|
||||
return {
|
||||
list: response.data?.data?.list || [],
|
||||
total: response.data?.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
params={[
|
||||
{
|
||||
key: 'status',
|
||||
placeholder: t('status'),
|
||||
options: [
|
||||
{ label: t('notStarted'), value: '0' },
|
||||
{ label: t('inProgress'), value: '1' },
|
||||
{ label: t('completed'), value: '2' },
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
'use client';
|
||||
|
||||
import { filterServerList, queryNodeTag } from '@/services/admin/server';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Combobox } from '@workspace/ui/custom-components/combobox';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import TagInput from '@workspace/ui/custom-components/tag-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
export type ProtocolName =
|
||||
| 'shadowsocks'
|
||||
| 'vmess'
|
||||
| 'vless'
|
||||
| 'trojan'
|
||||
| 'hysteria2'
|
||||
| 'tuic'
|
||||
| 'anytls';
|
||||
|
||||
type ServerRow = API.Server;
|
||||
|
||||
const buildSchema = (t: ReturnType<typeof useTranslations>) =>
|
||||
z.object({
|
||||
name: z.string().trim().min(1, t('errors.nameRequired')),
|
||||
server_id: z
|
||||
.number({ message: t('errors.serverRequired') })
|
||||
.int()
|
||||
.gt(0, t('errors.serverRequired'))
|
||||
.optional(),
|
||||
protocol: z.string().min(1, t('errors.protocolRequired')),
|
||||
address: z.string().trim().min(1, t('errors.serverAddrRequired')),
|
||||
port: z
|
||||
.number({ message: t('errors.portRange') })
|
||||
.int()
|
||||
.min(1, t('errors.portRange'))
|
||||
.max(65535, t('errors.portRange')),
|
||||
tags: z.array(z.string()),
|
||||
});
|
||||
|
||||
export type NodeFormValues = z.infer<ReturnType<typeof buildSchema>>;
|
||||
|
||||
export default function NodeForm(props: {
|
||||
trigger: string;
|
||||
title: string;
|
||||
loading?: boolean;
|
||||
initialValues?: Partial<NodeFormValues>;
|
||||
onSubmit: (values: NodeFormValues) => Promise<boolean> | boolean;
|
||||
}) {
|
||||
const { trigger, title, loading, initialValues, onSubmit } = props;
|
||||
const t = useTranslations('nodes');
|
||||
const Scheme = useMemo(() => buildSchema(t), [t]);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const form = useForm<NodeFormValues>({
|
||||
resolver: zodResolver(Scheme),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
server_id: undefined,
|
||||
protocol: '',
|
||||
address: '',
|
||||
port: 0,
|
||||
tags: [],
|
||||
...initialValues,
|
||||
},
|
||||
});
|
||||
|
||||
const serverId = form.watch('server_id');
|
||||
|
||||
const { data } = useQuery({
|
||||
enabled: open,
|
||||
queryKey: ['filterServerListAll'],
|
||||
queryFn: async () => {
|
||||
const { data } = await filterServerList({ page: 1, size: 999999999 });
|
||||
return data?.data?.list || [];
|
||||
},
|
||||
});
|
||||
const servers: ServerRow[] = data as ServerRow[];
|
||||
|
||||
const { data: tagsData } = useQuery({
|
||||
enabled: open,
|
||||
queryKey: ['queryNodeTag'],
|
||||
queryFn: async () => {
|
||||
const { data } = await queryNodeTag();
|
||||
return data?.data?.tags || [];
|
||||
},
|
||||
});
|
||||
const existingTags: string[] = tagsData as string[];
|
||||
|
||||
const currentServer = useMemo(() => servers?.find((s) => s.id === serverId), [servers, serverId]);
|
||||
|
||||
const availableProtocols = useMemo(() => {
|
||||
return (currentServer?.protocols || [])
|
||||
.map((p) => ({
|
||||
protocol: (p as any).type as ProtocolName,
|
||||
port: (p as any).port as number | undefined,
|
||||
}))
|
||||
.filter((p) => !!p.protocol);
|
||||
}, [currentServer]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues) {
|
||||
form.reset({
|
||||
name: '',
|
||||
server_id: undefined,
|
||||
protocol: '',
|
||||
address: '',
|
||||
port: 0,
|
||||
tags: [],
|
||||
...initialValues,
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initialValues]);
|
||||
|
||||
function handleServerChange(nextId?: number | null) {
|
||||
const id = nextId ?? undefined;
|
||||
form.setValue('server_id', id);
|
||||
|
||||
const sel = servers.find((s) => s.id === id);
|
||||
const dirty = form.formState.dirtyFields as Record<string, any>;
|
||||
const currentValues = form.getValues();
|
||||
|
||||
if (!dirty.name) {
|
||||
form.setValue('name', (sel?.name as string) || '', { shouldDirty: false });
|
||||
}
|
||||
|
||||
if (
|
||||
!dirty.address &&
|
||||
(!currentValues.address || currentValues.address === (sel?.address as string))
|
||||
) {
|
||||
form.setValue('address', (sel?.address as string) || '', { shouldDirty: false });
|
||||
}
|
||||
|
||||
const allowed = (sel?.protocols || [])
|
||||
.map((p) => (p as any).type as ProtocolName)
|
||||
.filter(Boolean);
|
||||
|
||||
const currentProtocol = form.getValues('protocol') as ProtocolName;
|
||||
|
||||
if (!allowed.includes(currentProtocol)) {
|
||||
const firstProtocol = allowed[0] || '';
|
||||
form.setValue('protocol', firstProtocol as any);
|
||||
|
||||
if (firstProtocol) {
|
||||
handleProtocolChange(firstProtocol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleProtocolChange(nextProto?: ProtocolName | null) {
|
||||
const p = (nextProto || '') as ProtocolName | '';
|
||||
form.setValue('protocol', p);
|
||||
if (!p || !currentServer) return;
|
||||
|
||||
const dirty = form.formState.dirtyFields as Record<string, any>;
|
||||
const currentValues = form.getValues();
|
||||
|
||||
if (!dirty.port) {
|
||||
const hit = (currentServer.protocols as any[]).find((x) => (x as any).type === p);
|
||||
const port = (hit as any)?.port as number | undefined;
|
||||
const newPort = typeof port === 'number' && port > 0 ? port : 0;
|
||||
|
||||
if (!currentValues.port || currentValues.port === 0 || currentValues.port === newPort) {
|
||||
form.setValue('port', newPort, { shouldDirty: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button onClick={() => form.reset()}>{trigger}</Button>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent className='w-[560px] max-w-full'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6 pt-4'>
|
||||
<Form {...form}>
|
||||
<form className='grid grid-cols-1 gap-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='server_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('server')}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<number, false>
|
||||
placeholder={t('select_server')}
|
||||
value={field.value}
|
||||
options={servers.map((s) => ({
|
||||
value: s.id,
|
||||
label: `${s.name} (${(s.address as any) || ''})`,
|
||||
}))}
|
||||
onChange={(v) => handleServerChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='protocol'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('protocol')}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<string, false>
|
||||
placeholder={t('select_protocol')}
|
||||
value={field.value}
|
||||
options={availableProtocols.map((p) => ({
|
||||
value: p.protocol,
|
||||
label: `${p.protocol}${p.port ? ` (${p.port})` : ''}`,
|
||||
}))}
|
||||
onChange={(v) => handleProtocolChange((v as ProtocolName) || null)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(v) => form.setValue(field.name, v as string)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='address'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('address')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(v) => form.setValue(field.name, v as string)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='port'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('port')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder='1-65535'
|
||||
onValueChange={(v) => form.setValue(field.name, Number(v))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='tags'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('tags')}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
placeholder={t('tags_placeholder')}
|
||||
value={field.value || []}
|
||||
onChange={(v) => form.setValue(field.name, v)}
|
||||
options={existingTags}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('tags_description')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={form.handleSubmit(onSubmit, (errors) => {
|
||||
const key = Object.keys(errors)[0] as keyof typeof errors;
|
||||
if (key) toast.error(String(errors[key]?.message));
|
||||
return false;
|
||||
})}
|
||||
>
|
||||
{t('confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
createNode,
|
||||
deleteNode,
|
||||
filterNodeList,
|
||||
filterServerList,
|
||||
resetSortWithNode,
|
||||
toggleNodeStatus,
|
||||
updateNode,
|
||||
} from '@/services/admin/server';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import NodeForm from './node-form';
|
||||
|
||||
export default function NodesPage() {
|
||||
const t = useTranslations('nodes');
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data: servers = [] } = useQuery({
|
||||
queryKey: ['filterServerListAll'],
|
||||
queryFn: async () => {
|
||||
const { data } = await filterServerList({ page: 1, size: 999999999 });
|
||||
return data?.data?.list || [];
|
||||
},
|
||||
});
|
||||
|
||||
const getServerName = (id?: number) =>
|
||||
id ? (servers.find((s) => s.id === id)?.name ?? `#${id}`) : '—';
|
||||
const getServerOriginAddr = (id?: number) =>
|
||||
id ? (servers.find((s) => s.id === id)?.address ?? '—') : '—';
|
||||
const getProtocolOriginPort = (id?: number, proto?: string) => {
|
||||
if (!id || !proto) return '—';
|
||||
const hit = servers.find((s) => s.id === id)?.protocols?.find((p) => (p as any).type === proto);
|
||||
const p = (hit as any)?.port as number | undefined;
|
||||
return typeof p === 'number' ? String(p) : '—';
|
||||
};
|
||||
|
||||
return (
|
||||
<ProTable<API.Node, { search: string }>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t('pageTitle'),
|
||||
toolbar: (
|
||||
<NodeForm
|
||||
trigger={t('create')}
|
||||
title={t('drawerCreateTitle')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const body: API.CreateNodeRequest = {
|
||||
name: values.name,
|
||||
server_id: Number(values.server_id!),
|
||||
protocol: values.protocol,
|
||||
address: values.address,
|
||||
port: Number(values.port!),
|
||||
tags: values.tags || [],
|
||||
enabled: false,
|
||||
};
|
||||
await createNode(body);
|
||||
toast.success(t('created'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (e) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
id: 'enabled',
|
||||
header: t('enabled'),
|
||||
cell: ({ row }) => (
|
||||
<Switch
|
||||
checked={row.original.enabled}
|
||||
onCheckedChange={async (v) => {
|
||||
await toggleNodeStatus({ id: row.original.id, enable: v });
|
||||
toast.success(v ? t('enabled_on') : t('enabled_off'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{ accessorKey: 'name', header: t('name') },
|
||||
|
||||
{
|
||||
id: 'address_port',
|
||||
header: `${t('address')}:${t('port')}`,
|
||||
cell: ({ row }) => (row.original.address || '—') + ':' + (row.original.port ?? '—'),
|
||||
},
|
||||
|
||||
{
|
||||
id: 'server_id',
|
||||
header: t('server'),
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-wrap gap-2'>
|
||||
<Badge variant='outline'>
|
||||
{getServerName(row.original.server_id)} ·{' '}
|
||||
{getServerOriginAddr(row.original.server_id)}
|
||||
</Badge>
|
||||
<Badge variant='outline'>
|
||||
{row.original.protocol || '—'} ·{' '}
|
||||
{getProtocolOriginPort(row.original.server_id, row.original.protocol)}
|
||||
</Badge>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'tags',
|
||||
header: t('tags'),
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-wrap gap-1'>
|
||||
{(row.original.tags || []).length === 0
|
||||
? '—'
|
||||
: row.original.tags.map((tg) => (
|
||||
<Badge key={tg} variant='outline'>
|
||||
{tg}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
params={[{ key: 'search' }]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterNodeList({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
search: filter?.search || undefined,
|
||||
});
|
||||
const list = (data?.data?.list || []) as API.Node[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
return { list, total };
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<NodeForm
|
||||
key='edit'
|
||||
trigger={t('edit')}
|
||||
title={t('drawerEditTitle')}
|
||||
loading={loading}
|
||||
initialValues={{
|
||||
name: row.name,
|
||||
server_id: row.server_id,
|
||||
protocol: row.protocol as any,
|
||||
address: row.address as any,
|
||||
port: row.port as any,
|
||||
tags: (row.tags as any) || [],
|
||||
}}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const body: API.UpdateNodeRequest = {
|
||||
id: row.id,
|
||||
name: values.name,
|
||||
server_id: Number(values.server_id!),
|
||||
protocol: values.protocol,
|
||||
address: values.address,
|
||||
port: Number(values.port!),
|
||||
tags: values.tags || [],
|
||||
enabled: row.enabled,
|
||||
} as any;
|
||||
await updateNode(body);
|
||||
toast.success(t('updated'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (e) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('delete')}</Button>}
|
||||
title={t('confirmDeleteTitle')}
|
||||
description={t('confirmDeleteDesc')}
|
||||
onConfirm={async () => {
|
||||
await deleteNode({ id: row.id } as any);
|
||||
toast.success(t('deleted'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
<Button
|
||||
key='copy'
|
||||
variant='outline'
|
||||
onClick={async () => {
|
||||
const { id, enabled, created_at, updated_at, ...rest } = row as any;
|
||||
await createNode({
|
||||
name: rest.name,
|
||||
server_id: rest.server_id,
|
||||
protocol: rest.protocol,
|
||||
address: rest.address,
|
||||
port: rest.port,
|
||||
tags: rest.tags || [],
|
||||
enabled: false,
|
||||
} as any);
|
||||
toast.success(t('copied'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
>
|
||||
{t('copy')}
|
||||
</Button>,
|
||||
],
|
||||
batchRender(rows) {
|
||||
return [
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('delete')}</Button>}
|
||||
title={t('confirmDeleteTitle')}
|
||||
description={t('confirmDeleteDesc')}
|
||||
onConfirm={async () => {
|
||||
await Promise.all(rows.map((r) => deleteNode({ id: r.id } as any)));
|
||||
toast.success(t('deleted'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
onSort={async (source, target, items) => {
|
||||
const sourceIndex = items.findIndex((item) => String(item.id) === source);
|
||||
const targetIndex = items.findIndex((item) => String(item.id) === target);
|
||||
|
||||
const originalSorts = items.map((item) => item.sort);
|
||||
|
||||
const [movedItem] = items.splice(sourceIndex, 1);
|
||||
items.splice(targetIndex, 0, movedItem!);
|
||||
|
||||
const updatedItems = items.map((item, index) => {
|
||||
const originalSort = originalSorts[index];
|
||||
const newSort = originalSort !== undefined ? originalSort : item.sort;
|
||||
return { ...item, sort: newSort };
|
||||
});
|
||||
|
||||
const changedItems = updatedItems.filter((item, index) => {
|
||||
return item.sort !== items[index]?.sort;
|
||||
});
|
||||
|
||||
if (changedItems.length > 0) {
|
||||
resetSortWithNode({
|
||||
sort: changedItems.map((item) => ({
|
||||
id: item.id,
|
||||
sort: item.sort,
|
||||
})) as API.SortItem[],
|
||||
});
|
||||
}
|
||||
return updatedItems;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -2,23 +2,25 @@
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useRef } from 'react';
|
||||
|
||||
import { Display } from '@/components/display';
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import { getOrderList, updateOrderStatus } from '@/services/admin/order';
|
||||
import { getSubscribeList } from '@/services/admin/subscribe';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@workspace/ui/components/hover-card';
|
||||
import { Separator } from '@workspace/ui/components/separator';
|
||||
import { Combobox } from '@workspace/ui/custom-components/combobox';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { UserDetail } from '../user/user-detail';
|
||||
|
||||
export default function Page(props: any) {
|
||||
export default function Page() {
|
||||
const t = useTranslations('order');
|
||||
const sp = useSearchParams();
|
||||
|
||||
const statusOptions = [
|
||||
{ value: 1, label: t('status.1'), className: 'bg-orange-500' },
|
||||
@@ -35,15 +37,23 @@ export default function Page(props: any) {
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeList({
|
||||
page: 1,
|
||||
size: 9999,
|
||||
size: 999999999,
|
||||
});
|
||||
return data.data?.list as API.SubscribeGroup[];
|
||||
},
|
||||
});
|
||||
|
||||
const initialFilters = {
|
||||
search: sp.get('search') || undefined,
|
||||
status: sp.get('status') || undefined,
|
||||
subscribe_id: sp.get('subscribe_id') || undefined,
|
||||
user_id: sp.get('user_id') || undefined,
|
||||
};
|
||||
|
||||
return (
|
||||
<ProTable<API.Order, any>
|
||||
action={ref}
|
||||
initialFilters={initialFilters}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'order_no',
|
||||
@@ -146,7 +156,7 @@ export default function Page(props: any) {
|
||||
if ([1, 3, 4].includes(row.getValue('status'))) {
|
||||
return (
|
||||
<Combobox<number, false>
|
||||
placeholder='状态'
|
||||
placeholder={t('status.0')}
|
||||
value={row.original.status}
|
||||
onChange={async (value) => {
|
||||
await updateOrderStatus({
|
||||
@@ -165,7 +175,6 @@ export default function Page(props: any) {
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{ key: 'search' },
|
||||
{
|
||||
key: 'status',
|
||||
placeholder: t('status.0'),
|
||||
@@ -182,19 +191,15 @@ export default function Page(props: any) {
|
||||
value: String(item.id),
|
||||
})),
|
||||
},
|
||||
].concat(
|
||||
props.userId
|
||||
? []
|
||||
: [
|
||||
{
|
||||
key: 'user_id',
|
||||
placeholder: `${t('user')} ID`,
|
||||
options: undefined,
|
||||
},
|
||||
],
|
||||
)}
|
||||
{ key: 'search' },
|
||||
{
|
||||
key: 'user_id',
|
||||
placeholder: `${t('user')} ID`,
|
||||
options: undefined,
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await getOrderList({ ...pagination, ...filter, user_id: props.userId });
|
||||
const { data } = await getOrderList({ ...pagination, ...filter });
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
|
||||
@@ -75,9 +75,9 @@ export default function PaymentForm<T>({
|
||||
icon: z.string().optional(),
|
||||
domain: z.string().optional(),
|
||||
config: z.any(),
|
||||
fee_mode: z.coerce.number().min(0).max(2),
|
||||
fee_percent: z.coerce.number().optional(),
|
||||
fee_amount: z.coerce.number().optional(),
|
||||
fee_mode: z.number().min(0).max(2),
|
||||
fee_percent: z.number().optional(),
|
||||
fee_amount: z.number().optional(),
|
||||
description: z.string().optional(),
|
||||
});
|
||||
|
||||
@@ -155,7 +155,6 @@ export default function PaymentForm<T>({
|
||||
<ScrollArea className='-mx-6 h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6 px-6 pt-4'>
|
||||
{/* 基本信息分组 */}
|
||||
<div className='space-y-4'>
|
||||
<div className='grid grid-cols-1 gap-4 sm:grid-cols-2'>
|
||||
<FormField
|
||||
@@ -319,7 +318,7 @@ export default function PaymentForm<T>({
|
||||
}}
|
||||
defaultValue={field.value}
|
||||
value={field.value}
|
||||
// @ts-expect-error
|
||||
// @ts-expect-error - disabled prop type mismatch with SelectTrigger component
|
||||
disabled={isEdit && Boolean(initialValues?.platform)}
|
||||
>
|
||||
<FormControl>
|
||||
|
||||
@@ -93,7 +93,7 @@ export default function PaymentTable() {
|
||||
{
|
||||
accessorKey: 'platform',
|
||||
header: t('platform'),
|
||||
cell: ({ row }) => <Badge>{t(row.getValue('platform'))}</Badge>,
|
||||
cell: ({ row }) => <Badge>{t(row.original.platform)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'notify_url',
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { getTranslations } from 'next-intl/server';
|
||||
|
||||
import SubscribeTable from './subscribe-table';
|
||||
|
||||
export default async function Page() {
|
||||
const t = await getTranslations('product');
|
||||
|
||||
return <SubscribeTable />;
|
||||
}
|
||||
+103
-90
@@ -1,7 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { getNodeGroupList, getNodeList } from '@/services/admin/server';
|
||||
import { getSubscribeGroupList } from '@/services/admin/subscribe';
|
||||
import { filterNodeList, queryNodeTag } from '@/services/admin/server';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
@@ -62,8 +61,9 @@ const defaultValues = {
|
||||
traffic: 0,
|
||||
quota: 0,
|
||||
discount: [],
|
||||
server_group: [],
|
||||
server: [],
|
||||
language: '',
|
||||
node_tags: [],
|
||||
nodes: [],
|
||||
unit_time: 'Month',
|
||||
deduction_ratio: 0,
|
||||
purchase_with_discount: false,
|
||||
@@ -79,7 +79,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
trigger,
|
||||
title,
|
||||
}: Readonly<SubscribeFormProps<T>>) {
|
||||
const t = useTranslations('subscribe');
|
||||
const t = useTranslations('product');
|
||||
const [open, setOpen] = useState(false);
|
||||
const updateTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
@@ -87,7 +87,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
unit_price: z.number(),
|
||||
unit_time: z.string().default('Month'),
|
||||
unit_time: z.string(),
|
||||
replacement: z.number().optional(),
|
||||
discount: z
|
||||
.array(
|
||||
@@ -97,21 +97,21 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
inventory: z.number().optional().default(-1),
|
||||
speed_limit: z.number().optional().default(0),
|
||||
device_limit: z.number().optional().default(0),
|
||||
traffic: z.number().optional().default(0),
|
||||
quota: z.number().optional().default(0),
|
||||
group_id: z.number().optional().nullish(),
|
||||
server_group: z.array(z.number()).optional().default([]),
|
||||
server: z.array(z.number()).optional().default([]),
|
||||
deduction_ratio: z.number().optional().default(0),
|
||||
allow_deduction: z.boolean().optional().default(false),
|
||||
reset_cycle: z.number().optional().default(0),
|
||||
renewal_reset: z.boolean().optional().default(false),
|
||||
inventory: z.number().optional(),
|
||||
speed_limit: z.number().optional(),
|
||||
device_limit: z.number().optional(),
|
||||
traffic: z.number().optional(),
|
||||
quota: z.number().optional(),
|
||||
language: z.string().optional(),
|
||||
node_tags: z.array(z.string()).optional(),
|
||||
nodes: z.array(z.number()).optional(),
|
||||
deduction_ratio: z.number().optional(),
|
||||
allow_deduction: z.boolean().optional(),
|
||||
reset_cycle: z.number().optional(),
|
||||
renewal_reset: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const form = useForm({
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: assign(
|
||||
defaultValues,
|
||||
@@ -203,7 +203,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
});
|
||||
|
||||
if (hasChanges) {
|
||||
form.setValue(fieldName, calculatedValues, { shouldDirty: true });
|
||||
form.setValue(fieldName as any, calculatedValues, { shouldDirty: true });
|
||||
}
|
||||
}, 300);
|
||||
},
|
||||
@@ -229,35 +229,37 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
if (bool) setOpen(false);
|
||||
}
|
||||
|
||||
const { data: group } = useQuery({
|
||||
queryKey: ['getSubscribeGroupList'],
|
||||
const { data: nodes } = useQuery({
|
||||
queryKey: ['filterNodeListAll'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeGroupList();
|
||||
return data.data?.list as API.SubscribeGroup[];
|
||||
const { data } = await filterNodeList({ page: 1, size: 999999999 });
|
||||
return (data.data?.list || []) as API.Node[];
|
||||
},
|
||||
});
|
||||
|
||||
const { data: server } = useQuery({
|
||||
queryKey: ['getNodeList', 'all'],
|
||||
const { data: allTagsData } = useQuery({
|
||||
queryKey: ['queryNodeTag'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeList({
|
||||
page: 1,
|
||||
size: 9999,
|
||||
});
|
||||
return data.data?.list;
|
||||
const { data } = await queryNodeTag();
|
||||
return data?.data?.tags || [];
|
||||
},
|
||||
});
|
||||
|
||||
const { data: server_groups } = useQuery({
|
||||
queryKey: ['getNodeGroupList'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeGroupList();
|
||||
return (data.data?.list || []) as API.ServerGroup[];
|
||||
},
|
||||
});
|
||||
const nodeExtractedTags = Array.from(
|
||||
new Set(
|
||||
((nodes as API.Node[]) || [])
|
||||
.flatMap((n) => (Array.isArray(n.tags) ? n.tags : []))
|
||||
.filter(Boolean),
|
||||
),
|
||||
) as string[];
|
||||
|
||||
const allAvailableTags = (allTagsData as string[]) || [];
|
||||
|
||||
const tagGroups = Array.from(new Set([...allAvailableTags, ...nodeExtractedTags])).filter(
|
||||
Boolean,
|
||||
);
|
||||
|
||||
const unit_time = form.watch('unit_time');
|
||||
const unit_price = form.watch('unit_price');
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
@@ -275,7 +277,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='pt-4'>
|
||||
<Tabs defaultValue='basic' className='w-full'>
|
||||
@@ -290,7 +292,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value='servers' className='flex items-center gap-2'>
|
||||
<Server className='h-4 w-4' />
|
||||
{t('form.servers')}
|
||||
{t('form.nodes')}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -317,21 +319,20 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='group_id'
|
||||
name='language'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.groupId')}</FormLabel>
|
||||
<FormLabel>
|
||||
{t('form.language')}
|
||||
<span className='text-muted-foreground ml-1 text-[0.8rem]'>
|
||||
{t('form.languageDescription')}
|
||||
</span>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<number, false>
|
||||
placeholder={t('form.selectSubscribeGroup')}
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value || 0);
|
||||
}}
|
||||
options={group?.map((item) => ({
|
||||
label: item.name,
|
||||
value: item.id,
|
||||
}))}
|
||||
placeholder={t('form.languagePlaceholder')}
|
||||
onValueChange={(v) => form.setValue(field.name, v as string)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -669,7 +670,8 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
min: 0,
|
||||
step: 0.01,
|
||||
formatInput: (value) => unitConversion('centsToDollars', value),
|
||||
formatOutput: (value) => unitConversion('dollarsToCents', value),
|
||||
formatOutput: (value) =>
|
||||
unitConversion('dollarsToCents', value).toString(),
|
||||
},
|
||||
]}
|
||||
value={field.value}
|
||||
@@ -795,53 +797,61 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
<div className='space-y-6'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='server_group'
|
||||
name='node_tags'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.serverGroup')}</FormLabel>
|
||||
<FormLabel>{t('form.nodeGroup')}</FormLabel>
|
||||
<FormControl>
|
||||
<Accordion type='single' collapsible className='w-full'>
|
||||
{server_groups?.map((group: API.ServerGroup) => {
|
||||
{tagGroups.map((tag) => {
|
||||
const value = field.value || [];
|
||||
const tagId = tag;
|
||||
const nodesWithTag =
|
||||
(nodes as API.Node[])?.filter((n) =>
|
||||
(n.tags || []).includes(tag),
|
||||
) || [];
|
||||
|
||||
return (
|
||||
<AccordionItem key={group.id} value={String(group.id)}>
|
||||
<AccordionItem key={tag} value={String(tag)}>
|
||||
<AccordionTrigger>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Checkbox
|
||||
checked={value.includes(group.id!)}
|
||||
checked={value.includes(tagId as any)}
|
||||
onCheckedChange={(checked) => {
|
||||
return checked
|
||||
? form.setValue(field.name, [...value, group.id])
|
||||
? form.setValue(field.name, [...value, tagId] as any)
|
||||
: form.setValue(
|
||||
field.name,
|
||||
value.filter(
|
||||
(value: number) => value !== group.id,
|
||||
),
|
||||
value.filter((v: any) => v !== tagId),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Label>{group.name}</Label>
|
||||
<Label>
|
||||
{tag}
|
||||
<span className='text-muted-foreground ml-2 text-xs'>
|
||||
({nodesWithTag.length})
|
||||
</span>
|
||||
</Label>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<ul className='list-disc [&>li]:mt-2'>
|
||||
{server
|
||||
?.filter(
|
||||
(server: API.Server) => server.group_id === group.id,
|
||||
)
|
||||
?.map((node: API.Server) => {
|
||||
return (
|
||||
<li
|
||||
key={node.id}
|
||||
className='flex items-center justify-between *:flex-1'
|
||||
>
|
||||
<span>{node.name}</span>
|
||||
<span>{node.server_addr}</span>
|
||||
<span className='text-right'>{node.protocol}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
<ul className='space-y-1'>
|
||||
{(nodes as API.Node[])
|
||||
?.filter((n) => (n.tags || []).includes(tag))
|
||||
?.map((node) => (
|
||||
<li
|
||||
key={node.id}
|
||||
className='flex items-center justify-between gap-3'
|
||||
>
|
||||
<span className='flex-1'>{node.name}</span>
|
||||
<span className='flex-1'>
|
||||
{node.address}:{node.port}
|
||||
</span>
|
||||
<span className='flex-1 text-right'>
|
||||
{node.protocol}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
@@ -856,15 +866,15 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='server'
|
||||
name='nodes'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.server')}</FormLabel>
|
||||
<FormLabel>{t('form.node')}</FormLabel>
|
||||
<FormControl>
|
||||
<div className='flex flex-col gap-2'>
|
||||
{server
|
||||
?.filter((item: API.Server) => !item.group_id)
|
||||
?.map((item: API.Server) => {
|
||||
{(nodes as API.Node[])
|
||||
?.filter((item) => (item.tags || []).length === 0)
|
||||
?.map((item) => {
|
||||
const value = field.value || [];
|
||||
|
||||
return (
|
||||
@@ -880,10 +890,12 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Label className='flex w-full items-center justify-between *:flex-1'>
|
||||
<span>{item.name}</span>
|
||||
<span>{item.server_addr}</span>
|
||||
<span className='text-right'>{item.protocol}</span>
|
||||
<Label className='flex w-full items-center justify-between gap-3'>
|
||||
<span className='flex-1'>{item.name}</span>
|
||||
<span className='flex-1'>
|
||||
{item.address}:{item.port}
|
||||
</span>
|
||||
<span className='flex-1 text-right'>{item.protocol}</span>
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
@@ -916,7 +928,8 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
const keys = Object.keys(errors);
|
||||
for (const key of keys) {
|
||||
const formattedKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
||||
toast.error(`${t(`form.${formattedKey}`)} is ${errors[key]?.message}`);
|
||||
const error = (errors as any)[key];
|
||||
toast.error(`${t(`form.${formattedKey}`)} is ${error?.message}`);
|
||||
return false;
|
||||
}
|
||||
})}
|
||||
+5
-25
@@ -6,12 +6,10 @@ import {
|
||||
batchDeleteSubscribe,
|
||||
createSubscribe,
|
||||
deleteSubscribe,
|
||||
getSubscribeGroupList,
|
||||
getSubscribeList,
|
||||
subscribeSort,
|
||||
updateSubscribe,
|
||||
} from '@/services/admin/subscribe';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
@@ -22,18 +20,8 @@ import { toast } from 'sonner';
|
||||
import SubscribeForm from './subscribe-form';
|
||||
|
||||
export default function SubscribeTable() {
|
||||
const t = useTranslations('subscribe');
|
||||
const t = useTranslations('product');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { data: groups } = useQuery({
|
||||
queryKey: ['getSubscribeGroupList', 'all'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeGroupList({
|
||||
page: 1,
|
||||
size: 9999,
|
||||
});
|
||||
return data.data?.list as API.SubscribeGroup[];
|
||||
},
|
||||
});
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
return (
|
||||
<ProTable<API.SubscribeItem, { group_id: number; query: string }>
|
||||
@@ -70,14 +58,6 @@ export default function SubscribeTable() {
|
||||
{
|
||||
key: 'search',
|
||||
},
|
||||
{
|
||||
key: 'group_id',
|
||||
placeholder: t('subscribeGroup'),
|
||||
options: groups?.map((item) => ({
|
||||
label: item.name,
|
||||
value: String(item.id),
|
||||
})),
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getSubscribeList({
|
||||
@@ -176,11 +156,11 @@ export default function SubscribeTable() {
|
||||
cell: ({ row }) => <Display type='number' value={row.getValue('quota')} unlimited />,
|
||||
},
|
||||
{
|
||||
accessorKey: 'group_id',
|
||||
header: t('subscribeGroup'),
|
||||
accessorKey: 'language',
|
||||
header: t('language'),
|
||||
cell: ({ row }) => {
|
||||
const name = groups?.find((group) => group.id === row.getValue('group_id'))?.name;
|
||||
return name ? <Badge variant='outline'>{name}</Badge> : '--';
|
||||
const language = row.getValue('language') as string;
|
||||
return language ? <Badge variant='outline'>{language}</Badge> : '--';
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1,240 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { createRuleGroup } from '@/services/admin/server';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@workspace/ui/components/dialog';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { Progress } from '@workspace/ui/components/progress';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import yaml from 'js-yaml';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface ImportYamlRulesProps {
|
||||
onImportSuccess?: () => void;
|
||||
}
|
||||
|
||||
interface RuleGroup {
|
||||
name: string;
|
||||
rules: string[];
|
||||
}
|
||||
|
||||
export default function ImportYamlRules({ onImportSuccess }: ImportYamlRulesProps) {
|
||||
const t = useTranslations('rules');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [yamlContent, setYamlContent] = useState('');
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [importTotal, setImportTotal] = useState(0);
|
||||
const [analyzing, setAnalyzing] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const content = event.target?.result as string;
|
||||
setYamlContent(content);
|
||||
setOpen(true);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
|
||||
e.target.value = '';
|
||||
};
|
||||
|
||||
const processRule = (rule: string): { policyGroup: string; cleanRule: string } | null => {
|
||||
const parts = rule.split(',');
|
||||
|
||||
if (parts.length === 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let policyGroup = 'default';
|
||||
let cleanRule = rule;
|
||||
|
||||
if (parts.length >= 3) {
|
||||
const thirdPart = parts[2]?.trim();
|
||||
if (thirdPart) {
|
||||
policyGroup = thirdPart;
|
||||
}
|
||||
}
|
||||
|
||||
cleanRule = parts.slice(0, 2).join(',');
|
||||
|
||||
return { policyGroup, cleanRule };
|
||||
};
|
||||
|
||||
const parseRulesIntoGroups = (rules: string[]): Record<string, string[]> => {
|
||||
const groups: Record<string, string[]> = {};
|
||||
|
||||
for (const rule of rules) {
|
||||
if (!rule.trim()) continue;
|
||||
|
||||
const result = processRule(rule);
|
||||
if (result === null) continue;
|
||||
|
||||
const { policyGroup, cleanRule } = result;
|
||||
if (!groups[policyGroup]) {
|
||||
groups[policyGroup] = [];
|
||||
}
|
||||
|
||||
// 不插入 MATCH 规则,只用于标识默认规则组
|
||||
if (!rule.trim().startsWith('MATCH,')) {
|
||||
groups[policyGroup].push(cleanRule);
|
||||
}
|
||||
}
|
||||
|
||||
return groups;
|
||||
};
|
||||
|
||||
const checkIfDefaultRule = (originalRules: string[], groupName: string): boolean => {
|
||||
return originalRules.some((rule) => {
|
||||
const trimmedRule = rule.trim();
|
||||
if (!trimmedRule.startsWith('MATCH,')) return false;
|
||||
|
||||
// 检查 MATCH 规则是否属于当前组
|
||||
const parts = trimmedRule.split(',');
|
||||
if (parts.length >= 3) {
|
||||
const ruleGroup = parts[2]?.trim();
|
||||
return ruleGroup === groupName;
|
||||
}
|
||||
|
||||
return groupName === 'default';
|
||||
});
|
||||
};
|
||||
|
||||
const handleImport = async () => {
|
||||
if (!yamlContent) {
|
||||
toast.error(t('pleaseUploadFile'));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setAnalyzing(true);
|
||||
try {
|
||||
const parsedYaml = yaml.load(yamlContent) as any;
|
||||
|
||||
if (!parsedYaml || !parsedYaml.rules) {
|
||||
throw new Error(t('invalidYamlFormat'));
|
||||
}
|
||||
|
||||
let allRules: string[] = [];
|
||||
if (Array.isArray(parsedYaml.rules)) {
|
||||
allRules = parsedYaml.rules.filter((rule: string) => rule.trim());
|
||||
}
|
||||
|
||||
if (allRules.length === 0) {
|
||||
throw new Error(t('noValidRules'));
|
||||
}
|
||||
|
||||
const ruleGroups = parseRulesIntoGroups(allRules);
|
||||
const groups = Object.entries(ruleGroups).map(([name, rules]) => ({
|
||||
name,
|
||||
rules,
|
||||
}));
|
||||
|
||||
setImportTotal(groups.length);
|
||||
setAnalyzing(false);
|
||||
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
const group = groups[i];
|
||||
if (!group?.name || !group?.rules.length) continue;
|
||||
|
||||
const isDefault = checkIfDefaultRule(allRules, group.name);
|
||||
|
||||
await createRuleGroup({
|
||||
name: group.name,
|
||||
rules: group?.rules.join('\n'),
|
||||
enable: false,
|
||||
tags: [],
|
||||
icon: '',
|
||||
type: 'default',
|
||||
default: isDefault,
|
||||
});
|
||||
setImportProgress(i + 1);
|
||||
}
|
||||
|
||||
toast.success(t('importSuccess'));
|
||||
setOpen(false);
|
||||
setYamlContent('');
|
||||
setImportProgress(0);
|
||||
setImportTotal(0);
|
||||
onImportSuccess?.();
|
||||
} catch (error) {
|
||||
console.error('Import error:', error);
|
||||
toast.error(error instanceof Error ? error.message : t('importFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setAnalyzing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type='file'
|
||||
accept='.yml,.yaml'
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button variant='default' onClick={() => fileInputRef.current?.click()}>
|
||||
{t('import')}
|
||||
</Button>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className='sm:max-w-[500px]'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('importYamlRules')}</DialogTitle>
|
||||
<DialogDescription>{t('importYamlDescription')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className='grid gap-4 py-4'>
|
||||
{yamlContent && (
|
||||
<div className='grid gap-2'>
|
||||
<Label htmlFor='preview'>{t('preview')}</Label>
|
||||
<Textarea
|
||||
id='preview'
|
||||
value={yamlContent}
|
||||
readOnly
|
||||
rows={10}
|
||||
className='font-mono text-xs'
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{importTotal > 0 && (
|
||||
<div className='grid gap-2'>
|
||||
<div className='flex justify-between text-sm'>
|
||||
<span>{analyzing ? t('analyzing') : t('importing')}</span>
|
||||
<span>
|
||||
{importProgress} / {importTotal}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={(importProgress / importTotal) * 100} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant='outline' onClick={() => setOpen(false)} disabled={loading}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleImport} disabled={loading || !yamlContent}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('import')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
createRuleGroup,
|
||||
deleteRuleGroup,
|
||||
getRuleGroupList,
|
||||
updateRuleGroup,
|
||||
} from '@/services/admin/server';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/legacy/image';
|
||||
import Link from 'next/link';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import ImportYamlRules from './import-yaml-rules';
|
||||
import RuleForm from './rule-form';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('rules');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<API.ServerRuleGroup, { query: string }>
|
||||
action={ref}
|
||||
header={{
|
||||
toolbar: (
|
||||
<div className='flex gap-2'>
|
||||
<Button variant='default' asChild>
|
||||
<Link href='/template/rules.yml' target='_blank' download>
|
||||
{t('downloadTemplate')}
|
||||
</Link>
|
||||
</Button>
|
||||
<ImportYamlRules onImportSuccess={() => ref.current?.refresh()} />
|
||||
<RuleForm<API.CreateRuleGroupRequest>
|
||||
trigger={t('create')}
|
||||
title={t('createRule')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createRuleGroup({
|
||||
name: values.name,
|
||||
rules: values.rules || '',
|
||||
enable: false,
|
||||
tags: values.tags || [],
|
||||
icon: values.icon || '',
|
||||
type: values.type || 'default',
|
||||
default: false,
|
||||
});
|
||||
toast.success(t('createSuccess'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
params={[
|
||||
{
|
||||
key: 'search',
|
||||
placeholder: t('searchRule'),
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getRuleGroupList({
|
||||
...pagination,
|
||||
...filters,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'enable',
|
||||
header: t('enable'),
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<Switch
|
||||
defaultChecked={row.getValue('enable')}
|
||||
onCheckedChange={async (checked) => {
|
||||
await updateRuleGroup({
|
||||
...row.original,
|
||||
enable: checked,
|
||||
} as API.UpdateRuleGroupRequest);
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'default',
|
||||
header: t('defaultRule'),
|
||||
cell: ({ row }) => (
|
||||
<Switch
|
||||
defaultChecked={row.original.default}
|
||||
onCheckedChange={async (checked) => {
|
||||
await updateRuleGroup({
|
||||
...row.original,
|
||||
default: checked,
|
||||
} as API.UpdateRuleGroupRequest);
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'type',
|
||||
header: t('type'),
|
||||
cell: ({ row }) => {
|
||||
const type = row.original.type || 'default';
|
||||
if (type === 'default') {
|
||||
return <Badge variant='default'>{t('default')}</Badge>;
|
||||
}
|
||||
if (type === 'reject') {
|
||||
return <Badge variant='destructive'>{t('reject')}</Badge>;
|
||||
}
|
||||
if (type === 'direct') {
|
||||
return <Badge variant='secondary'>{t('direct')}</Badge>;
|
||||
}
|
||||
return <Badge variant='default'>{t('default')}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: t('name'),
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
{row.original.icon && (
|
||||
<Image
|
||||
src={row.original.icon}
|
||||
alt={row.original.name}
|
||||
className='h-6 w-6 rounded-md'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
)}
|
||||
<span>{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'tags',
|
||||
header: t('tags'),
|
||||
cell: ({ row }) => {
|
||||
const tags = row.original.tags.filter((item) => item) || [];
|
||||
if (!tags.length) return '--';
|
||||
return (
|
||||
<>
|
||||
{tags.map((tag) => (
|
||||
<Badge key={tag} variant='outline' className='mr-1'>
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('createdAt'),
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
]}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<RuleForm<API.UpdateRuleGroupRequest>
|
||||
key='edit'
|
||||
trigger={t('edit')}
|
||||
title={t('editRule')}
|
||||
loading={loading}
|
||||
initialValues={row}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateRuleGroup({
|
||||
id: row.id,
|
||||
name: values.name,
|
||||
tags: values.tags,
|
||||
rules: values.rules,
|
||||
enable: row.enable,
|
||||
icon: values.icon,
|
||||
type: values.type,
|
||||
default: row.default,
|
||||
});
|
||||
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 deleteRuleGroup({ 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('delete')}</Button>}
|
||||
title={t('confirmDelete')}
|
||||
description={t('deleteWarning')}
|
||||
onConfirm={async () => {
|
||||
for (const row of rows) {
|
||||
await deleteRuleGroup({ id: row.id });
|
||||
}
|
||||
toast.success(t('deleteSuccess'));
|
||||
ref.current?.reset();
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getNodeTagList } from '@/services/admin/server';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
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 { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { Combobox } from '@workspace/ui/custom-components/combobox';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(1, { message: '请输入规则名称' }),
|
||||
tags: z.array(z.string()).default([]),
|
||||
rules: z.string().default(''),
|
||||
icon: z.string().default(''),
|
||||
type: z.string().default('default'),
|
||||
});
|
||||
|
||||
interface RuleFormProps<T> {
|
||||
onSubmit: (data: T) => Promise<boolean> | boolean;
|
||||
initialValues?: T;
|
||||
loading?: boolean;
|
||||
trigger: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export default function RuleForm<T extends Record<string, any>>({
|
||||
onSubmit,
|
||||
initialValues,
|
||||
loading,
|
||||
trigger,
|
||||
title,
|
||||
}: RuleFormProps<T>) {
|
||||
const t = useTranslations('rules');
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const form = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
...initialValues,
|
||||
} as any,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues) {
|
||||
form.reset(initialValues);
|
||||
}
|
||||
}, [form, initialValues]);
|
||||
|
||||
async function handleSubmit(data: { [x: string]: any }) {
|
||||
const bool = await onSubmit(data as T);
|
||||
if (bool) setOpen(false);
|
||||
}
|
||||
|
||||
const { data: tags } = useQuery({
|
||||
queryKey: ['getNodeTagList'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeTagList();
|
||||
return data.data?.tags || [];
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
form.reset();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{trigger}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 px-6 pt-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='icon'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('appIcon')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('enterIconUrl')}
|
||||
value={field.value}
|
||||
suffix={
|
||||
<UploadImage
|
||||
className='bg-muted h-9 rounded-none border-none px-2'
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value as string);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('enterRuleName')}
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='type'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('type')}</FormLabel>
|
||||
<FormControl>
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('selectType')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value='default'>{t('default')}</SelectItem>
|
||||
<SelectItem value='reject'>{t('reject')}</SelectItem>
|
||||
<SelectItem value='direct'>{t('direct')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='tags'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('tagsLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<string, true>
|
||||
multiple
|
||||
placeholder={t('selectTags')}
|
||||
value={field.value}
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
options={tags?.map((item: string) => ({
|
||||
value: item,
|
||||
label: item,
|
||||
}))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='rules'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('rulesLabel')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder={t('enterRules')}
|
||||
value={field.value}
|
||||
rows={10}
|
||||
onChange={(e) => {
|
||||
form.setValue(field.name, e.target.value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className='text-muted-foreground mt-1 text-xs'>
|
||||
<pre>{t('rulesFormat')}</pre>
|
||||
<div className='border-muted mt-2 space-y-1 border-l-2 pl-2'>
|
||||
<p className='font-mono'>DOMAIN,example.com</p>
|
||||
<p className='font-mono'>DOMAIN-SUFFIX,google.com,DIRECT</p>
|
||||
<p className='font-mono'>DOMAIN-KEYWORD,amazon,REJECT</p>
|
||||
<p className='font-mono'>IP-CIDR,192.168.0.0/16</p>
|
||||
<p className='font-mono'>IP-CIDR6,2001:db8::/32,REJECT</p>
|
||||
<p className='font-mono'>SRC-IP-CIDR,192.168.1.201/32</p>
|
||||
<p className='font-mono'>GEOIP,CN,DIRECT</p>
|
||||
<p className='font-mono'>GEOIP,US</p>
|
||||
<p className='font-mono'>DST-PORT,80,DIRECT</p>
|
||||
<p className='font-mono'>SRC-PORT,7777,REJECT</p>
|
||||
<p className='font-mono'>PROCESS-NAME,telegram</p>
|
||||
</div>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button
|
||||
variant='outline'
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} onClick={form.handleSubmit(handleSubmit)}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const protocols = ['shadowsocks', 'vmess', 'vless', 'trojan', 'hysteria2', 'tuic', 'anytls'];
|
||||
|
||||
const nullableString = z.string().nullish();
|
||||
const portSchema = z.number().max(65535).nullish();
|
||||
const securityConfigSchema = z
|
||||
.object({
|
||||
sni: nullableString,
|
||||
allow_insecure: z.boolean().nullable().default(false),
|
||||
fingerprint: nullableString,
|
||||
reality_private_key: nullableString,
|
||||
reality_public_key: nullableString,
|
||||
reality_short_id: nullableString,
|
||||
reality_server_addr: nullableString,
|
||||
reality_server_port: portSchema,
|
||||
})
|
||||
.nullish();
|
||||
|
||||
const transportConfigSchema = z
|
||||
.object({
|
||||
path: nullableString,
|
||||
host: nullableString,
|
||||
service_name: nullableString,
|
||||
})
|
||||
.nullish();
|
||||
|
||||
const baseProtocolSchema = z.object({
|
||||
port: portSchema,
|
||||
transport: z.string(),
|
||||
transport_config: transportConfigSchema,
|
||||
security: z.string(),
|
||||
security_config: securityConfigSchema,
|
||||
});
|
||||
|
||||
const shadowsocksSchema = z.object({
|
||||
method: z.string(),
|
||||
port: portSchema,
|
||||
server_key: nullableString,
|
||||
});
|
||||
|
||||
const vmessSchema = baseProtocolSchema;
|
||||
|
||||
const vlessSchema = baseProtocolSchema.extend({
|
||||
flow: nullableString,
|
||||
});
|
||||
|
||||
const trojanSchema = baseProtocolSchema;
|
||||
|
||||
const hysteria2Schema = z.object({
|
||||
port: portSchema,
|
||||
hop_ports: nullableString,
|
||||
hop_interval: z.number().nullish(),
|
||||
obfs_password: nullableString,
|
||||
security: z.string(),
|
||||
security_config: securityConfigSchema,
|
||||
});
|
||||
|
||||
const tuicSchema = z.object({
|
||||
port: portSchema,
|
||||
disable_sni: z.boolean().default(false),
|
||||
reduce_rtt: z.boolean().default(false),
|
||||
udp_relay_mode: z.string().default('native'),
|
||||
congestion_controller: z.string().default('bbr'),
|
||||
security_config: securityConfigSchema,
|
||||
});
|
||||
|
||||
const anytlsSchema = z.object({
|
||||
port: portSchema,
|
||||
security_config: securityConfigSchema,
|
||||
});
|
||||
|
||||
const protocolConfigSchema = z.discriminatedUnion('protocol', [
|
||||
z.object({
|
||||
protocol: z.literal('shadowsocks'),
|
||||
config: shadowsocksSchema,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('vmess'),
|
||||
config: vmessSchema,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('vless'),
|
||||
config: vlessSchema,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('trojan'),
|
||||
config: trojanSchema,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('hysteria2'),
|
||||
config: hysteria2Schema,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('tuic'),
|
||||
config: tuicSchema,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('anytls'),
|
||||
config: anytlsSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
const baseFormSchema = z.object({
|
||||
name: z.string(),
|
||||
tags: z.array(z.string()).nullish().default([]),
|
||||
country: z.string().nullish(),
|
||||
city: z.string().nullish(),
|
||||
server_addr: z.string(),
|
||||
speed_limit: z.number().nullish(),
|
||||
traffic_ratio: z.number().default(1),
|
||||
group_id: z.number().nullish(),
|
||||
relay_mode: z.string().nullish().default('none'),
|
||||
relay_node: z
|
||||
.array(
|
||||
z.object({
|
||||
host: z.string(),
|
||||
port: portSchema,
|
||||
prefix: z.string().nullish(),
|
||||
}),
|
||||
)
|
||||
.nullish()
|
||||
.default([]),
|
||||
});
|
||||
|
||||
export const formSchema = z.intersection(baseFormSchema, protocolConfigSchema);
|
||||
@@ -1,145 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
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 {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
});
|
||||
|
||||
interface GroupFormProps<T> {
|
||||
onSubmit: (data: T) => Promise<boolean> | boolean;
|
||||
initialValues?: T;
|
||||
loading?: boolean;
|
||||
trigger: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export default function GroupForm<T extends Record<string, any>>({
|
||||
onSubmit,
|
||||
initialValues,
|
||||
loading,
|
||||
trigger,
|
||||
title,
|
||||
}: GroupFormProps<T>) {
|
||||
const t = useTranslations('server');
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const form = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
...initialValues,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
form?.reset(initialValues);
|
||||
}, [form, initialValues]);
|
||||
|
||||
async function handleSubmit(data: { [x: string]: any }) {
|
||||
const bool = await onSubmit(data as T);
|
||||
|
||||
if (bool) setOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
form.reset();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{trigger}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 px-6 pt-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('group.form.name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='description'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('group.form.description')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button
|
||||
variant='outline'
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{t('group.form.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} onClick={form.handleSubmit(handleSubmit)}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}{' '}
|
||||
{t('group.form.confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
batchDeleteNodeGroup,
|
||||
createNodeGroup,
|
||||
deleteNodeGroup,
|
||||
getNodeGroupList,
|
||||
updateNodeGroup,
|
||||
} from '@/services/admin/server';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import GroupForm from './group-form';
|
||||
|
||||
export default function GroupTable() {
|
||||
const t = useTranslations('server');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<API.ServerGroup, any>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t('group.title'),
|
||||
toolbar: (
|
||||
<GroupForm<API.CreateNodeGroupRequest>
|
||||
trigger={t('group.create')}
|
||||
title={t('group.createNodeGroup')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createNodeGroup(values);
|
||||
toast.success(t('group.createdSuccessfully'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: t('group.name'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'description',
|
||||
header: t('group.description'),
|
||||
cell: ({ row }) => <p className='line-clamp-3'>{row.getValue('description')}</p>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'updated_at',
|
||||
header: t('group.updatedAt'),
|
||||
cell: ({ row }) => formatDate(row.getValue('updated_at')),
|
||||
},
|
||||
]}
|
||||
request={async () => {
|
||||
const { data } = await getNodeGroupList();
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<GroupForm<API.ServerGroup>
|
||||
key='edit'
|
||||
trigger={t('group.edit')}
|
||||
title={t('group.editNodeGroup')}
|
||||
loading={loading}
|
||||
initialValues={row}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateNodeGroup({
|
||||
...row,
|
||||
...values,
|
||||
});
|
||||
toast.success(t('group.createdSuccessfully'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
|
||||
title={t('group.confirmDelete')}
|
||||
description={t('group.deleteWarning')}
|
||||
onConfirm={async () => {
|
||||
await deleteNodeGroup({
|
||||
id: row.id!,
|
||||
});
|
||||
toast.success(t('group.deletedSuccessfully'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('group.cancel')}
|
||||
confirmText={t('group.confirm')}
|
||||
/>,
|
||||
],
|
||||
batchRender(rows) {
|
||||
return [
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
|
||||
title={t('group.confirmDelete')}
|
||||
description={t('group.deleteWarning')}
|
||||
onConfirm={async () => {
|
||||
await batchDeleteNodeGroup({
|
||||
ids: rows.map((item) => item.id),
|
||||
});
|
||||
toast.success(t('group.deleteSuccess'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('group.cancel')}
|
||||
confirmText={t('group.confirm')}
|
||||
/>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getNodeConfig,
|
||||
getNodeMultiplier,
|
||||
setNodeMultiplier,
|
||||
updateNodeConfig,
|
||||
} from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { ChartContainer, ChartTooltip } from '@workspace/ui/components/chart';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { DicesIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Cell, Legend, Pie, PieChart } from 'recharts';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const COLORS = [
|
||||
'hsl(var(--chart-1))',
|
||||
'hsl(var(--chart-2))',
|
||||
'hsl(var(--chart-3))',
|
||||
'hsl(var(--chart-4))',
|
||||
'hsl(var(--chart-5))',
|
||||
];
|
||||
|
||||
const MINUTES_IN_DAY = 1440; // 24 * 60
|
||||
|
||||
function getTimeRangeData(slots: API.TimePeriod[]) {
|
||||
const timePoints = slots
|
||||
.filter((slot) => slot.start_time && slot.end_time)
|
||||
.flatMap((slot) => {
|
||||
const [startH = 0, startM = 0] = slot.start_time.split(':').map(Number);
|
||||
const [endH = 0, endM = 0] = slot?.end_time.split(':').map(Number);
|
||||
const start = startH * 60 + startM;
|
||||
let end = endH * 60 + endM;
|
||||
if (end < start) end += MINUTES_IN_DAY;
|
||||
return { start, end, multiplier: slot.multiplier };
|
||||
})
|
||||
.sort((a, b) => a.start - b.start);
|
||||
|
||||
const result = [];
|
||||
let currentMinute = 0;
|
||||
|
||||
timePoints.forEach((point) => {
|
||||
if (point.start > currentMinute) {
|
||||
result.push({
|
||||
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - ${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')}`,
|
||||
value: point.start - currentMinute,
|
||||
multiplier: 1,
|
||||
});
|
||||
}
|
||||
result.push({
|
||||
name: `${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')} - ${Math.floor((point.end / 60) % 24)}:${String(point.end % 60).padStart(2, '0')}`,
|
||||
value: point.end - point.start,
|
||||
multiplier: point.multiplier,
|
||||
});
|
||||
currentMinute = point.end % MINUTES_IN_DAY;
|
||||
});
|
||||
|
||||
if (currentMinute < MINUTES_IN_DAY) {
|
||||
result.push({
|
||||
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - 24:00`,
|
||||
value: MINUTES_IN_DAY - currentMinute,
|
||||
multiplier: 1,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export default function NodeConfig() {
|
||||
const t = useTranslations('server.config');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getNodeConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeConfig();
|
||||
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateNodeConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.NodeConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
const [timeSlots, setTimeSlots] = useState<API.TimePeriod[]>([]);
|
||||
|
||||
const { data: NodeMultiplier, refetch: refetchNodeMultiplier } = useQuery({
|
||||
queryKey: ['getNodeMultiplier'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeMultiplier();
|
||||
if (timeSlots.length === 0) {
|
||||
setTimeSlots(data.data?.periods || []);
|
||||
}
|
||||
return data.data?.periods || [];
|
||||
},
|
||||
});
|
||||
|
||||
const chartTimeSlots = useMemo(() => {
|
||||
return getTimeRangeData(timeSlots);
|
||||
}, [timeSlots]);
|
||||
|
||||
const chartConfig = useMemo(() => {
|
||||
return chartTimeSlots?.reduce(
|
||||
(acc, item, index) => {
|
||||
acc[item.name] = {
|
||||
label: item.name,
|
||||
color: COLORS[index % COLORS.length] || 'hsl(var(--default-chart-color))',
|
||||
};
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, { label: string; color: string }>,
|
||||
);
|
||||
}, [data]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('communicationKey')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('communicationKeyDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={data?.node_secret}
|
||||
onValueBlur={(value) => updateConfig('node_secret', value)}
|
||||
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)}`;
|
||||
updateConfig('node_secret', formatted);
|
||||
}}
|
||||
className='cursor-pointer'
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('nodePullInterval')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('nodePullIntervalDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
onValueBlur={(value) => updateConfig('node_pull_interval', value)}
|
||||
suffix='S'
|
||||
value={data?.node_pull_interval}
|
||||
placeholder={t('inputPlaceholder')}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('nodePushInterval')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('nodePushIntervalDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
step={0.1}
|
||||
value={data?.node_push_interval}
|
||||
onValueBlur={(value) => updateConfig('node_push_interval', value)}
|
||||
placeholder={t('inputPlaceholder')}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('dynamicMultiplier')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('dynamicMultiplierDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='flex justify-end gap-2'>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => {
|
||||
setTimeSlots(NodeMultiplier || []);
|
||||
}}
|
||||
>
|
||||
{t('reset')}
|
||||
</Button>
|
||||
<Button
|
||||
size='sm'
|
||||
onClick={() => {
|
||||
setNodeMultiplier({
|
||||
periods: timeSlots,
|
||||
}).then(async () => {
|
||||
const result = await refetchNodeMultiplier();
|
||||
if (result.data) setTimeSlots(result.data);
|
||||
toast.success(t('saveSuccess'));
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t('save')}
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className='flex flex-col-reverse gap-8 px-4 pt-6 md:flex-row md:items-start'>
|
||||
<div className='w-full md:w-1/2'>
|
||||
<ChartContainer config={chartConfig} className='mx-auto aspect-[4/3] max-w-[400px]'>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartTimeSlots}
|
||||
cx='50%'
|
||||
cy='50%'
|
||||
labelLine={false}
|
||||
outerRadius='80%'
|
||||
fill='#8884d8'
|
||||
dataKey='value'
|
||||
label={({ name, percent, multiplier }) =>
|
||||
`${(multiplier || 0)?.toFixed(2)}x (${(percent * 100).toFixed(0)}%)`
|
||||
}
|
||||
>
|
||||
{chartTimeSlots.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<ChartTooltip
|
||||
content={({ payload }) => {
|
||||
if (payload && payload.length) {
|
||||
const data = payload[0]?.payload;
|
||||
return (
|
||||
<div className='bg-background rounded-lg border p-2 shadow-sm'>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-muted-foreground text-[0.70rem] uppercase'>
|
||||
{t('timeSlot')}
|
||||
</span>
|
||||
<span className='text-muted-foreground font-bold'>
|
||||
{data.name || '其他'}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-muted-foreground text-[0.70rem] uppercase'>
|
||||
{t('multiplier')}
|
||||
</span>
|
||||
<span className='font-bold'>{data.multiplier.toFixed(2)}x</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
<div className='w-full md:w-1/2'>
|
||||
<ArrayInput<API.TimePeriod>
|
||||
fields={[
|
||||
{
|
||||
name: 'start_time',
|
||||
prefix: t('startTime'),
|
||||
type: 'time',
|
||||
},
|
||||
{ name: 'end_time', prefix: t('endTime'), type: 'time' },
|
||||
{ name: 'multiplier', prefix: t('multiplier'), type: 'number', placeholder: '0' },
|
||||
]}
|
||||
value={timeSlots}
|
||||
onChange={setTimeSlots}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,112 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from '@workspace/ui/components/accordion';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Progress } from '@workspace/ui/components/progress';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import { UserSubscribeDetail } from '../user/user-detail';
|
||||
|
||||
export function formatPercentage(value: number): string {
|
||||
return `${value.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
export function NodeStatusCell({ status }: { status: API.NodeStatus }) {
|
||||
const t = useTranslations('server.node');
|
||||
const [openItem, setOpenItem] = useState<string | null>(null);
|
||||
|
||||
const { online, cpu, mem, disk, updated_at } = status || {
|
||||
online: {},
|
||||
cpu: 0,
|
||||
mem: 0,
|
||||
disk: 0,
|
||||
updated_at: 0,
|
||||
};
|
||||
const isOnline = updated_at > 0;
|
||||
const badgeVariant = isOnline ? 'default' : 'destructive';
|
||||
const badgeText = isOnline ? t('normal') : t('abnormal');
|
||||
const onlineCount = (online && Object.keys(online).length) || 0;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className='flex items-center gap-2 text-xs *:flex-1'>
|
||||
<div className='flex items-center space-x-1'>
|
||||
<Badge variant={badgeVariant}>{badgeText}</Badge>
|
||||
<span className='font-medium'>
|
||||
{t('onlineCount')}: {onlineCount}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex flex-col space-y-1'>
|
||||
<div className='flex justify-between'>
|
||||
<span>CPU</span>
|
||||
<span>{formatPercentage(cpu ?? 0)}</span>
|
||||
</div>
|
||||
<Progress value={cpu ?? 0} className='h-2' max={100} />
|
||||
</div>
|
||||
<div className='flex flex-col space-y-1'>
|
||||
<div className='flex justify-between'>
|
||||
<span>{t('memory')}</span>
|
||||
<span>{formatPercentage(mem ?? 0)}</span>
|
||||
</div>
|
||||
<Progress value={mem ?? 0} className='h-2' max={100} />
|
||||
</div>
|
||||
<div className='flex flex-col space-y-1'>
|
||||
<div className='flex justify-between'>
|
||||
<span>{t('disk')}</span>
|
||||
<span>{formatPercentage(disk ?? 0)}</span>
|
||||
</div>
|
||||
<Progress value={disk ?? 0} className='h-2' max={100} />
|
||||
</div>
|
||||
{isOnline && (
|
||||
<div>
|
||||
{t('lastUpdated')}: {formatDate(updated_at ?? 0)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
{isOnline && onlineCount > 0 && (
|
||||
<TooltipContent className='bg-card text-foreground w-96'>
|
||||
<ScrollArea className='h-[540px] rounded-md border px-4 py-2'>
|
||||
<h4 className='py-1 text-sm font-semibold'>{t('onlineUsers')}</h4>
|
||||
<Accordion
|
||||
type='single'
|
||||
collapsible
|
||||
className='w-full'
|
||||
onValueChange={(value) => setOpenItem(value)}
|
||||
>
|
||||
{Object.entries(online).map(([uid, ips]) => (
|
||||
<AccordionItem key={uid} value={uid}>
|
||||
<AccordionTrigger>{`[UID: ${uid}] - ${ips[0]}`}</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<ul>
|
||||
{ips.map((ip: string) => (
|
||||
<li key={ip}>{ip}</li>
|
||||
))}
|
||||
</ul>
|
||||
<UserSubscribeDetail id={Number(uid)} enabled={openItem === uid} />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
</ScrollArea>
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,320 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Display } from '@/components/display';
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
batchDeleteNode,
|
||||
createNode,
|
||||
deleteNode,
|
||||
getNodeGroupList,
|
||||
getNodeList,
|
||||
nodeSort,
|
||||
updateNode,
|
||||
} from '@/services/admin/server';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import NodeForm from './node-form';
|
||||
import { NodeStatusCell } from './node-status';
|
||||
|
||||
export default function NodeTable() {
|
||||
const t = useTranslations('server.node');
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data: groups } = useQuery({
|
||||
queryKey: ['getNodeGroupList'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeGroupList();
|
||||
return (data.data?.list || []) as API.ServerGroup[];
|
||||
},
|
||||
});
|
||||
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<API.Server, { groupId: number; search: string }>
|
||||
action={ref}
|
||||
header={{
|
||||
toolbar: (
|
||||
<NodeForm<API.CreateNodeRequest>
|
||||
trigger={t('create')}
|
||||
title={t('createNode')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createNode({ ...values, enable: false });
|
||||
toast.success(t('createSuccess'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: t('id'),
|
||||
cell: ({ row }) => (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Badge
|
||||
variant='outline'
|
||||
className={cn('text-primary-foreground', {
|
||||
'bg-green-500': row.original.protocol === 'shadowsocks',
|
||||
'bg-rose-500': row.original.protocol === 'vmess',
|
||||
'bg-blue-500': row.original.protocol === 'vless',
|
||||
'bg-yellow-500': row.original.protocol === 'trojan',
|
||||
'bg-purple-500': row.original.protocol === 'hysteria2',
|
||||
'bg-cyan-500': row.original.protocol === 'tuic',
|
||||
'bg-gray-500': row.original.protocol === 'anytls',
|
||||
})}
|
||||
>
|
||||
{row.getValue('id')}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{row.original.protocol}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'enable',
|
||||
header: t('enable'),
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<Switch
|
||||
checked={row.getValue('enable')}
|
||||
onCheckedChange={async (checked) => {
|
||||
await updateNode({
|
||||
...row.original,
|
||||
id: row.original.id!,
|
||||
enable: checked,
|
||||
} as API.UpdateNodeRequest);
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: t('name'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'server_addr',
|
||||
header: t('serverAddr'),
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div className='flex gap-1'>
|
||||
<Badge variant='outline'>
|
||||
{row.original.country} - {row.original.city}
|
||||
</Badge>
|
||||
<Badge variant='outline'>{row.getValue('server_addr')}</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: t('status'),
|
||||
cell: ({ row }) => {
|
||||
return <NodeStatusCell status={row.original?.status} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'speed_limit',
|
||||
header: t('speedLimit'),
|
||||
cell: ({ row }) => (
|
||||
<Display type='trafficSpeed' value={row.getValue('speed_limit')} unlimited />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'traffic_ratio',
|
||||
header: t('trafficRatio'),
|
||||
cell: ({ row }) => <Badge variant='outline'>{row.getValue('traffic_ratio')} X</Badge>,
|
||||
},
|
||||
|
||||
{
|
||||
accessorKey: 'group_id',
|
||||
header: t('nodeGroup'),
|
||||
cell: ({ row }) => {
|
||||
const name = groups?.find((group) => group.id === row.getValue('group_id'))?.name;
|
||||
return name ? <Badge variant='outline'>{name}</Badge> : t('noData');
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'tags',
|
||||
header: t('tags'),
|
||||
cell: ({ row }) => {
|
||||
const tags = (row.getValue('tags') as string[]) || [];
|
||||
return tags.length > 0 ? (
|
||||
<div className='flex gap-1'>
|
||||
{tags.map((tag) => (
|
||||
<Badge key={tag} variant='outline'>
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
t('noData')
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
params={[
|
||||
{
|
||||
key: 'search',
|
||||
},
|
||||
{
|
||||
key: 'group_id',
|
||||
placeholder: t('nodeGroup'),
|
||||
options: groups?.map((item) => ({
|
||||
label: item.name,
|
||||
value: String(item.id),
|
||||
})),
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await getNodeList({
|
||||
...pagination,
|
||||
...filter,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<NodeForm<API.Server>
|
||||
key='edit'
|
||||
trigger={t('edit')}
|
||||
title={t('editNode')}
|
||||
loading={loading}
|
||||
initialValues={row}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateNode({ ...row, ...values } as API.UpdateNodeRequest);
|
||||
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 deleteNode({
|
||||
id: row.id,
|
||||
});
|
||||
toast.success(t('deleteSuccess'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
<Button
|
||||
key='copy'
|
||||
variant='outline'
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { id, sort, enable, updated_at, created_at, status, ...params } = row;
|
||||
await createNode({
|
||||
...params,
|
||||
enable: false,
|
||||
} as API.CreateNodeRequest);
|
||||
toast.success(t('copySuccess'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('copy')}
|
||||
</Button>,
|
||||
],
|
||||
batchRender(rows) {
|
||||
return [
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('delete')}</Button>}
|
||||
title={t('confirmDelete')}
|
||||
description={t('deleteWarning')}
|
||||
onConfirm={async () => {
|
||||
await batchDeleteNode({
|
||||
ids: rows.map((item) => item.id),
|
||||
});
|
||||
toast.success(t('deleteSuccess'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
onSort={async (source, target, items) => {
|
||||
const sourceIndex = items.findIndex((item) => String(item.id) === source);
|
||||
const targetIndex = items.findIndex((item) => String(item.id) === target);
|
||||
|
||||
const originalSorts = items.map((item) => item.sort);
|
||||
|
||||
const [movedItem] = items.splice(sourceIndex, 1);
|
||||
items.splice(targetIndex, 0, movedItem!);
|
||||
|
||||
const updatedItems = items.map((item, index) => {
|
||||
const originalSort = originalSorts[index];
|
||||
const newSort = originalSort !== undefined ? originalSort : item.sort;
|
||||
return { ...item, sort: newSort };
|
||||
});
|
||||
|
||||
const changedItems = updatedItems.filter((item, index) => {
|
||||
return item.sort !== items[index]?.sort;
|
||||
});
|
||||
|
||||
if (changedItems.length > 0) {
|
||||
nodeSort({
|
||||
sort: changedItems.map((item) => ({ id: item.id, sort: item.sort })),
|
||||
});
|
||||
}
|
||||
|
||||
return updatedItems;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { getTranslations } from 'next-intl/server';
|
||||
|
||||
import GroupTable from './group-table';
|
||||
import NodeConfig from './node-config';
|
||||
import NodeTable from './node-table';
|
||||
|
||||
export default async function Page() {
|
||||
const t = await getTranslations('server');
|
||||
|
||||
return (
|
||||
<Tabs defaultValue='node'>
|
||||
<TabsList>
|
||||
<TabsTrigger value='node'>{t('tabs.node')}</TabsTrigger>
|
||||
<TabsTrigger value='group'>{t('tabs.nodeGroup')}</TabsTrigger>
|
||||
<TabsTrigger value='config'>{t('tabs.nodeConfig')}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value='node'>
|
||||
<NodeTable />
|
||||
</TabsContent>
|
||||
<TabsContent value='group'>
|
||||
<GroupTable />
|
||||
</TabsContent>
|
||||
<TabsContent value='config'>
|
||||
<NodeConfig />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,928 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const protocols = [
|
||||
'shadowsocks',
|
||||
'vmess',
|
||||
'vless',
|
||||
'trojan',
|
||||
'hysteria2',
|
||||
'tuic',
|
||||
'anytls',
|
||||
'socks',
|
||||
'naive',
|
||||
'http',
|
||||
'meru',
|
||||
] as const;
|
||||
|
||||
export type FieldConfig = {
|
||||
name: string;
|
||||
type: 'input' | 'select' | 'switch' | 'number' | 'textarea';
|
||||
label: string;
|
||||
placeholder?: string | ((t: (key: string) => string, protocol: any) => string);
|
||||
options?: readonly string[];
|
||||
defaultValue?: any;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
suffix?: string;
|
||||
password?: number;
|
||||
condition?: (protocol: any, values: any) => boolean;
|
||||
group?: 'basic' | 'transport' | 'security' | 'reality' | 'plugin';
|
||||
gridSpan?: 1 | 2;
|
||||
};
|
||||
|
||||
// Global label map for display; fallback to raw value if missing
|
||||
export const LABELS = {
|
||||
// transport
|
||||
'tcp': 'TCP',
|
||||
'udp': 'UDP',
|
||||
'websocket': 'WebSocket',
|
||||
'grpc': 'gRPC',
|
||||
'mkcp': 'mKCP',
|
||||
'httpupgrade': 'HTTP Upgrade',
|
||||
'xhttp': 'XHTTP',
|
||||
// security
|
||||
'none': 'NONE',
|
||||
'tls': 'TLS',
|
||||
'reality': 'Reality',
|
||||
// fingerprint
|
||||
'chrome': 'Chrome',
|
||||
'firefox': 'Firefox',
|
||||
'safari': 'Safari',
|
||||
'ios': 'IOS',
|
||||
'android': 'Android',
|
||||
'edge': 'edge',
|
||||
'360': '360',
|
||||
'qq': 'QQ',
|
||||
// multiplex
|
||||
'off': 'Off',
|
||||
'low': 'Low',
|
||||
'middle': 'Middle',
|
||||
'high': 'High',
|
||||
// ss plugins
|
||||
'v2ray-plugin': 'V2Ray Plugin',
|
||||
'simple-obfs': 'Simple Obfs',
|
||||
} as const;
|
||||
|
||||
// Flat arrays for enum-like sets
|
||||
export const SS_CIPHERS = [
|
||||
'aes-128-gcm',
|
||||
'aes-192-gcm',
|
||||
'aes-256-gcm',
|
||||
'chacha20-ietf-poly1305',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
'2022-blake3-chacha20-poly1305',
|
||||
] as const;
|
||||
|
||||
export const SS_PLUGINS = ['none', 'simple-obfs', 'v2ray-plugin'] as const;
|
||||
|
||||
export const TRANSPORTS = {
|
||||
vmess: ['tcp', 'websocket', 'grpc'] as const,
|
||||
vless: ['tcp', 'websocket', 'grpc', 'mkcp', 'httpupgrade', 'xhttp'] as const,
|
||||
trojan: ['tcp', 'websocket', 'grpc'] as const,
|
||||
meru: ['tcp', 'udp'] as const,
|
||||
} as const;
|
||||
|
||||
export const SECURITY = {
|
||||
vmess: ['none', 'tls'] as const,
|
||||
vless: ['none', 'tls', 'reality'] as const,
|
||||
trojan: ['tls'] as const,
|
||||
hysteria2: ['tls'] as const,
|
||||
tuic: ['tls'] as const,
|
||||
anytls: ['tls'] as const,
|
||||
naive: ['none', 'tls'] as const,
|
||||
http: ['none', 'tls'] as const,
|
||||
} as const;
|
||||
|
||||
export const FLOWS = {
|
||||
vless: ['none', 'xtls-rprx-direct', 'xtls-rprx-splice', 'xtls-rprx-vision'] as const,
|
||||
} as const;
|
||||
|
||||
export const TUIC_UDP_RELAY_MODES = ['native', 'quic'] as const;
|
||||
export const TUIC_CONGESTION = ['bbr', 'cubic', 'new_reno'] as const;
|
||||
export const FINGERPRINTS = [
|
||||
'chrome',
|
||||
'firefox',
|
||||
'safari',
|
||||
'ios',
|
||||
'android',
|
||||
'edge',
|
||||
'360',
|
||||
'qq',
|
||||
] as const;
|
||||
|
||||
export const multiplexLevels = ['off', 'low', 'middle', 'high'] as const;
|
||||
|
||||
export function getLabel(value: string): string {
|
||||
const label = (LABELS as Record<string, string>)[value];
|
||||
return label ?? value.toUpperCase();
|
||||
}
|
||||
|
||||
const nullableString = z.string().nullish();
|
||||
const nullableBool = z.boolean().nullish();
|
||||
const nullablePort = z.number().int().min(0).max(65535).nullish();
|
||||
|
||||
const ss = z.object({
|
||||
type: z.literal('shadowsocks'),
|
||||
host: nullableString,
|
||||
port: nullablePort,
|
||||
cipher: z.enum(SS_CIPHERS as any).nullish(),
|
||||
server_key: nullableString,
|
||||
plugin: z.enum(SS_PLUGINS as any).nullish(),
|
||||
plugin_options: nullableString,
|
||||
});
|
||||
|
||||
const vmess = z.object({
|
||||
type: z.literal('vmess'),
|
||||
host: nullableString,
|
||||
port: nullablePort,
|
||||
transport: z.enum(TRANSPORTS.vmess as any).nullish(),
|
||||
security: z.enum(SECURITY.vmess as any).nullish(),
|
||||
path: nullableString,
|
||||
service_name: nullableString,
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
});
|
||||
|
||||
const vless = z.object({
|
||||
type: z.literal('vless'),
|
||||
host: nullableString,
|
||||
port: nullablePort,
|
||||
transport: z.enum(TRANSPORTS.vless as any).nullish(),
|
||||
security: z.enum(SECURITY.vless as any).nullish(),
|
||||
path: nullableString,
|
||||
service_name: nullableString,
|
||||
flow: z.enum(FLOWS.vless as any).nullish(),
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
reality_server_addr: nullableString,
|
||||
reality_server_port: nullablePort,
|
||||
reality_private_key: nullableString,
|
||||
reality_public_key: nullableString,
|
||||
reality_short_id: nullableString,
|
||||
});
|
||||
|
||||
const trojan = z.object({
|
||||
type: z.literal('trojan'),
|
||||
host: nullableString,
|
||||
port: nullablePort,
|
||||
transport: z.enum(TRANSPORTS.trojan as any).nullish(),
|
||||
security: z.enum(SECURITY.trojan as any).nullish(),
|
||||
path: nullableString,
|
||||
service_name: nullableString,
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
});
|
||||
|
||||
const hysteria2 = z.object({
|
||||
type: z.literal('hysteria2'),
|
||||
hop_ports: nullableString,
|
||||
hop_interval: z.number().nullish(),
|
||||
obfs_password: nullableString,
|
||||
port: nullablePort,
|
||||
security: z.enum(SECURITY.hysteria2 as any).nullish(),
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
up_mbps: z.number().nullish(),
|
||||
down_mbps: z.number().nullish(),
|
||||
});
|
||||
|
||||
const tuic = z.object({
|
||||
type: z.literal('tuic'),
|
||||
host: nullableString,
|
||||
port: nullablePort,
|
||||
disable_sni: z.boolean().nullish(),
|
||||
reduce_rtt: z.boolean().nullish(),
|
||||
udp_relay_mode: z.enum(TUIC_UDP_RELAY_MODES as any).nullish(),
|
||||
congestion_controller: z.enum(TUIC_CONGESTION as any).nullish(),
|
||||
security: z.enum(SECURITY.tuic as any).nullish(),
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
});
|
||||
|
||||
const anytls = z.object({
|
||||
type: z.literal('anytls'),
|
||||
port: nullablePort,
|
||||
security: z.enum(SECURITY.anytls as any).nullish(),
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
padding_scheme: nullableString,
|
||||
});
|
||||
|
||||
const socks = z.object({
|
||||
type: z.literal('socks'),
|
||||
port: nullablePort,
|
||||
});
|
||||
|
||||
const naive = z.object({
|
||||
type: z.literal('naive'),
|
||||
port: nullablePort,
|
||||
security: z.enum(SECURITY.naive as any).nullish(),
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
});
|
||||
|
||||
const http = z.object({
|
||||
type: z.literal('http'),
|
||||
port: nullablePort,
|
||||
security: z.enum(SECURITY.http as any).nullish(),
|
||||
sni: nullableString,
|
||||
allow_insecure: nullableBool,
|
||||
fingerprint: nullableString,
|
||||
});
|
||||
|
||||
const meru = z.object({
|
||||
type: z.literal('meru'),
|
||||
port: nullablePort,
|
||||
multiplex: z.enum(multiplexLevels).nullish(),
|
||||
transport: z.enum(TRANSPORTS.meru as any).nullish(),
|
||||
});
|
||||
|
||||
export const protocolApiScheme = z.discriminatedUnion('type', [
|
||||
ss,
|
||||
vmess,
|
||||
vless,
|
||||
trojan,
|
||||
hysteria2,
|
||||
tuic,
|
||||
anytls,
|
||||
socks,
|
||||
naive,
|
||||
http,
|
||||
meru,
|
||||
]);
|
||||
|
||||
export const formSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
address: z.string().min(1),
|
||||
country: z.string().optional(),
|
||||
city: z.string().optional(),
|
||||
ratio: z.number().default(1),
|
||||
protocols: z.array(protocolApiScheme),
|
||||
});
|
||||
|
||||
export type ServerFormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export type ProtocolType = (typeof protocols)[number];
|
||||
|
||||
export function getProtocolDefaultConfig(proto: ProtocolType) {
|
||||
switch (proto) {
|
||||
case 'shadowsocks':
|
||||
return {
|
||||
type: 'shadowsocks',
|
||||
port: null,
|
||||
cipher: 'chacha20-ietf-poly1305',
|
||||
server_key: null,
|
||||
plugin: 'none',
|
||||
plugin_opts: null,
|
||||
} as any;
|
||||
case 'vmess':
|
||||
return { type: 'vmess', port: null, transport: 'tcp', security: 'none' } as any;
|
||||
case 'vless':
|
||||
return { type: 'vless', port: null, transport: 'tcp', security: 'none', flow: 'none' } as any;
|
||||
case 'trojan':
|
||||
return { type: 'trojan', port: null, transport: 'tcp', security: 'tls' } as any;
|
||||
case 'hysteria2':
|
||||
return {
|
||||
type: 'hysteria2',
|
||||
port: null,
|
||||
hop_ports: null,
|
||||
hop_interval: null,
|
||||
obfs_password: null,
|
||||
security: 'tls',
|
||||
up_mbps: null,
|
||||
down_mbps: null,
|
||||
} as any;
|
||||
case 'tuic':
|
||||
return {
|
||||
type: 'tuic',
|
||||
port: null,
|
||||
disable_sni: false,
|
||||
reduce_rtt: false,
|
||||
udp_relay_mode: 'native',
|
||||
congestion_controller: 'bbr',
|
||||
security: 'tls',
|
||||
sni: null,
|
||||
allow_insecure: false,
|
||||
fingerprint: 'chrome',
|
||||
} as any;
|
||||
case 'socks':
|
||||
return {
|
||||
type: 'socks',
|
||||
port: null,
|
||||
} as any;
|
||||
case 'naive':
|
||||
return {
|
||||
type: 'naive',
|
||||
port: null,
|
||||
security: 'none',
|
||||
} as any;
|
||||
case 'http':
|
||||
return {
|
||||
type: 'http',
|
||||
port: null,
|
||||
security: 'none',
|
||||
} as any;
|
||||
case 'meru':
|
||||
return {
|
||||
type: 'meru',
|
||||
port: null,
|
||||
multiplex: 'off',
|
||||
transport: 'tcp',
|
||||
} as any;
|
||||
case 'anytls':
|
||||
return {
|
||||
type: 'anytls',
|
||||
port: null,
|
||||
security: 'tls',
|
||||
padding_scheme: null,
|
||||
sni: null,
|
||||
allow_insecure: false,
|
||||
fingerprint: 'chrome',
|
||||
} as any;
|
||||
default:
|
||||
return {} as any;
|
||||
}
|
||||
}
|
||||
|
||||
export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
|
||||
shadowsocks: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'cipher',
|
||||
type: 'select',
|
||||
label: 'encryption_method',
|
||||
options: SS_CIPHERS,
|
||||
defaultValue: 'chacha20-ietf-poly1305',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'server_key',
|
||||
type: 'input',
|
||||
label: 'server_key',
|
||||
password: 32,
|
||||
group: 'basic',
|
||||
condition: (p) =>
|
||||
[
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
'2022-blake3-chacha20-poly1305',
|
||||
].includes(p.cipher),
|
||||
},
|
||||
{
|
||||
name: 'plugin',
|
||||
type: 'select',
|
||||
label: 'plugin',
|
||||
options: SS_PLUGINS,
|
||||
defaultValue: 'none',
|
||||
group: 'plugin',
|
||||
},
|
||||
{
|
||||
name: 'plugin_opts',
|
||||
type: 'textarea',
|
||||
label: 'plugin_opts',
|
||||
placeholder: (t: (key: string) => string, p: any) => {
|
||||
switch (p.plugin) {
|
||||
case 'simple-obfs':
|
||||
return 'obfs=http;obfs-host=www.bing.com;path=/';
|
||||
case 'v2ray-plugin':
|
||||
return 'WebSocket: mode=websocket;host=mydomain.me;path=/;tls=true\n\nQUIC: mode=quic;host=mydomain.me';
|
||||
default:
|
||||
return 'key=value;key2=value2';
|
||||
}
|
||||
},
|
||||
group: 'plugin',
|
||||
condition: (p) => ['simple-obfs', 'v2ray-plugin'].includes(p.plugin),
|
||||
},
|
||||
],
|
||||
vmess: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'transport',
|
||||
type: 'select',
|
||||
label: 'transport',
|
||||
options: TRANSPORTS.vmess,
|
||||
defaultValue: 'tcp',
|
||||
group: 'transport',
|
||||
},
|
||||
{
|
||||
name: 'security',
|
||||
type: 'select',
|
||||
label: 'security',
|
||||
options: SECURITY.vmess,
|
||||
defaultValue: 'none',
|
||||
group: 'security',
|
||||
},
|
||||
{
|
||||
name: 'host',
|
||||
type: 'input',
|
||||
label: 'host',
|
||||
group: 'transport',
|
||||
condition: (p) => ['websocket', 'xhttp', 'httpupgrade'].includes(p.transport),
|
||||
},
|
||||
{
|
||||
name: 'path',
|
||||
type: 'input',
|
||||
label: 'path',
|
||||
group: 'transport',
|
||||
condition: (p) => ['websocket', 'xhttp', 'httpupgrade'].includes(p.transport),
|
||||
},
|
||||
{
|
||||
name: 'service_name',
|
||||
type: 'input',
|
||||
label: 'service_name',
|
||||
group: 'transport',
|
||||
condition: (p) => p.transport === 'grpc',
|
||||
},
|
||||
{
|
||||
name: 'sni',
|
||||
type: 'input',
|
||||
label: 'security_sni',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'allow_insecure',
|
||||
type: 'switch',
|
||||
label: 'security_allow_insecure',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
],
|
||||
vless: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'flow',
|
||||
type: 'select',
|
||||
label: 'flow',
|
||||
options: FLOWS.vless,
|
||||
defaultValue: 'none',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'transport',
|
||||
type: 'select',
|
||||
label: 'transport',
|
||||
options: TRANSPORTS.vless,
|
||||
defaultValue: 'tcp',
|
||||
group: 'transport',
|
||||
},
|
||||
{
|
||||
name: 'security',
|
||||
type: 'select',
|
||||
label: 'security',
|
||||
options: SECURITY.vless,
|
||||
defaultValue: 'none',
|
||||
group: 'security',
|
||||
},
|
||||
{
|
||||
name: 'host',
|
||||
type: 'input',
|
||||
label: 'host',
|
||||
group: 'transport',
|
||||
condition: (p) => ['websocket', 'mkcp', 'httpupgrade', 'xhttp'].includes(p.transport),
|
||||
},
|
||||
{
|
||||
name: 'path',
|
||||
type: 'input',
|
||||
label: 'path',
|
||||
group: 'transport',
|
||||
condition: (p) => ['websocket', 'mkcp', 'httpupgrade', 'xhttp'].includes(p.transport),
|
||||
},
|
||||
{
|
||||
name: 'service_name',
|
||||
type: 'input',
|
||||
label: 'service_name',
|
||||
group: 'transport',
|
||||
condition: (p) => p.transport === 'grpc',
|
||||
},
|
||||
{
|
||||
name: 'sni',
|
||||
type: 'input',
|
||||
label: 'security_sni',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'allow_insecure',
|
||||
type: 'switch',
|
||||
label: 'security_allow_insecure',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'reality_server_addr',
|
||||
type: 'input',
|
||||
label: 'security_server_address',
|
||||
placeholder: (t) => t('security_server_address_placeholder'),
|
||||
group: 'reality',
|
||||
condition: (p) => p.security === 'reality',
|
||||
},
|
||||
{
|
||||
name: 'reality_server_port',
|
||||
type: 'number',
|
||||
label: 'security_server_port',
|
||||
min: 1,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'reality',
|
||||
condition: (p) => p.security === 'reality',
|
||||
},
|
||||
{
|
||||
name: 'reality_private_key',
|
||||
type: 'input',
|
||||
label: 'security_private_key',
|
||||
placeholder: (t) => t('security_private_key_placeholder'),
|
||||
group: 'reality',
|
||||
condition: (p) => p.security === 'reality',
|
||||
},
|
||||
{
|
||||
name: 'reality_public_key',
|
||||
type: 'input',
|
||||
label: 'security_public_key',
|
||||
placeholder: (t) => t('security_public_key_placeholder'),
|
||||
group: 'reality',
|
||||
condition: (p) => p.security === 'reality',
|
||||
},
|
||||
{
|
||||
name: 'reality_short_id',
|
||||
type: 'input',
|
||||
label: 'security_short_id',
|
||||
group: 'reality',
|
||||
condition: (p) => p.security === 'reality',
|
||||
},
|
||||
],
|
||||
trojan: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'transport',
|
||||
type: 'select',
|
||||
label: 'transport',
|
||||
options: TRANSPORTS.trojan,
|
||||
defaultValue: 'tcp',
|
||||
group: 'transport',
|
||||
},
|
||||
{
|
||||
name: 'security',
|
||||
type: 'select',
|
||||
label: 'security',
|
||||
options: SECURITY.trojan,
|
||||
defaultValue: 'tls',
|
||||
group: 'security',
|
||||
},
|
||||
{
|
||||
name: 'host',
|
||||
type: 'input',
|
||||
label: 'host',
|
||||
group: 'transport',
|
||||
condition: (p) => ['websocket', 'xhttp', 'httpupgrade'].includes(p.transport),
|
||||
},
|
||||
{
|
||||
name: 'path',
|
||||
type: 'input',
|
||||
label: 'path',
|
||||
group: 'transport',
|
||||
condition: (p) => ['websocket', 'xhttp', 'httpupgrade'].includes(p.transport),
|
||||
},
|
||||
{
|
||||
name: 'service_name',
|
||||
type: 'input',
|
||||
label: 'service_name',
|
||||
group: 'transport',
|
||||
condition: (p) => p.transport === 'grpc',
|
||||
},
|
||||
{
|
||||
name: 'sni',
|
||||
type: 'input',
|
||||
label: 'security_sni',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'allow_insecure',
|
||||
type: 'switch',
|
||||
label: 'security_allow_insecure',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
],
|
||||
hysteria2: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'hop_ports',
|
||||
type: 'input',
|
||||
label: 'hop_ports',
|
||||
placeholder: (t) => t('hop_ports_placeholder'),
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'hop_interval',
|
||||
type: 'number',
|
||||
label: 'hop_interval',
|
||||
placeholder: 'e.g. 300',
|
||||
min: 0,
|
||||
suffix: 'S',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'obfs_password',
|
||||
type: 'input',
|
||||
label: 'obfs_password',
|
||||
placeholder: (t) => t('obfs_password_placeholder'),
|
||||
password: 16,
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'up_mbps',
|
||||
type: 'number',
|
||||
label: 'up_mbps',
|
||||
min: 0,
|
||||
placeholder: (t) => t('bandwidth_placeholder'),
|
||||
suffix: 'Mbps',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'down_mbps',
|
||||
type: 'number',
|
||||
label: 'down_mbps',
|
||||
min: 0,
|
||||
placeholder: (t) => t('bandwidth_placeholder'),
|
||||
suffix: 'Mbps',
|
||||
group: 'basic',
|
||||
},
|
||||
{ name: 'sni', type: 'input', label: 'security_sni', group: 'security' },
|
||||
{ name: 'allow_insecure', type: 'switch', label: 'security_allow_insecure', group: 'security' },
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
},
|
||||
],
|
||||
tuic: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'udp_relay_mode',
|
||||
type: 'select',
|
||||
label: 'udp_relay_mode',
|
||||
options: TUIC_UDP_RELAY_MODES,
|
||||
defaultValue: 'native',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'congestion_controller',
|
||||
type: 'select',
|
||||
label: 'congestion_controller',
|
||||
options: TUIC_CONGESTION,
|
||||
defaultValue: 'bbr',
|
||||
group: 'basic',
|
||||
},
|
||||
{ name: 'disable_sni', type: 'switch', label: 'disable_sni', group: 'basic' },
|
||||
{ name: 'reduce_rtt', type: 'switch', label: 'reduce_rtt', group: 'basic' },
|
||||
{ name: 'sni', type: 'input', label: 'security_sni', group: 'security' },
|
||||
{ name: 'allow_insecure', type: 'switch', label: 'security_allow_insecure', group: 'security' },
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
},
|
||||
],
|
||||
socks: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
],
|
||||
naive: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'security',
|
||||
type: 'select',
|
||||
label: 'security',
|
||||
options: SECURITY.naive,
|
||||
defaultValue: 'none',
|
||||
group: 'security',
|
||||
},
|
||||
{
|
||||
name: 'sni',
|
||||
type: 'input',
|
||||
label: 'security_sni',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'allow_insecure',
|
||||
type: 'switch',
|
||||
label: 'security_allow_insecure',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
],
|
||||
http: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'security',
|
||||
type: 'select',
|
||||
label: 'security',
|
||||
options: SECURITY.http,
|
||||
defaultValue: 'none',
|
||||
group: 'security',
|
||||
},
|
||||
{
|
||||
name: 'sni',
|
||||
type: 'input',
|
||||
label: 'security_sni',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'allow_insecure',
|
||||
type: 'switch',
|
||||
label: 'security_allow_insecure',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
condition: (p) => p.security !== 'none',
|
||||
},
|
||||
],
|
||||
meru: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'multiplex',
|
||||
type: 'select',
|
||||
label: 'multiplex',
|
||||
options: multiplexLevels,
|
||||
defaultValue: 'off',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'transport',
|
||||
type: 'select',
|
||||
label: 'transport',
|
||||
options: TRANSPORTS.meru,
|
||||
defaultValue: 'tcp',
|
||||
group: 'transport',
|
||||
},
|
||||
],
|
||||
anytls: [
|
||||
{
|
||||
name: 'port',
|
||||
type: 'number',
|
||||
label: 'port',
|
||||
min: 0,
|
||||
max: 65535,
|
||||
placeholder: '1-65535',
|
||||
group: 'basic',
|
||||
},
|
||||
{
|
||||
name: 'padding_scheme',
|
||||
type: 'textarea',
|
||||
label: 'padding_scheme',
|
||||
placeholder: (t: (key: string) => string) => t('padding_scheme_placeholder'),
|
||||
group: 'basic',
|
||||
},
|
||||
{ name: 'sni', type: 'input', label: 'security_sni', group: 'security' },
|
||||
{ name: 'allow_insecure', type: 'switch', label: 'security_allow_insecure', group: 'security' },
|
||||
{
|
||||
name: 'fingerprint',
|
||||
type: 'select',
|
||||
label: 'security_fingerprint',
|
||||
options: FINGERPRINTS,
|
||||
defaultValue: 'chrome',
|
||||
group: 'security',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
'use client';
|
||||
|
||||
import { UserDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { IpLink } from '@/components/ip-link';
|
||||
import { ProTable } from '@/components/pro-table';
|
||||
import { getUserSubscribeById } from '@/services/admin/user';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { formatBytes } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
|
||||
function UserSubscribeInfo({
|
||||
subscribeId,
|
||||
open,
|
||||
type,
|
||||
}: {
|
||||
subscribeId: number;
|
||||
open: boolean;
|
||||
type: 'account' | 'subscribeName' | 'subscribeId' | 'trafficUsage' | 'expireTime';
|
||||
}) {
|
||||
const t = useTranslations('servers');
|
||||
const { data } = useQuery({
|
||||
enabled: subscribeId !== 0 && open,
|
||||
queryKey: ['getUserSubscribeById', subscribeId],
|
||||
queryFn: async () => {
|
||||
const { data } = await getUserSubscribeById({ id: subscribeId });
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) return <span className='text-muted-foreground'>--</span>;
|
||||
|
||||
switch (type) {
|
||||
case 'account':
|
||||
if (!data.user_id) return <span className='text-muted-foreground'>--</span>;
|
||||
return <UserDetail id={data.user_id} />;
|
||||
|
||||
case 'subscribeName':
|
||||
if (!data.subscribe?.name) return <span className='text-muted-foreground'>--</span>;
|
||||
return <span className='text-sm'>{data.subscribe.name}</span>;
|
||||
|
||||
case 'subscribeId':
|
||||
if (!data.id) return <span className='text-muted-foreground'>--</span>;
|
||||
return <span className='font-mono text-sm'>{data.id}</span>;
|
||||
|
||||
case 'trafficUsage': {
|
||||
const usedTraffic = data.upload + data.download;
|
||||
const totalTraffic = data.traffic || 0;
|
||||
return (
|
||||
<div className='min-w-0 text-sm'>
|
||||
<div className='break-words'>
|
||||
{formatBytes(usedTraffic)} / {totalTraffic > 0 ? formatBytes(totalTraffic) : '无限制'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
case 'expireTime': {
|
||||
if (!data.expire_time) return <span className='text-muted-foreground'>--</span>;
|
||||
const isExpired = data.expire_time < Date.now() / 1000;
|
||||
return (
|
||||
<div className='flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2'>
|
||||
<span className='text-sm'>{formatDate(data.expire_time)}</span>
|
||||
{isExpired && (
|
||||
<Badge variant='destructive' className='w-fit px-1 py-0 text-xs'>
|
||||
{t('expired')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
default:
|
||||
return <span className='text-muted-foreground'>--</span>;
|
||||
}
|
||||
}
|
||||
|
||||
export default function OnlineUsersCell({ status }: { status?: API.ServerStatus }) {
|
||||
const t = useTranslations('servers');
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<button className='hover:text-foreground text-muted-foreground flex items-center gap-2 bg-transparent p-0 text-sm'>
|
||||
<Badge variant='secondary'>{status?.online.length}</Badge>
|
||||
<span>{t('onlineUsers')}</span>
|
||||
</button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='h-screen w-screen max-w-none sm:h-auto sm:w-[900px] sm:max-w-[90vw]'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('onlineUsers')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className='-mx-6 h-[calc(100vh-48px-16px)] overflow-y-auto px-6 py-4 sm:h-[calc(100dvh-48px-16px-env(safe-area-inset-top))]'>
|
||||
<ProTable<API.ServerOnlineUser, Record<string, unknown>>
|
||||
header={{ hidden: true }}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'ip',
|
||||
header: t('ipAddresses'),
|
||||
cell: ({ row }) => {
|
||||
const ips = row.original.ip;
|
||||
return (
|
||||
<div className='flex min-w-0 flex-col gap-1'>
|
||||
{ips.map((item, i) => (
|
||||
<div className='whitespace-nowrap text-sm' key={i}>
|
||||
<Badge>{item.protocol}</Badge>
|
||||
<IpLink ip={item.ip} className='ml-1 font-medium' />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('user'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo
|
||||
subscribeId={Number(row.original.subscribe_id)}
|
||||
open={open}
|
||||
type='account'
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscription',
|
||||
header: t('subscription'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo
|
||||
subscribeId={Number(row.original.subscribe_id)}
|
||||
open={open}
|
||||
type='subscribeName'
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscribeId',
|
||||
header: t('subscribeId'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo
|
||||
subscribeId={Number(row.original.subscribe_id)}
|
||||
open={open}
|
||||
type='subscribeId'
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'traffic',
|
||||
header: t('traffic'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo
|
||||
subscribeId={Number(row.original.subscribe_id)}
|
||||
open={open}
|
||||
type='trafficUsage'
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'expireTime',
|
||||
header: t('expireTime'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo
|
||||
subscribeId={Number(row.original.subscribe_id)}
|
||||
open={open}
|
||||
type='expireTime'
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
request={async () => ({
|
||||
list: status?.online || [],
|
||||
total: status?.online?.length || 0,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
'use client';
|
||||
// Online users detail moved to separate component
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
createServer,
|
||||
deleteServer,
|
||||
filterServerList,
|
||||
hasMigrateSeverNode,
|
||||
migrateServerNode,
|
||||
resetSortWithServer,
|
||||
updateServer,
|
||||
} from '@/services/admin/server';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Card, CardContent } from '@workspace/ui/components/card';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import OnlineUsersCell from './online-users-cell';
|
||||
import ServerConfig from './server-config';
|
||||
import ServerForm from './server-form';
|
||||
|
||||
type ProtocolName = 'shadowsocks' | 'vmess' | 'vless' | 'trojan' | 'hysteria2' | 'tuic' | 'anytls';
|
||||
|
||||
const PROTOCOL_COLORS: Record<ProtocolName, string> = {
|
||||
shadowsocks: 'bg-green-500',
|
||||
vmess: 'bg-rose-500',
|
||||
vless: 'bg-blue-500',
|
||||
trojan: 'bg-yellow-500',
|
||||
hysteria2: 'bg-purple-500',
|
||||
tuic: 'bg-cyan-500',
|
||||
anytls: 'bg-gray-500',
|
||||
};
|
||||
|
||||
function PctBar({ value }: { value: number }) {
|
||||
const v = value.toFixed(2);
|
||||
return (
|
||||
<div className='min-w-24'>
|
||||
<div className='text-xs leading-none'>{v}%</div>
|
||||
<div className='bg-muted h-1.5 w-full rounded'>
|
||||
<div className='bg-primary h-1.5 rounded' style={{ width: `${v}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RegionIpCell({
|
||||
country,
|
||||
city,
|
||||
ip,
|
||||
t,
|
||||
}: {
|
||||
country?: string;
|
||||
city?: string;
|
||||
ip?: string;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const region = [country, city].filter(Boolean).join(' / ') || t('notAvailable');
|
||||
return (
|
||||
<div className='flex items-center gap-1'>
|
||||
<Badge variant='outline'>{region}</Badge>
|
||||
<Badge variant='outline'>{ip || t('notAvailable')}</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServersPage() {
|
||||
const t = useTranslations('servers');
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [migrating, setMigrating] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
const { data: hasMigrate, refetch: refetchHasMigrate } = useQuery({
|
||||
queryKey: ['hasMigrateSeverNode'],
|
||||
queryFn: async () => {
|
||||
const { data } = await hasMigrateSeverNode();
|
||||
return data.data?.has_migrate;
|
||||
},
|
||||
});
|
||||
|
||||
const handleMigrate = async () => {
|
||||
setMigrating(true);
|
||||
try {
|
||||
const { data } = await migrateServerNode();
|
||||
const fail = data.data?.fail || 0;
|
||||
if (fail > 0) {
|
||||
toast.error(data.data?.message);
|
||||
} else {
|
||||
toast.success(t('migrated'));
|
||||
}
|
||||
refetchHasMigrate();
|
||||
ref.current?.refresh();
|
||||
} catch (error) {
|
||||
toast.error(t('migrateFailed'));
|
||||
} finally {
|
||||
setMigrating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='space-y-4'>
|
||||
<Card>
|
||||
<CardContent className='p-4'>
|
||||
<ServerConfig />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ProTable<API.Server, { search: string }>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t('pageTitle'),
|
||||
toolbar: (
|
||||
<div className='flex gap-2'>
|
||||
{hasMigrate && (
|
||||
<Button variant='outline' onClick={handleMigrate} disabled={migrating}>
|
||||
{migrating ? t('migrating') : t('migrate')}
|
||||
</Button>
|
||||
)}
|
||||
<ServerForm
|
||||
trigger={t('create')}
|
||||
title={t('drawerCreateTitle')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createServer(values as unknown as API.CreateServerRequest);
|
||||
toast.success(t('created'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (e) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: t('id'),
|
||||
cell: ({ row }) => <Badge>{row.getValue('id')}</Badge>,
|
||||
},
|
||||
{ accessorKey: 'name', header: t('name') },
|
||||
{
|
||||
id: 'region_ip',
|
||||
header: t('address'),
|
||||
cell: ({ row }) => (
|
||||
<RegionIpCell
|
||||
country={row.original.country as unknown as string}
|
||||
city={row.original.city as unknown as string}
|
||||
ip={row.original.address as unknown as string}
|
||||
t={t}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'protocols',
|
||||
header: t('protocols'),
|
||||
cell: ({ row }) => {
|
||||
const list = (row.original.protocols || []) as API.Protocol[];
|
||||
if (!list.length) return t('noData');
|
||||
return (
|
||||
<div className='flex flex-wrap gap-1'>
|
||||
{list.map((p, idx) => {
|
||||
const proto = ((p as any)?.type || '') as ProtocolName | '';
|
||||
if (!proto) return null;
|
||||
const color = PROTOCOL_COLORS[proto as ProtocolName];
|
||||
const port = (p as any)?.port as number | undefined;
|
||||
const label = `${proto}${port ? ` (${port})` : ''}`;
|
||||
return (
|
||||
<Badge
|
||||
key={idx}
|
||||
variant='outline'
|
||||
className={cn('text-primary-foreground', color)}
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
id: 'status',
|
||||
header: t('status'),
|
||||
cell: ({ row }) => {
|
||||
const offline = row.original.status.status === 'offline';
|
||||
return (
|
||||
<div className='flex items-center gap-2'>
|
||||
<span
|
||||
className={cn(
|
||||
'inline-block h-2.5 w-2.5 rounded-full',
|
||||
offline ? 'bg-zinc-400' : 'bg-emerald-500',
|
||||
)}
|
||||
/>
|
||||
<span className='text-sm'>{offline ? t('offline') : t('online')}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'cpu',
|
||||
header: t('cpu'),
|
||||
cell: ({ row }) => (
|
||||
<PctBar value={(row.original.status?.cpu as unknown as number) ?? 0} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'mem',
|
||||
header: t('memory'),
|
||||
cell: ({ row }) => (
|
||||
<PctBar value={(row.original.status?.mem as unknown as number) ?? 0} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'disk',
|
||||
header: t('disk'),
|
||||
cell: ({ row }) => (
|
||||
<PctBar value={(row.original.status?.disk as unknown as number) ?? 0} />
|
||||
),
|
||||
},
|
||||
|
||||
{
|
||||
id: 'online_users',
|
||||
header: t('onlineUsers'),
|
||||
cell: ({ row }) => <OnlineUsersCell status={row.original.status as API.ServerStatus} />,
|
||||
},
|
||||
{
|
||||
id: 'traffic_ratio',
|
||||
header: t('traffic_ratio'),
|
||||
cell: ({ row }) => {
|
||||
const raw = row.original.ratio as unknown;
|
||||
const ratio = Number(raw ?? 1) || 1;
|
||||
return <span className='text-sm'>{ratio.toFixed(2)}x</span>;
|
||||
},
|
||||
},
|
||||
]}
|
||||
params={[{ key: 'search' }]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await filterServerList({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
search: filter?.search || undefined,
|
||||
});
|
||||
const list = (data?.data?.list || []) as API.Server[];
|
||||
const total = (data?.data?.total ?? list.length) as number;
|
||||
return { list, total };
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<ServerForm
|
||||
key='edit'
|
||||
trigger={t('edit')}
|
||||
title={t('drawerEditTitle')}
|
||||
initialValues={row as any}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// ServerForm already returns API-shaped body; add id for update
|
||||
await updateServer({
|
||||
id: row.id,
|
||||
...(values as unknown as Omit<API.UpdateServerRequest, 'id'>),
|
||||
});
|
||||
toast.success(t('updated'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (e) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('delete')}</Button>}
|
||||
title={t('confirmDeleteTitle')}
|
||||
description={t('confirmDeleteDesc')}
|
||||
onConfirm={async () => {
|
||||
await deleteServer({ id: row.id } as any);
|
||||
toast.success(t('deleted'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
<Button
|
||||
key='copy'
|
||||
variant='outline'
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
const { id, created_at, updated_at, last_reported_at, status, ...others } =
|
||||
row as any;
|
||||
const body: API.CreateServerRequest = {
|
||||
name: others.name,
|
||||
country: others.country,
|
||||
city: others.city,
|
||||
ratio: others.ratio,
|
||||
address: others.address,
|
||||
protocols: others.protocols || [],
|
||||
};
|
||||
await createServer(body);
|
||||
toast.success(t('copied'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
}}
|
||||
>
|
||||
{t('copy')}
|
||||
</Button>,
|
||||
],
|
||||
batchRender(rows) {
|
||||
return [
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('delete')}</Button>}
|
||||
title={t('confirmDeleteTitle')}
|
||||
description={t('confirmDeleteDesc')}
|
||||
onConfirm={async () => {
|
||||
await Promise.all(rows.map((r) => deleteServer({ id: r.id })));
|
||||
toast.success(t('deleted'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
onSort={async (source, target, items) => {
|
||||
const sourceIndex = items.findIndex((item) => String(item.id) === source);
|
||||
const targetIndex = items.findIndex((item) => String(item.id) === target);
|
||||
|
||||
const originalSorts = items.map((item) => item.sort);
|
||||
|
||||
const [movedItem] = items.splice(sourceIndex, 1);
|
||||
items.splice(targetIndex, 0, movedItem!);
|
||||
|
||||
const updatedItems = items.map((item, index) => {
|
||||
const originalSort = originalSorts[index];
|
||||
const newSort = originalSort !== undefined ? originalSort : item.sort;
|
||||
return { ...item, sort: newSort };
|
||||
});
|
||||
|
||||
const changedItems = updatedItems.filter((item, index) => {
|
||||
return item.sort !== items[index]?.sort;
|
||||
});
|
||||
|
||||
if (changedItems.length > 0) {
|
||||
resetSortWithServer({
|
||||
sort: changedItems.map((item) => ({
|
||||
id: item.id,
|
||||
sort: item.sort,
|
||||
})) as API.SortItem[],
|
||||
});
|
||||
}
|
||||
return updatedItems;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getNodeConfig,
|
||||
getNodeMultiplier,
|
||||
setNodeMultiplier,
|
||||
updateNodeConfig,
|
||||
} from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { ChartContainer, ChartTooltip } from '@workspace/ui/components/chart';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { DicesIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Cell, Legend, Pie, PieChart } from 'recharts';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const COLORS = [
|
||||
'hsl(var(--chart-1))',
|
||||
'hsl(var(--chart-2))',
|
||||
'hsl(var(--chart-3))',
|
||||
'hsl(var(--chart-4))',
|
||||
'hsl(var(--chart-5))',
|
||||
];
|
||||
|
||||
const MINUTES_IN_DAY = 1440;
|
||||
|
||||
function getTimeRangeData(slots: API.TimePeriod[]) {
|
||||
const timePoints = slots
|
||||
.filter((slot) => slot.start_time && slot.end_time)
|
||||
.flatMap((slot) => {
|
||||
const [startH = 0, startM = 0] = slot.start_time.split(':').map(Number);
|
||||
const [endH = 0, endM = 0] = slot.end_time.split(':').map(Number);
|
||||
const start = startH * 60 + startM;
|
||||
let end = endH * 60 + endM;
|
||||
if (end < start) end += MINUTES_IN_DAY;
|
||||
return { start, end, multiplier: slot.multiplier };
|
||||
})
|
||||
.sort((a, b) => a.start - b.start);
|
||||
|
||||
const result: { name: string; value: number; multiplier: number }[] = [];
|
||||
let currentMinute = 0;
|
||||
|
||||
timePoints.forEach((point) => {
|
||||
if (point.start > currentMinute) {
|
||||
result.push({
|
||||
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - ${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')}`,
|
||||
value: point.start - currentMinute,
|
||||
multiplier: 1,
|
||||
});
|
||||
}
|
||||
result.push({
|
||||
name: `${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')} - ${Math.floor((point.end / 60) % 24)}:${String(point.end % 60).padStart(2, '0')}`,
|
||||
value: point.end - point.start,
|
||||
multiplier: point.multiplier,
|
||||
});
|
||||
currentMinute = point.end % MINUTES_IN_DAY;
|
||||
});
|
||||
|
||||
if (currentMinute < MINUTES_IN_DAY) {
|
||||
result.push({
|
||||
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - 24:00`,
|
||||
value: MINUTES_IN_DAY - currentMinute,
|
||||
multiplier: 1,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const nodeConfigSchema = z.object({
|
||||
node_secret: z.string().optional(),
|
||||
node_pull_interval: z.number().optional(),
|
||||
node_push_interval: z.number().optional(),
|
||||
});
|
||||
type NodeConfigFormData = z.infer<typeof nodeConfigSchema>;
|
||||
|
||||
export default function ServerConfig() {
|
||||
const t = useTranslations('servers');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [timeSlots, setTimeSlots] = useState<API.TimePeriod[]>([]);
|
||||
|
||||
const { data: cfgResp, refetch: refetchCfg } = useQuery({
|
||||
queryKey: ['getNodeConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeConfig();
|
||||
return data.data as API.NodeConfig | undefined;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const { data: periodsResp, refetch: refetchPeriods } = useQuery({
|
||||
queryKey: ['getNodeMultiplier'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeMultiplier();
|
||||
return (data.data?.periods || []) as API.TimePeriod[];
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<NodeConfigFormData>({
|
||||
resolver: zodResolver(nodeConfigSchema),
|
||||
defaultValues: {
|
||||
node_secret: '',
|
||||
node_pull_interval: undefined,
|
||||
node_push_interval: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (cfgResp) {
|
||||
form.reset({
|
||||
node_secret: cfgResp.node_secret ?? '',
|
||||
node_pull_interval: cfgResp.node_pull_interval as number | undefined,
|
||||
node_push_interval: cfgResp.node_push_interval as number | undefined,
|
||||
});
|
||||
}
|
||||
}, [cfgResp, form]);
|
||||
|
||||
useEffect(() => {
|
||||
if (periodsResp) {
|
||||
setTimeSlots(periodsResp);
|
||||
}
|
||||
}, [periodsResp]);
|
||||
|
||||
const chartTimeSlots = useMemo(() => getTimeRangeData(timeSlots), [timeSlots]);
|
||||
const chartConfig = useMemo(() => {
|
||||
return chartTimeSlots.reduce(
|
||||
(acc, item, index) => {
|
||||
acc[item.name] = {
|
||||
label: item.name,
|
||||
color: COLORS[index % COLORS.length] || 'hsl(var(--default-chart-color))',
|
||||
};
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, { label: string; color: string }>,
|
||||
);
|
||||
}, [chartTimeSlots]);
|
||||
|
||||
async function onSubmit(values: NodeConfigFormData) {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateNodeConfig(values as API.NodeConfig);
|
||||
toast.success(t('config.saveSuccess'));
|
||||
await refetchCfg();
|
||||
setOpen(false);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function savePeriods() {
|
||||
await setNodeMultiplier({ periods: timeSlots });
|
||||
await refetchPeriods();
|
||||
toast.success(t('config.saveSuccess'));
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:resistor-nodes' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('config.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('config.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent className='w-[720px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('config.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='server-config-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-4 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='node_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.communicationKey')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('config.inputPlaceholder')}
|
||||
value={field.value || ''}
|
||||
onValueChange={field.onChange}
|
||||
suffix={
|
||||
<div className='bg-muted flex h-9 items-center 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('node_secret', formatted);
|
||||
}}
|
||||
className='cursor-pointer'
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.communicationKeyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='node_pull_interval'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.nodePullInterval')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
suffix='S'
|
||||
value={field.value as any}
|
||||
onValueChange={field.onChange}
|
||||
placeholder={t('config.inputPlaceholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.nodePullIntervalDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='node_push_interval'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.nodePushInterval')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
suffix='S'
|
||||
step={0.1}
|
||||
value={field.value as any}
|
||||
onValueChange={field.onChange}
|
||||
placeholder={t('config.inputPlaceholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.nodePushIntervalDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className='mt-6 space-y-3'>
|
||||
<Label className='text-base'>{t('config.dynamicMultiplier')}</Label>
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t('config.dynamicMultiplierDescription')}
|
||||
</p>
|
||||
|
||||
<div className='flex flex-col-reverse gap-8 md:flex-row md:items-start'>
|
||||
<div className='w-full md:w-1/2'>
|
||||
<ArrayInput<API.TimePeriod>
|
||||
fields={[
|
||||
{ name: 'start_time', prefix: t('config.startTime'), type: 'time' },
|
||||
{ name: 'end_time', prefix: t('config.endTime'), type: 'time' },
|
||||
{
|
||||
name: 'multiplier',
|
||||
prefix: t('config.multiplier'),
|
||||
type: 'number',
|
||||
placeholder: '0',
|
||||
},
|
||||
]}
|
||||
value={timeSlots}
|
||||
onChange={setTimeSlots}
|
||||
/>
|
||||
<div className='mt-3 flex gap-2'>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => setTimeSlots(periodsResp || [])}
|
||||
>
|
||||
{t('config.reset')}
|
||||
</Button>
|
||||
<Button size='sm' onClick={savePeriods}>
|
||||
{t('config.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='w-full md:w-1/2'>
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className='mx-auto aspect-[4/3] max-w-[400px]'
|
||||
>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartTimeSlots}
|
||||
cx='50%'
|
||||
cy='50%'
|
||||
labelLine={false}
|
||||
outerRadius='80%'
|
||||
fill='#8884d8'
|
||||
dataKey='value'
|
||||
label={({ percent, multiplier }) =>
|
||||
`${(multiplier || 0)?.toFixed(2)}x (${(percent * 100).toFixed(0)}%)`
|
||||
}
|
||||
>
|
||||
{chartTimeSlots.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<ChartTooltip
|
||||
content={({ payload }) => {
|
||||
if (payload && payload.length) {
|
||||
const d = payload[0]?.payload as any;
|
||||
return (
|
||||
<div className='bg-background rounded-lg border p-2 shadow-sm'>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-muted-foreground text-[0.70rem] uppercase'>
|
||||
{t('config.timeSlot')}
|
||||
</span>
|
||||
<span className='text-muted-foreground font-bold'>
|
||||
{d.name || '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-muted-foreground text-[0.70rem] uppercase'>
|
||||
{t('config.multiplier')}
|
||||
</span>
|
||||
<span className='font-bold'>
|
||||
{Number(d.multiplier).toFixed(2)}x
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={saving} onClick={() => setOpen(false)}>
|
||||
{t('config.actions.cancel')}
|
||||
</Button>
|
||||
<Button disabled={saving} type='submit' form='server-config-form'>
|
||||
<Icon icon='mdi:loading' className={saving ? 'mr-2 animate-spin' : 'hidden'} />
|
||||
{t('config.actions.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from '@workspace/ui/components/accordion';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
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 { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
FieldConfig,
|
||||
formSchema,
|
||||
getLabel,
|
||||
getProtocolDefaultConfig,
|
||||
PROTOCOL_FIELDS,
|
||||
protocols as PROTOCOLS,
|
||||
ServerFormValues,
|
||||
} from './form-schema';
|
||||
|
||||
function DynamicField({
|
||||
field,
|
||||
control,
|
||||
protocolIndex,
|
||||
protocolData,
|
||||
t,
|
||||
}: {
|
||||
field: FieldConfig;
|
||||
control: any;
|
||||
protocolIndex: number;
|
||||
protocolData: any;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const fieldName = `protocols.${protocolIndex}.${field.name}` as const;
|
||||
|
||||
if (field.condition && !field.condition(protocolData, {})) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const commonProps = {
|
||||
control,
|
||||
name: fieldName,
|
||||
};
|
||||
|
||||
switch (field.type) {
|
||||
case 'input':
|
||||
return (
|
||||
<FormField
|
||||
{...commonProps}
|
||||
render={({ field: fieldProps }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t(field.label)}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...fieldProps}
|
||||
type='text'
|
||||
placeholder={
|
||||
field.placeholder
|
||||
? typeof field.placeholder === 'function'
|
||||
? field.placeholder(t, protocolData)
|
||||
: field.placeholder
|
||||
: undefined
|
||||
}
|
||||
onValueChange={(v) => fieldProps.onChange(v)}
|
||||
suffix={
|
||||
field.password ? (
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
onClick={() => {
|
||||
const length = field.password || 16;
|
||||
const result = uid(length).toLowerCase();
|
||||
fieldProps.onChange(result);
|
||||
}}
|
||||
>
|
||||
<Icon icon='mdi:refresh' className='h-4 w-4' />
|
||||
</Button>
|
||||
) : (
|
||||
field.suffix
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'number':
|
||||
return (
|
||||
<FormField
|
||||
{...commonProps}
|
||||
render={({ field: fieldProps }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t(field.label)}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...fieldProps}
|
||||
type='number'
|
||||
min={field.min}
|
||||
max={field.max}
|
||||
step={field.step || 1}
|
||||
suffix={field.suffix}
|
||||
placeholder={
|
||||
field.placeholder
|
||||
? typeof field.placeholder === 'function'
|
||||
? field.placeholder(t, protocolData)
|
||||
: field.placeholder
|
||||
: undefined
|
||||
}
|
||||
onValueChange={(v) => fieldProps.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'select':
|
||||
if (!field.options || field.options.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<FormField
|
||||
{...commonProps}
|
||||
render={({ field: fieldProps }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t(field.label)}</FormLabel>
|
||||
<FormControl>
|
||||
<Select
|
||||
value={fieldProps.value ?? field.defaultValue}
|
||||
onValueChange={(v) => fieldProps.onChange(v)}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{field.options?.map((option) => (
|
||||
<SelectItem key={option} value={option}>
|
||||
{getLabel(option)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'switch':
|
||||
return (
|
||||
<FormField
|
||||
{...commonProps}
|
||||
render={({ field: fieldProps }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t(field.label)}</FormLabel>
|
||||
<FormControl>
|
||||
<div className='pt-2'>
|
||||
<Switch
|
||||
checked={!!fieldProps.value}
|
||||
onCheckedChange={(checked) => fieldProps.onChange(checked)}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'textarea':
|
||||
return (
|
||||
<FormField
|
||||
{...commonProps}
|
||||
render={({ field: fieldProps }) => (
|
||||
<FormItem className='col-span-2'>
|
||||
<FormLabel>{t(field.label)}</FormLabel>
|
||||
<FormControl>
|
||||
<textarea
|
||||
{...fieldProps}
|
||||
value={fieldProps.value ?? ''}
|
||||
className='border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex min-h-[80px] w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50'
|
||||
placeholder={
|
||||
field.placeholder
|
||||
? typeof field.placeholder === 'function'
|
||||
? field.placeholder(t, protocolData)
|
||||
: t(field.placeholder)
|
||||
: undefined
|
||||
}
|
||||
onChange={(e) => fieldProps.onChange(e.target.value)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function renderFieldsByGroup(
|
||||
fields: FieldConfig[],
|
||||
group: string,
|
||||
control: any,
|
||||
protocolIndex: number,
|
||||
protocolData: any,
|
||||
t: (key: string) => string,
|
||||
) {
|
||||
const groupFields = fields.filter((field) => field.group === group);
|
||||
if (groupFields.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
{groupFields.map((field) => (
|
||||
<DynamicField
|
||||
key={field.name}
|
||||
field={field}
|
||||
control={control}
|
||||
protocolIndex={protocolIndex}
|
||||
protocolData={protocolData}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderGroupCard(
|
||||
title: string,
|
||||
fields: FieldConfig[],
|
||||
group: string,
|
||||
control: any,
|
||||
protocolIndex: number,
|
||||
protocolData: any,
|
||||
t: (key: string) => string,
|
||||
) {
|
||||
const groupFields = fields.filter((field) => field.group === group);
|
||||
if (groupFields.length === 0) return null;
|
||||
|
||||
const visibleFields = groupFields.filter(
|
||||
(field) => !field.condition || field.condition(protocolData, {}),
|
||||
);
|
||||
|
||||
if (visibleFields.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className='relative'>
|
||||
<fieldset className='border-border rounded-lg border'>
|
||||
<legend className='text-foreground bg-background ml-3 px-1 py-1 text-sm font-medium'>
|
||||
{t(title)}
|
||||
</legend>
|
||||
<div className='p-4 pt-2'>
|
||||
{renderFieldsByGroup(fields, group, control, protocolIndex, protocolData, t)}
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerForm(props: {
|
||||
trigger: string;
|
||||
title: string;
|
||||
loading?: boolean;
|
||||
initialValues?: Partial<ServerFormValues>;
|
||||
onSubmit: (values: ServerFormValues) => Promise<boolean> | boolean;
|
||||
}) {
|
||||
const { trigger, title, loading, initialValues, onSubmit } = props;
|
||||
const t = useTranslations('servers');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [accordionValue, setAccordionValue] = useState<string>();
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
address: '',
|
||||
country: '',
|
||||
city: '',
|
||||
ratio: 1,
|
||||
protocols: [],
|
||||
...initialValues,
|
||||
},
|
||||
});
|
||||
const { control } = form;
|
||||
|
||||
const protocolsValues = useWatch({ control, name: 'protocols' });
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues) {
|
||||
form.reset({
|
||||
name: '',
|
||||
address: '',
|
||||
country: '',
|
||||
city: '',
|
||||
ratio: 1,
|
||||
...initialValues,
|
||||
protocols: PROTOCOLS.map((type) => {
|
||||
const existingProtocol = initialValues.protocols?.find((p) => p.type === type);
|
||||
return existingProtocol || getProtocolDefaultConfig(type);
|
||||
}),
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initialValues]);
|
||||
|
||||
async function handleSubmit(values: Record<string, any>) {
|
||||
const filtered = (values?.protocols || []).filter((p: any, index: number) => {
|
||||
const port = Number(p?.port);
|
||||
const protocolType = PROTOCOLS[index];
|
||||
return protocolType && p && Number.isFinite(port) && port > 0 && port <= 65535;
|
||||
});
|
||||
|
||||
if (filtered.length === 0) {
|
||||
toast.error(t('validation_failed'));
|
||||
return;
|
||||
}
|
||||
|
||||
const result = {
|
||||
name: values.name,
|
||||
country: values.country,
|
||||
city: values.city,
|
||||
ratio: Number(values.ratio || 1),
|
||||
address: values.address,
|
||||
protocols: filtered,
|
||||
};
|
||||
|
||||
const ok = await onSubmit(result);
|
||||
if (ok) {
|
||||
form.reset();
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!initialValues) {
|
||||
const full = PROTOCOLS.map((t) => getProtocolDefaultConfig(t));
|
||||
form.reset({
|
||||
name: '',
|
||||
address: '',
|
||||
country: '',
|
||||
city: '',
|
||||
ratio: 1,
|
||||
protocols: full,
|
||||
});
|
||||
}
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{trigger}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[700px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<Form {...form}>
|
||||
<form className='grid grid-cols-1 gap-2 px-6 pt-4'>
|
||||
<div className='grid grid-cols-3 gap-2'>
|
||||
<FormField
|
||||
control={control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name='country'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('country')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name='city'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('city')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
<FormField
|
||||
control={control}
|
||||
name='address'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('address')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('address_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name='ratio'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('traffic_ratio')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
step={0.1}
|
||||
min={0}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className='my-3'>
|
||||
<h3 className='text-foreground text-sm font-semibold'>
|
||||
{t('protocol_configurations')}
|
||||
</h3>
|
||||
<p className='text-muted-foreground mt-1 text-xs'>
|
||||
{t('protocol_configurations_desc')}
|
||||
</p>
|
||||
</div>
|
||||
<Accordion
|
||||
type='single'
|
||||
collapsible
|
||||
className='w-full space-y-3'
|
||||
value={accordionValue}
|
||||
onValueChange={setAccordionValue}
|
||||
>
|
||||
{PROTOCOLS.map((type) => {
|
||||
const i = Math.max(
|
||||
0,
|
||||
PROTOCOLS.findIndex((t) => t === type),
|
||||
);
|
||||
const current = (protocolsValues[i] || {}) as Record<string, any>;
|
||||
const isEnabled = current.port && Number(current.port) > 0;
|
||||
const fields = PROTOCOL_FIELDS[type] || [];
|
||||
return (
|
||||
<AccordionItem key={type} value={type} className='mb-2 rounded-lg border'>
|
||||
<AccordionTrigger className='px-4 py-3 hover:no-underline'>
|
||||
<div className='flex w-full items-center justify-between'>
|
||||
<div className='flex flex-col items-start'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='font-medium capitalize'>{type}</span>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'text-muted-foreground text-xs',
|
||||
isEnabled && 'text-green-500',
|
||||
)}
|
||||
>
|
||||
{isEnabled ? t('enabled') : t('disabled')}
|
||||
</span>
|
||||
</div>
|
||||
<div className='mr-2 flex items-center gap-1'>
|
||||
{current.transport && (
|
||||
<Badge variant='secondary' className='text-xs'>
|
||||
{current.transport.toUpperCase()}
|
||||
</Badge>
|
||||
)}
|
||||
{current.security && current.security !== 'none' && (
|
||||
<Badge variant='outline' className='text-xs'>
|
||||
{current.security.toUpperCase()}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{current.port && <Badge className='text-xs'>{current.port}</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className='px-4 pb-4 pt-0'>
|
||||
<div className='-mx-4 space-y-4 rounded-b-lg border-t px-4 pt-4'>
|
||||
{renderGroupCard('basic', fields, 'basic', control, i, current, t)}
|
||||
{renderGroupCard('plugin', fields, 'plugin', control, i, current, t)}
|
||||
{renderGroupCard(
|
||||
'transport',
|
||||
fields,
|
||||
'transport',
|
||||
control,
|
||||
i,
|
||||
current,
|
||||
t,
|
||||
)}
|
||||
{renderGroupCard('security', fields, 'security', control, i, current, t)}
|
||||
{renderGroupCard('reality', fields, 'reality', control, i, current, t)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
})}
|
||||
</Accordion>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={form.handleSubmit(handleSubmit, (errors) => {
|
||||
console.log(errors, form.getValues());
|
||||
const key = Object.keys(errors)[0] as keyof typeof errors;
|
||||
if (key) toast.error(String(errors[key]?.message));
|
||||
return false;
|
||||
})}
|
||||
>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />} {t('confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { getSubscribeConfig, updateSubscribeConfig } from '@/services/admin/system';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
|
||||
const subscribeConfigSchema = z.object({
|
||||
single_model: z.boolean().optional(),
|
||||
pan_domain: z.boolean().optional(),
|
||||
subscribe_path: z.string().optional(),
|
||||
subscribe_domain: z.string().optional(),
|
||||
user_agent_limit: z.boolean().optional(),
|
||||
user_agent_list: z.string().optional(),
|
||||
});
|
||||
|
||||
type SubscribeConfigFormData = z.infer<typeof subscribeConfigSchema>;
|
||||
|
||||
export default function ConfigForm() {
|
||||
const t = useTranslations('subscribe');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getSubscribeConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<SubscribeConfigFormData>({
|
||||
resolver: zodResolver(subscribeConfigSchema),
|
||||
defaultValues: {
|
||||
single_model: false,
|
||||
pan_domain: false,
|
||||
subscribe_path: '',
|
||||
subscribe_domain: '',
|
||||
user_agent_limit: false,
|
||||
user_agent_list: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: SubscribeConfigFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateSubscribeConfig(values as API.SubscribeConfig);
|
||||
toast.success(t('config.updateSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('config.updateError'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:cog' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('config.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('config.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('config.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='subscribe-config-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='single_model'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.singleSubscriptionMode')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('config.singleSubscriptionModeDescription')}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='pan_domain'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.wildcardResolution')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.wildcardResolutionDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='subscribe_path'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.subscriptionPath')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('config.subscriptionPathPlaceholder')}
|
||||
value={field.value}
|
||||
onValueBlur={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.subscriptionPathDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='subscribe_domain'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.subscriptionDomain')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-32'
|
||||
placeholder={`${t('config.subscriptionDomainPlaceholder')}\nexample.com\nwww.example.com`}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.subscriptionDomainDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='user_agent_limit'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.userAgentLimit', { userAgent: 'User-Agent' })}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('config.userAgentLimitDescription', { userAgent: 'User-Agent' })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='user_agent_list'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t('config.userAgentList', {
|
||||
userAgent: 'User-Agent',
|
||||
})}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-32'
|
||||
placeholder={`${t('config.userAgentListPlaceholder', { userAgent: 'User-Agent' })}\nClashX\nClashForAndroid\nClash-verge`}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('config.userAgentListDescription', { userAgent: 'User-Agent' })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('actions.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='subscribe-config-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('actions.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
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 {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
});
|
||||
|
||||
interface GroupFormProps<T> {
|
||||
onSubmit: (data: T) => Promise<boolean> | boolean;
|
||||
initialValues?: T;
|
||||
loading?: boolean;
|
||||
trigger: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export default function GroupForm<T extends Record<string, any>>({
|
||||
onSubmit,
|
||||
initialValues,
|
||||
loading,
|
||||
trigger,
|
||||
title,
|
||||
}: GroupFormProps<T>) {
|
||||
const t = useTranslations('subscribe');
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const form = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
...initialValues,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
form?.reset(initialValues);
|
||||
}, [form, initialValues]);
|
||||
|
||||
async function handleSubmit(data: { [x: string]: any }) {
|
||||
const bool = await onSubmit(data as T);
|
||||
|
||||
if (bool) setOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
form.reset();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{trigger}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 px-6 pt-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('group.form.name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='description'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('group.form.description')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button
|
||||
variant='outline'
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{t('group.form.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} onClick={form.handleSubmit(handleSubmit)}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}{' '}
|
||||
{t('group.form.confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
batchDeleteSubscribeGroup,
|
||||
createSubscribeGroup,
|
||||
deleteSubscribeGroup,
|
||||
getSubscribeGroupList,
|
||||
updateSubscribeGroup,
|
||||
} from '@/services/admin/subscribe';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import GroupForm from './form';
|
||||
|
||||
const GroupTable = () => {
|
||||
const t = useTranslations('subscribe');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<API.SubscribeGroup, any>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t('group.title'),
|
||||
toolbar: (
|
||||
<GroupForm<API.CreateSubscribeGroupRequest>
|
||||
trigger={t('group.create')}
|
||||
title={t('group.createSubscribeGroup')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createSubscribeGroup(values);
|
||||
toast.success(t('group.createSuccess'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: t('group.name'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'description',
|
||||
header: t('group.description'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'updated_at',
|
||||
header: t('group.updatedAt'),
|
||||
cell: ({ row }) => formatDate(row.getValue('updated_at')),
|
||||
},
|
||||
]}
|
||||
request={async () => {
|
||||
const { data } = await getSubscribeGroupList();
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<GroupForm<API.SubscribeGroup>
|
||||
key='edit'
|
||||
trigger={t('group.edit')}
|
||||
title={t('group.editSubscribeGroup')}
|
||||
loading={loading}
|
||||
initialValues={row}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateSubscribeGroup({
|
||||
...row,
|
||||
...values,
|
||||
});
|
||||
toast.success(t('group.updateSuccess'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
|
||||
title={t('group.confirmDelete')}
|
||||
description={t('group.deleteWarning')}
|
||||
onConfirm={async () => {
|
||||
await deleteSubscribeGroup({
|
||||
id: row.id,
|
||||
});
|
||||
toast.success(t('group.deleteSuccess'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('group.cancel')}
|
||||
confirmText={t('group.confirm')}
|
||||
/>,
|
||||
],
|
||||
batchRender(rows) {
|
||||
return [
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
|
||||
title={t('group.confirmDelete')}
|
||||
description={t('group.deleteWarning')}
|
||||
onConfirm={async () => {
|
||||
await batchDeleteSubscribeGroup({
|
||||
ids: rows.map((item) => item.id),
|
||||
});
|
||||
toast.success(t('group.deleteSuccess'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('group.cancel')}
|
||||
confirmText={t('group.confirm')}
|
||||
/>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default GroupTable;
|
||||
@@ -1,30 +1,23 @@
|
||||
import { getTranslations } from 'next-intl/server';
|
||||
'use client';
|
||||
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { Card, CardContent } from '@workspace/ui/components/card';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import ConfigForm from './config-form';
|
||||
import { ProtocolForm } from './protocol-form';
|
||||
|
||||
import GroupTable from './group/table';
|
||||
import SubscribeConfig from './subscribe-config';
|
||||
import SubscribeTable from './subscribe-table';
|
||||
|
||||
export default async function Page() {
|
||||
const t = await getTranslations('subscribe');
|
||||
export default function SubscribePage() {
|
||||
const t = useTranslations('subscribe');
|
||||
|
||||
return (
|
||||
<Tabs defaultValue='subscribe'>
|
||||
<TabsList>
|
||||
<TabsTrigger value='subscribe'>{t('tabs.subscribe')}</TabsTrigger>
|
||||
<TabsTrigger value='group'>{t('tabs.subscribeGroup')}</TabsTrigger>
|
||||
<TabsTrigger value='config'>{t('tabs.subscribeConfig')}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value='subscribe'>
|
||||
<SubscribeTable />
|
||||
</TabsContent>
|
||||
<TabsContent value='group'>
|
||||
<GroupTable />
|
||||
</TabsContent>
|
||||
<TabsContent value='config'>
|
||||
<SubscribeConfig />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<div className='space-y-4'>
|
||||
<h2 className='text-lg font-semibold'>{t('config.title')}</h2>
|
||||
<Card>
|
||||
<CardContent className='p-4'>
|
||||
<ConfigForm />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ProtocolForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,836 @@
|
||||
'use client';
|
||||
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import {
|
||||
createSubscribeApplication,
|
||||
deleteSubscribeApplication,
|
||||
getSubscribeApplicationList,
|
||||
updateSubscribeApplication,
|
||||
} from '@/services/admin/application';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { Input } from '@workspace/ui/components/input';
|
||||
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,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { GoTemplateEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
import { TemplatePreview } from './template-preview';
|
||||
|
||||
const createClientFormSchema = (t: any) =>
|
||||
z.object({
|
||||
name: z.string().min(1, t('form.validation.nameRequired')),
|
||||
description: z.string().optional(),
|
||||
icon: z.string().optional(),
|
||||
user_agent: z.string().min(1, `User-Agent ${t('form.validation.userAgentRequiredSuffix')}`),
|
||||
scheme: z.string().optional(),
|
||||
template: z.string(),
|
||||
output_format: z.string(),
|
||||
download_link: z.object({
|
||||
windows: z.string().optional(),
|
||||
mac: z.string().optional(),
|
||||
linux: z.string().optional(),
|
||||
ios: z.string().optional(),
|
||||
android: z.string().optional(),
|
||||
harmony: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
type ClientFormData = z.infer<ReturnType<typeof createClientFormSchema>>;
|
||||
|
||||
export function ProtocolForm() {
|
||||
const t = useTranslations('subscribe');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editingClient, setEditingClient] = useState<API.SubscribeApplication | null>(null);
|
||||
const tableRef = useRef<ProTableActions>(null);
|
||||
|
||||
const clientFormSchema = createClientFormSchema(t);
|
||||
|
||||
const form = useForm<ClientFormData>({
|
||||
resolver: zodResolver(clientFormSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
description: '',
|
||||
icon: '',
|
||||
user_agent: '',
|
||||
scheme: '',
|
||||
template: '',
|
||||
output_format: '',
|
||||
download_link: {
|
||||
windows: '',
|
||||
mac: '',
|
||||
linux: '',
|
||||
ios: '',
|
||||
android: '',
|
||||
harmony: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const request = async (
|
||||
pagination: { page: number; size: number },
|
||||
filter: Record<string, unknown>,
|
||||
) => {
|
||||
const { data } = await getSubscribeApplicationList({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
});
|
||||
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
};
|
||||
|
||||
const columns: ColumnDef<API.SubscribeApplication, any>[] = [
|
||||
{
|
||||
accessorKey: 'is_default',
|
||||
header: t('table.columns.default'),
|
||||
cell: ({ row }) => (
|
||||
<Switch
|
||||
checked={row.original.is_default || false}
|
||||
onCheckedChange={async (checked) => {
|
||||
await updateSubscribeApplication({
|
||||
...row.original,
|
||||
is_default: checked,
|
||||
});
|
||||
tableRef.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: t('table.columns.name'),
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
{row.original.icon && (
|
||||
<div className='relative h-6 w-6 flex-shrink-0'>
|
||||
<Image
|
||||
src={row.original.icon}
|
||||
alt={row.original.name}
|
||||
width={24}
|
||||
height={24}
|
||||
className='rounded object-contain'
|
||||
onError={() => {
|
||||
console.log(`Failed to load image for ${row.original.name}`);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<span className='font-medium'>{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_agent',
|
||||
header: 'User-Agent',
|
||||
cell: ({ row }) => (
|
||||
<div className='text-muted-foreground max-w-[150px] truncate font-mono text-sm'>
|
||||
{row.original.user_agent}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'output_format',
|
||||
header: t('table.columns.outputFormat'),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant='secondary' className='text-xs'>
|
||||
{t(`outputFormats.${row.original.output_format}`) || row.original.output_format}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'download_link',
|
||||
header: t('table.columns.supportedPlatforms'),
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div className='flex flex-wrap gap-1'>
|
||||
{Object.entries(row.original.download_link || {}).map(([key, value]) => {
|
||||
if (value) {
|
||||
return (
|
||||
<Badge key={key} variant='secondary' className='text-xs'>
|
||||
{t(`platforms.${key}`)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'description',
|
||||
header: t('table.columns.description'),
|
||||
cell: ({ row }) => (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<div className='text-muted-foreground max-w-[200px] truncate text-sm'>
|
||||
{row.original.description}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className='max-w-xs'>
|
||||
<p>{row.original.description}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const handleAdd = () => {
|
||||
setEditingClient(null);
|
||||
form.reset({
|
||||
name: '',
|
||||
description: '',
|
||||
icon: '',
|
||||
user_agent: '',
|
||||
scheme: '',
|
||||
template: '',
|
||||
output_format: '',
|
||||
download_link: {
|
||||
windows: '',
|
||||
mac: '',
|
||||
linux: '',
|
||||
ios: '',
|
||||
android: '',
|
||||
harmony: '',
|
||||
},
|
||||
});
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (client: API.SubscribeApplication) => {
|
||||
setEditingClient(client);
|
||||
form.reset(client);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (client: API.SubscribeApplication) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await deleteSubscribeApplication({ id: client.id });
|
||||
tableRef.current?.refresh();
|
||||
toast.success(t('actions.deleteSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Failed to delete client:', error);
|
||||
toast.error(t('actions.deleteFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchDelete = async (clients: API.SubscribeApplication[]) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await Promise.all(clients.map((client) => deleteSubscribeApplication({ id: client.id })));
|
||||
tableRef.current?.refresh();
|
||||
toast.success(t('actions.batchDeleteSuccess', { count: clients.length }));
|
||||
} catch (error) {
|
||||
console.error('Failed to batch delete clients:', error);
|
||||
toast.error(t('actions.deleteFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (data: ClientFormData) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (editingClient) {
|
||||
await updateSubscribeApplication({
|
||||
...data,
|
||||
is_default: editingClient.is_default,
|
||||
id: editingClient.id,
|
||||
});
|
||||
toast.success(t('actions.updateSuccess'));
|
||||
} else {
|
||||
await createSubscribeApplication({
|
||||
...data,
|
||||
is_default: false,
|
||||
});
|
||||
toast.success(t('actions.createSuccess'));
|
||||
}
|
||||
|
||||
setOpen(false);
|
||||
tableRef.current?.refresh();
|
||||
} catch (error) {
|
||||
console.error('Failed to save client:', error);
|
||||
toast.error(t('actions.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ProTable<API.SubscribeApplication, Record<string, unknown>>
|
||||
action={tableRef}
|
||||
columns={columns}
|
||||
request={request}
|
||||
header={{
|
||||
title: <h2 className='text-lg font-semibold'>{t('protocol.title')}</h2>,
|
||||
toolbar: <Button onClick={handleAdd}>{t('actions.add')}</Button>,
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<TemplatePreview
|
||||
key='preview'
|
||||
applicationId={row.id}
|
||||
output_format={row.output_format}
|
||||
/>,
|
||||
<Button
|
||||
key='edit'
|
||||
onClick={() => handleEdit(row as unknown as API.SubscribeApplication)}
|
||||
>
|
||||
{t('actions.edit')}
|
||||
</Button>,
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={
|
||||
<Button variant='destructive' disabled={loading}>
|
||||
{t('actions.delete')}
|
||||
</Button>
|
||||
}
|
||||
title={t('actions.confirmDelete')}
|
||||
description={t('actions.deleteWarning')}
|
||||
onConfirm={() => handleDelete(row as unknown as API.SubscribeApplication)}
|
||||
cancelText={t('actions.cancel')}
|
||||
confirmText={t('actions.confirm')}
|
||||
/>,
|
||||
],
|
||||
batchRender: (rows) => [
|
||||
<ConfirmButton
|
||||
key='batchDelete'
|
||||
trigger={<Button variant='destructive'>{t('actions.batchDelete')}</Button>}
|
||||
title={t('actions.confirmDelete')}
|
||||
description={t('actions.batchDeleteWarning', { count: rows.length })}
|
||||
onConfirm={() => handleBatchDelete(rows as unknown as API.SubscribeApplication[])}
|
||||
cancelText={t('actions.cancel')}
|
||||
confirmText={t('actions.confirm')}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
/>
|
||||
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetContent className='w-[580px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{editingClient ? t('form.editTitle') : t('form.addTitle')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
|
||||
<Form {...form}>
|
||||
<form className='space-y-6 py-4'>
|
||||
<Tabs defaultValue='basic' className='w-full'>
|
||||
<TabsList className='grid w-full grid-cols-3'>
|
||||
<TabsTrigger value='basic'>{t('form.tabs.basic')}</TabsTrigger>
|
||||
<TabsTrigger value='template'>{t('form.tabs.template')}</TabsTrigger>
|
||||
<TabsTrigger value='download'>{t('form.tabs.download')}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value='basic' className='space-y-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='icon'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.fields.icon')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='text'
|
||||
placeholder='https://example.com/icon.png'
|
||||
suffix={
|
||||
<UploadImage
|
||||
className='bg-muted h-9 rounded-none border-none px-2'
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value as string);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value as string);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('form.descriptions.icon')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.fields.name')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder='Clash for Windows' {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{t('form.descriptions.name')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='user_agent'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>User-Agent</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder='Clash' {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('form.descriptions.userAgentPrefix')}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='description'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.fields.description')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder={t('form.descriptions.description')} {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>{t('form.descriptions.description')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='template' className='space-y-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='output_format'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('form.fields.outputFormat')}</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder='Select ...' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value='base64'>{t('outputFormats.base64')}</SelectItem>
|
||||
<SelectItem value='yaml'>{t('outputFormats.yaml')}</SelectItem>
|
||||
<SelectItem value='json'>{t('outputFormats.json')}</SelectItem>
|
||||
<SelectItem value='conf'>{t('outputFormats.conf')}</SelectItem>
|
||||
<SelectItem value='plain'>{t('outputFormats.plain')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormDescription>{t('form.descriptions.outputFormat')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='scheme'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel className='flex items-center gap-2'>
|
||||
{t('form.fields.scheme')}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:help-circle-outline'
|
||||
className='text-muted-foreground h-4 w-4'
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side='right'
|
||||
className='bg-secondary text-secondary-foreground max-w-md'
|
||||
>
|
||||
<div className='space-y-2 text-sm'>
|
||||
<div className='font-medium'>
|
||||
{t('form.descriptions.scheme.title')}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className='font-medium'>
|
||||
{t('form.descriptions.scheme.variables')}
|
||||
</div>
|
||||
<ul className='ml-2 list-disc space-y-1 text-xs'>
|
||||
<li>
|
||||
<code className='rounded px-1'>{'${url}'}</code> -{' '}
|
||||
{t('form.descriptions.scheme.urlVariable')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>{'${name}'}</code> -{' '}
|
||||
{t('form.descriptions.scheme.nameVariable')}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className='font-medium'>
|
||||
{t('form.descriptions.scheme.functions')}
|
||||
</div>
|
||||
<ul className='ml-2 list-disc space-y-1 text-xs'>
|
||||
<li>
|
||||
<code className='rounded px-1'>
|
||||
{'${encodeURIComponent(...)}'}
|
||||
</code>{' '}
|
||||
- {t('form.descriptions.scheme.urlEncoding')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>
|
||||
{'${window.btoa(...)}'}
|
||||
</code>{' '}
|
||||
- {t('form.descriptions.scheme.base64Encoding')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>
|
||||
{'${JSON.stringify(...)}'}
|
||||
</code>{' '}
|
||||
- {t('form.descriptions.scheme.jsonStringify')}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder='clash://install-config?url=${url}&name=${name}'
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='template'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel className='flex items-center gap-2'>
|
||||
{t('form.fields.template')}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:help-circle-outline'
|
||||
className='text-muted-foreground h-4 w-4'
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side='right'
|
||||
className='bg-secondary text-secondary-foreground max-w-md'
|
||||
>
|
||||
<div className='space-y-2 text-sm'>
|
||||
<div className='font-medium'>
|
||||
{t('form.descriptions.template.title')}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className='font-medium'>
|
||||
{t('form.descriptions.template.variables')}
|
||||
</div>
|
||||
<ul className='ml-2 list-disc space-y-1 text-xs'>
|
||||
<li>
|
||||
<code className='rounded px-1'>.SiteName</code> -{' '}
|
||||
{t('form.descriptions.template.siteName')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>.SubscribeName</code> -{' '}
|
||||
{t('form.descriptions.template.subscribeName')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>.Proxies</code> -{' '}
|
||||
{t('form.descriptions.template.nodes')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>.UserInfo</code> -{' '}
|
||||
{t('form.descriptions.template.userInfo')}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className='font-medium'>
|
||||
{t('form.descriptions.template.functions')}
|
||||
</div>
|
||||
<ul className='ml-2 list-disc space-y-1 text-xs'>
|
||||
<li>
|
||||
<code className='rounded px-1'>
|
||||
{'{{range .Proxies}}...{{end}}'}
|
||||
</code>{' '}
|
||||
- {t('form.descriptions.template.range')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>
|
||||
{'{{if .condition}}...{{end}}'}
|
||||
</code>{' '}
|
||||
- {t('form.descriptions.template.if')}
|
||||
</li>
|
||||
<li>
|
||||
<code className='rounded px-1'>{'{{sprig_func}}'}</code> -{' '}
|
||||
{t('form.descriptions.template.sprig')}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<GoTemplateEditor
|
||||
showLineNumbers
|
||||
schema={{
|
||||
SiteName: { type: 'string', description: 'Site name' },
|
||||
SubscribeName: { type: 'string', description: 'Subscribe name' },
|
||||
Proxies: {
|
||||
type: 'array',
|
||||
description: 'Array of proxy nodes',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
Name: { type: 'string', description: 'Node name' },
|
||||
Server: { type: 'string', description: 'Server host' },
|
||||
Port: { type: 'number', description: 'Server port' },
|
||||
Type: { type: 'string', description: 'Proxy type' },
|
||||
Tags: {
|
||||
type: 'array',
|
||||
description: 'Node tags',
|
||||
items: { type: 'string' },
|
||||
},
|
||||
Sort: { type: 'number', description: 'Node sort order' },
|
||||
// Security Options
|
||||
Security: {
|
||||
type: 'string',
|
||||
description: 'Security protocol',
|
||||
},
|
||||
SNI: {
|
||||
type: 'string',
|
||||
description: 'Server Name Indication for TLS',
|
||||
},
|
||||
AllowInsecure: {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Allow insecure connections (skip certificate verification)',
|
||||
},
|
||||
Fingerprint: {
|
||||
type: 'string',
|
||||
description: 'Client fingerprint for TLS connections',
|
||||
},
|
||||
RealityServerAddr: {
|
||||
type: 'string',
|
||||
description: 'Reality server address',
|
||||
},
|
||||
RealityServerPort: {
|
||||
type: 'number',
|
||||
description: 'Reality server port',
|
||||
},
|
||||
RealityPrivateKey: {
|
||||
type: 'string',
|
||||
description: 'Reality private key for authentication',
|
||||
},
|
||||
RealityPublicKey: {
|
||||
type: 'string',
|
||||
description: 'Reality public key for authentication',
|
||||
},
|
||||
RealityShortId: {
|
||||
type: 'string',
|
||||
description: 'Reality short ID for authentication',
|
||||
},
|
||||
// Transport Options
|
||||
Transport: {
|
||||
type: 'string',
|
||||
description: 'Transport protocol (e.g., ws, http, grpc)',
|
||||
},
|
||||
Host: {
|
||||
type: 'string',
|
||||
description: 'For WebSocket/HTTP/HTTPS',
|
||||
},
|
||||
Path: { type: 'string', description: 'For HTTP/HTTPS' },
|
||||
ServiceName: {
|
||||
type: 'string',
|
||||
description: 'For gRPC',
|
||||
},
|
||||
// Shadowsocks Options
|
||||
Method: { type: 'string', description: 'Encryption method' },
|
||||
ServerKey: {
|
||||
type: 'string',
|
||||
description: 'For Shadowsocks 2022',
|
||||
},
|
||||
// Vmess/Vless/Trojan Options
|
||||
Flow: {
|
||||
type: 'string',
|
||||
description: 'Flow for Vmess/Vless/Trojan',
|
||||
},
|
||||
// Hysteria2 Options
|
||||
HopPorts: {
|
||||
type: 'string',
|
||||
description: 'Comma-separated list of hop ports',
|
||||
},
|
||||
HopInterval: {
|
||||
type: 'number',
|
||||
description: 'Interval for hop ports in seconds',
|
||||
},
|
||||
ObfsPassword: {
|
||||
type: 'string',
|
||||
description: 'Obfuscation password for Hysteria2',
|
||||
},
|
||||
// Tuic Options
|
||||
DisableSNI: {
|
||||
type: 'boolean',
|
||||
description: 'Disable SNI',
|
||||
},
|
||||
ReduceRtt: {
|
||||
type: 'boolean',
|
||||
description: 'Reduce RTT',
|
||||
},
|
||||
UDPRelayMode: {
|
||||
type: 'string',
|
||||
description: 'UDP relay mode (e.g., "full", "partial")',
|
||||
},
|
||||
CongestionController: {
|
||||
type: 'string',
|
||||
description: 'Congestion controller (e.g., "cubic", "bbr")',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
UserInfo: {
|
||||
type: 'object',
|
||||
description: 'User information',
|
||||
properties: {
|
||||
Password: { type: 'string', description: 'User password' },
|
||||
ExpiredAt: { type: 'string', description: 'Expiration date' },
|
||||
Download: { type: 'number', description: 'Downloaded bytes' },
|
||||
Upload: { type: 'number', description: 'Uploaded bytes' },
|
||||
Traffic: { type: 'number', description: 'Total traffic bytes' },
|
||||
SubscribeURL: {
|
||||
type: 'string',
|
||||
description: 'Subscription URL',
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
enableSprig
|
||||
value={field.value || ''}
|
||||
onChange={(value) => field.onChange(value)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='download' className='space-y-4'>
|
||||
<div className='space-y-4'>
|
||||
<div className='grid gap-3'>
|
||||
{['windows', 'mac', 'linux', 'ios', 'android', 'harmony'].map((key) => (
|
||||
<FormField
|
||||
key={key}
|
||||
control={form.control}
|
||||
name={
|
||||
`download_link.${key}` as `download_link.${keyof ClientFormData['download_link']}`
|
||||
}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t(`platforms.${key}`)}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(`platforms.${key}`)} {t('form.descriptions.downloadLink')}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' onClick={() => setOpen(false)}>
|
||||
{t('actions.cancel')}
|
||||
</Button>
|
||||
<Button onClick={form.handleSubmit(onSubmit)} disabled={loading}>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{editingClient ? t('actions.update') : t('actions.add')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
'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('updateSuccess'));
|
||||
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')}\nexample.com\nwww.example.com`}
|
||||
defaultValue={data?.subscribe_domain}
|
||||
onBlur={(e) => {
|
||||
updateConfig('subscribe_domain', e.target.value);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
'use client';
|
||||
|
||||
import { previewSubscribeTemplate } from '@/services/admin/application';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@workspace/ui/components/sheet';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { Markdown } from '@workspace/ui/custom-components/markdown';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface TemplatePreviewProps {
|
||||
applicationId: number;
|
||||
output_format?: string;
|
||||
}
|
||||
|
||||
export function TemplatePreview({ applicationId, output_format }: TemplatePreviewProps) {
|
||||
const t = useTranslations('subscribe.templatePreview');
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['previewSubscribeTemplate', applicationId],
|
||||
queryFn: () => previewSubscribeTemplate({ id: applicationId }, { skipErrorHandler: true }),
|
||||
enabled: isOpen && !!applicationId,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const originalContent = data?.data?.data?.template || '';
|
||||
const errorMessage = (error as any)?.data?.msg || error?.message || t('failed');
|
||||
const displayContent = originalContent || (error ? errorMessage : '');
|
||||
|
||||
const getDecodedContent = () => {
|
||||
if (output_format === 'base64' && originalContent) {
|
||||
try {
|
||||
return atob(originalContent);
|
||||
} catch {
|
||||
return t('base64.decodeError');
|
||||
}
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const getDisplayContent = () => {
|
||||
switch (output_format) {
|
||||
case 'base64':
|
||||
return `\`\`\`base64\n# ${t('base64.originalContent')}\n${displayContent}\n\n# ${t('base64.decodedContent')}\n${getDecodedContent()}\n\`\`\``;
|
||||
case 'yaml':
|
||||
return `\`\`\`yaml\n${displayContent}\n\`\`\``;
|
||||
case 'json':
|
||||
return `\`\`\`json\n${displayContent}\n\`\`\``;
|
||||
case 'conf':
|
||||
return `\`\`\`ini\n${displayContent}\n\`\`\``;
|
||||
case 'plain':
|
||||
return `\`\`\`text\n${displayContent}\n\`\`\``;
|
||||
default:
|
||||
return displayContent;
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setIsOpen(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant='ghost' size='sm' onClick={() => setIsOpen(true)}>
|
||||
<Icon icon='mdi:eye' className='mr-2 h-4 w-4' />
|
||||
{t('preview')}
|
||||
</Button>
|
||||
<Sheet open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<SheetContent className='w-[800px] max-w-[90vw] md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
{isLoading ? (
|
||||
<div className='flex items-center justify-center'>
|
||||
<Icon icon='mdi:loading' className='h-6 w-6 animate-spin' />
|
||||
<span className='ml-2'>{t('loading')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className='*:text-sm [&_pre>div>div+div]:max-h-[calc(100dvh-48px-36px-36px)] [&_pre>div>div+div]:overflow-auto'>
|
||||
<Markdown>{getDisplayContent()}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
'use client';
|
||||
|
||||
import { getCurrencyConfig, updateCurrencyConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
// Constants
|
||||
const EXCHANGE_RATE_HOST_URL = 'https://exchangerate.host';
|
||||
|
||||
const currencySchema = z.object({
|
||||
access_key: z.string().optional(),
|
||||
currency_unit: z.string().min(1),
|
||||
currency_symbol: z.string().min(1),
|
||||
});
|
||||
|
||||
type CurrencyFormData = z.infer<typeof currencySchema>;
|
||||
|
||||
export default function CurrencyConfig() {
|
||||
const t = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getCurrencyConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getCurrencyConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open, // Only request data when the modal is open
|
||||
});
|
||||
|
||||
const form = useForm<CurrencyFormData>({
|
||||
resolver: zodResolver(currencySchema),
|
||||
defaultValues: {
|
||||
access_key: '',
|
||||
currency_unit: 'USD',
|
||||
currency_symbol: '$',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: CurrencyFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateCurrencyConfig(values as API.CurrencyConfig);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:currency-usd' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('currency.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('currency.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('currency.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='currency-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='access_key'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('currency.accessKey')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('currency.accessKeyPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t('currency.accessKeyDescription', { url: EXCHANGE_RATE_HOST_URL })}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='currency_unit'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('currency.currencyUnit')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('currency.currencyUnitPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('currency.currencyUnitDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='currency_symbol'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('currency.currencySymbol')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('currency.currencySymbolPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('currency.currencySymbolDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='currency-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
'use client';
|
||||
|
||||
import { getPrivacyPolicyConfig, updatePrivacyPolicyConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
|
||||
import { MarkdownEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const privacyPolicySchema = z.object({
|
||||
privacy_policy: z.string().optional(),
|
||||
});
|
||||
|
||||
type PrivacyPolicyFormData = z.infer<typeof privacyPolicySchema>;
|
||||
|
||||
export default function PrivacyPolicyConfig() {
|
||||
const t = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getPrivacyPolicyConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getPrivacyPolicyConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<PrivacyPolicyFormData>({
|
||||
resolver: zodResolver(privacyPolicySchema),
|
||||
defaultValues: {
|
||||
privacy_policy: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset({
|
||||
privacy_policy: data.privacy_policy || '',
|
||||
});
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: PrivacyPolicyFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updatePrivacyPolicyConfig(values as API.PrivacyPolicyConfig);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:shield-account-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('privacyPolicy.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('privacyPolicy.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('privacyPolicy.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='privacy-policy-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='privacy_policy'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('privacyPolicy.title')}</FormLabel>
|
||||
<FormControl>
|
||||
<MarkdownEditor value={field.value || ''} onChange={field.onChange} />
|
||||
</FormControl>
|
||||
<FormDescription>{t('privacyPolicy.description')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='privacy-policy-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
'use client';
|
||||
|
||||
import { getSiteConfig, updateSiteConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { JSONEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const siteSchema = z.object({
|
||||
site_logo: z.string().optional(),
|
||||
site_name: z.string().min(1),
|
||||
site_desc: z.string().optional(),
|
||||
keywords: z.string().optional(),
|
||||
custom_html: z.string().optional(),
|
||||
host: z.string().optional(),
|
||||
custom_data: z.any().optional(),
|
||||
});
|
||||
|
||||
type SiteFormData = z.infer<typeof siteSchema>;
|
||||
|
||||
export default function SiteConfig() {
|
||||
const t = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getSiteConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSiteConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<SiteFormData>({
|
||||
resolver: zodResolver(siteSchema),
|
||||
defaultValues: {
|
||||
site_logo: '',
|
||||
site_name: '',
|
||||
site_desc: '',
|
||||
keywords: '',
|
||||
custom_html: '',
|
||||
host: '',
|
||||
custom_data: {},
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: SiteFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateSiteConfig(values as API.SiteConfig);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:web' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('site.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('site.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('site.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form id='site-form' onSubmit={form.handleSubmit(onSubmit)} className='space-y-2 pt-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='site_logo'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.logo')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('site.logoPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
suffix={
|
||||
<UploadImage
|
||||
className='bg-muted h-9 rounded-none border-none px-2'
|
||||
onChange={(value) => {
|
||||
field.onChange(value);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.logoDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='site_name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.siteName')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('site.siteNamePlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.siteNameDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='site_desc'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.siteDesc')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('site.siteDescPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.siteDescDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='keywords'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.keywords')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('site.keywordsPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.keywordsDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='custom_html'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.customHtml')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-32'
|
||||
placeholder={t('site.customHtmlDescription')}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.customHtmlDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='host'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.siteDomain')}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className='h-32'
|
||||
placeholder={`${t('site.siteDomainPlaceholder')}\nexample.com\nwww.example.com`}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.siteDomainDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='custom_data'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('site.customData')}</FormLabel>
|
||||
<FormControl>
|
||||
<JSONEditor
|
||||
schema={{
|
||||
type: 'object',
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
website: { type: 'string', title: 'Website' },
|
||||
contacts: {
|
||||
type: 'object',
|
||||
title: 'Contacts',
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
email: { type: 'string', title: 'Email' },
|
||||
telephone: { type: 'string', title: 'Telephone' },
|
||||
address: { type: 'string', title: 'Address' },
|
||||
},
|
||||
},
|
||||
community: {
|
||||
type: 'object',
|
||||
title: 'Community',
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
telegram: { type: 'string', title: 'Telegram' },
|
||||
twitter: { type: 'string', title: 'Twitter' },
|
||||
discord: { type: 'string', title: 'Discord' },
|
||||
instagram: { type: 'string', title: 'Instagram' },
|
||||
linkedin: { type: 'string', title: 'Linkedin' },
|
||||
facebook: { type: 'string', title: 'Facebook' },
|
||||
github: { type: 'string', title: 'Github' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
value={field.value}
|
||||
onBlur={(value) => field.onChange(value)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('site.customDataDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='site-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
'use client';
|
||||
|
||||
import { getTosConfig, updateTosConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { MarkdownEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const tosSchema = z.object({
|
||||
tos_content: z.string().optional(),
|
||||
});
|
||||
|
||||
type TosFormData = z.infer<typeof tosSchema>;
|
||||
|
||||
export default function TosConfig() {
|
||||
const t = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getTosConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getTosConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<TosFormData>({
|
||||
resolver: zodResolver(tosSchema),
|
||||
defaultValues: {
|
||||
tos_content: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset({
|
||||
tos_content: data.tos_content || '',
|
||||
});
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: TosFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateTosConfig(values as API.TosConfig);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:file-document-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('tos.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('tos.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('tos.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form id='tos-form' onSubmit={form.handleSubmit(onSubmit)} className='space-y-2 pt-4'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='tos_content'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('tos.title')}</FormLabel>
|
||||
<FormControl>
|
||||
<MarkdownEditor value={field.value || ''} onChange={field.onChange} />
|
||||
</FormControl>
|
||||
<FormDescription>{t('tos.description')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='tos-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getCurrencyConfig, updateCurrencyConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Site() {
|
||||
const t = useTranslations('system.currency');
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getCurrencyConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getCurrencyConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateCurrencyConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.CurrencyConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('accessKey')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('accessKeyDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
value={data?.access_key}
|
||||
onValueBlur={(value) => updateConfig('access_key', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('currencyUnit')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('currencyUnitDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='USD'
|
||||
value={data?.currency_unit}
|
||||
onValueBlur={(value) => updateConfig('currency_unit', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('currencySymbol')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('currencySymbolDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder='$'
|
||||
value={data?.currency_symbol}
|
||||
onValueBlur={(value) => updateConfig('currency_symbol', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
'use client';
|
||||
|
||||
import { getLogSetting, updateLogSetting } from '@/services/admin/log';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const logCleanupSchema = z.object({
|
||||
auto_clear: z.boolean(),
|
||||
clear_days: z.number().min(1),
|
||||
});
|
||||
|
||||
type LogCleanupFormData = z.infer<typeof logCleanupSchema>;
|
||||
|
||||
export default function LogCleanupForm() {
|
||||
const t = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getLogSetting'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getLogSetting();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<LogCleanupFormData>({
|
||||
resolver: zodResolver(logCleanupSchema),
|
||||
defaultValues: {
|
||||
auto_clear: false,
|
||||
clear_days: 30,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: LogCleanupFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateLogSetting(values as API.LogSetting);
|
||||
toast.success(t('common.saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('common.saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:delete-sweep' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('logCleanup.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('logCleanup.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('logCleanup.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='log-cleanup-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='auto_clear'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('logCleanup.autoClear')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('logCleanup.autoClearDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='clear_days'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('logCleanup.clearDays')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
placeholder={t('logCleanup.clearDaysPlaceholder')}
|
||||
value={field.value?.toString()}
|
||||
onValueChange={(value) => field.onChange(Number(value))}
|
||||
disabled={!form.watch('auto_clear')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('logCleanup.clearDaysDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='log-cleanup-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +1,66 @@
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { getTranslations } from 'next-intl/server';
|
||||
import Currency from './currency';
|
||||
import PrivacyPolicy from './privacy-policy';
|
||||
import Site from './site';
|
||||
import Tos from './tos';
|
||||
'use client';
|
||||
|
||||
export default async function Page() {
|
||||
const t = await getTranslations('system');
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import CurrencyForm from './basic-settings/currency-form';
|
||||
import PrivacyPolicyForm from './basic-settings/privacy-policy-form';
|
||||
import SiteForm from './basic-settings/site-form';
|
||||
import TosForm from './basic-settings/tos-form';
|
||||
import LogCleanupForm from './log-cleanup/log-cleanup-form';
|
||||
import InviteForm from './user-security/invite-form';
|
||||
import RegisterForm from './user-security/register-form';
|
||||
import VerifyCodeForm from './user-security/verify-code-form';
|
||||
import VerifyForm from './user-security/verify-form';
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('system');
|
||||
|
||||
const formSections = [
|
||||
{
|
||||
title: t('basicSettings'),
|
||||
forms: [
|
||||
{ component: SiteForm },
|
||||
{ component: CurrencyForm },
|
||||
{ component: TosForm },
|
||||
{ component: PrivacyPolicyForm },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('userSecuritySettings'),
|
||||
forms: [
|
||||
{ component: RegisterForm },
|
||||
{ component: InviteForm },
|
||||
{ component: VerifyForm },
|
||||
{ component: VerifyCodeForm },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('logSettings'),
|
||||
forms: [{ component: LogCleanupForm }],
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Tabs defaultValue='site'>
|
||||
<TabsList className='h-full flex-wrap'>
|
||||
<TabsTrigger value='site'>{t('tabs.site')}</TabsTrigger>
|
||||
<TabsTrigger value='currency'>{t('tabs.currency')}</TabsTrigger>
|
||||
<TabsTrigger value='tos'>{t('tabs.tos')}</TabsTrigger>
|
||||
<TabsTrigger value='privacy-policy'>{t('privacy-policy.title')}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value='site'>
|
||||
<Site />
|
||||
</TabsContent>
|
||||
<TabsContent value='currency'>
|
||||
<Currency />
|
||||
</TabsContent>
|
||||
<TabsContent value='tos'>
|
||||
<Tos />
|
||||
</TabsContent>
|
||||
<TabsContent value='privacy-policy'>
|
||||
<PrivacyPolicy />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<div className='space-y-8'>
|
||||
{formSections.map((section, sectionIndex) => (
|
||||
<div key={sectionIndex}>
|
||||
<h2 className='mb-4 text-lg font-semibold'>{section.title}</h2>
|
||||
<Table>
|
||||
<TableBody>
|
||||
{section.forms.map((form, formIndex) => {
|
||||
const FormComponent = form.component;
|
||||
return (
|
||||
<TableRow key={formIndex}>
|
||||
<TableCell>
|
||||
<FormComponent />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getPrivacyPolicyConfig, updatePrivacyPolicyConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { MarkdownEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function PrivacyPolicy() {
|
||||
const t = useTranslations('system.privacy-policy');
|
||||
const { data, refetch, isFetched } = useQuery({
|
||||
queryKey: ['getPrivacyPolicyConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getPrivacyPolicyConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updatePrivacyPolicyConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.PrivacyPolicyConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
isFetched && (
|
||||
<div className='h-[calc(100dvh-132px-env(safe-area-inset-top))] overflow-hidden'>
|
||||
<MarkdownEditor
|
||||
title={t('title')}
|
||||
value={data?.privacy_policy}
|
||||
onBlur={(value) => {
|
||||
if (data?.privacy_policy !== value) {
|
||||
updateConfig('privacy_policy', value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getSiteConfig, updateSiteConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
|
||||
import { Textarea } from '@workspace/ui/components/textarea';
|
||||
import { JSONEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Site() {
|
||||
const t = useTranslations('system.site');
|
||||
const ref = useRef<API.SiteConfig | undefined>(undefined);
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getSiteConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSiteConfig();
|
||||
ref.current = data.data;
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateSiteConfig({
|
||||
...ref.current,
|
||||
[key]: value,
|
||||
} as API.SiteConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('logo')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('logoDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('logoPlaceholder')}
|
||||
value={data?.site_logo}
|
||||
onValueBlur={(value) => updateConfig('site_logo', value)}
|
||||
suffix={
|
||||
<UploadImage
|
||||
className='bg-muted h-9 rounded-none border-none px-2'
|
||||
onChange={(value) => {
|
||||
updateConfig('site_logo', value);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('siteName')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('siteNameDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('siteNamePlaceholder')}
|
||||
value={data?.site_name}
|
||||
onValueBlur={(value) => updateConfig('site_name', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('siteDesc')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('siteDescDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('siteDescPlaceholder')}
|
||||
value={data?.site_desc}
|
||||
onValueBlur={(value) => updateConfig('site_desc', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('keywords')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('keywordsDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<EnhancedInput
|
||||
placeholder={t('keywordsDescription')}
|
||||
value={data?.keywords}
|
||||
onValueBlur={(value) => updateConfig('keywords', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('customHtml')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('customHtmlDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Textarea
|
||||
className='h-52'
|
||||
placeholder={t('customHtmlDescription')}
|
||||
defaultValue={data?.custom_html}
|
||||
onBlur={(e) => {
|
||||
updateConfig('custom_html', e.target.value);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell className='align-top'>
|
||||
<Label>{t('siteDomain')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('siteDomainDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<Textarea
|
||||
className='h-52'
|
||||
placeholder={`${t('siteDomainPlaceholder')}\nexample.com\nwww.example.com`}
|
||||
defaultValue={data?.host}
|
||||
onBlur={(e) => {
|
||||
updateConfig('host', e.target.value);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<Label>{t('customData')}</Label>
|
||||
<p className='text-muted-foreground text-xs'>{t('customDataDescription')}</p>
|
||||
</TableCell>
|
||||
<TableCell className='w-1/2 text-right'>
|
||||
<JSONEditor
|
||||
schema={{
|
||||
type: 'object',
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
website: { type: 'string', title: 'Website' },
|
||||
contacts: {
|
||||
type: 'object',
|
||||
title: 'Contacts',
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
email: { type: 'string', title: 'Email' },
|
||||
telephone: { type: 'string', title: 'Telephone' },
|
||||
address: { type: 'string', title: 'Address' },
|
||||
},
|
||||
},
|
||||
community: {
|
||||
type: 'object',
|
||||
title: 'Community',
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
telegram: { type: 'string', title: 'Telegram' },
|
||||
twitter: { type: 'string', title: 'Twitter' },
|
||||
discord: { type: 'string', title: 'Discord' },
|
||||
instagram: { type: 'string', title: 'Instagram' },
|
||||
linkedin: { type: 'string', title: 'Linkedin' },
|
||||
facebook: { type: 'string', title: 'Facebook' },
|
||||
github: { type: 'string', title: 'Github' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
value={data?.custom_data}
|
||||
onBlur={(value) => updateConfig('custom_data', value)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getTosConfig, updateTosConfig } from '@/services/admin/system';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { MarkdownEditor } from '@workspace/ui/custom-components/editor';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function Tos() {
|
||||
const t = useTranslations('system.tos');
|
||||
const { data, refetch, isFetched } = useQuery({
|
||||
queryKey: ['getTosConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getTosConfig();
|
||||
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
async function updateConfig(key: string, value: unknown) {
|
||||
if (data?.[key] === value) return;
|
||||
try {
|
||||
await updateTosConfig({
|
||||
...data,
|
||||
[key]: value,
|
||||
} as API.TosConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
} catch (error) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
isFetched && (
|
||||
<div className='h-[calc(100dvh-132px-env(safe-area-inset-top))] overflow-hidden'>
|
||||
<MarkdownEditor
|
||||
title={t('title')}
|
||||
value={data?.tos_content}
|
||||
onBlur={(value) => {
|
||||
if (data?.tos_content !== value) {
|
||||
updateConfig('tos_content', value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
'use client';
|
||||
|
||||
import { getInviteConfig, updateInviteConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const inviteSchema = z.object({
|
||||
forced_invite: z.boolean().optional(),
|
||||
referral_percentage: z.number().optional(),
|
||||
only_first_purchase: z.boolean().optional(),
|
||||
});
|
||||
|
||||
type InviteFormData = z.infer<typeof inviteSchema>;
|
||||
|
||||
export default function InviteConfig() {
|
||||
const t = useTranslations('system.invite');
|
||||
const systemT = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getInviteConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getInviteConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<InviteFormData>({
|
||||
resolver: zodResolver(inviteSchema),
|
||||
defaultValues: {
|
||||
forced_invite: false,
|
||||
referral_percentage: 0,
|
||||
only_first_purchase: false,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: InviteFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateInviteConfig(values as API.InviteConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:account-multiple-plus-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='invite-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='forced_invite'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('forcedInvite')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('forcedInviteDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='referral_percentage'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('referralPercentage')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={0}
|
||||
max={100}
|
||||
suffix='%'
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('referralPercentageDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='only_first_purchase'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('onlyFirstPurchase')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('onlyFirstPurchaseDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{systemT('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='invite-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{systemT('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
'use client';
|
||||
|
||||
import { getSubscribeList } from '@/services/admin/subscribe';
|
||||
import { getRegisterConfig, updateRegisterConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Combobox } from '@workspace/ui/custom-components/combobox';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const registerSchema = z.object({
|
||||
stop_register: z.boolean().optional(),
|
||||
enable_trial: z.boolean().optional(),
|
||||
trial_subscribe: z.number().optional(),
|
||||
trial_time: z.number().optional(),
|
||||
trial_time_unit: z.string().optional(),
|
||||
enable_ip_register_limit: z.boolean().optional(),
|
||||
ip_register_limit: z.number().optional(),
|
||||
ip_register_limit_duration: z.number().optional(),
|
||||
});
|
||||
|
||||
type RegisterFormData = z.infer<typeof registerSchema>;
|
||||
|
||||
export default function RegisterConfig() {
|
||||
const t = useTranslations('system.register');
|
||||
const systemT = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getRegisterConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getRegisterConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const { data: subscribe } = useQuery({
|
||||
queryKey: ['getSubscribeList', 'all'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSubscribeList({
|
||||
page: 1,
|
||||
size: 9999,
|
||||
});
|
||||
return data.data?.list as API.Subscribe[];
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<RegisterFormData>({
|
||||
resolver: zodResolver(registerSchema),
|
||||
defaultValues: {
|
||||
stop_register: false,
|
||||
enable_trial: false,
|
||||
trial_subscribe: undefined,
|
||||
trial_time: 0,
|
||||
trial_time_unit: 'day',
|
||||
enable_ip_register_limit: false,
|
||||
ip_register_limit: 1,
|
||||
ip_register_limit_duration: 1,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: RegisterFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateRegisterConfig(values as API.RegisterConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:account-plus-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='register-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='stop_register'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('stopNewUserRegistration')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('stopNewUserRegistrationDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enable_ip_register_limit'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('ipRegistrationLimit')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('ipRegistrationLimitDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{form.watch('enable_ip_register_limit') && (
|
||||
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='ip_register_limit'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('registrationLimitCount')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={1}
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('registrationLimitCountDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='ip_register_limit_duration'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('registrationLimitExpire')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={1}
|
||||
suffix={t('minute')}
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('registrationLimitExpireDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enable_trial'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('enableTrial')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('enableTrialDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{form.watch('enable_trial') && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='trial_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('trialConfig')}</FormLabel>
|
||||
<FormControl>
|
||||
<div className='flex gap-2'>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={0}
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
className='flex-1'
|
||||
prefix={
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='trial_subscribe'
|
||||
render={({ field }) => (
|
||||
<Combobox
|
||||
placeholder={t('selectPlaceholder')}
|
||||
value={field.value}
|
||||
onChange={(value: number) => {
|
||||
if (value) {
|
||||
field.onChange(value);
|
||||
}
|
||||
}}
|
||||
options={
|
||||
subscribe?.map((item) => ({
|
||||
label: item.name,
|
||||
value: item.id,
|
||||
})) || []
|
||||
}
|
||||
className='bg-secondary w-32 rounded-r-none'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
suffix={
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='trial_time_unit'
|
||||
render={({ field: unitField }) => (
|
||||
<Combobox
|
||||
placeholder={t('selectPlaceholder')}
|
||||
value={unitField.value}
|
||||
onChange={(value: string) => {
|
||||
unitField.onChange(value);
|
||||
}}
|
||||
options={[
|
||||
{ label: t('none'), value: 'None' },
|
||||
{ label: t('year'), value: 'Year' },
|
||||
{ label: t('month'), value: 'Month' },
|
||||
{ label: t('day'), value: 'Day' },
|
||||
{ label: t('hour'), value: 'Hour' },
|
||||
{ label: t('minute'), value: 'Minute' },
|
||||
]}
|
||||
className='bg-secondary w-32 rounded-l-none'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormDescription>{t('trialConfigDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{systemT('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='register-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{systemT('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
'use client';
|
||||
|
||||
import { getVerifyCodeConfig, updateVerifyCodeConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const verifyCodeSchema = z.object({
|
||||
verify_code_expire_time: z.number().optional(),
|
||||
verify_code_interval: z.number().optional(),
|
||||
verify_code_limit: z.number().optional(),
|
||||
});
|
||||
|
||||
type VerifyCodeFormData = z.infer<typeof verifyCodeSchema>;
|
||||
|
||||
export default function VerifyCodeConfig() {
|
||||
const t = useTranslations('system.verifyCode');
|
||||
const systemT = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getVerifyCodeConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getVerifyCodeConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<VerifyCodeFormData>({
|
||||
resolver: zodResolver(verifyCodeSchema),
|
||||
defaultValues: {
|
||||
verify_code_expire_time: 300,
|
||||
verify_code_interval: 60,
|
||||
verify_code_limit: 10,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: VerifyCodeFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateVerifyCodeConfig(values as API.VerifyCodeConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:message-text-clock-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='verify-code-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='verify_code_expire_time'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('expireTime')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={60}
|
||||
suffix={t('seconds')}
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('expireTimeDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='verify_code_interval'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('interval')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={30}
|
||||
suffix={t('seconds')}
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('intervalDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='verify_code_limit'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('dailyLimit')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('inputPlaceholder')}
|
||||
value={field.value}
|
||||
type='number'
|
||||
min={1}
|
||||
suffix={t('times')}
|
||||
onValueBlur={(value) => field.onChange(Number(value))}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('dailyLimitDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{systemT('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='verify-code-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{systemT('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
'use client';
|
||||
|
||||
import { getVerifyConfig, updateVerifyConfig } from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const verifySchema = z.object({
|
||||
turnstile_site_key: z.string().optional(),
|
||||
turnstile_secret: z.string().optional(),
|
||||
enable_register_verify: z.boolean().optional(),
|
||||
enable_login_verify: z.boolean().optional(),
|
||||
enable_password_verify: z.boolean().optional(),
|
||||
});
|
||||
|
||||
type VerifyFormData = z.infer<typeof verifySchema>;
|
||||
|
||||
export default function VerifyConfig() {
|
||||
const t = useTranslations('system.verify');
|
||||
const systemT = useTranslations('system');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ['getVerifyConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getVerifyConfig();
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<VerifyFormData>({
|
||||
resolver: zodResolver(verifySchema),
|
||||
defaultValues: {
|
||||
turnstile_site_key: '',
|
||||
turnstile_secret: '',
|
||||
enable_register_verify: false,
|
||||
enable_login_verify: false,
|
||||
enable_password_verify: false,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
form.reset(data);
|
||||
}
|
||||
}, [data, form]);
|
||||
|
||||
async function onSubmit(values: VerifyFormData) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateVerifyConfig(values as API.VerifyConfig);
|
||||
toast.success(t('saveSuccess'));
|
||||
refetch();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(t('saveFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between transition-colors'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:shield-check-outline' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='verify-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-2 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='turnstile_site_key'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('turnstileSiteKey')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('turnstileSiteKeyPlaceholder')}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('turnstileSiteKeyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='turnstile_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('turnstileSecret')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('turnstileSecretPlaceholder')}
|
||||
value={field.value}
|
||||
type='password'
|
||||
onValueChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('turnstileSecretDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enable_register_verify'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('enableRegisterVerify')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('enableRegisterVerifyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enable_login_verify'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('enableLoginVerify')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('enableLoginVerifyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='enable_password_verify'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('enablePasswordVerify')}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
className='float-end !mt-0'
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('enablePasswordVerifyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{systemT('common.cancel')}
|
||||
</Button>
|
||||
<Button disabled={loading} type='submit' form='verify-form'>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
|
||||
{systemT('common.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -7,12 +7,12 @@ import {
|
||||
getTicketList,
|
||||
updateTicketStatus,
|
||||
} from '@/services/admin/ticket';
|
||||
import { formatDate } from '@/utils/common';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
@@ -23,9 +23,7 @@ import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import NextImage from 'next/legacy/image';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { UserDetail } from '../user/user-detail';
|
||||
@@ -130,7 +128,7 @@ export default function Page() {
|
||||
render(row) {
|
||||
if (row.status !== 4) {
|
||||
return [
|
||||
<Button key='reply' size='sm' onClick={() => setTicketId(row.id)}>
|
||||
<Button key='reply' onClick={() => setTicketId(row.id)}>
|
||||
{t('reply')}
|
||||
</Button>,
|
||||
<ConfirmButton
|
||||
@@ -166,13 +164,25 @@ export default function Page() {
|
||||
if (!open) setTicketId(null);
|
||||
}}
|
||||
>
|
||||
<DrawerContent className='container mx-auto h-screen'>
|
||||
<DrawerContent className='container mx-auto h-screen *:select-text'>
|
||||
<DrawerHeader className='border-b text-left'>
|
||||
<DrawerTitle>{ticket?.title}</DrawerTitle>
|
||||
<DrawerDescription>{ticket?.description}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<ScrollArea className='h-full overflow-hidden' ref={scrollRef}>
|
||||
<div className='flex h-screen flex-col gap-4 p-4'>
|
||||
<div className='flex h-full flex-col gap-4 p-4'>
|
||||
{/* 显示工单描述作为第一条用户消息 */}
|
||||
{ticket?.description && (
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-col gap-1'>
|
||||
<p className='text-muted-foreground text-sm'>{formatDate(ticket.created_at)}</p>
|
||||
<p className='bg-accent w-fit rounded-lg p-2 font-medium'>
|
||||
{ticket.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 显示后续跟进消息 */}
|
||||
{ticket?.follow?.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
@@ -193,7 +203,8 @@ export default function Page() {
|
||||
>
|
||||
{item.type === 1 && item.content}
|
||||
{item.type === 2 && (
|
||||
<NextImage
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={item.content!}
|
||||
width={300}
|
||||
height={300}
|
||||
|
||||
@@ -1,351 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { getSystemLog, getVersion, restartSystem } from '@/services/admin/tool';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from '@workspace/ui/components/accordion';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@workspace/ui/components/alert-dialog';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@workspace/ui/components/card';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { formatDate } from '@workspace/ui/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import packageJson from '../../../../../package.json';
|
||||
|
||||
const getLogLevelColor = (level: string) => {
|
||||
const colorMap: { [key: string]: string } = {
|
||||
INFO: 'bg-blue-100 text-blue-800 hover:bg-blue-200',
|
||||
WARN: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-200',
|
||||
ERROR: 'bg-red-100 text-red-800 hover:bg-red-200',
|
||||
};
|
||||
return colorMap[level] || 'bg-gray-100 text-gray-800 hover:bg-gray-200';
|
||||
};
|
||||
|
||||
export default function Page() {
|
||||
const t = useTranslations('tool');
|
||||
const {
|
||||
data: logs,
|
||||
refetch,
|
||||
isLoading,
|
||||
} = useQuery({
|
||||
queryKey: ['getSystemLog'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getSystemLog();
|
||||
return data.data?.list || [];
|
||||
},
|
||||
});
|
||||
|
||||
const [openRestart, setOpenRestart] = useState(false);
|
||||
const [isRestarting, setIsRestarting] = useState(false);
|
||||
|
||||
const { data: latestReleases } = useQuery({
|
||||
queryKey: ['getLatestReleases'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const [webResponse, serverResponse] = await Promise.all([
|
||||
fetch('https://api.github.com/repos/perfect-panel/ppanel-web/releases/latest'),
|
||||
fetch('https://api.github.com/repos/perfect-panel/server/releases/latest'),
|
||||
]);
|
||||
|
||||
const webData = webResponse.ok ? await webResponse.json() : null;
|
||||
const serverData = serverResponse.ok ? await serverResponse.json() : null;
|
||||
|
||||
return {
|
||||
web: webData
|
||||
? {
|
||||
version: webData.tag_name,
|
||||
url: webData.html_url,
|
||||
publishedAt: webData.published_at,
|
||||
}
|
||||
: null,
|
||||
server: serverData
|
||||
? {
|
||||
version: serverData.tag_name,
|
||||
url: serverData.html_url,
|
||||
publishedAt: serverData.published_at,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch latest releases:', error);
|
||||
return { web: null, server: null };
|
||||
}
|
||||
},
|
||||
staleTime: 60 * 60 * 1000,
|
||||
retry: 1,
|
||||
retryDelay: 10000,
|
||||
});
|
||||
|
||||
// 检查是否有新版本
|
||||
const hasNewVersion =
|
||||
latestReleases?.web && packageJson.version !== latestReleases.web.version.replace(/^v/, '');
|
||||
|
||||
const { data: systemInfo } = useQuery({
|
||||
queryKey: ['getVersion'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getVersion();
|
||||
|
||||
const versionString = data.data?.version || '';
|
||||
const releaseVersionRegex = /^[Vv]?\d+\.\d+\.\d+$/;
|
||||
const timeMatch = versionString.match(/\(([^)]+)\)/);
|
||||
const timeInBrackets = timeMatch ? timeMatch[1] : '';
|
||||
|
||||
const versionWithoutTime = versionString.replace(/\([^)]*\)/, '').trim();
|
||||
const isDevelopment = !releaseVersionRegex.test(versionWithoutTime);
|
||||
|
||||
let baseVersion = versionWithoutTime;
|
||||
let versionSuffix = '';
|
||||
let lastUpdated = '';
|
||||
|
||||
if (isDevelopment && versionWithoutTime.includes('-')) {
|
||||
const parts = versionWithoutTime.split('-');
|
||||
baseVersion = parts[0] || versionWithoutTime;
|
||||
versionSuffix = parts.slice(1).join('-');
|
||||
}
|
||||
|
||||
lastUpdated = formatDate(new Date(timeInBrackets || Date.now())) || '';
|
||||
|
||||
const displayVersion =
|
||||
baseVersion.startsWith('V') || baseVersion.startsWith('v')
|
||||
? baseVersion
|
||||
: `V${baseVersion}`;
|
||||
|
||||
return {
|
||||
isRelease: !isDevelopment,
|
||||
version: displayVersion,
|
||||
lastUpdated,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const hasServerNewVersion =
|
||||
latestReleases?.server &&
|
||||
systemInfo &&
|
||||
systemInfo.version.replace(/^V/, '') !== latestReleases.server.version.replace(/^v/, '');
|
||||
|
||||
return (
|
||||
<Card className='border-none'>
|
||||
<CardHeader className='flex flex-col items-start justify-between sm:flex-row sm:items-center'>
|
||||
<div>
|
||||
<CardTitle>{t('systemServices')}</CardTitle>
|
||||
<CardDescription>{t('viewLogsAndManage')}</CardDescription>
|
||||
</div>
|
||||
<div className='mt-4 flex flex-col space-y-2 sm:mt-0 sm:flex-row sm:space-x-2 sm:space-y-0'>
|
||||
{/* <AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button>{t('systemUpgrade')}</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('confirmSystemUpgrade')}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t('upgradeDescription')}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
|
||||
<AlertDialogAction>{t('confirmUpgrade')}</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog> */}
|
||||
<AlertDialog open={openRestart} onOpenChange={setOpenRestart}>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant='destructive'>{t('systemReboot')}</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('confirmSystemReboot')}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t('rebootDescription')}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
|
||||
<Button
|
||||
onClick={async () => {
|
||||
setIsRestarting(true);
|
||||
await restartSystem();
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000));
|
||||
setIsRestarting(false);
|
||||
setOpenRestart(false);
|
||||
}}
|
||||
disabled={isRestarting}
|
||||
>
|
||||
{isRestarting && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}{' '}
|
||||
{isRestarting ? t('rebooting') : t('confirmReboot')}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='space-y-4'>
|
||||
{/* 版本信息紧凑显示 */}
|
||||
<div className='flex flex-col space-y-2 sm:flex-row sm:space-x-3 sm:space-y-0'>
|
||||
{/* 用户端/管理端版本 */}
|
||||
<div className='bg-muted/30 flex flex-1 items-center justify-between rounded-md p-2'>
|
||||
<div className='flex items-center'>
|
||||
<Icon icon='mdi:web' className='mr-2 h-4 w-4 text-green-600' />
|
||||
<div className='flex items-center space-x-2'>
|
||||
<span className='text-xs font-medium'>{t('webVersion')}</span>
|
||||
<Badge variant='default' className='px-1.5 py-0.5 text-xs'>
|
||||
V{packageJson.version}
|
||||
</Badge>
|
||||
{hasNewVersion && (
|
||||
<Badge variant='destructive' className='animate-pulse px-1.5 py-0.5 text-xs'>
|
||||
{t('newVersionAvailable')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{hasNewVersion && (
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-6 px-2 text-xs'
|
||||
onClick={() =>
|
||||
window.open(
|
||||
latestReleases?.web?.url ||
|
||||
'https://github.com/perfect-panel/ppanel-web/releases',
|
||||
'_blank',
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon icon='mdi:open-in-new' className='mr-1 h-3 w-3' />
|
||||
{t('viewNewVersion')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 服务端版本 */}
|
||||
<div className='bg-muted/30 flex flex-1 items-center justify-between rounded-md p-2'>
|
||||
<div className='flex items-center'>
|
||||
<Icon icon='mdi:server' className='mr-2 h-4 w-4 text-blue-600' />
|
||||
<div className='flex items-center space-x-2'>
|
||||
<span className='text-xs font-medium'>{t('serverVersion')}</span>
|
||||
<Badge
|
||||
variant={!systemInfo?.isRelease ? 'destructive' : 'default'}
|
||||
className='px-1.5 py-0.5 text-xs'
|
||||
>
|
||||
{systemInfo?.version || 'V1.0.0'}
|
||||
{!systemInfo?.isRelease && (
|
||||
<span className='ml-1'>{t('developmentVersion')}</span>
|
||||
)}
|
||||
</Badge>
|
||||
{hasServerNewVersion && (
|
||||
<Badge variant='destructive' className='animate-pulse px-1.5 py-0.5 text-xs'>
|
||||
{t('newVersionAvailable')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center space-x-2'>
|
||||
{hasServerNewVersion && (
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-6 px-2 text-xs'
|
||||
onClick={() =>
|
||||
window.open(
|
||||
latestReleases?.server?.url ||
|
||||
'https://github.com/perfect-panel/server/releases',
|
||||
'_blank',
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon icon='mdi:open-in-new' className='mr-1 h-3 w-3' />
|
||||
{t('viewNewVersion')}
|
||||
</Button>
|
||||
)}
|
||||
<div className='text-muted-foreground hidden text-right text-xs sm:block'>
|
||||
<div className='font-mono'>{systemInfo?.lastUpdated || '--'}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Card className='overflow-hidden'>
|
||||
<CardHeader className='bg-secondary py-1'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<CardTitle>{t('systemLogs')}</CardTitle>
|
||||
<Button variant='ghost' size='icon' disabled={isLoading} onClick={() => refetch()}>
|
||||
<Icon
|
||||
icon='uil:refresh'
|
||||
className={`h-5 w-5 ${isLoading ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
<span className='sr-only'>{t('refreshLogs')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='p-0'>
|
||||
<ScrollArea className='h-[calc(100dvh-300px)] w-full rounded-md'>
|
||||
{isLoading ? (
|
||||
<div className='flex h-full items-center justify-center'>
|
||||
<Icon icon='uil:loading' className='text-primary h-8 w-8 animate-spin' />
|
||||
</div>
|
||||
) : (
|
||||
<Accordion type='single' collapsible className='w-full'>
|
||||
{logs?.map((log: any, index: number) => (
|
||||
<AccordionItem key={index} value={`item-${index}`} className='px-4'>
|
||||
<AccordionTrigger className='hover:no-underline'>
|
||||
<div className='flex w-full flex-col items-start space-y-2 sm:flex-row sm:items-center sm:space-x-4 sm:space-y-0'>
|
||||
<span className='text-xs font-medium sm:text-sm'>{log.timestamp}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className='px-2'>
|
||||
{Object.entries(log).map(([key, value]) => (
|
||||
<div
|
||||
key={key}
|
||||
className='grid grid-cols-1 gap-2 text-xs sm:grid-cols-2 sm:text-sm'
|
||||
>
|
||||
<span className='font-medium'>{key}:</span>
|
||||
<span className='break-all'>{value as string}</span>
|
||||
</div>
|
||||
))}
|
||||
{/* <div className='grid grid-cols-1 gap-2 text-xs sm:grid-cols-2 sm:text-sm'>
|
||||
<div className='font-medium'>{t('ip')}:</div>
|
||||
<div>{log.ip}</div>
|
||||
<div className='font-medium'>{t('request')}:</div>
|
||||
<div className='break-all'>{log.request}</div>
|
||||
<div className='font-medium'>{t('status')}:</div>
|
||||
<div>{log.status}</div>
|
||||
<div className='font-medium'>{t('caller')}:</div>
|
||||
<div className='break-all'>{log.caller}</div>
|
||||
<div className='font-medium'>{t('errors')}:</div>
|
||||
<div className='break-all'>{log.errors || t('none')}</div>
|
||||
<div className='font-medium'>{t('query')}:</div>
|
||||
<div className='break-all'>{log.query || t('none')}</div>
|
||||
<div className='font-medium'>{t('userAgent')}:</div>
|
||||
<div className='break-all'>{log['user-agent']}</div>
|
||||
</div> */}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user