15 Commits

Author SHA1 Message Date
Eamon
bc29a025b0 网关列表添加清理过期连接按钮功能 2026-05-09 13:45:59 +08:00
Eamon
85f9e68e32 添加优惠券发放的功能 & 切换后台线上和线下首页区别 2026-05-08 16:02:48 +08:00
Eamon
7cd1a7cbe7 修整优惠券页面,添加发放功能及权限控制 & 用户添加查看优惠券发放详情 & 添加切换线上环境页面显示功能 2026-04-28 11:16:54 +08:00
Eamon
66ee6bb9fd 搜索框和输入框保持一行 & 添加菜单里的页面会员号数据显示 2026-04-23 16:43:44 +08:00
Eamon
b041bd3b01 发布v1.7.0版本 2026-04-23 14:14:37 +08:00
Eamon
385869604a 网关添加secret密钥字段 & 更新脚本的远程仓库地址 2026-04-23 11:04:57 +08:00
Eamon
dca32c435a 套餐管理添加IP检查状态字段 2026-04-22 13:26:44 +08:00
Eamon
4b1d87bb14 修复页面重叠的问题 & 网关状态转换 2026-04-21 17:05:19 +08:00
Eamon
69c8029b8b 网关取消删除添加启用和停用功能 & 产品页套餐添加sort 排序和 count_min 最低购买数量字段 2026-04-20 16:32:21 +08:00
Eamon
2377616a07 发布v1.4.0版本 2026-04-18 18:15:03 +08:00
Eamon
9cb7d597cd 添加网关列表权限 2026-04-18 17:58:40 +08:00
Eamon
e5586f06d1 添加网关列表页面 & 添加单价不能低于最低价格校验 2026-04-18 17:41:27 +08:00
Eamon
13be8f3270 搜索框加空格校验 & 发布v1.3.0版本 2026-04-16 14:28:03 +08:00
c850831915 修复套餐编码顺序问题 2026-04-16 10:43:48 +08:00
aa0ab93ba9 修复创建套餐编码格式问题 & 其他样式问题 2026-04-16 10:43:48 +08:00
41 changed files with 1895 additions and 441 deletions

View File

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

View File

@@ -9,8 +9,8 @@ if ($confrim -ne "y") {
exit 0
}
docker build -t repo.lanhuip.com:8554/lanhu/admin:latest .
docker build -t repo.lanhuip.com:8554/lanhu/admin:$($args[0]) .
docker build -t repo.lanhuip.com/lanhu/admin:latest .
docker build -t repo.lanhuip.com/lanhu/admin:$($args[0]) .
docker push repo.lanhuip.com:8554/lanhu/admin:latest
docker push repo.lanhuip.com:8554/lanhu/admin:$($args[0])
docker push repo.lanhuip.com/lanhu/admin:latest
docker push repo.lanhuip.com/lanhu/admin:$($args[0])

View File

@@ -6,7 +6,7 @@ export async function getPageBalance(params: {
page: number
size: number
user_phone?: string
bill_id?: string
bill_no?: string
created_at_start?: Date
created_at_end?: Date
}) {
@@ -21,7 +21,7 @@ export async function getBalance(params: {
size: number
user_id: number
user_phone?: string
bill_id?: string
bill_no?: string
created_at_start?: Date
created_at_end?: Date
}) {

View File

@@ -7,22 +7,28 @@ export async function getPagCoupon(params: { page: number; size: number }) {
}
export async function createCoupon(data: {
code: string
name: string
amount: number
remark?: string
min_amount?: number
count: number
status: number
min_amount: number
expire_at?: Date
expire_in?: number
expire_type: number
}) {
return callByUser<Coupon>("/api/admin/coupon/create", data)
}
export async function updateCoupon(data: {
code: string
id: number
name: string
amount: number
remark?: string
min_amount?: number
min_amount: number
count: number
status: number
expire_type: number
expire_at?: Date
status?: number
expire_in?: number
}) {
return callByUser<Coupon>("/api/admin/coupon/update", data)
}
@@ -32,3 +38,21 @@ export async function deleteCoupon(id: number) {
id,
})
}
export async function getReleaseCoupon(data: {
coupon_id: number
user_id: number
}) {
return callByUser<Coupon>("/api/admin/coupon/update/assign", data)
}
export async function getUserCoupon(data: {
page: number
size: number
user_id: number
}) {
return callByUser<PageRecord<Coupon>>(
"/api/admin/coupon-user/page/of-user",
data,
)
}

10
src/actions/env.ts Normal file
View File

@@ -0,0 +1,10 @@
import { toast } from "sonner"
const NODE_ENV = process.env.NODE_ENV
export async function getNodeEnv() {
if (!NODE_ENV) {
toast.error(`接口请求错误:NODE_ENV为空`)
}
return NODE_ENV
}

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

