修整优惠券页面,添加发放功能及权限控制 & 用户添加查看优惠券发放详情 & 添加切换线上环境页面显示功能

This commit is contained in:
Eamon
2026-04-28 11:16:54 +08:00
parent 66ee6bb9fd
commit 7cd1a7cbe7
15 changed files with 765 additions and 198 deletions

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,10 @@ export async function deleteCoupon(id: number) {
id,
})
}
export async function issueCoupon(data: {
coupon_id: number
user_id: number
}) {
return callByUser<Coupon>("/api/admin/coupon/update/assign", 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
}

View File

@@ -54,6 +54,7 @@ import {
ScopeUserReadNotBind,
ScopeUserReadOne,
} from "@/lib/scopes"
import Logo from "./logo"
// Navigation Context
interface NavigationContextType {
@@ -255,7 +256,7 @@ const menuSections: { title: string; items: NavItemProps[] }[] = [
href: "/gateway",
icon: DoorClosedIcon,
label: "网关列表",
requiredScope:ScopeProxyRead
requiredScope: ScopeProxyRead,
},
{
href: "/admin",
@@ -301,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>
<Logo collapsed={collapsed} />
{/* Navigation Menu */}
<ScrollArea className="flex-1 py-3 overflow-hidden">
<nav className="space-y-3">

View File

@@ -0,0 +1,28 @@
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

@@ -142,7 +142,7 @@ export default function BalancePage() {
</Field>
)}
/>
<Button type="submit"></Button>
<Button
type="button"
@@ -155,7 +155,7 @@ export default function BalancePage() {
>
</Button>
</div>
</div>
</form>
<Suspense>
@@ -167,7 +167,7 @@ export default function BalancePage() {
accessorFn: row => row.user?.phone || "",
},
{
header: "账单号",
header: "账单号",
accessorFn: row => row.bill?.bill_no || "",
},
{

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,
@@ -116,10 +111,7 @@ export default function UserQueryPage() {
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入手机号" />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -131,10 +123,7 @@ export default function UserQueryPage() {
name="name"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入姓名" />
<FieldError>{fieldState.error?.message}</FieldError>

View File

@@ -0,0 +1,10 @@
"use client"
import { useRouter, useSearchParams } from "next/navigation"
export default function IssuePage() {
const router = useRouter()
const searchParams = useSearchParams()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
return <div></div>
}

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

@@ -0,0 +1,346 @@
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 { issueCoupon } 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 IssueCoupon(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 issueCoupon({
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

@@ -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 { IssueCoupon } from "./issue"
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}>
<IssueCoupon
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

@@ -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

@@ -37,6 +37,7 @@ import {
ScopeBatchReadOfUser,
ScopeBillReadOfUser,
ScopeChannelReadOfUser,
ScopeCouponWriteAssign,
ScopeResourceRead,
ScopeTradeReadOfUser,
ScopeUserWrite,
@@ -131,10 +132,7 @@ export default function CustPage() {
name="account"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-80 flex"
>
<Field data-invalid={fieldState.invalid} className="w-80 flex">
<FieldLabel>//</FieldLabel>
<Input {...field} placeholder="请输入账号/手机号/邮箱" />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -146,10 +144,7 @@ export default function CustPage() {
name="name"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入姓名" />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -203,10 +198,7 @@ export default function CustPage() {
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -218,10 +210,7 @@ export default function CustPage() {
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex"
>
<Field data-invalid={fieldState.invalid} className="w-40 flex">
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
@@ -243,7 +232,7 @@ export default function CustPage() {
</Button>
<Button type="submit"></Button>
</div>
</div>
</form>
<Suspense>
@@ -459,6 +448,17 @@ export default function CustPage() {
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeCouponWriteAssign}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/issue?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
</DropdownMenuContent>
</DropdownMenu>
</div>

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

@@ -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"
@@ -89,4 +90,4 @@ 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 ScopeProxyWriteStatus = "proxy:write:status" // 更改代理状态

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
}