6 Commits

Author SHA1 Message Date
a0b0956677 免费与菜单提示文字 2026-04-21 16:19:11 +08:00
Eamon-meng
27e694ee0d 取消关闭支付弹窗调用关闭订单接口 & 添加未实名去支付时的拦截 2026-04-20 16:22:49 +08:00
Eamon-meng
74d53c619d 购买套餐添加count_min字段 2026-04-20 15:36:50 +08:00
8f8def3a87 完善异常跳转 2026-04-20 15:34:49 +08:00
Eamon-meng
ed73d8579f 更新发布v1.7.0 2026-04-18 17:36:22 +08:00
Eamon-meng
e3c61a77e6 修复未登录时提取ip时的套餐显示和不调用获取套餐接口 2026-04-18 17:13:26 +08:00
18 changed files with 220 additions and 115 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "lanhu-web", "name": "lanhu-web",
"version": "1.6.0", "version": "1.8.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev -H 0.0.0.0 --turbopack", "dev": "next dev -H 0.0.0.0 --turbopack",

View File

@@ -2,6 +2,7 @@
import {API_BASE_URL, ApiResponse, CLIENT_ID, CLIENT_SECRET} from '@/lib/api' import {API_BASE_URL, ApiResponse, CLIENT_ID, CLIENT_SECRET} from '@/lib/api'
import {add, isBefore} from 'date-fns' import {add, isBefore} from 'date-fns'
import {cookies, headers} from 'next/headers' import {cookies, headers} from 'next/headers'
import {redirect} from 'next/navigation'
import {cache} from 'react' import {cache} from 'react'
export type TokenResp = { export type TokenResp = {
@@ -106,7 +107,6 @@ const _callByUser = cache(async <R = undefined>(
// ====================== // ======================
async function call<R = undefined>(url: string, body: RequestInit['body'], auth?: string): Promise<ApiResponse<R>> { async function call<R = undefined>(url: string, body: RequestInit['body'], auth?: string): Promise<ApiResponse<R>> {
let response: Response
try { try {
const reqHeaders = await headers() const reqHeaders = await headers()
const reqIP = reqHeaders.get('x-forwarded-for') const reqIP = reqHeaders.get('x-forwarded-for')
@@ -118,15 +118,14 @@ async function call<R = undefined>(url: string, body: RequestInit['body'], auth?
if (reqIP) callHeaders['X-Forwarded-For'] = reqIP if (reqIP) callHeaders['X-Forwarded-For'] = reqIP
if (reqUA) callHeaders['User-Agent'] = reqUA if (reqUA) callHeaders['User-Agent'] = reqUA
response = await fetch(url, { const response = await fetch(url, {
method: 'POST', method: 'POST',
headers: callHeaders, headers: callHeaders,
body, body,
}) })
}
catch (e) { if (response.status === 401) {
console.error('后端请求失败', url, (e as Error).message) return redirect('/login?redirect=' + encodeURIComponent(url.replace(API_BASE_URL, '')))
throw new Error(`请求失败,网络错误`)
} }
const type = response.headers.get('Content-Type') ?? 'text/plain' const type = response.headers.get('Content-Type') ?? 'text/plain'
@@ -168,6 +167,11 @@ async function call<R = undefined>(url: string, body: RequestInit['body'], auth?
throw new Error(`无法解析响应数据,未处理的 Content-Type: ${type}`) throw new Error(`无法解析响应数据,未处理的 Content-Type: ${type}`)
} }
catch (e) {
console.error('后端请求失败', url, (e as Error).message)
throw new Error(`请求失败,网络错误`)
}
}
// 导出 // 导出
export { export {

View File

@@ -237,7 +237,7 @@ export default function CustomPage() {
<section className="relative rounded-lg overflow-hidden h-48 lg:h-56"> <section className="relative rounded-lg overflow-hidden h-48 lg:h-56">
<Image <Image
src={group} src={group}
alt="免费试用背景" alt="立即试用背景"
fill fill
className="object-cover" className="object-cover"
priority priority
@@ -251,9 +251,9 @@ export default function CustomPage() {
className={merge( className={merge(
'bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-md whitespace-nowrap', 'bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-md whitespace-nowrap',
)} )}
onClick={() => router.push('/login')} onClick={() => router.push('/product')}
> >
</Button> </Button>
</div> </div>
</div> </div>

View File

@@ -10,13 +10,13 @@ export default function Addr({channel}: {
const expired = isBefore(channel.expired_at, new Date()) const expired = isBefore(channel.expired_at, new Date())
return ( return (
<div className={`${expired ? 'text-weak' : ''}`}> <>
<span>{ip}:{port}</span> <span>{ip}:{port}</span>
{expired && ( {expired && (
<Badge variant="secondary"> <Badge className="ml-2 bg-orange-100 text-orange-700 hover:bg-orange-100 dark:bg-orange-900/30 dark:text-orange-400">
</Badge> </Badge>
)} )}
</div> </>
) )
} }

View File

@@ -192,7 +192,7 @@ export default function ChannelsPage(props: ChannelsPageProps) {
<span ></span> <span ></span>
<div className="flex flex-wrap gap-1 max-w-[200px]"> <div className="flex flex-wrap gap-1 max-w-[200px]">
{channel.whitelists.split(',').map((ip, index) => ( {channel.whitelists.split(',').map((ip, index) => (
<Badge key={index} variant="secondary"> <Badge key={index} className="bg-green-100 text-green-700 hover:bg-green-100 dark:bg-green-900/30 dark:text-green-400">
{ip.trim()} {ip.trim()}
</Badge > </Badge >
))} ))}
@@ -201,7 +201,7 @@ export default function ChannelsPage(props: ChannelsPageProps) {
) : hasAuth ? ( ) : hasAuth ? (
<div className="flex flex-col"> <div className="flex flex-col">
<span></span> <span></span>
<Badge variant="secondary"> <Badge className="bg-blue-100 text-blue-700 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400">
{channel.username}:{channel.password} {channel.username}:{channel.password}
</Badge > </Badge >
</div> </div>

View File

@@ -103,25 +103,33 @@ export function Header() {
<div className="flex-auto flex items-center gap-2"> <div className="flex-auto flex items-center gap-2">
<Button <Button
theme="ghost" theme="ghost"
className="w-9 h-9 ml-4 md:ml-0" className="h-9 ml-4 md:ml-0"
onClick={toggleNavbar}> onClick={toggleNavbar}>
{navbar {navbar ? (
? <PanelLeftCloseIcon/> <>
: <PanelLeftOpenIcon/> <PanelLeftCloseIcon/>
} <span className="text-foreground/90"></span>
</>
) : (
<>
<PanelLeftOpenIcon/>
<span className="text-foreground/90"></span>
</>
)}
</Button> </Button>
<span className="max-md:hidden"> <span className="max-md:hidden"></span>
<div className="max-md:hidden h-5 w-px bg-gray-300 mx-2"/>
</span> <Link
href="/admin/identify"
className="max-md:hidden flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-800 transition-colors"
>
<IdCard size={16}/>
<span></span>
</Link>
</div> </div>
{/* right */} <div className="flex-none flex items-center justify-end pr-4 max-md:hidden gap-3">
<div className="flex-none flex items-center justify-end pr-4 max-md:hidden gap-2"> <Link href="/" className="flex-none h-16 flex items-center justify-center text-sm">
<Link
href="/"
className={merge(
`flex-none h-16 flex items-center justify-center`,
)}>
</Link> </Link>
<Suspense> <Suspense>
@@ -176,7 +184,7 @@ export function Navbar() {
<TooltipProvider> <TooltipProvider>
<NavItem href="/admin" icon={<UserRound size={20}/>} label="账户总览" expand={navbar}/> <NavItem href="/admin" icon={<UserRound size={20}/>} label="账户总览" expand={navbar}/>
<NavTitle label="快速开始"/> <NavTitle label="快速开始"/>
<NavItem href="/admin/identify" icon={<IdCard size={20}/>} label="实名认证" expand={navbar}/> {/* <NavItem href="/admin/identify" icon={<IdCard size={20}/>} label="实名认证" expand={navbar}/> */}
<NavItem href="/admin/whitelist" icon={<LockKeyhole size={20}/>} label="白名单" expand={navbar}/> <NavItem href="/admin/whitelist" icon={<LockKeyhole size={20}/>} label="白名单" expand={navbar}/>
<NavItem href="/admin/purchase" icon={<ShoppingCart size={20}/>} label="购买套餐" expand={navbar}/> <NavItem href="/admin/purchase" icon={<ShoppingCart size={20}/>} label="购买套餐" expand={navbar}/>
<NavItem href="/admin/extract" icon={<HardDriveUpload size={20}/>} label="提取 IP" expand={navbar}/> <NavItem href="/admin/extract" icon={<HardDriveUpload size={20}/>} label="提取 IP" expand={navbar}/>

View File

@@ -9,7 +9,7 @@ import {Button} from '@/components/ui/button'
import {useForm, useFormContext, useWatch} from 'react-hook-form' import {useForm, useFormContext, useWatch} from 'react-hook-form'
import {Alert, AlertTitle} from '@/components/ui/alert' import {Alert, AlertTitle} from '@/components/ui/alert'
import {ArrowRight, Box, CircleAlert, CopyIcon, ExternalLinkIcon, LinkIcon, Loader, Plus, Timer} from 'lucide-react' import {ArrowRight, Box, CircleAlert, CopyIcon, ExternalLinkIcon, LinkIcon, Loader, Plus, Timer} from 'lucide-react'
import {memo, ReactNode, useEffect, useRef, useState} from 'react' import {memo, ReactNode, Suspense, use, useEffect, useRef, useState} from 'react'
import {useStatus} from '@/lib/states' import {useStatus} from '@/lib/states'
import {allResource} from '@/actions/resource' import {allResource} from '@/actions/resource'
import {Resource} from '@/lib/models' import {Resource} from '@/lib/models'
@@ -113,7 +113,9 @@ const FormFields = memo(() => {
return ( return (
<div className="flex flex-col gap-6 items-stretch max-w-[calc(160px*4+1rem*3)]"> <div className="flex flex-col gap-6 items-stretch max-w-[calc(160px*4+1rem*3)]">
{/* 选择套餐 */} {/* 选择套餐 */}
<Suspense>
<SelectResource/> <SelectResource/>
</Suspense>
{/* 地区筛选 */} {/* 地区筛选 */}
<SelectRegion/> <SelectRegion/>
@@ -332,8 +334,13 @@ FormFields.displayName = 'FormFields'
function SelectResource() { function SelectResource() {
const [resources, setResources] = useState<Resource[]>([]) const [resources, setResources] = useState<Resource[]>([])
const [status, setStatus] = useStatus() const [status, setStatus] = useStatus()
const profile = useProfileStore(state => state.profile) const profile = use(useProfileStore(store => store.profile))
const getResources = async () => { const getResources = async () => {
if (!profile) {
setStatus('done')
setResources([])
return
}
setStatus('load') setStatus('load')
try { try {
const resp = await allResource() const resp = await allResource()
@@ -352,7 +359,7 @@ function SelectResource() {
useEffect(() => { useEffect(() => {
getResources().then() getResources().then()
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []) }, [profile])
return ( return (
<FormField name="resource" className="md:max-w-[calc(160px*2+1rem)]" label="选择套餐" classNames={{label: 'max-md:text-sm'}}> <FormField name="resource" className="md:max-w-[calc(160px*2+1rem)]" label="选择套餐" classNames={{label: 'max-md:text-sm'}}>
@@ -372,8 +379,8 @@ function SelectResource() {
</div> </div>
) : !profile ? ( ) : !profile ? (
<div className="p-4 flex gap-1 items-center"> <div className="p-4 flex gap-1 items-center">
<Loader className="animate-spin" size={20}/> {/* <Loader className="animate-spin" size={20}/> */}
<span><Link href="/login" className="text-blue-600 hover:underline"></Link></span> <span className="text-gray-600"><Link href="/login" className="text-blue-600 hover:text-blue-700 font-medium"></Link></span>
</div> </div>
) : resources.length === 0 ? ( ) : resources.length === 0 ? (
<div className="p-4 flex gap-1 items-center"> <div className="p-4 flex gap-1 items-center">

View File

@@ -17,21 +17,21 @@ export type PaymentModalProps = {
export function PaymentModal(props: PaymentModalProps) { export function PaymentModal(props: PaymentModalProps) {
// 手动关闭时的处理 // 手动关闭时的处理
const handleClose = async () => { const handleClose = async () => {
try { // try {
const res = await payClose({ // const res = await payClose({
trade_no: props.inner_no, // trade_no: props.inner_no,
method: props.method, // method: props.method,
}) // })
if (!res.success) { // if (!res.success) {
throw new Error(res.message) // throw new Error(res.message)
} // }
} // }
catch (error) { // catch (error) {
console.error('关闭订单失败:', error) // console.error('关闭订单失败:', error)
} // }
finally { // finally {
props.onClose?.() props.onClose?.()
} // }
} }
// SSE处理方式检查支付状态 // SSE处理方式检查支付状态

View File

@@ -30,6 +30,7 @@ export default function Purchase() {
const res = profile const res = profile
? await listProduct({}) ? await listProduct({})
: await listProductHome({}) : await listProductHome({})
console.log(res, 'res')
if (res.success) { if (res.success) {
setProductList(res.data) setProductList(res.data)

View File

@@ -3,18 +3,18 @@ import {FormField} from '@/components/ui/form'
import {RadioGroup} from '@/components/ui/radio-group' import {RadioGroup} from '@/components/ui/radio-group'
import FormOption from '@/components/composites/purchase/option' import FormOption from '@/components/composites/purchase/option'
import {Schema} from '@/components/composites/purchase/long/form' import {Schema} from '@/components/composites/purchase/long/form'
import {useEffect} from 'react' import {useEffect, useMemo} from 'react'
import {useFormContext, useWatch} from 'react-hook-form' import {useFormContext, useWatch} from 'react-hook-form'
import {Card} from '@/components/ui/card' import {Card} from '@/components/ui/card'
import {BillingMethodField} from '../shared/billing-method-field' import {BillingMethodField} from '../shared/billing-method-field'
import {FeatureList} from '../shared/feature-list' import {FeatureList} from '../shared/feature-list'
import {NumberStepperField} from '../shared/number-stepper-field' import {NumberStepperField} from '../shared/number-stepper-field'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku' import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
export default function Center({skuData}: { export default function Center({skuData}: {
skuData: PurchaseSkuData skuData: PurchaseSkuData
}) { }) {
const {setValue} = useFormContext<Schema>() const {setValue, getValues} = useFormContext<Schema>()
const type = useWatch<Schema>({name: 'type'}) as Schema['type'] const type = useWatch<Schema>({name: 'type'}) as Schema['type']
const live = useWatch<Schema>({name: 'live'}) as Schema['live'] const live = useWatch<Schema>({name: 'live'}) as Schema['live']
const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire'] const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire']
@@ -26,6 +26,27 @@ export default function Center({skuData}: {
? getAvailablePurchaseExpires(skuData, {mode: type, live}) ? getAvailablePurchaseExpires(skuData, {mode: type, live})
: [] : []
const currentCountMin = useMemo(() => {
if (!type || !live) return 0
const expireValue = type === '1' ? expire : '0'
return getPurchaseSkuCountMin(skuData, {mode: type, live, expire: expireValue})
}, [type, live, expire, skuData])
useEffect(() => {
if (type === '1') {
const current = getValues('daily_limit')
if (current < currentCountMin) {
setValue('daily_limit', currentCountMin)
}
}
else {
const current = getValues('quota')
if (current < currentCountMin) {
setValue('quota', currentCountMin)
}
}
}, [currentCountMin, type, setValue, getValues])
useEffect(() => { useEffect(() => {
const nextType = modeList.includes(type) ? type : modeList[0] const nextType = modeList.includes(type) ? type : modeList[0]
@@ -146,14 +167,14 @@ export default function Center({skuData}: {
<NumberStepperField <NumberStepperField
name="daily_limit" name="daily_limit"
label="每日提取上限" label="每日提取上限"
min={100} min={currentCountMin || 100}
step={100} step={100}
/> />
) : ( ) : (
<NumberStepperField <NumberStepperField
name="quota" name="quota"
label="IP 购买数量" label="IP 购买数量"
min={500} min={currentCountMin || 500}
step={100} step={100}
/> />
)} )}

View File

@@ -5,7 +5,7 @@ import {Form} from '@/components/ui/form'
import * as z from 'zod' import * as z from 'zod'
import {zodResolver} from '@hookform/resolvers/zod' import {zodResolver} from '@hookform/resolvers/zod'
import {ProductItem} from '@/actions/product' import {ProductItem} from '@/actions/product'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, parsePurchaseSkuList} from '../shared/sku' import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, parsePurchaseSkuList} from '../shared/sku'
import {PurchaseSidePanel} from '../shared/side-panel' import {PurchaseSidePanel} from '../shared/side-panel'
const schema = z.object({ const schema = z.object({
@@ -25,6 +25,11 @@ export default function LongForm({skuList}: {skuList: ProductItem['skus']}) {
const defaultExpire = defaultMode === '1' const defaultExpire = defaultMode === '1'
? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0' ? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0'
: '0' : '0'
const defaultCountMin = getPurchaseSkuCountMin(skuData, {
mode: defaultMode,
live: defaultLive,
expire: defaultExpire,
})
const form = useForm<Schema>({ const form = useForm<Schema>({
resolver: zodResolver(schema), resolver: zodResolver(schema),
@@ -32,8 +37,8 @@ export default function LongForm({skuList}: {skuList: ProductItem['skus']}) {
type: defaultMode, type: defaultMode,
live: defaultLive, live: defaultLive,
expire: defaultExpire, expire: defaultExpire,
quota: 500, quota: defaultMode === '2' ? Math.max(defaultCountMin, 500) : 500,
daily_limit: 100, daily_limit: defaultMode === '1' ? Math.max(defaultCountMin, 100) : 100,
pay_type: 'balance', // 余额支付 pay_type: 'balance', // 余额支付
}, },
}) })

View File

@@ -49,6 +49,9 @@ export function NumberStepperField(props: NumberStepperFieldProps) {
className="w-40 h-10 border border-gray-200 rounded-sm text-center" className="w-40 h-10 border border-gray-200 rounded-sm text-center"
min={props.min} min={props.min}
step={props.step} step={props.step}
onInvalid={(e) => {
e.preventDefault()
}}
onBlur={(event) => { onBlur={(event) => {
field.onBlur() field.onBlur()
const nextValue = Number(event.target.value) const nextValue = Number(event.target.value)

View File

@@ -14,6 +14,7 @@ import {ExtraResp} from '@/lib/api'
import {formatPurchaseLiveLabel} from './sku' import {formatPurchaseLiveLabel} from './sku'
import {User} from '@/lib/models' import {User} from '@/lib/models'
import {PurchaseFormValues} from './form-values' import {PurchaseFormValues} from './form-values'
import {IdCard} from 'lucide-react'
const emptyPrice: ExtraResp<typeof getPrice> = { const emptyPrice: ExtraResp<typeof getPrice> = {
price: '0.00', price: '0.00',
@@ -107,6 +108,7 @@ export function PurchaseSidePanel(props: PurchaseSidePanelProps) {
<span className="text-xl text-orange-500">{discountedPrice}</span> <span className="text-xl text-orange-500">{discountedPrice}</span>
</p> </p>
{profile ? ( {profile ? (
profile.id_type !== 0 ? (
<> <>
<FieldPayment balance={profile.balance}/> <FieldPayment balance={profile.balance}/>
<Pay <Pay
@@ -116,6 +118,20 @@ export function PurchaseSidePanel(props: PurchaseSidePanelProps) {
resource={resource} resource={resource}
/> />
</> </>
) : (
<div className="flex flex-col gap-3">
<p className="text-sm text-gray-500">
</p>
<Link
href="/admin/identify"
className={buttonVariants()}
>
<IdCard size={16} className="mr-1"/>
</Link>
</div>
)
) : ( ) : (
<Link href="/login" className={buttonVariants()}> <Link href="/login" className={buttonVariants()}>

View File

@@ -7,11 +7,13 @@ export type PurchaseSkuItem = {
live: string live: string
expire: string expire: string
price: string price: string
count_min: number
} }
export type PurchaseSkuData = { export type PurchaseSkuData = {
items: PurchaseSkuItem[] items: PurchaseSkuItem[]
priceMap: Map<string, string> priceMap: Map<string, string>
countMinMap: Map<string, number>
modeList: PurchaseMode[] modeList: PurchaseMode[]
liveList: string[] liveList: string[]
expireList: string[] expireList: string[]
@@ -24,6 +26,7 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
const items: PurchaseSkuItem[] = [] const items: PurchaseSkuItem[] = []
const priceMap = new Map<string, string>() const priceMap = new Map<string, string>()
const countMinMap = new Map<string, number>()
const modeSet = new Set<PurchaseMode>() const modeSet = new Set<PurchaseMode>()
const liveSet = new Set<number>() const liveSet = new Set<number>()
const expireSet = new Set<number>() const expireSet = new Set<number>()
@@ -45,6 +48,8 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
live: liveValue, live: liveValue,
expire: expireValue, expire: expireValue,
}) })
const countMin = typeof sku.count_min === 'number' ? sku.count_min : Number(sku.count_min) || 0
countMinMap.set(code, countMin)
items.push({ items.push({
code, code,
@@ -52,6 +57,7 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
live: liveValue, live: liveValue,
expire: expireValue, expire: expireValue,
price: sku.price, price: sku.price,
count_min: countMin,
}) })
priceMap.set(code, sku.price) priceMap.set(code, sku.price)
modeSet.add(mode) modeSet.add(mode)
@@ -75,6 +81,7 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
return { return {
items, items,
priceMap, priceMap,
countMinMap,
modeList: (['2', '1'] as const).filter(mode => modeSet.has(mode)), modeList: (['2', '1'] as const).filter(mode => modeSet.has(mode)),
liveList: sortNumericValues(liveSet), liveList: sortNumericValues(liveSet),
expireList: sortNumericValues(expireSet), expireList: sortNumericValues(expireSet),
@@ -163,3 +170,11 @@ export function formatPurchaseLiveLabel(live: string, kind: PurchaseKind) {
return `${minutes} 分钟` return `${minutes} 分钟`
} }
export function getPurchaseSkuCountMin(
skuData: PurchaseSkuData,
props: {mode: PurchaseMode, live: string, expire: string},
): number {
const key = getPurchaseSkuKey(props)
return skuData.countMinMap.get(key) ?? 0
}

View File

@@ -2,21 +2,22 @@
import {FormField} from '@/components/ui/form' import {FormField} from '@/components/ui/form'
import {RadioGroup} from '@/components/ui/radio-group' import {RadioGroup} from '@/components/ui/radio-group'
import FormOption from '@/components/composites/purchase/option' import FormOption from '@/components/composites/purchase/option'
import {useEffect} from 'react' import {useEffect, useMemo} from 'react'
import {useFormContext, useWatch} from 'react-hook-form' import {useFormContext, useWatch} from 'react-hook-form'
import {Schema} from '@/components/composites/purchase/short/form' import {Schema} from '@/components/composites/purchase/short/form'
import {Card} from '@/components/ui/card' import {Card} from '@/components/ui/card'
import {BillingMethodField} from '../shared/billing-method-field' import {BillingMethodField} from '../shared/billing-method-field'
import {FeatureList} from '../shared/feature-list' import {FeatureList} from '../shared/feature-list'
import {NumberStepperField} from '../shared/number-stepper-field' import {NumberStepperField} from '../shared/number-stepper-field'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku' import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
export default function Center({ export default function Center({
skuData, skuData,
}: { }: {
skuData: PurchaseSkuData skuData: PurchaseSkuData
}) { }) {
const {setValue} = useFormContext<Schema>() // const {setValue} = useFormContext<Schema>()
const {setValue, getValues} = useFormContext<Schema>()
const type = useWatch<Schema>({name: 'type'}) as Schema['type'] const type = useWatch<Schema>({name: 'type'}) as Schema['type']
const live = useWatch<Schema>({name: 'live'}) as Schema['live'] const live = useWatch<Schema>({name: 'live'}) as Schema['live']
const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire'] const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire']
@@ -28,6 +29,25 @@ export default function Center({
? getAvailablePurchaseExpires(skuData, {mode: type, live}) ? getAvailablePurchaseExpires(skuData, {mode: type, live})
: [] : []
const currentCountMin = useMemo(() => {
if (!type || !live) return 0
const expireValue = type === '1' ? expire : '0'
return getPurchaseSkuCountMin(skuData, {mode: type, live, expire: expireValue})
}, [type, live, expire, skuData])
useEffect(() => {
if (type === '1') {
const current = getValues('daily_limit')
if (current < currentCountMin) {
setValue('daily_limit', currentCountMin)
}
}
else {
const current = getValues('quota')
if (current < currentCountMin) {
setValue('quota', currentCountMin)
}
}
}, [currentCountMin, type, setValue, getValues])
useEffect(() => { useEffect(() => {
const nextType = modeList.includes(type) ? type : modeList[0] const nextType = modeList.includes(type) ? type : modeList[0]
@@ -151,14 +171,14 @@ export default function Center({
<NumberStepperField <NumberStepperField
name="daily_limit" name="daily_limit"
label="每日提取上限" label="每日提取上限"
min={2000} min={currentCountMin || 2000}
step={1000} step={1000}
/> />
) : ( ) : (
<NumberStepperField <NumberStepperField
name="quota" name="quota"
label="IP 购买数量" label="IP 购买数量"
min={10000} min={currentCountMin || 10000}
step={5000} step={5000}
/> />
)} )}

View File

@@ -5,7 +5,7 @@ import {Form} from '@/components/ui/form'
import * as z from 'zod' import * as z from 'zod'
import {zodResolver} from '@hookform/resolvers/zod' import {zodResolver} from '@hookform/resolvers/zod'
import {ProductItem} from '@/actions/product' import {ProductItem} from '@/actions/product'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, parsePurchaseSkuList} from '../shared/sku' import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, parsePurchaseSkuList} from '../shared/sku'
import {PurchaseSidePanel} from '../shared/side-panel' import {PurchaseSidePanel} from '../shared/side-panel'
const schema = z.object({ const schema = z.object({
@@ -25,15 +25,19 @@ export default function ShortForm({skuList}: {skuList: ProductItem['skus']}) {
const defaultExpire = defaultMode === '1' const defaultExpire = defaultMode === '1'
? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0' ? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0'
: '0' : '0'
const defaultCountMin = getPurchaseSkuCountMin(skuData, {
mode: defaultMode,
live: defaultLive,
expire: defaultExpire,
})
const form = useForm<Schema>({ const form = useForm<Schema>({
resolver: zodResolver(schema), resolver: zodResolver(schema),
defaultValues: { defaultValues: {
type: defaultMode, type: defaultMode,
live: defaultLive, live: defaultLive,
expire: defaultExpire, expire: defaultExpire,
quota: 10_000, // >= 10000, quota: defaultMode === '2' ? defaultCountMin || 10000 : 10000,
daily_limit: 2_000, // >= 2000 daily_limit: defaultMode === '1' ? defaultCountMin || 2000 : 2000,
pay_type: 'balance', // 余额支付 pay_type: 'balance', // 余额支付
}, },
}) })

View File

@@ -26,7 +26,7 @@ function Resolved(props: {
router.push(profile ? '/admin/purchase' : '/product') router.push(profile ? '/admin/purchase' : '/product')
}} }}
> >
</button> </button>
) )
} }
@@ -42,7 +42,7 @@ function Pending(props: {
router.push('/product') router.push('/product')
}} }}
> >
</button> </button>
) )
} }

View File

@@ -1,6 +1,7 @@
export type ProductSku = { export type ProductSku = {
id: number id: number
code: string code: string
count_min: number
name: string name: string
price: string price: string
price_min: string price_min: string