6 Commits

16 changed files with 567 additions and 101 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "lanhu-admin",
"version": "1.3.0",
"version": "1.6.0",
"private": true,
"scripts": {
"dev": "next dev -H 0.0.0.0 -p 3001 --turbopack",

29
src/actions/gateway.ts Normal file
View File

@@ -0,0 +1,29 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { Gateway } from "@/models/gateway"
import { callByUser } from "./base"
export async function getGatewayPage(params: { page: number; size: number }) {
return callByUser<PageRecord<Gateway>>("/api/admin/proxy/page", params)
}
export async function createGateway(data: {
mac: string
ip: string
host?: string
type: number
status: number
}) {
return callByUser<Gateway>("/api/admin/proxy/create", data)
}
export async function updateGateway(data:{
id: number,
status: number}
) {
return callByUser<Gateway>("/api/admin/proxy/update/status",
data
)
}

View File

@@ -45,6 +45,7 @@ export async function updateProductSku(data: {
price?: string
discount_id?: number | null
price_min?: string
count_min?: number | null
}) {
return callByUser<ProductSku>("/api/admin/product/sku/update", {
id: data.id,
@@ -53,6 +54,7 @@ export async function updateProductSku(data: {
price: data.price,
discount_id: data.discount_id,
price_min: data.price_min,
count_min: data.count_min,
})
}

View File

@@ -28,7 +28,7 @@ export async function listResourceShort(params: ResourceListParams) {
)
}
export async function updateResource(data: { id: number; active?: boolean }) {
export async function updateResource(data: { id: number; active?: boolean; checkip?: boolean}) {
return callByUser<Resources>("/api/admin/resource/update", data)
}

View File

@@ -88,6 +88,7 @@ export default function Appbar(props: { admin: Admin }) {
discount: "折扣管理",
statistics: "数据统计",
balance: "余额明细",
gateway: "网关列表",
}
return labels[path] || path
@@ -103,7 +104,7 @@ export default function Appbar(props: { admin: Admin }) {
}
return (
<header className="bg-white flex-none basis-16 border-b border-gray-200 flex items-center justify-between px-6">
<header className="bg-white flex-none basis-16 border-b border-gray-200 flex items-center justify-between px-6 z-40">
{/* 面包屑导航 */}
<div className="flex items-center text-sm">
{breadcrumbs.map((crumb, index) => (
@@ -193,7 +194,7 @@ export default function Appbar(props: { admin: Admin }) {
</div>
)}
<div className="py-1">
<div className="py-1 ">
<Link
href="/profile"
className="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"

View File

@@ -0,0 +1,243 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import z from "zod"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { toast } from "sonner"
import { createGateway } from "@/actions/gateway"
const schema = z.object({
mac: z.string(),
ip: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, {
message: "IP地址格式不正确请使用如 192.168.1.1 的格式"
}),
host: z.string().regex(/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/, {
message: "域名格式不正确,请使用如 example.com 的格式"
}).or(z.literal("")),
type: z.string().optional(),
status: z.string().optional(),
})
export default function CreatePage(props: { onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
mac: "",
ip: "",
host: "",
type: "1",
status: "0",
},
})
const onSubmit = async (data: z.infer<typeof schema>) => {
setIsLoading(true)
try {
const payload = {
mac: data.mac.trim(),
ip: data.ip.trim(),
host: data?.host.trim(),
type: data.type ? Number(data.type) : 0,
status: data.status ? Number(data.status) : 0,
}
const res = await createGateway(payload)
if (res.success) {
toast.success("添加网关成功")
setOpen(false)
props.onSuccess?.()
form.reset()
}else {
toast.error(res.message || "添加失败")
}
} catch (error) {
console.error("添加网关失败:", error)
const message = error instanceof Error ? error.message : error
toast.error(`添加失败: ${message}`)
} finally {
setIsLoading(false)
}
}
const handleCancel = () => {
setOpen(false)
form.reset()
}
const statusOptions = [
{ value: "0", label: "离线" },
{ value: "1", label: "在线" },
]
const typeOptions = [
{ value: "1", label: "自有" },
{ value: "2", label: "白银" },
]
return (
<Dialog
open={open}
onOpenChange={newOpen => {
setOpen(newOpen)
if (!newOpen) {
form.reset()
}
}}
>
<DialogTrigger asChild>
<Button></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form
id="gateway-create"
onSubmit={form.handleSubmit(onSubmit)}
>
<FieldGroup>
<Controller
control={form.control}
name="mac"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-mac">:</FieldLabel>
<Input
id="gateway-create-mac"
placeholder="请输入MAC地址00:11:22:33:44:55"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && fieldState.error && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="ip"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-ip">IP地址:</FieldLabel>
<Input
id="gateway-create-ip"
placeholder="请输入IP地址192.168.1.1"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && fieldState.error && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="host"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-host">:</FieldLabel>
<Input
id="gateway-create-host"
placeholder="请输入域名example.com"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && fieldState.error && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="type"
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-9">
<SelectValue placeholder="请选择网关类型" />
</SelectTrigger>
<SelectContent>
{typeOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && fieldState.error && (
<FieldError>{fieldState.error?.message}</FieldError>
)}
</Field>
)}
/>
<Controller
control={form.control}
name="status"
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-9">
<SelectValue placeholder="请选择网关状态" />
</SelectTrigger>
<SelectContent>
{statusOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && fieldState.error && (
<FieldError>{fieldState.error?.message}</FieldError>
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter className="gap-2">
<Button variant="ghost" onClick={handleCancel} disabled={isLoading}>
</Button>
<Button type="submit" form="gateway-create" disabled={isLoading}>
{isLoading ? "添加中..." : "添加"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,103 @@
"use client"
import { format } from "date-fns"
import { Suspense, useCallback, useState } from "react"
import { toast } from "sonner"
import { getGatewayPage, updateGateway } from "@/actions/gateway"
import { Auth } from "@/components/auth"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import { ScopeProxyWrite } from "@/lib/scopes"
import type { Gateway } from "@/models/gateway"
import CreatePage from "./create"
export default function GatewayPage() {
const [loading, setLoading] = useState(false)
const getGatewayPageWrapper = useCallback((page: number, size: number) => {
return getGatewayPage({ page, size })
}, [])
const table = useDataTable(getGatewayPageWrapper)
const handleToggle = async (id: number, status: number) => {
setLoading(true)
try {
const result = await updateGateway({
id:id,
status: status === 0 ? 1 : 0
})
if (result.success) {
toast.success(status === 0 ? "启用成功" : "停用成功")
table.refresh()
} else {
toast.error(result.message || "操作失败")
}
} catch (error) {
toast.error("操作失败")
} finally {
setLoading(false)
}
}
return (
<Page>
<Auth scope={ScopeProxyWrite}>
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<CreatePage onSuccess={table.refresh} />
</div>
</div>
</Auth>
<Suspense>
<DataTable<Gateway>
{...table}
status={loading ? "load" : "done"}
columns={[
{
header: "域名",
accessorKey: "host",
},
{ header: "IP地址", accessorKey: "ip" },
{
header: "MAC地址",
accessorKey: "mac",
},
{
header: "类型",
accessorKey: "type",
cell: ({ row }) => (row.original.type === 1 ? "自有" : "白银"),
},
{
header: "状态",
accessorKey: "status",
cell: ({ row }) => (row.original.status === 0 ? "离线" : "在线"),
},
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-2">
<Button
onClick={() => handleToggle(row.original.id, row.original.status)}
disabled={loading}
variant={row.original.status === 0 ? "default" : "destructive"}
>
{row.original.status === 0 ? "启用" : "停用"}
</Button>
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -9,6 +9,7 @@ import {
ComputerIcon,
ContactRound,
DollarSign,
DoorClosedIcon,
FolderCode,
Home,
KeyRound,
@@ -46,6 +47,7 @@ import {
ScopeDiscountRead,
ScopePermissionRead,
ScopeProductRead,
ScopeProxyRead,
ScopeResourceRead,
ScopeTradeRead,
ScopeUserRead,
@@ -249,6 +251,12 @@ const menuSections: { title: string; items: NavItemProps[] }[] = [
{
title: "系统",
items: [
{
href: "/gateway",
icon: DoorClosedIcon,
label: "网关列表",
requiredScope:ScopeProxyRead
},
{
href: "/admin",
icon: Shield,

View File

@@ -34,25 +34,39 @@ import {
import type { ProductDiscount } from "@/models/product_discount"
import type { SelectedProduct } from "./type"
const schema = z.object({
code: z.string().min(1, "请输入套餐编码"),
name: z.string().min(1, "请输入套餐名称"),
price: z
.string()
.min(1, "请输入单价")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数单价",
),
discount_id: z.string().optional(),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
),
})
const schema = z
.object({
code: z.string().min(1, "请输入套餐编码"),
name: z.string().min(1, "请输入套餐名称"),
price: z
.string()
.min(1, "请输入单价")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数单价",
),
discount_id: z.string().optional(),
count_min: z.string().min(1, "请输入最低购买数量"),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
),
})
.refine(
data => {
const price = Number(data.price)
const priceMin = Number(data.price_min)
if (isNaN(price) || isNaN(priceMin)) return true
return price >= priceMin
},
{
message: "单价不能低于最低价格",
path: ["price"],
},
)
export function CreateProductSku(props: {
product?: SelectedProduct
@@ -164,19 +178,6 @@ export function CreateProductSku(props: {
placeholder="请输入单价"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
@@ -195,19 +196,6 @@ export function CreateProductSku(props: {
placeholder="请输入最低价格"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
@@ -215,7 +203,26 @@ export function CreateProductSku(props: {
</Field>
)}
/>
<Controller
control={form.control}
name="count_min"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-create-price">
</FieldLabel>
<Input
id="sku-create-price"
placeholder="请输入最低购买数量"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="discount_id"

View File

@@ -141,6 +141,7 @@ function ProductSkus(props: {
},
},
{ header: "最低价格", accessorKey: "price_min" },
{ header: "最低购买数量", accessorKey: "count_min" },
{
header: "创建时间",
accessorFn: row => format(row.created_at, "yyyy-MM-dd HH:mm"),

View File

@@ -34,25 +34,48 @@ import {
import type { ProductDiscount } from "@/models/product_discount"
import type { ProductSku } from "@/models/product_sku"
const schema = z.object({
code: z.string().min(1, "请输入套餐编码"),
name: z.string().min(1, "请输入套餐名称"),
price: z
.string()
.min(1, "请输入单价")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数单价",
),
discount_id: z.string().optional(),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
),
})
const schema = z
.object({
code: z.string().min(1, "请输入套餐编码"),
name: z.string().min(1, "请输入套餐名称"),
price: z
.string()
.min(1, "请输入单价")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数单价",
),
discount_id: z.string().optional(),
count_min: z
.string()
.min(1, "请输入最低购买数量")
.refine(
v =>
!Number.isNaN(Number(v)) &&
Number.isInteger(Number(v)) &&
Number(v) > 0,
"请输入有效的正整数",
),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
),
})
.refine(
data => {
const price = Number(data.price)
const priceMin = Number(data.price_min)
if (isNaN(price) || isNaN(priceMin)) return true
return price >= priceMin
},
{
message: "单价不能低于最低价格",
path: ["price"],
},
)
export function UpdateProductSku(props: {
sku: ProductSku
@@ -69,6 +92,7 @@ export function UpdateProductSku(props: {
price: props.sku.price,
discount_id: props.sku.discount ? String(props.sku.discount.id) : "",
price_min: props.sku.price_min ?? "",
count_min: String(props.sku.count_min),
},
})
@@ -94,7 +118,9 @@ export function UpdateProductSku(props: {
? Number(data.discount_id)
: null,
price_min: data.price_min,
count_min: Number(data.count_min),
})
console.log(resp, "resp")
if (resp.success) {
toast.success("套餐修改成功")
@@ -117,6 +143,7 @@ export function UpdateProductSku(props: {
price: props.sku.price,
discount_id: props.sku.discount ? String(props.sku.discount.id) : "",
price_min: props.sku.price_min ?? "",
count_min: props.sku.count_min ? String(props.sku.count_min) : "",
})
}
setOpen(value)
@@ -167,19 +194,6 @@ export function UpdateProductSku(props: {
placeholder="请输入单价"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
@@ -192,25 +206,34 @@ export function UpdateProductSku(props: {
name="price_min"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-create-price"></FieldLabel>
<FieldLabel htmlFor="sku-update-price-min">
</FieldLabel>
<Input
id="sku-create-price"
id="sku-update-price-min"
placeholder="请输入最低价格"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="count_min"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-update-count-min">
</FieldLabel>
<Input
id="sku-update-count-min"
placeholder="请输入最低购买数量"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />

View File

@@ -255,7 +255,30 @@ function ResourceList({ resourceType }: ResourceListProps) {
},
[refreshTable],
)
const handleCheckipChange = useCallback(
async (resource: Resources) => {
const newCheckip = !resource.checkip
setUpdatingId(resource.id)
try {
await updateResource({
id: resource.id,
checkip: newCheckip,
})
toast.success("更新成功", {
description: `IP检查已${newCheckip ? "启用IP检查" : "停用IP检查"}`,
})
refreshTable()
} catch (error) {
console.error("更新IP检查状态失败:", error)
toast.error("更新失败", {
description: error instanceof Error ? error.message : "请稍后重试",
})
} finally {
setUpdatingId(null)
}
},
[refreshTable],
)
const onFilter = handleSubmit(data => {
const result: FilterParams = {}
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
@@ -388,7 +411,7 @@ function ResourceList({ resourceType }: ResourceListProps) {
{
id: "action",
meta: { pin: "right" },
header: "状态",
header: "操作",
cell: ({ row }: { row: { original: Resources } }) => {
const resource = row.original
const isLoading = updatingId === resource.id
@@ -411,12 +434,19 @@ function ResourceList({ resourceType }: ResourceListProps) {
{isLoading && (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
)}
<Button
onClick={() => handleCheckipChange(resource)}
variant={resource.checkip ? "destructive" : "default"}
disabled={isLoading}
>
{resource.checkip ? "停用IP检查" : "启用IP检查"}
</Button>
</div>
)
},
},
],
[isLong, updatingId, handleStatusChange],
[isLong, updatingId, handleStatusChange, handleCheckipChange],
)
return (

View File

@@ -73,7 +73,6 @@ export const ScopeTrade = "trade"
export const ScopeTradeRead = "trade:read" // 读取交易列表
export const ScopeTradeReadOfUser = "trade:read:of_user" // 读取指定用户的交易列表
export const ScopeTradeWrite = "trade:write" // 写入交易
export const ScopeTradeWriteComplete = "trade:write:complete" // 完成交易
// 账单
export const ScopeBill = "bill"
@@ -85,3 +84,9 @@ export const ScopeBillWrite = "bill:write" // 写入账单
export const ScopeBalanceActivity = "balance_activity"
export const ScopeBalanceActivityRead = "balance_activity:read" // 读取余额变动列表
export const ScopeBalanceActivityReadOfUser = "balance_activity:read:of_user" // 读取指定用户的余额变动列表
// 代理
export const ScopeProxy = "proxy"
export const ScopeProxyRead = "proxy:read" // 读取代理列表
export const ScopeProxyWrite = "proxy:write" // 写入代理
export const ScopeProxyWriteStatus = "proxy:write:status" // 更改代理状态

11
src/models/gateway.ts Normal file
View File

@@ -0,0 +1,11 @@
export type Gateway = {
id: number
version: string
mac: string
ip: string
host: string
type: number
status: number
meta: string
created_at: Date
}

View File

@@ -11,4 +11,6 @@ export type ProductSku = Model & {
product?: Product
price_min?: string
discount?: ProductDiscount
sort: number
count_min: number
}

View File

@@ -10,6 +10,7 @@ type ResourceBase = {
updated_at: Date
deleted_at: Date | null
user: User
checkip:boolean
}
type ResourceShort = {