@@ -0,0 +1,28 @@
"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
secret: string
}) {
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)
}
export async function clear(data: { proxy_id: number }) {
return callByUser<PageRecord>("/api/admin/channel/sync/clear-expired", 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

@@ -9,6 +9,7 @@ import {
ComputerIcon,
ContactRound,
DollarSign,
DoorClosedIcon,
FolderCode,
Home,
KeyRound,
@@ -23,7 +24,7 @@ import {
} from "lucide-react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { createContext, type ReactNode, useContext, useState } from "react"
import { createContext, type ReactNode, Suspense, useContext, useState } from "react"
import { twJoin } from "tailwind-merge"
import { Auth } from "@/components/auth"
import { Button } from "@/components/ui/button"
@@ -46,12 +47,14 @@ import {
ScopeDiscountRead,
ScopePermissionRead,
ScopeProductRead,
ScopeProxyRead,
ScopeResourceRead,
ScopeTradeRead,
ScopeUserRead,
ScopeUserReadNotBind,
ScopeUserReadOne,
} from "@/lib/scopes"
import Logo from "./logo"
// Navigation Context
interface NavigationContextType {
@@ -249,6 +252,12 @@ const menuSections: { title: string; items: NavItemProps[] }[] = [
{
title: "系统",
items: [
{
href: "/gateway",
icon: DoorClosedIcon,
label: "网关列表",
requiredScope: ScopeProxyRead,
},
{
href: "/admin",
icon: Shield,
@@ -293,22 +302,13 @@ export default function Navigation() {
<NavigationContext.Provider value={contextValue}>
<aside
className={twJoin(
"bg-background border-r border-border transition-all duration-300 ease-in-out flex flex-col h-full",
"bg-white border-r border-slate-200 transition-all duration-300 ease-in-out flex flex-col h-full",
collapsed ? "w-16" : "w-64",
)}
>
{/*Logo 区域 */}
<div className="h-16 flex items-center justify-center border-b border-border p-4 shrink-0">
{!collapsed ? (
<span className="text-xl font-bold tracking-wide text-foreground">
</span>
) : (
<span className="text-xl font-bold mx-auto text-foreground">
<ComputerIcon />
</span>
)}
</div>
<Suspense><Logo collapsed={collapsed} /></Suspense>
{/* Navigation Menu */}
<ScrollArea className="flex-1 py-3 overflow-hidden">
<nav className="space-y-3">

View File

@@ -0,0 +1,29 @@
import { ComputerIcon } from "lucide-react"
import { getNodeEnv } from "@/actions/env"
import { cn } from "@/lib/utils"
export default async function Logo(props: { collapsed: boolean }) {
const env = await getNodeEnv()
return (
<div
className={cn(
`h-16 flex items-center justify-between border-b px-4 shrink-0`,
env === "production" && "bg-amber-100",
)}
>
{!props.collapsed ? (
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
<ComputerIcon className="h-4 w-4" />
</div>
<span className="text-xl font-bold tracking-wide"></span>
</div>
) : (
<div className="w-full flex justify-center">
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center"></div>
</div>
)}
</div>
)
}

View File

@@ -36,7 +36,6 @@ import { UpdateAdmin } from "./update"
export default function AdminPage() {
const table = useDataTable((page, size) => getPageAdmin({ page, size }))
console.log(table, "table")
return (
<Page>

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

@@ -19,7 +19,7 @@ import type { Balance } from "@/models/balance"
type FilterValues = {
user_phone?: string
bill_id?: string
bill_no?: string
admin_id?: string
created_at_start?: Date
created_at_end?: Date
@@ -28,7 +28,7 @@ type FilterValues = {
const filterSchema = z
.object({
phone: z.string().optional(),
bill_id: z.string().optional(),
bill_no: z.string().optional(),
admin_id: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
@@ -56,7 +56,7 @@ export default function BalancePage() {
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
bill_id: "",
bill_no: "",
admin_id: "",
created_at_start: "",
created_at_end: "",
@@ -70,11 +70,10 @@ export default function BalancePage() {
const table = useDataTable<Balance>(fetchUsers)
console.log(table, "table")
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone) result.user_phone = data.phone
if (data.bill_id) result.bill_id = data.bill_id
if (data.phone?.trim()) result.user_phone = data.phone.trim()
if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
@@ -86,7 +85,7 @@ export default function BalancePage() {
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="phone"
control={control}
@@ -102,7 +101,7 @@ export default function BalancePage() {
)}
/>
<Controller
name="bill_id"
name="bill_no"
control={control}
render={({ field, fieldState }) => (
<Field
@@ -143,9 +142,7 @@ export default function BalancePage() {
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
@@ -158,7 +155,7 @@ export default function BalancePage() {
>
</Button>
</FieldGroup>
</div>
</form>
<Suspense>
@@ -170,7 +167,7 @@ export default function BalancePage() {
accessorFn: row => row.user?.phone || "",
},
{
header: "账单号",
header: "账单号",
accessorFn: row => row.bill?.bill_no || "",
},
{

View File

@@ -113,8 +113,8 @@ export default function BatchPage() {
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入批次号" />
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入提取编号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
@@ -256,10 +256,10 @@ export default function BatchPage() {
accessorFn: row => row.user?.phone || "",
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "批次号", accessorKey: "batch_no" },
{ header: "提取编号", accessorKey: "batch_no" },
{ header: "省份", accessorKey: "prov" },
{ header: "城市", accessorKey: "city" },
{ header: "提取IP", accessorKey: "ip" },
{ header: "用户IP", accessorKey: "ip" },
{ header: "运营商", accessorKey: "isp" },
{ header: "提取数量", accessorKey: "count" },
{

View File

@@ -113,8 +113,8 @@ export default function ChannelPage() {
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入批次号" />
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入提取编号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
@@ -244,7 +244,7 @@ export default function ChannelPage() {
accessorFn: row => row.user?.phone || "-",
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "批次号", accessorKey: "batch_no" },
{ header: "提取编号", accessorKey: "batch_no" },
{
header: "节点",
accessorFn: row => row.ip || row.edge_ref || row.edge_id,

View File

@@ -20,7 +20,7 @@ import type { Balance } from "@/models/balance"
type FilterValues = {
user_phone?: string
bill_id?: string
bill_no?: string
created_at_start?: Date
created_at_end?: Date
}
@@ -28,7 +28,7 @@ type FilterValues = {
const filterSchema = z
.object({
phone: z.string().optional(),
bill_id: z.string().optional(),
bill_no: z.string().optional(),
admin_id: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
@@ -55,14 +55,13 @@ export default function BalancePage() {
const router = useRouter()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
console.log(userPhone, "userPhone")
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
bill_id: "",
bill_no: "",
admin_id: "",
created_at_start: "",
created_at_end: "",
@@ -72,12 +71,11 @@ export default function BalancePage() {
const table = useDataTable<Balance>((page, size) =>
getBalance({ page, size, user_id: Number(userId), ...filters }),
)
console.log(table, "仅用户的table")
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone) result.user_phone = data.phone
if (data.bill_id) result.bill_id = data.bill_id
if (data.phone?.trim()) result.user_phone = data.phone.trim()
if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
@@ -100,9 +98,9 @@ export default function BalancePage() {
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="bill_id"
name="bill_no"
control={control}
render={({ field, fieldState }) => (
<Field
@@ -143,9 +141,7 @@ export default function BalancePage() {
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
@@ -158,7 +154,7 @@ export default function BalancePage() {
>
</Button>
</FieldGroup>
</div>
</form>
<Suspense>

View File

@@ -0,0 +1,109 @@
"use client"
import { useState } from "react"
import { toast } from "sonner"
import { getPagCoupon } from "@/actions/coupon"
import { DataTable, useDataTable } from "@/components/data-table"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import type { Coupon } from "@/models/coupon"
export function IssueCouponForUser(props: {
userId: number
userPhone: string
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const table = useDataTable<Coupon>((page, size) =>
getPagCoupon({ page, size }),
)
const handleIssue = async (coupon: Coupon) => {
// try {
// const result = await issueCouponToUser({
// user_id: props.userId,
// coupon_id: coupon.id,
// coupon_name: coupon.name,
// })
// if (result.success) {
// toast.success(`成功发放「${coupon.name}」给用户 ${props.userPhone}`)
// props.onSuccess?.()
// setOpen(false)
// } else {
// toast.error(result.message || "发放失败")
// }
// } catch (error) {
// const message = error instanceof Error ? error.message : "发放失败"
// toast.error(`发放优惠券失败: ${message}`)
// }
}
return (
<Dialog
open={open}
onOpenChange={newOpen => {
setOpen(newOpen)
if (newOpen) {
table.refresh()
}
}}
>
<DialogTrigger asChild>
<Button></Button>
</DialogTrigger>
<DialogContent
className="max-h-[85vh] overflow-y-auto"
style={{ width: "auto", minWidth: "800px", maxWidth: "90vw" }}
>
<DialogHeader>
<DialogTitle> {props.userPhone}</DialogTitle>
</DialogHeader>
<DataTable<Coupon>
{...table}
columns={[
{ header: "优惠券名称", accessorKey: "name" },
{ header: "优惠券金额", accessorKey: "amount" },
{ header: "最低消费金额", accessorKey: "min_amount" },
{
header: "状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
if (status === 0) {
return <span className="text-yellow-600"></span>
}
if (status === 1) {
return <span className="text-green-600"></span>
}
return <span>-</span>
},
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<Button size="sm" onClick={() => handleIssue(row.original)}>
</Button>
),
},
]}
/>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,275 @@
"use client"
import { format } from "date-fns"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import { getUserCoupon } from "@/actions/coupon"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Coupon } from "@/models/coupon"
export default function CouponPage() {
const router = useRouter()
const searchParams = useSearchParams()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
const table = useDataTable<Coupon>((page, size) => {
return getUserCoupon({
user_id: Number(userId),
page,
size,
})
})
console.log(table, "table")
const expireLabel = (coupon: Coupon) => {
switch (coupon.expire_type) {
case 0:
return "永久有效"
case 1:
return coupon.expire_at
? format(new Date(coupon.expire_at), "yyyy-MM-dd")
: ""
case 2:
return coupon.expire_in ? `发放后${coupon.expire_in}` : ""
default:
return ""
}
}
return (
<Page>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Button onClick={() => router.back()} className="gap-2">
</Button>
<span className="text-gray-600">: {userPhone}</span>
</div>
</div>
<Suspense>
<DataTable<Coupon>
{...table}
columns={[
{ header: "优惠券名称", accessorKey: "name" },
{ header: "券码", accessorKey: "code" },
{ header: "金额", accessorKey: "amount" },
{ header: "最低消费", accessorKey: "min_amount" },
{
header: "状态",
accessorKey: "coupon_status",
},
{
header: "过期信息",
id: "expire",
cell: ({ row }) => expireLabel(row.original),
},
{
header: "发放时间",
accessorKey: "issued_at",
// cell: ({ row }) =>
// format(new Date(row.original.issued_at), "yyyy-MM-dd HH:mm"),
},
{
header: "备注",
accessorKey: "remark",
cell: ({ row }) => (
<span className="text-gray-500">
{row.original.remark || "-"}
</span>
),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-2">
<UpdateStatusDialog
coupon={row.original}
userId={Number(userId)}
onSuccess={table.refresh}
/>
<RevokeDialog
coupon={row.original}
userId={Number(userId)}
onSuccess={table.refresh}
/>
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}
function UpdateStatusDialog({
coupon,
userId,
onSuccess,
}: {
coupon: Coupon
userId: number
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const [selectedStatus, setSelectedStatus] =
useState(
// String(coupon.coupon_status),
)
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
// setLoading(true)
// try {
// const status = Number(selectedStatus)
// const result = await updateUserCouponStatus({
// user_id: userId,
// coupon_id: coupon.id,
// coupon_status: status,
// })
// if (result.success) {
// toast.success("状态更新成功")
// onSuccess?.()
// setOpen(false)
// } else {
// toast.error(result.message || "更新失败")
// }
// } catch (error) {
// const message = error instanceof Error ? error.message : "更新失败"
// toast.error(`状态更新失败: ${message}`)
// } finally {
// setLoading(false)
// }
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<div className="py-4">
<p className="text-sm text-gray-600 mb-3">
: {coupon.name} ({coupon.code})
</p>
<Select value={selectedStatus}>
<SelectTrigger>
<SelectValue placeholder="请选择状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">使</SelectItem>
<SelectItem value="2">使</SelectItem>
<SelectItem value="3"></SelectItem>
<SelectItem value="0"></SelectItem>
</SelectContent>
</Select>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button onClick={handleConfirm} disabled={loading}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
function RevokeDialog({
coupon,
userId,
onSuccess,
}: {
coupon: Coupon
userId: number
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
// setLoading(true)
// try {
// const result = await revokeUserCoupon({
// user_id: userId,
// coupon_id: coupon.id,
// })
// if (result.success) {
// toast.success("撤销成功")
// onSuccess?.()
// } else {
// toast.error(result.message || "撤销失败")
// }
// } catch (error) {
// const message = error instanceof Error ? error.message : "撤销失败"
// toast.error(`撤销失败: ${message}`)
// } finally {
// setLoading(false)
// }
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive" disabled={loading}>
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{coupon.name}({coupon.code})
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={handleConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View File

@@ -19,12 +19,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
ScopeBalanceActivityReadOfUser,
@@ -111,15 +106,12 @@ export default function UserQueryPage() {
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入手机号" />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -131,19 +123,13 @@ export default function UserQueryPage() {
name="name"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入姓名" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Auth scope={ScopeUserWrite}>
<AddUserDialog onSuccess={refreshTable} />
</Auth>
@@ -151,7 +137,7 @@ export default function UserQueryPage() {
</Button>
<Button type="submit"></Button>
</FieldGroup>
</div>
</form>
<Suspense>
@@ -176,7 +162,7 @@ export default function UserQueryPage() {
2: "代理商注册",
3: "代理商添加",
}
return sourceMap[row.original.source] ?? "未知"
return sourceMap[row.original.source] ?? "官网注册"
},
},
{
@@ -263,7 +249,7 @@ export default function UserQueryPage() {
<DropdownMenuItem
onClick={() => {
router.push(
`/client/trade?userId=${row.original.id}`,
`/client/trade?userId=${row.original.id}&phone=${row.original.phone}`,
)
}}
>
@@ -274,7 +260,7 @@ export default function UserQueryPage() {
<DropdownMenuItem
onClick={() => {
router.push(
`/client/billing?userId=${row.original.id}`,
`/client/billing?userId=${row.original.id}&phone=${row.original.phone}`,
)
}}
>
@@ -285,7 +271,7 @@ export default function UserQueryPage() {
<DropdownMenuItem
onClick={() => {
router.push(
`/client/resources?userId=${row.original.id}`,
`/client/resources?userId=${row.original.id}&phone=${row.original.phone}`,
)
}}
>
@@ -296,7 +282,7 @@ export default function UserQueryPage() {
<DropdownMenuItem
onClick={() => {
router.push(
`/client/batch?userId=${row.original.id}`,
`/client/batch?userId=${row.original.id}&phone=${row.original.phone}`,
)
}}
>
@@ -307,7 +293,7 @@ export default function UserQueryPage() {
<DropdownMenuItem
onClick={() => {
router.push(
`/client/channel?userId=${row.original.id}`,
`/client/channel?userId=${row.original.id}&phone=${row.original.phone}`,
)
}}
>

View File

@@ -122,7 +122,7 @@ export default function TradePage() {
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="inner_no"
control={control}
@@ -137,7 +137,6 @@ export default function TradePage() {
</Field>
)}
/>
<Controller
name="method"
control={control}
@@ -161,7 +160,6 @@ export default function TradePage() {
</Field>
)}
/>
<Controller
name="platform"
control={control}
@@ -182,7 +180,6 @@ export default function TradePage() {
</Field>
)}
/>
<Controller
name="status"
control={control}
@@ -204,7 +201,6 @@ export default function TradePage() {
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
@@ -219,7 +215,6 @@ export default function TradePage() {
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
@@ -234,9 +229,6 @@ export default function TradePage() {
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
@@ -249,7 +241,7 @@ export default function TradePage() {
>
</Button>
</FieldGroup>
</div>
</form>
<Suspense>
@@ -330,7 +322,7 @@ export default function TradePage() {
? "电脑网站"
: platform === 2
? "手机网站"
: "-"
: ""
},
},
{

View File

@@ -17,13 +17,49 @@ import {
} from "@/components/ui/dialog"
import { FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
const schema = z.object({
code: z.string().min(1, "请输入优惠券名称"),
amount: z.string().min(1, "请输入优惠券金额"),
remark: z.string().optional(),
min_amount: z.string().optional(),
name: z.string().min(1, "请输入优惠券名称"),
amount: z.string()
.min(1, "请输入优惠券金额")
.regex(/^\d+(\.\d+)?$/, "请输入有效的金额数字")
.refine(val => Number(val) > 0, "优惠券金额必须大于0"),
count: z.string()
.min(1, "请输入优惠券数量")
.regex(/^\d+$/, "请输入正整数")
.refine(val => Number(val) >= 1, "优惠券数量至少为1"),
min_amount: z.string()
.min(1, "请输入最低消费金额")
.regex(/^\d+(\.\d+)?$/, "请输入有效的金额数字")
.refine(val => Number(val) >= 0, "最低消费金额不能为负数"),
expire_at: z.string().optional(),
expire_type: z.string().min(1, "请选择过期类型"),
expire_in: z.string().optional(),
status:z.string().optional()
}).superRefine((data, ctx) => {
const expireType = Number(data.expire_type);
if (!data.expire_type) return;
if (expireType === 1 && !data.expire_at) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "请选择过期时间",
path: ["expire_at"]
});
}
if (expireType === 2 && !data.expire_in) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "请输入过期时长天数",
path: ["expire_in"]
});
}
})
export function CreateDiscount(props: { onSuccess?: () => void }) {
@@ -32,25 +68,33 @@ export function CreateDiscount(props: { onSuccess?: () => void }) {
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
code: "",
remark: "",
amount: "0",
min_amount: "0",
name: "",
count: "",
amount: "",
min_amount: "",
expire_at: "",
expire_in: "",
expire_type: "",
status: "0",
},
mode: "onChange",
})
const { control, handleSubmit, reset } = form
const { control, handleSubmit, reset, watch } = form
const watchExpireType = watch("expire_type")
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const expireType = Number(data.expire_type)
const payload = {
code: data.code,
name: data.name,
amount: Number(data.amount),
remark: data?.remark,
count: Number(data?.count),
status:Number(data.status),
min_amount: Number(data?.min_amount),
expire_at: data?.expire_at ? new Date(data.expire_at) : undefined,
expire_in: expireType === 2 ? Number(data.expire_in) : undefined,
expire_type: expireType,
}
const resp = await createCoupon(payload)
if (resp.success) {
@@ -93,10 +137,10 @@ export function CreateDiscount(props: { onSuccess?: () => void }) {
<FieldGroup>
<Controller
control={control}
name="code"
name="name"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -107,10 +151,10 @@ export function CreateDiscount(props: { onSuccess?: () => void }) {
<Controller
control={control}
name="remark"
name="count"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -124,20 +168,9 @@ export function CreateDiscount(props: { onSuccess?: () => void }) {
name="amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
@@ -148,43 +181,97 @@ export function CreateDiscount(props: { onSuccess?: () => void }) {
name="min_amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="expire_at"
name="status"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-30 pt-2">:</FieldLabel>
<Input
type="date"
min={new Date().toISOString().split("T")[0]}
{...field}
/>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="expire_type"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择过期类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
{watchExpireType === "1" && (
<Controller
control={control}
name="expire_at"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="date"
min={new Date().toISOString().split("T")[0]}
{...field}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
)}
{watchExpireType === "2" && (
<Controller
control={control}
name="expire_in"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min="0"
placeholder="请输入过期天数"
{...field}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
)}
</FieldGroup>
</form>

View File

@@ -3,6 +3,7 @@ import { format } from "date-fns"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import { deleteCoupon, getPagCoupon } from "@/actions/coupon"
import { Auth } from "@/components/auth"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
@@ -17,8 +18,10 @@ import {
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import { ScopeCouponWriteAssign } from "@/lib/scopes"
import type { Coupon } from "@/models/coupon"
import { CreateDiscount } from "./create"
import { ReleaseCoupon } from "./release"
import { UpdateCoupon } from "./update"
export default function CouponPage() {
@@ -36,30 +39,59 @@ export default function CouponPage() {
<DataTable<Coupon>
{...table}
columns={[
{ header: "所属用户", accessorKey: "user_id" },
{ header: "代码", accessorKey: "code" },
{ header: "备注", accessorKey: "remark" },
{ header: "金额", accessorKey: "amount" },
{ header: "优惠券名称", accessorKey: "name" },
{ header: "优惠券数量", accessorKey: "count" },
{ header: "优惠券金额", accessorKey: "amount" },
{ header: "最低消费金额", accessorKey: "min_amount" },
{
header: "状态",
header: "优惠券状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
if (status === 0) {
return <span className="text-yellow-600">使</span>
return <span className="text-yellow-600"></span>
}
if (status === 1) {
return <span className="text-green-600">使</span>
return <span className="text-green-600"></span>
}
return <span>-</span>
},
},
{
header: "过期类型",
accessorFn: row => {
switch (row.expire_type) {
case 0:
return "不过期"
case 1:
return "固定日期"
case 2:
return "相对日期"
default:
return ""
}
},
},
{
header: "过期时长(天)",
accessorKey: "expire_in",
},
{
header: "过期时间",
accessorKey: "expire_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
cell: ({ row }) => {
const coupon = row.original
if (coupon.expire_type === 2 && coupon.expire_in) {
const expireDate = new Date(coupon.created_at)
expireDate.setDate(expireDate.getDate() + coupon.expire_in)
return format(expireDate, "yyyy-MM-dd HH:mm")
}
if (coupon.expire_type === 1 && coupon.expire_at) {
return format(new Date(coupon.expire_at), "yyyy-MM-dd HH:mm")
}
return <span></span>
},
},
{
header: "创建时间",
@@ -67,12 +99,6 @@ export default function CouponPage() {
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorKey: "updated_at",
cell: ({ row }) =>
format(new Date(row.original.updated_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
@@ -87,6 +113,12 @@ export default function CouponPage() {
coupon={row.original}
onSuccess={table.refresh}
/>
<Auth scope={ScopeCouponWriteAssign}>
<ReleaseCoupon
coupon={row.original}
onSuccess={table.refresh}
/>
</Auth>
</div>
),
},
@@ -135,7 +167,7 @@ function DeleteCoupon({
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{coupon.code}
{coupon.name}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>

View File

@@ -0,0 +1,349 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { getReleaseCoupon } from "@/actions/coupon"
import { getPageUser } from "@/actions/user"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { Coupon } from "@/models/coupon"
import type { User } from "@/models/user"
interface UserQueryParams {
account?: string
name?: string
}
const filterSchema = z.object({
phone: z.string().optional(),
name: z.string().optional(),
})
type FormValues = z.infer<typeof filterSchema>
export function ReleaseCoupon(props: {
coupon: Coupon
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const [userList, setUserList] = useState<User[]>([])
const [loading, setLoading] = useState(false)
const [currentFilters, setCurrentFilters] = useState<UserQueryParams>({})
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
name: "",
},
})
const fetchUsers = useCallback(async (filters: UserQueryParams = {}) => {
setLoading(true)
try {
setOpen(true)
const res = await getPageUser(filters)
if (res.success) {
const data = Array.isArray(res.data) ? res.data : [res.data]
setUserList(data)
} else {
toast.error(res.message || "获取用户失败")
setUserList([])
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`获取用户失败: ${message}`)
} finally {
setLoading(false)
}
}, [])
const onFilter = handleSubmit((data: FormValues) => {
const params: UserQueryParams = {}
if (data.phone?.trim()) params.account = data.phone.trim()
if (data.name?.trim()) params.name = data.name.trim()
if (Object.keys(params).length === 0) {
toast.info("请至少输入一个搜索条件")
return
}
setCurrentFilters(params)
fetchUsers(params)
})
const handleReset = useCallback(() => {
reset()
setCurrentFilters({})
setUserList([])
}, [reset])
const handleIssueCoupon = useCallback(
async (users: User[], coupon: Coupon) => {
console.log(coupon, "couponcouponcoupon")
const targetUser = users[0]
if (!targetUser || !targetUser.id) {
toast.error("用户信息无效")
return
}
if (!coupon || !coupon.id) {
toast.error("优惠券信息无效")
return
}
if (coupon.status !== 1) {
toast.error("优惠券不可用,请检查优惠券状态")
return
}
try {
const result = await getReleaseCoupon({
coupon_id: coupon.id,
user_id: targetUser.id,
})
console.log({
coupon_id: coupon.id,
user_id: targetUser.id,
})
console.log(result, "resultresultresultresultresult")
if (result.success) {
toast.success(
`成功发放优惠券给用户 ${targetUser.phone || targetUser.username}`,
)
setOpen(false)
handleReset()
props.onSuccess?.()
} else {
toast.error("发放失败,请稍后重试")
}
} catch (error) {
const message = error instanceof Error ? error.message : "发放失败"
toast.error(`发放优惠券失败: ${message}`)
}
},
[props.onSuccess, handleReset],
)
return (
<Dialog
open={open}
onOpenChange={newOpen => {
setOpen(newOpen)
if (!newOpen) {
handleReset()
}
}}
>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent
className="max-h-[85vh] overflow-y-auto"
style={{ width: "auto", minWidth: "800px", maxWidth: "90vw" }}
>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form onSubmit={onFilter} className="bg-card rounded-lg">
<div className="flex items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入手机号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Button type="button" variant="outline" onClick={handleReset}>
</Button>
<Button type="submit"></Button>
</div>
</form>
<Suspense fallback={<div className="py-8 text-center">...</div>}>
{loading ? (
<div className="py-8 text-center">...</div>
) : userList.length === 0 ? (
<div className="py-8 text-center text-gray-500"></div>
) : (
<div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1">
{userList.map(user => (
<div
key={user.id}
className="border rounded-lg overflow-hidden hover:shadow-md transition-shadow"
>
<div className="bg-gray-50 px-4 py-3 border-b flex items-center justify-between flex-wrap gap-2">
<div className="flex items-center gap-3">
<span className="font-medium text-base">
{user.phone || "未绑定手机"}
</span>
<div className="flex gap-2">
<Badge
variant={user.id_type === 1 ? "default" : "secondary"}
className={
user.id_type === 1
? "bg-green-100 text-green-700 hover:bg-green-100"
: "bg-gray-100 text-gray-600 hover:bg-gray-100"
}
>
{user.id_type === 1 ? "✓ 已认证" : "○ 未认证"}
</Badge>
<Badge
variant={
user.status === 1 ? "default" : "destructive"
}
className={
user.status === 1
? "bg-green-100 text-green-700 hover:bg-green-100"
: "bg-red-100 text-red-700 hover:bg-red-100"
}
>
{user.status === 1 ? "正常" : "禁用"}
</Badge>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-gray-500">
:
<span
className={`ml-1 font-semibold ${
Number(user.balance) > 0
? "text-green-600"
: "text-orange-600"
}`}
>
¥{(Number(user.balance) || 0).toFixed(2)}
</span>
</span>
</div>
</div>
<div className="p-4">
<div className="grid grid-cols-3 gap-4">
<div className="space-y-2">
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{user.name || ""}
</span>
</div>
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{user.username || ""}
</span>
</div>
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{user.admin?.name || ""}
</span>
</div>
</div>
<div className="space-y-2">
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{(() => {
const sourceMap: Record<number, string> = {
0: "官网注册",
1: "管理员添加",
2: "代理商注册",
3: "代理商添加",
}
return sourceMap[user.source] ?? "官网注册"
})()}
</span>
</div>
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{user.contact_wechat || ""}
</span>
</div>
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{user.created_at
? format(new Date(user.created_at), "yyyy-MM-dd")
: ""}
</span>
</div>
</div>
<div className="space-y-2">
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
</span>
<span className="text-gray-900">
{user.last_login
? format(
new Date(user.last_login),
"yyyy-MM-dd HH:mm",
)
: "-"}
</span>
</div>
<div className="text-sm">
<span className="text-gray-500 w-20 inline-block">
IP
</span>
<span className="text-gray-900">
{user.last_login_ip || "-"}
</span>
</div>
</div>
</div>
</div>
</div>
))}
</div>
)}
</Suspense>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost" onClick={handleReset}>
</Button>
</DialogClose>
<Button
type="button"
onClick={() => handleIssueCoupon(userList, props.coupon)}
disabled={!userList || userList.length === 0}
>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -26,12 +26,40 @@ import {
import type { Coupon } from "@/models/coupon"
const schema = z.object({
code: z.string().min(1, "请输入优惠券名称"),
amount: z.string().min(1, "请输入优惠券金额"),
remark: z.string().optional(),
min_amount: z.string().optional(),
name: z.string().min(1, "请输入优惠券名称"),
amount: z.string()
.min(1, "请输入优惠券金额")
.regex(/^\d+(\.\d+)?$/, "请输入有效的金额数字")
.refine(val => Number(val) > 0, "优惠券金额必须大于0"),
count: z.string()
.min(1, "请输入优惠券数量")
.regex(/^\d+$/, "请输入正整数")
.refine(val => Number(val) >= 1, "优惠券数量至少为1"),
min_amount: z.string()
.min(1, "请输入最低消费金额")
.regex(/^\d+(\.\d+)?$/, "请输入有效的金额数字")
.refine(val => Number(val) >= 0, "最低消费金额不能为负数"),
expire_at: z.string().optional(),
status: z.string().optional(),
expire_type: z.string().min(1, "请选择过期类型"),
expire_in: z.string().optional(),
status:z.string().optional()
}).superRefine((data, ctx) => {
const expireType = Number(data.expire_type);
if (!data.expire_type) return;
if (expireType === 1 && !data.expire_at) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "请选择过期时间",
path: ["expire_at"]
});
}
if (expireType === 2 && !data.expire_in) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "请输入过期时长天数",
path: ["expire_in"]
});
}
})
export function UpdateCoupon(props: {
@@ -43,32 +71,36 @@ export function UpdateCoupon(props: {
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
code: props.coupon.code || "",
remark: props.coupon.remark || "",
amount: String(props.coupon.amount || 0),
min_amount: String(props.coupon.min_amount || 0),
expire_at: props.coupon.expire_at
? new Date(props.coupon.expire_at).toISOString().split("T")[0]
name: props.coupon.name,
amount: String(props.coupon.amount),
min_amount: String(props.coupon.min_amount),
expire_at: props?.coupon.expire_at
? new Date(props?.coupon.expire_at).toISOString().split("T")[0]
: "",
status: String(props.coupon.status || "0"),
status: String(props.coupon.status),
count: String(props.coupon.count),
expire_in: String(props?.coupon.expire_in),
},
mode: "onChange",
})
const { control, handleSubmit, reset } = form
const { control, handleSubmit, reset, watch } = form
const watchExpireType = watch("expire_type")
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const expireType = Number(data.expire_type)
const payload = {
id: props.coupon.id,
code: data.code,
name: data.name,
amount: Number(data.amount),
remark: data.remark,
min_amount: Number(data.min_amount),
expire_at: data.expire_at ? new Date(data.expire_at) : undefined,
count: Number(data.count),
status: Number(data.status),
expire_type: expireType,
expire_at: data.expire_at ? new Date(data.expire_at) : undefined,
expire_in: expireType === 2 ? Number(data.expire_in) : undefined,
}
const resp = await updateCoupon(payload)
const resp = await updateCoupon(payload)
if (resp.success) {
toast.success("优惠券修改成功")
props.onSuccess?.()
@@ -85,14 +117,16 @@ export function UpdateCoupon(props: {
const handleOpenChange = (value: boolean) => {
if (value) {
reset({
code: props.coupon.code || "",
remark: props.coupon.remark || "",
amount: String(props.coupon.amount || 0),
min_amount: String(props.coupon.min_amount || 0),
name: props.coupon.name,
count: String(props.coupon.count),
amount: String(props.coupon.amount ),
min_amount: String(props.coupon.min_amount),
expire_at: props.coupon.expire_at
? new Date(props.coupon.expire_at).toISOString().split("T")[0]
: "",
status: String(props.coupon.status || "0"),
status: String(props.coupon.status),
expire_type: String(props.coupon.expire_type),
expire_in: String(props.coupon.expire_in),
})
}
setOpen(value)
@@ -115,10 +149,10 @@ export function UpdateCoupon(props: {
<FieldGroup>
<Controller
control={control}
name="code"
name="name"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -129,10 +163,10 @@ export function UpdateCoupon(props: {
<Controller
control={control}
name="remark"
name="count"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -146,20 +180,9 @@ export function UpdateCoupon(props: {
name="amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
@@ -171,58 +194,28 @@ export function UpdateCoupon(props: {
name="min_amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="expire_at"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="date"
min={new Date().toISOString().split("T")[0]}
{...field}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="status"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0">使</SelectItem>
<SelectItem value="1">使</SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
@@ -230,6 +223,68 @@ export function UpdateCoupon(props: {
</div>
)}
/>
<Controller
control={control}
name="expire_type"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择过期类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
{watchExpireType === "1" && (
<Controller
control={control}
name="expire_at"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="date"
min={new Date().toISOString().split("T")[0]}
{...field}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
)}
{watchExpireType === "2" && (
<Controller
control={control}
name="expire_in"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min="0"
placeholder="请输入过期天数"
{...field}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
)}
</FieldGroup>
</form>

View File

@@ -18,12 +18,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
@@ -37,6 +32,7 @@ import {
ScopeBatchReadOfUser,
ScopeBillReadOfUser,
ScopeChannelReadOfUser,
ScopeCouponWriteAssign,
ScopeResourceRead,
ScopeTradeReadOfUser,
ScopeUserWrite,
@@ -109,8 +105,8 @@ export default function CustPage() {
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.account) result.account = data.account
if (data.name) result.name = data.name
if (data.account?.trim()) result.account = data.account.trim()
if (data.name?.trim()) result.name = data.name.trim()
if (data.identified && data.identified !== "all")
result.identified = data.identified === "1"
if (data.enabled && data.enabled !== "all")
@@ -126,15 +122,12 @@ export default function CustPage() {
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="account"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-80 flex-none"
>
<Field data-invalid={fieldState.invalid} className="w-80 flex">
<FieldLabel>//</FieldLabel>
<Input {...field} placeholder="请输入账号/手机号/邮箱" />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -146,10 +139,7 @@ export default function CustPage() {
name="name"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入姓名" />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -203,10 +193,7 @@ export default function CustPage() {
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -218,19 +205,13 @@ export default function CustPage() {
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Auth scope={ScopeUserWrite}>
<AddUserDialog onSuccess={refreshTable} />
</Auth>
@@ -246,7 +227,7 @@ export default function CustPage() {
</Button>
<Button type="submit"></Button>
</FieldGroup>
</div>
</form>
<Suspense>
@@ -462,6 +443,17 @@ export default function CustPage() {
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeCouponWriteAssign}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/coupon?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
</DropdownMenuContent>
</DropdownMenu>
</div>

View File

@@ -0,0 +1,269 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createGateway } from "@/actions/gateway"
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"
const schema = z.object({
mac: z.string().min(1, "请填写mac地址"),
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(),
secret: z.string().min(1, "请填写密钥"),
})
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",
secret: "",
},
})
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,
secret: data.secret.trim(),
}
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="secret"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-secret">:</FieldLabel>
<Input
id="gateway-create-secret"
placeholder="请输入密匙"
{...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,140 @@
"use client"
import { format } from "date-fns"
import { Suspense, useCallback, useState } from "react"
import { toast } from "sonner"
import { clear, 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 { ScopeChannelWriteClearExpired, 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) {
const message = error instanceof Error ? error.message : error
toast.error(`操作失败: ${message}`)
} finally {
setLoading(false)
}
}
const clearExpired = async (val: Gateway) => {
setLoading(true)
try {
const result = await clear({
proxy_id: val.id,
})
if (result.success) {
const count =
result.data && "count" in result.data ? result.data.count : 0
toast.success(`清理过期连接成功,共 ${count}`)
} else {
toast.error(result.message || "清理过期连接失败,请稍后重试一下~")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`清理过期连接失败: ${message}`)
} finally {
setLoading(false)
}
}
return (
<Page>
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<Auth scope={ScopeProxyWrite}>
<CreatePage onSuccess={table.refresh} />
</Auth>
</div>
</div>
<Suspense>
<DataTable<Gateway>
{...table}
status={loading ? "load" : "done"}
columns={[
{
header: "域名",
accessorKey: "host",
},
{ header: "IP地址", accessorKey: "ip" },
{
header: "MAC地址",
accessorKey: "mac",
},
{
header: "密钥",
accessorKey: "secret",
},
{
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>
<Auth scope={ScopeChannelWriteClearExpired}>
<Button onClick={() => clearExpired(row.original)}>
</Button>
</Auth>
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -1,7 +1,7 @@
import { type ReactNode, Suspense } from "react"
import { getProfile } from "@/actions/auth"
import Navigation from "@/app/(root)/_navigation"
import Appbar from "@/app/(root)/appbar"
import Navigation from "@/app/(root)/navigation"
import SetScopes from "./scopes"
export type RootLayoutProps = {

View File

@@ -139,7 +139,7 @@ function PermissionTable() {
}, [data])
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-3 overflow-auto">
{process.env.NODE_ENV === "development" && (
<div>
<Button variant="outline" size="sm" onClick={handleCopy}>
@@ -150,7 +150,7 @@ function PermissionTable() {
)}
<Table>
<TableHeader>
<TableRow className="h-10">
<TableRow className="h-10 sticky top-0 bg-background">
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>

View File

@@ -34,27 +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,
"请输入有效的正数单价",
)
.refine(val => /^\d+(\.\d{1,2})?$/.test(val), "价格最多只能保留两位小数"),
discount_id: z.string().optional(),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
)
.refine(val => /^\d+(\.\d{1,2})?$/.test(val), "价格最多只能保留两位小数"),
})
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
@@ -166,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]} />
@@ -197,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]} />
@@ -217,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

@@ -99,7 +99,6 @@ function ProductSkus(props: {
)
const table = useDataTable(action)
console.log(table, "table")
return (
<div className="flex-auto overflow-hidden flex flex-col items-stretch gap-3">
@@ -130,18 +129,19 @@ function ProductSkus(props: {
),
},
{ header: "套餐名称", accessorKey: "name" },
{ header: "单价", accessorFn: row => Number(row.price).toFixed(2) },
{ header: "单价", accessorFn: row => Number(row.price) },
{ header: "折扣", accessorFn: row => row.discount?.name ?? "—" },
{
header: "最终价格",
header: "折后价",
accessorFn: row => {
const value = row.discount
? (Number(row.price) * Number(row.discount.discount)) / 100
: Number(row.price)
return Number(value.toFixed(2))
return Number(value)
},
},
{ header: "最低价格", accessorKey: "price_min" },
{ header: "最低购买数量", accessorKey: "count_min" },
{
header: "创建时间",
accessorFn: row => format(row.created_at, "yyyy-MM-dd HH:mm"),

View File

@@ -34,27 +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,
"请输入有效的正数单价",
)
.refine(val => /^\d+(\.\d{1,2})?$/.test(val), "价格最多只能保留两位小数"),
discount_id: z.string().optional(),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
)
.refine(val => /^\d+(\.\d{1,2})?$/.test(val), "价格最多只能保留两位小数"),
})
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
@@ -71,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),
},
})
@@ -85,8 +107,6 @@ export function UpdateProductSku(props: {
}, [open])
const onSubmit = async (data: z.infer<typeof schema>) => {
console.log(data, "data")
try {
const resp = await updateProductSku({
id: props.sku.id,
@@ -98,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("套餐修改成功")
@@ -121,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)
@@ -171,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]} />
@@ -196,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

@@ -171,7 +171,7 @@ function getTodayUsage(lastAt: Date | null | undefined, daily: number) {
export default function ResourcesPage() {
return (
<Page>
<Tabs defaultValue="short">
<Tabs defaultValue="short" className="overflow-hidden">
<TabsList className="bg-card">
<TabsTrigger value="short" className="h-10 px-4 shadow-none">
@@ -181,7 +181,10 @@ export default function ResourcesPage() {
</TabsTrigger>
</TabsList>
<TabsContent value="short" className="flex flex-col gap-4">
<TabsContent
value="short"
className="flex flex-col gap-4 overflow-hidden"
>
<ResourceList resourceType="short" />
</TabsContent>
<TabsContent value="long" className="flex flex-col gap-4">
@@ -222,7 +225,7 @@ function ResourceList({ resourceType }: ResourceListProps) {
)
const table = useDataTable<Resources>(fetchResources)
console.log(table, "我的套餐的table")
const refreshTable = useCallback(() => {
setFilters(prev => ({ ...prev }))
}, [])
@@ -252,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()
@@ -385,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
@@ -408,17 +434,24 @@ 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 (
<div className="space-y-3">
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-col gap-3 overflow-hidden">
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg flex-none">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="user_phone"
@@ -554,7 +587,13 @@ function ResourceList({ resourceType }: ResourceListProps) {
</form>
<Suspense fallback={<div className="text-center p-4">...</div>}>
<DataTable<Resources> {...table} columns={columns} />
<DataTable<Resources>
{...table}
columns={columns}
classNames={{
root: "flex-auto overflow-hidden",
}}
/>
</Suspense>
</div>
)

View File

@@ -115,14 +115,14 @@ export default function TradePage() {
<Page>
{/* 筛选表单 */}
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="user_phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
className="w-40 flex"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
@@ -137,7 +137,7 @@ export default function TradePage() {
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
className="w-40 flex"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入订单号" />
@@ -219,7 +219,7 @@ export default function TradePage() {
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
className="w-40 flex"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
@@ -234,7 +234,7 @@ export default function TradePage() {
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
className="w-40 flex"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
@@ -242,9 +242,7 @@ export default function TradePage() {
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
@@ -257,7 +255,7 @@ export default function TradePage() {
>
</Button>
</FieldGroup>
</div>
</form>
<Suspense>

View File

@@ -13,7 +13,6 @@ import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
@@ -55,7 +54,7 @@ export default function UserPage() {
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone) result.phone = data.phone
if (data.phone?.trim()) result.phone = data.phone.trim()
setFilters(result)
table.pagination.onPageChange(1)
})
@@ -63,14 +62,14 @@ export default function UserPage() {
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<div className="flex items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
className="w-40 flex"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入手机号" />
@@ -78,9 +77,7 @@ export default function UserPage() {
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
@@ -89,11 +86,12 @@ export default function UserPage() {
reset()
setFilters({})
setLoading(false)
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</div>
</form>
<Suspense>
@@ -199,4 +197,4 @@ export default function UserPage() {
</Suspense>
</Page>
)
}
}

View File

@@ -45,20 +45,27 @@ function ProductShortCode<T extends { code: string }>(
const { field, fieldState } = props
const params = new URLSearchParams(field.value)
const mode = params.get("mode") || "quota"
const live = params.get("live") || "0"
const expire = params.get("expire") || "0"
const setParams = (data: {
mode?: string
live?: string
expire?: string
}) => {
if (data.mode) params.set("mode", data.mode)
if (data.live) params.set("live", data.live)
if (data.expire) params.set("expire", data.expire)
field.onChange(params.toString())
const newParams = new URLSearchParams()
newParams.set("mode", data.mode || mode)
newParams.set("live", data.live || live)
newParams.set("expire", data.expire || expire)
console.log(newParams.toString())
field.onChange(newParams.toString())
}
const onModeChange = (value: string) => {
setParams({ mode: value })
}
const onLiveChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
@@ -67,6 +74,7 @@ function ProductShortCode<T extends { code: string }>(
if (!/^([0-9]+)$/.test(value)) return
setParams({ live: value })
}
const onExpireChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
@@ -82,10 +90,7 @@ function ProductShortCode<T extends { code: string }>(
<FieldGroup>
<Field>
<FieldLabel></FieldLabel>
<Select
defaultValue={params.get("mode") ?? "quota"}
onValueChange={onModeChange}
>
<Select defaultValue={mode} onValueChange={onModeChange}>
<SelectTrigger>
<SelectValue placeholder="请选择套餐类型" />
</SelectTrigger>
@@ -97,20 +102,12 @@ function ProductShortCode<T extends { code: string }>(
</Field>
<Field>
<FieldLabel></FieldLabel>
<Input
type="number"
value={params.get("live") ?? "0"}
onChange={onLiveChange}
/>
<Input type="number" value={live} onChange={onLiveChange} />
</Field>
{params.get("mode") === "time" && (
<Field>
<FieldLabel></FieldLabel>
<Input
type="number"
value={params.get("expire") ?? "0"}
onChange={onExpireChange}
/>
<Input type="number" value={expire} onChange={onExpireChange} />
</Field>
)}
{fieldState.error && <FieldError errors={[fieldState.error]} />}
@@ -125,20 +122,31 @@ function ProductLongCode<T extends { code: string }>(
const { field, fieldState } = props
const params = new URLSearchParams(field.value)
const mode = params.get("mode") || "quota"
const live = params.get("live") || "0"
const expire = params.get("expire") || "0"
const setParams = (data: {
mode?: string
live?: string
expire?: string
}) => {
if (data.mode) params.set("mode", data.mode)
if (data.live) params.set("live", data.live)
if (data.expire) params.set("expire", data.expire)
field.onChange(params.toString())
const newParams = new URLSearchParams()
newParams.set("mode", data.mode || mode)
newParams.set("live", data.live || live)
newParams.set("expire", data.expire || expire)
console.log(newParams.toString())
field.onChange(newParams.toString())
}
const onModeChange = (value: string) => {
setParams({ mode: value })
if (value === "quota") {
setParams({ mode: value, expire: "0" })
} else {
setParams({ mode: value })
}
}
const onLiveChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
@@ -147,6 +155,7 @@ function ProductLongCode<T extends { code: string }>(
if (!/^([0-9]+)$/.test(value)) return
setParams({ live: value })
}
const onExpireChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
@@ -162,10 +171,7 @@ function ProductLongCode<T extends { code: string }>(
<FieldGroup>
<Field>
<FieldLabel></FieldLabel>
<Select
defaultValue={params.get("mode") ?? "quota"}
onValueChange={onModeChange}
>
<Select defaultValue={mode} onValueChange={onModeChange}>
<SelectTrigger>
<SelectValue placeholder="请选择套餐类型" />
</SelectTrigger>
@@ -177,20 +183,12 @@ function ProductLongCode<T extends { code: string }>(
</Field>
<Field>
<FieldLabel></FieldLabel>
<Input
type="number"
value={params.get("live") ?? "0"}
onChange={onLiveChange}
/>
<Input type="number" value={live} onChange={onLiveChange} />
</Field>
{params.get("mode") === "time" && (
<Field>
<FieldLabel></FieldLabel>
<Input
type="number"
value={params.get("expire") ?? "0"}
onChange={onExpireChange}
/>
<Input type="number" value={expire} onChange={onExpireChange} />
</Field>
)}
{fieldState.error && <FieldError errors={[fieldState.error]} />}

View File

@@ -55,6 +55,7 @@ export const ScopeUserWriteBind = "user:write:bind" // 用户认领
export const ScopeCoupon = "coupon"
export const ScopeCouponRead = "coupon:read" // 读取优惠券列表
export const ScopeCouponWrite = "coupon:write" // 写入优惠券
export const ScopeCouponWriteAssign = "coupon:write:assign" // 发放优惠券
// 批次
export const ScopeBatch = "batch"
@@ -73,7 +74,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 +85,10 @@ 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" // 更改代理状态
export const ScopeChannelWriteClearExpired = "channel:write:clear_expired" //清理过期连接

View File

@@ -1,12 +1,16 @@
export type Coupon = {
id: number
created_at: Date
updated_at: Date
name: string
user_id: number
code: string
remark: string
amount: number
min_amount: number
count: number
status: number
expire_type: number
created_at: Date
updated_at: Date
expire_at: Date
expire_in: number
}

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 = {