12 Commits

Author SHA1 Message Date
Eamon-meng
0ec2499bad 修改提取IP页面请求参数文档 2026-07-14 17:56:02 +08:00
Eamon-meng
95f9388a3f 修改提取ip链接 2026-07-04 13:06:29 +08:00
Eamon-meng
7e69501e84 提取代理接口文档修改类型 2026-07-02 14:07:14 +08:00
Eamon-meng
c74e19a062 完善选择地区的树组件 2026-07-02 13:51:02 +08:00
Eamon-meng
4f165c6a97 提取IP页面取消去重选项 2026-07-02 13:51:01 +08:00
Eamon-meng
dc877c3ea0 ip管理表格添加提取地区列 & 提取IP取消运营商字段选项 & 调整购买页价格显示问题 2026-07-02 13:51:00 +08:00
94ab3f55a8 新增 v2 提取接口 2026-07-02 13:49:57 +08:00
Eamon-meng
c2465ece04 支付弹窗不使用sse改调用后端接口返回 2026-06-18 18:19:40 +08:00
Eamon-meng
c297c2330e 调整购买页面价格显示 2026-06-18 18:19:36 +08:00
Eamon-meng
96abb97a9a 提取不显示主机格式字段 2026-06-18 18:19:32 +08:00
bdd4424f44 接口请求返回登录页后不再重定向 2026-06-17 14:00:09 +08:00
dfaf39e37e 修复跳转异常拦截问题 2026-06-17 13:34:48 +08:00
25 changed files with 425 additions and 182 deletions

View File

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

View File

@@ -1,6 +1,7 @@
'use server'
import {API_BASE_URL, ApiResponse, CLIENT_ID, CLIENT_SECRET} from '@/lib/api'
import {add, isBefore} from 'date-fns'
import {isRedirectError} from 'next/dist/client/components/redirect-error'
import {cookies, headers} from 'next/headers'
import {redirect} from 'next/navigation'
import {cache} from 'react'
@@ -125,7 +126,7 @@ async function call<R = undefined>(url: string, body: RequestInit['body'], auth?
})
if (response.status === 401) {
return redirect('/login?redirect=' + encodeURIComponent(url.replace(API_BASE_URL, '')))
return redirect('/login')
}
const type = response.headers.get('Content-Type') ?? 'text/plain'
@@ -169,6 +170,9 @@ async function call<R = undefined>(url: string, body: RequestInit['body'], auth?
}
catch (e) {
console.error('后端请求失败', url, (e as Error).message)
if (isRedirectError(e)) {
throw e
}
throw new Error(`请求失败,网络错误`)
}
}

View File

@@ -37,6 +37,19 @@ export async function createChannels(params: {
return callPublic<CreateChannelsResp[]>('/api/channel/create', params)
}
export async function createChannelsV2(params: {
resource_no: string
protocol: number
auth_type: number
count: number
prov?: string
city?: string
isp?: number
host_format?: number
}) {
return callPublic<CreateChannelsResp[]>('/api/channel/create/v2', params)
}
export async function createChannelsV3(params: {
resource_no: string
protocol: number

View File

@@ -80,12 +80,14 @@ export async function completeResource(props: {
}) {
return callByUser('/api/trade/complete', props)
}
type PayCloseData = {
status: 0 | 1 | 2
}
export async function payClose(props: {
trade_no: string
method: number
}) {
return callByUser('/api/trade/cancel', props)
return callByUser<PayCloseData>('/api/trade/finish', props)
}
export async function getPrice(props: CreateResourceReq) {

View File

@@ -22,50 +22,19 @@ export async function GET(req: NextRequest) {
if (!count) {
throw new Error('需要指定通道创建数量')
}
// const prov = params.get('a') || undefined
const area_id = params.get('b') || undefined
const isp = params.get('s') || undefined
const hostFormat = params.get('rh') || 'domain'
const isNumeric = /^\d+$/.test(resourceParam)
let result
if (!isNumeric) {
console.log(area_id, 'area_id', params.get('b'), 'params.get')
result = await createChannelsV3({
resource_no: resourceParam,
auth_type: Number(auth_type),
protocol: Number(protocol),
count: Number(count),
// prov,
area_id: Number(area_id),
isp: Number(isp),
host_format: hostFormat === 'domain' ? 1 : 2,
})
console.log({
resource_no: resourceParam,
auth_type: Number(auth_type),
protocol: Number(protocol),
count: Number(count),
// prov,
area_id: Number(area_id),
isp: Number(isp),
host_format: hostFormat === 'domain' ? 1 : 2,
})
}
else {
result = await createChannels({
resource_id: Number(resourceParam),
auth_type: Number(auth_type),
protocol: Number(protocol),
count: Number(count),
// prov,
area_id: Number(area_id),
isp: Number(isp),
host_format: hostFormat === 'domain' ? 1 : 2,
})
}
const result = await createChannelsV3({
resource_no: resourceParam,
auth_type: Number(auth_type),
protocol: Number(protocol),
count: Number(count),
area_id: Number(area_id),
isp: Number(isp),
host_format: hostFormat === 'domain' ? 1 : 2,
})
if (!result.success) {
throw new Error(result.message)
}

View File

@@ -0,0 +1,93 @@
import {NextRequest, NextResponse} from 'next/server'
import {createChannels, createChannelsV2, createChannelsV3} from '@/actions/channel'
export async function GET(req: NextRequest) {
const params = req.nextUrl.searchParams
try {
const resourceParam = params.get('i')
if (!resourceParam) {
throw new Error('需要指定资源ID')
}
let protocol = params.get('x')
if (!protocol) {
protocol = '1'
}
const auth_type = params.get('t')
if (!auth_type) {
throw new Error('需要指定认证类型')
}
const count = params.get('n')
if (!count) {
throw new Error('需要指定通道创建数量')
}
const prov = params.get('a') || undefined
const city = params.get('b') || undefined
const isp = params.get('s') || undefined
const hostFormat = params.get('rh') || 'domain'
const result = await createChannelsV2({
resource_no: resourceParam,
auth_type: Number(auth_type),
protocol: Number(protocol),
count: Number(count),
prov,
city,
isp: Number(isp),
host_format: hostFormat === 'domain' ? 1 : 2,
})
if (!result.success) {
throw new Error(result.message)
}
const format = params.get('rt')
const rBreaker = params.get('rb') || '13,10'
const rSeparator = params.get('rs') || '124'
const breaker = rBreaker.split(',').map(code => String.fromCharCode(parseInt(code))).join('')
const separator = rSeparator.split(',').map(code => String.fromCharCode(parseInt(code))).join('')
switch (format) {
case 'json':
if (hostFormat === 'domain') {
const domainFormatData = result.data.map(item => ({
host: item.host,
port: item.port,
...(item.username && item.password ? {username: item.username, password: item.password} : {}),
}))
return NextResponse.json(domainFormatData)
}
else {
const ipFormatData = result.data.map(item => ({
ip: item.ip,
port: item.port,
...(item.username && item.password ? {username: item.username, password: item.password} : {}),
}))
return NextResponse.json(ipFormatData)
}
case 'text':
const text = result.data.map((item) => {
let hostValue: string
if (hostFormat === 'domain') {
hostValue = item.host
}
else {
hostValue = item.ip
}
const list = [hostValue, String(item.port)]
if (item.username && item.password) {
list.push(item.username)
list.push(item.password)
}
return list.join(separator)
}).join(breaker)
return new NextResponse(text)
}
}
catch (error) {
console.error('Error creating channels:', error)
return NextResponse.json({error: (error as Error).message})
}
}

View File

@@ -2,20 +2,17 @@
## 请求方式
`GET https://lanhuip.com/api/extract`
`GET https://lanhuip.com/proxies/v2`
## 请求参数
| 参数名 | 类型 | 必填 | 描述 |
|--------|----------|------|----------------------------------------------------------------------------------------------------------------------------|
| i | number | 是 | 用于提取的套餐 ID |
| i | string | 是 | 用于提取的套餐 ID |
| t | number | 是 | 认证类型1 - 白名单2 - 密码 |
| a | string | 否 | 归属地省份。默认全局随机 |
| b | string | 否 | 归属地城市。默认全局随机 |
| s | string | 否 | 归属地运营商。默认全局随机 |
| d | string | 否 | 是否去重1 - 是0 - 否。默认为是 |
| rt | string | 否 | 返回类型1 - TXT2 - JSON。默认 TXT
| rh | string | 否 | 返回时主机字段的格式1 - 域名2 - IP。默认为域名 |
| a | string | 否 | 归属地省份,直接传省份名称,例如:广东,默认或不传时为不限 |
| b | string | 否 | 归属地城市,直接传城市名称,例如:上海,默认或不传时为不限 |
| rt | string | 否 | 返回类型1 - TXT2 - JSON。默认 TXT |
| rs | number[] | 否 | 返回时要使用的分隔符,值为该字符的 ascii 编码,可以有多个字符,多个字符用半角逗号连接。默认为 13,10即回车 + 换行(\r\n |
| rb | number[] | 否 | 返回时要使用的换行符,值为该字符的 ascii 编码,可以有多个字符,多个字符用半角逗号连接。默认为 124即垂直线 \| |
| n | number | 否 | 提取数量。默认为 1 |
@@ -39,7 +36,7 @@
### 请求示例
```http
GET https://lanhuip.com/api/extract?i=1&t=2&a=广东省&b=广州市&s=移动&d=1&rt=2&n=3
GET https://lanhuip.com/proxies/v2?i=1&t=2&a=广东省&b=广州市&s=移动&d=1&rt=2&n=3
```
### 响应示例
@@ -72,7 +69,7 @@ GET https://lanhuip.com/api/extract?i=1&t=2&a=广东省&b=广州市&s=移动&d=1
### 请求示例
```http
GET https://lanhuip.com/api/extract?i=24&t=1&a=广东省&b=广州市&d=1&rt=text&rh=ip&rs=124&rb=13%2C10&n=1
GET https://lanhuip.com/proxies/v2?i=24&t=1&a=广东省&b=广州市&d=1&rt=text&rh=ip&rs=124&rb=13%2C10&n=1
```
### 响应示例

View File

@@ -197,7 +197,7 @@ export default function BalancePage(props: BalancePageProps) {
<div className="flex items-center gap-1">
<span
className={`font-semibold ${
isPositive ? 'text-green-600' : 'text-red-600'
isPositive ? 'text-red-600' : 'text-green-600'
}`}
>
{isPositive ? '+' : ''}

View File

@@ -178,6 +178,21 @@ export default function ChannelsPage(props: ChannelsPageProps) {
header: '代理地址',
cell: ({row}) => <Addr channel={row.original}/>,
},
{
header: '地区',
cell: ({row}) => {
const prov = row.original.filter_prov
const city = row.original.filter_city
const parts = []
if (prov && prov !== 'all') parts.push(prov)
if (city && city !== 'all') parts.push(city)
return (
<div className="text-sm">
{parts.length > 0 ? parts.join(' / ') : '不限'}
</div>
)
},
},
{
header: '认证方式',
cell: ({row}) => {

View File

@@ -26,12 +26,12 @@ const schema = z.object({
prov: z.string().optional(),
city: z.string().optional(),
regionType: z.enum(['unlimited', 'specific']).default('unlimited'),
isp: z.enum(['all', '1', '2', '3'], {required_error: '请选择运营商'}),
// isp: z.enum(['all', '1', '2', '3'], {required_error: '请选择运营商'}),
proto: z.enum(['all', '1', '2'], {required_error: '请选择协议'}),
authType: z.enum(['1', '2'], {required_error: '请选择认证方式'}),
distinct: z.enum(['1', '0'], {required_error: '请选择去重选项'}),
// distinct: z.enum(['1', '0'], {required_error: '请选择去重选项'}),
format: z.enum(['text', 'json'], {required_error: '请选择导出格式'}),
hostFormat: z.enum(['domain', 'ip'], {required_error: '请选择主机格式'}),
// hostFormat: z.enum(['domain', 'ip'], {required_error: '请选择主机格式'}),
separator: z.string({required_error: '请选择分隔符'}),
breaker: z.string({required_error: '请选择换行符'}),
count: z.number({required_error: '请输入有效的数量'}).min(1),
@@ -48,12 +48,12 @@ export default function Extract(props: ExtractProps) {
resolver: zodResolver(schema),
defaultValues: {
regionType: 'unlimited',
isp: 'all',
// isp: 'all',
proto: 'all',
authType: '1',
count: 1,
distinct: '1',
hostFormat: 'ip',
// distinct: '1',
// hostFormat: 'ip',
format: 'text',
breaker: '13,10',
separator: '124',
@@ -108,7 +108,7 @@ const FormFields = memo(() => {
<SelectRegion/>
{/* 运营商筛选 */}
<FormField name="isp" label="运营商筛选" classNames={{label: 'max-md:text-sm'}}>
{/* <FormField name="isp" label="运营商筛选" classNames={{label: 'max-md:text-sm'}}>
{({id, field}) => (
<RadioGroup
onValueChange={field.onChange}
@@ -133,7 +133,7 @@ const FormFields = memo(() => {
</FormLabel>
</RadioGroup>
)}
</FormField>
</FormField> */}
{/* 协议类型 */}
<FormField name="proto" label="协议类型" classNames={{label: 'max-md:text-sm'}}>
@@ -182,7 +182,7 @@ const FormFields = memo(() => {
</FormField>
{/* 去重选项 */}
<FormField name="distinct" className="md:max-w-[calc(160px*2+1rem)]" label="去重选项" classNames={{label: 'max-md:text-sm'}}>
{/* <FormField name="distinct" className="md:max-w-[calc(160px*2+1rem)]" label="去重选项" classNames={{label: 'max-md:text-sm'}}>
{({id, field}) => (
<RadioGroup
onValueChange={field.onChange}
@@ -198,7 +198,7 @@ const FormFields = memo(() => {
</FormLabel>
</RadioGroup>
)}
</FormField>
</FormField> */}
{/* 导出格式 */}
<FormField name="format" className="md:max-w-[calc(160px*2+1rem)]" label="导出格式" classNames={{label: 'max-md:text-sm'}}>
@@ -221,7 +221,7 @@ const FormFields = memo(() => {
</FormField>
{/* 主机格式 */}
<FormField name="hostFormat" className="md:max-w-[calc(160px*2+1rem)]" label="主机格式" classNames={{label: 'max-md:text-sm'}}>
{/* <FormField name="hostFormat" className="md:max-w-[calc(160px*2+1rem)]" label="主机格式" classNames={{label: 'max-md:text-sm'}}>
{({id, field}) => (
<RadioGroup
onValueChange={field.onChange}
@@ -238,7 +238,7 @@ const FormFields = memo(() => {
</FormLabel>
</RadioGroup>
)}
</FormField>
</FormField> */}
{/* 分隔符 */}
<FormField name="separator" className="md:max-w-[calc(160px*3+1rem*2)]" label="分隔符" classNames={{label: 'max-md:text-sm'}}>
@@ -711,7 +711,7 @@ function ApplyLink() {
}
function link(values: Schema) {
const {resource, prov, city, isp, proto, authType, distinct, format: formatType, hostFormat, separator, breaker, count} = values
const {resource, prov, city, proto, authType, format: formatType, separator, breaker, count} = values
console.log(values, 'values')
const sp = new URLSearchParams()
@@ -721,10 +721,10 @@ function link(values: Schema) {
if (prov) sp.set('b', prov)
if (city) sp.set('b', city)
if (isp != 'all') sp.set('s', isp)
sp.set('d', distinct)
sp.set('s', 'all')
sp.set('d', '1')
sp.set('rt', formatType)
sp.set('rh', hostFormat)
sp.set('rh', 'ip')
sp.set('rs', separator)
sp.set('rb', breaker)
sp.set('n', String(count))

View File

@@ -8,7 +8,7 @@ import {payClose} from '@/actions/resource'
import {useEffect} from 'react'
import {UniversalDesktopPayment} from './universal-desktop-payment'
import {useAppStore} from '@/components/stores/app'
import {toast} from 'sonner'
export type PaymentModalProps = {
onConfirm: (showFail: boolean) => Promise<void>
onClose: () => void
@@ -17,45 +17,49 @@ export type PaymentModalProps = {
export function PaymentModal(props: PaymentModalProps) {
// 手动关闭时的处理
const handleClose = async () => {
// try {
// const res = await payClose({
// trade_no: props.inner_no,
// method: props.method,
// })
// if (!res.success) {
// throw new Error(res.message)
// }
// }
// catch (error) {
// console.error('关闭订单失败:', error)
// }
// finally {
props.onClose?.()
// }
try {
const res = await payClose({
trade_no: props.inner_no,
method: props.method,
})
if (!res.success) {
throw new Error(res.message || '请求失败')
}
if (res.data.status === 1) {
toast.success('已支付成功!')
}
}
catch (error) {
console.error('关闭订单失败:', error)
}
finally {
props.onClose?.()
}
}
// SSE处理方式检查支付状态
const apiUrl = useAppStore('apiUrl')
useEffect(() => {
const eventSource = new EventSource(
`${apiUrl}/api/trade/check?trade_no=${props.inner_no}&method=${props.method}`,
)
eventSource.onmessage = async (event) => {
switch (event.data) {
case '1':
props.onConfirm?.(true)
case '2':
props.onClose?.()
}
}
eventSource.onerror = (error) => {
console.error('SSE 连接错误:', error)
}
// const apiUrl = useAppStore('apiUrl')
// useEffect(() => {
// const eventSource = new EventSource(
// `${apiUrl}/api/trade/check?trade_no=${props.inner_no}&method=${props.method}`,
// )
// eventSource.onmessage = async (event) => {
// switch (event.data) {
// case '1':
// props.onConfirm?.(true)
// case '2':
// props.onClose?.()
// }
// }
// eventSource.onerror = (error) => {
// console.error('SSE 连接错误:', error)
// }
return () => {
eventSource.close()
}
}, [apiUrl, props])
// return () => {
// eventSource.close()
// }
// }, [apiUrl, props])
return (
<Dialog

View File

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

View File

@@ -9,7 +9,7 @@ import {Card} from '@/components/ui/card'
import {BillingMethodField} from '../shared/billing-method-field'
import {FeatureList} from '../shared/feature-list'
import {NumberStepperField} from '../shared/number-stepper-field'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuDiscount, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
export default function Center({skuData}: {
skuData: PurchaseSkuData
@@ -18,7 +18,7 @@ export default function Center({skuData}: {
const type = useWatch<Schema>({name: 'type'}) as Schema['type']
const live = useWatch<Schema>({name: 'live'}) as Schema['live']
const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire']
const {modeList, priceMap} = skuData
const {modeList, priceMap, discountMap} = skuData
const liveList = type === '1'
? getAvailablePurchaseLives(skuData, {mode: type, expire})
: getAvailablePurchaseLives(skuData, {mode: type})
@@ -134,7 +134,7 @@ export default function Center({skuData}: {
setValue('expire', nextExpireList[0])
}
}}
className="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-4">
className="grid grid-cols-[repeat(auto-fill,minmax(150px,1fr))] gap-4">
{liveList.map((live) => {
const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire})
? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0'
@@ -144,6 +144,11 @@ export default function Center({skuData}: {
live,
expire: priceExpire,
})
const discount = getPurchaseSkuDiscount(discountMap, {
mode: type,
live,
expire: priceExpire,
})
return (
<FormOption
key={live}
@@ -151,6 +156,8 @@ export default function Center({skuData}: {
value={live}
label={`${Number(live) / 60} 小时`}
description={price && `${price}/IP`}
price={price}
discount={discount}
compare={field.value}
/>
)

View File

@@ -20,7 +20,7 @@ export type Schema = z.infer<typeof schema>
export default function LongForm({skuList}: {skuList: ProductItem['skus']}) {
const skuData = parsePurchaseSkuList('long', skuList)
const defaultMode = skuData.modeList.includes('1') ? '1' : '2'
const defaultMode = skuData.modeList.includes('2') ? '2' : '1'
const defaultLive = getAvailablePurchaseLives(skuData, {mode: defaultMode})[0] || ''
const defaultExpire = defaultMode === '1'
? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0'
@@ -46,7 +46,7 @@ export default function LongForm({skuList}: {skuList: ProductItem['skus']}) {
return (
<Form form={form} className="flex flex-col lg:flex-row gap-4">
<Center skuData={skuData}/>
<PurchaseSidePanel kind="long"/>
<PurchaseSidePanel kind="long" skuData={skuData}/>
</Form>
)
}

View File

@@ -9,12 +9,37 @@ export type FormOptionProps = {
value: string
label?: string
description?: string
price?: string
discount?: number
compare: string
className?: string
children?: ReactNode
}
export default function FormOption(props: FormOptionProps) {
// 安全地解析价格
const priceNum = props.price ? parseFloat(props.price) : NaN
const isValidPrice = !isNaN(priceNum) && priceNum > 0
const discount = typeof props.discount === 'number' ? props.discount : undefined
const hasDiscount = isValidPrice && discount !== undefined && discount < 100
const discountedPrice = hasDiscount ? priceNum * discount / 100 : null
const formatPrice = (price: number | string): string => {
const num = typeof price === 'string' ? parseFloat(price) : price
// 如果是 NaN 或无效值,返回空字符串
if (isNaN(num) || !isFinite(num)) return ''
const str = num.toString()
if (!str.includes('.')) return str
const decimal = str.split('.')[1]
if (/^0+$/.test(decimal)) return Math.floor(num).toString()
if (decimal.length <= 2) return str
return num.toFixed(4).replace(/\.?0+$/, '')
}
return (
<>
<FormLabel
@@ -28,7 +53,24 @@ export default function FormOption(props: FormOptionProps) {
{props.children ? props.children : (
<>
<span>{props.label}</span>
{props.description && <p className="text-sm text-gray-500">{props.description}</p>}
{props.description && !isValidPrice && (
<p className="text-sm text-gray-500">{props.description}</p>
)}
{isValidPrice && (
<div className="flex items-center flex-col">
{hasDiscount ? (
<>
<p className="text-sm font-medium">{formatPrice(discountedPrice!)}/IP</p>
<p className="text-sm text-gray-500 line-through">:{formatPrice(props.price!)}/IP</p>
{/* <span className="text-xs font-medium text-orange-600 bg-orange-50 px-1.5 py-0.5 rounded-full">
{props.discount}折
</span> */}
</>
) : (
<p className="text-sm">{formatPrice(props.price!)}/IP</p>
)}
</div>
)}
</>
)}
</FormLabel>

View File

@@ -34,16 +34,6 @@ export function BillingMethodField(props: {
}}
className="flex gap-4 max-md:flex-col"
>
{props.modeList.includes('1') && (
<FormOption
id={`${id}-1`}
value="1"
label="包时套餐"
description="适用于每日提取量稳定的业务场景"
compare={field.value}
/>
)}
{props.modeList.includes('2') && (
<FormOption
id={`${id}-2`}
@@ -53,6 +43,15 @@ export function BillingMethodField(props: {
compare={field.value}
/>
)}
{props.modeList.includes('1') && (
<FormOption
id={`${id}-1`}
value="1"
label="包时套餐"
description="适用于每日提取量稳定的业务场景"
compare={field.value}
/>
)}
</RadioGroup>
)}
</FormField>

View File

@@ -11,7 +11,7 @@ const defaultFeatures = [
'IP时效3-30分钟(可定制)',
'IP资源定期筛选',
'包量/包时计费方式',
'每日去重量500万',
'每日去重量50万',
]
export function FeatureList(props: {

View File

@@ -11,7 +11,7 @@ import {FieldPayment} from './field-payment'
import {buildPurchaseResource, PurchaseKind, PurchaseSelection} from './resource'
import {getPrice, getPriceHome} from '@/actions/resource'
import {ExtraResp} from '@/lib/api'
import {formatPurchaseLiveLabel} from './sku'
import {formatPurchaseLiveLabel, getPurchaseSkuCountMin, PurchaseSkuData} from './sku'
import {User} from '@/lib/models'
import {PurchaseFormValues} from './form-values'
import {IdCard} from 'lucide-react'
@@ -25,6 +25,7 @@ const emptyPrice: ExtraResp<typeof getPrice> = {
export type PurchaseSidePanelProps = {
kind: PurchaseKind
skuData: PurchaseSkuData
}
export function PurchaseSidePanel(props: PurchaseSidePanelProps) {
@@ -44,7 +45,7 @@ export function PurchaseSidePanel(props: PurchaseSidePanelProps) {
expire,
dailyLimit,
}
const {priceData, isLoading, isError} = usePurchasePrice(profile, selection)
const {priceData, isLoading, isError} = usePurchasePrice(profile, selection, props.skuData)
const {price, actual: discountedPrice = '0.00'} = priceData
const totalDiscount = getTotalDiscount(price, discountedPrice)
const hasDiscount = Number(totalDiscount) > 0
@@ -154,7 +155,7 @@ export function PurchaseSidePanel(props: PurchaseSidePanelProps) {
)
}
function usePurchasePrice(profile: User | null, selection: PurchaseSelection) {
function usePurchasePrice(profile: User | null, selection: PurchaseSelection, skuData: PurchaseSkuData) {
const [priceData, setPriceData] = useState<ExtraResp<typeof getPrice>>(emptyPrice)
const [isLoading, setIsLoading] = useState(true)
const [isError, setIsError] = useState(false)
@@ -164,6 +165,15 @@ function usePurchasePrice(profile: User | null, selection: PurchaseSelection) {
useEffect(() => {
const requestId = ++requestIdRef.current
const expireValue = mode === '1' ? expire : '0'
const countMin = getPurchaseSkuCountMin(skuData, {mode, live, expire: expireValue})
const quantity = mode === '1' ? dailyLimit : quota
if (countMin > 0 && quantity < countMin) {
setIsLoading(false)
setIsError(false)
return
}
const loadPrice = async () => {
setIsLoading(true)
setIsError(false)
@@ -177,6 +187,7 @@ function usePurchasePrice(profile: User | null, selection: PurchaseSelection) {
expire,
dailyLimit,
})
const response = profile
? await getPrice(resource)
: await getPriceHome(resource)
@@ -184,7 +195,9 @@ function usePurchasePrice(profile: User | null, selection: PurchaseSelection) {
if (requestId !== requestIdRef.current) {
return
}
if (!response.success) {
throw new Error(response.message)
}
if (response.success) {
setPriceData({
price: response.data.price,
@@ -211,7 +224,7 @@ function usePurchasePrice(profile: User | null, selection: PurchaseSelection) {
}
loadPrice()
}, [dailyLimit, expire, kind, live, mode, profile, quota])
}, [dailyLimit, expire, kind, live, mode, profile, quota, skuData])
return {priceData, isLoading, isError}
}

View File

@@ -8,12 +8,14 @@ export type PurchaseSkuItem = {
expire: string
price: string
count_min: number
discount: number
}
export type PurchaseSkuData = {
items: PurchaseSkuItem[]
priceMap: Map<string, string>
countMinMap: Map<string, number>
discountMap: Map<string, number>
modeList: PurchaseMode[]
liveList: string[]
expireList: string[]
@@ -27,6 +29,7 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
const items: PurchaseSkuItem[] = []
const priceMap = new Map<string, string>()
const countMinMap = new Map<string, number>()
const discountMap = new Map<string, number>()
const modeSet = new Set<PurchaseMode>()
const liveSet = new Set<number>()
const expireSet = new Set<number>()
@@ -51,6 +54,7 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
const countMin = typeof sku.count_min === 'number' ? sku.count_min : Number(sku.count_min) || 0
countMinMap.set(code, countMin)
const skuDiscount = sku.discount ?? 100
items.push({
code,
mode,
@@ -58,8 +62,10 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
expire: expireValue,
price: sku.price,
count_min: countMin,
discount: skuDiscount,
})
priceMap.set(code, sku.price)
discountMap.set(code, skuDiscount)
modeSet.add(mode)
liveSet.add(live)
@@ -82,6 +88,7 @@ export function parsePurchaseSkuList(kind: PurchaseKind, skuList: ProductItem['s
items,
priceMap,
countMinMap,
discountMap,
modeList: (['2', '1'] as const).filter(mode => modeSet.has(mode)),
liveList: sortNumericValues(liveSet),
expireList: sortNumericValues(expireSet),
@@ -157,6 +164,14 @@ export function getPurchaseSkuPrice(priceMap: Map<string, string>, props: {
return priceMap.get(getPurchaseSkuKey(props))
}
export function getPurchaseSkuDiscount(discountMap: Map<string, number>, props: {
mode: PurchaseMode
live: string
expire: string
}) {
return discountMap.get(getPurchaseSkuKey(props))
}
export function formatPurchaseLiveLabel(live: string, kind: PurchaseKind) {
const minutes = Number(live)

View File

@@ -9,7 +9,7 @@ import {Card} from '@/components/ui/card'
import {BillingMethodField} from '../shared/billing-method-field'
import {FeatureList} from '../shared/feature-list'
import {NumberStepperField} from '../shared/number-stepper-field'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuDiscount, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
export default function Center({
skuData,
@@ -20,7 +20,7 @@ export default function Center({
const type = useWatch<Schema>({name: 'type'}) as Schema['type']
const live = useWatch<Schema>({name: 'live'}) as Schema['live']
const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire']
const {modeList, priceMap} = skuData
const {modeList, priceMap, discountMap} = skuData
const liveList = type === '1'
? getAvailablePurchaseLives(skuData, {mode: type, expire})
: getAvailablePurchaseLives(skuData, {mode: type})
@@ -135,7 +135,7 @@ export default function Center({
setValue('expire', nextExpireList[0])
}
}}
className="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-4">
className="grid grid-cols-[repeat(auto-fill,minmax(150px,1fr))] gap-4">
{liveList.map((live) => {
const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire})
? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0'
@@ -145,6 +145,11 @@ export default function Center({
live,
expire: priceExpire,
})
const discount = getPurchaseSkuDiscount(discountMap, {
mode: type,
live,
expire: priceExpire,
})
const minutes = Number(live)
const hours = minutes / 60
const label = minutes % 60 === 0 ? `${hours} 小时` : `${minutes} 分钟`
@@ -155,6 +160,8 @@ export default function Center({
value={live}
label={label}
description={price && `${price}/IP`}
price={price}
discount={discount}
compare={field.value}
/>
)

View File

@@ -20,7 +20,7 @@ export type Schema = z.infer<typeof schema>
export default function ShortForm({skuList}: {skuList: ProductItem['skus']}) {
const skuData = parsePurchaseSkuList('short', skuList)
const defaultMode = skuData.modeList.includes('1') ? '1' : '2'
const defaultMode = skuData.modeList.includes('2') ? '2' : '1'
const defaultLive = getAvailablePurchaseLives(skuData, {mode: defaultMode})[0] || ''
const defaultExpire = defaultMode === '1'
? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0'
@@ -42,11 +42,12 @@ export default function ShortForm({skuList}: {skuList: ProductItem['skus']}) {
pay_type: 'balance', // 余额支付
},
})
console.log(skuData, 'skuData')
return (
<Form form={form} className="flex flex-col lg:flex-row gap-4">
<Center skuData={skuData}/>
<PurchaseSidePanel kind="short"/>
<PurchaseSidePanel kind="short" skuData={skuData}/>
</Form>
)
}

View File

@@ -1,7 +1,7 @@
'use client'
import * as React from 'react'
import {CheckIcon, ChevronsUpDown} from 'lucide-react'
import {CheckIcon, ChevronDown, ChevronRight, ChevronsUpDown} from 'lucide-react'
import {merge} from '@/lib/utils'
import {Button} from '@/components/ui/button'
@@ -10,7 +10,7 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover'
import {ReactNode, useRef, useState} from 'react'
import {ReactNode, useState} from 'react'
import {Input} from '@/components/ui/input'
type ComboboxItem = {
@@ -28,6 +28,7 @@ type ComboboxProps = {
value?: string[]
onChange?: (value: string[]) => void
children?: React.ReactNode
searchPlaceholder?: string
}
export function Combobox(props: ComboboxProps) {
@@ -56,22 +57,51 @@ export function Combobox(props: ComboboxProps) {
const [wait, setWait] = useState(false)
const [filter, setFilter] = useState<string>('')
const [filtered, setFiltered] = useState<ComboboxItem[]>([])
const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set())
const onFilter = async () => {
const toggleExpand = (key: string) => {
setExpandedKeys((prev) => {
const next = new Set(prev)
if (next.has(key)) {
next.delete(key)
}
else {
next.add(key)
}
return next
})
}
const onSearch = async () => {
if (wait) return
const cond = filter.trim()
console.log('onFilter', cond)
setWait(true)
if (cond.length > 0) {
setFiltered(mapFilter(JSON.parse(JSON.stringify(props.options)), cond))
const result = mapFilter(JSON.parse(JSON.stringify(props.options)), cond)
setFiltered(result)
setExpandedKeys(collectAllKeys(result))
}
else {
setFiltered(props.options)
setExpandedKeys(new Set())
}
console.log('onFilter end')
setWait(false)
}
const collectAllKeys = (items: ComboboxItem[]): Set<string> => {
const keys = new Set<string>()
const walk = (list: ComboboxItem[]) => {
list.forEach((item) => {
if (item.children?.length) {
keys.add(item.value)
walk(item.children)
}
})
}
walk(items)
return keys
}
const mapFilter = (items: ComboboxItem[], cond: string): ComboboxItem[] => {
const nItems: ComboboxItem[] = []
items.forEach((item) => {
@@ -97,6 +127,7 @@ export function Combobox(props: ComboboxProps) {
if (status) {
setFiltered(props.options)
setFilter('')
setExpandedKeys(new Set())
}
}}>
<PopoverTrigger asChild>
@@ -117,18 +148,18 @@ export function Combobox(props: ComboboxProps) {
</Button>
</PopoverTrigger>
<PopoverContent
className="p-0 rounded-lg w-[var(--radix-popover-trigger-width)] h-[var(--radix-popover-content-available-height)] flex flex-col overflow-hidden"
className="p-0 rounded-lg w-(--radix-popover-trigger-width) h-(--radix-popover-content-available-height) flex flex-col overflow-hidden"
align="start"
collisionPadding={6}
>
<div className="p-2 flex gap-2 flex-none">
<Input
className="h-9 placeholder:text-weak placeholder:text-sm"
placeholder="搜索地区"
placeholder={props.searchPlaceholder || '搜索地区'}
value={filter}
onChange={event => setFilter(event.target.value)}
/>
<Button className="h-9" onClick={onFilter} disabled={wait}>
<Button className="h-9" onClick={onSearch} disabled={wait}>
</Button>
</div>
@@ -136,11 +167,13 @@ export function Combobox(props: ComboboxProps) {
<OptionList
options={filtered}
value={values}
onChange={(value) => {
console.log(value.map(item => item.value))
props.onChange?.(value.map(item => item.value))
expandedKeys={expandedKeys}
onToggleExpand={toggleExpand}
onChange={(pathValue) => {
props.onChange?.(pathValue)
setOpen(false)
}}/>
}}
/>
</div>
</PopoverContent>
</Popover>
@@ -150,51 +183,76 @@ export function Combobox(props: ComboboxProps) {
function OptionList(props: {
options: ComboboxItem[]
value: string[]
onChange: (value: ComboboxItem[]) => void
path?: ComboboxItem[]
expandedKeys: Set<string>
onToggleExpand: (key: string) => void
onChange: (value: string[]) => void
path?: string[]
depth?: number
}) {
const depth = props.depth || 0
const parent = props.path || []
const indent = depth * 16
const parentPath = props.path || []
return (
<ul style={{
marginLeft: `${indent}px`,
}}>
<ul>
{props.options.map((item, i) => {
const path = [...parent, item]
const pathValue = path.map(item => item.value)
const equal = pathValue.join(`.`) === props.value?.join('.')
const path = [...parentPath, item.value]
const hasChildren = !!item.children?.length
const expanded = props.expandedKeys.has(item.value)
const isCurrentLevel = path.length === props.value.filter(Boolean).length
const isActivePath = path.every((v, idx) => v === props.value[idx])
return (
<li key={i}>
<OptionItem key={`${i}`} item={item} active={equal} onChange={() => props.onChange?.(path)}/>
{item.children?.length
&& <OptionList depth={depth + 1} options={item.children} value={props.value} path={path} onChange={props.onChange}/>
}
<div
className={merge(
`transition-colors duration-100 ease-in-out`,
`pr-4 py-2 rounded-md`,
`flex items-center gap-1`,
`hover:bg-muted hover:text-foreground cursor-pointer`,
isActivePath ? 'text-foreground' : 'text-muted-foreground',
)}
style={{paddingLeft: `${depth * 20 + 16}px`}}
>
{hasChildren ? (
<span
className="flex-none cursor-pointer p-0.5 hover:bg-muted rounded shrink-0"
onClick={(e) => {
e.stopPropagation()
props.onToggleExpand(item.value)
}}
>
{expanded
? <ChevronDown className="h-4 w-4"/>
: <ChevronRight className="h-4 w-4"/>
}
</span>
) : (
<span className="w-5 shrink-0"/>
)}
<span
className="flex-1 min-w-0 truncate"
onClick={() => props.onChange(path)}
>
{item.label}
</span>
{isCurrentLevel && isActivePath && (
<CheckIcon className="h-4 w-4 shrink-0"/>
)}
</div>
{hasChildren && expanded && (
<OptionList
depth={depth + 1}
options={item.children!}
value={props.value}
expandedKeys={props.expandedKeys}
onToggleExpand={props.onToggleExpand}
onChange={props.onChange}
path={path}
/>
)}
</li>
)
})}
</ul>
)
}
function OptionItem(props: {
key: string
item: ComboboxItem
active: boolean
onChange?: () => void
}) {
return (
<div
className={merge(
`transition-colors, duration-100 ease-in-out`,
`px-4 py-2 text-muted-foreground rounded-md`,
`flex justify-between items-center`,
`hover:bg-muted hover:text-foreground`,
)}
onClick={props.onChange}>
{props.item.label}
</div>
)
}

View File

@@ -1,7 +1,7 @@
export const siteConfig = {
name: '蓝狐代理',
shortName: '蓝狐代理',
url: (process.env.API_BASE_URL || 'https://prov.lanhuip.com').replace(/\/$/, ''),
url: (process.env.API_BASE_URL || 'https://lanhuip.com').replace(/\/$/, ''),
description: '蓝狐代理 - 稳定、高速、安全的代理服务提供HTTP代理、SOCKS5代理、动态IP、静态IP、爬虫代理等产品保护您的隐私畅游互联网',
keywords: ['代理ip', '国内代理ip', 'http代理', '动态ip', '静态ip', '爬虫代理', '独享代理', 'socks5代理'],
author: '蓝狐团队',

View File

@@ -104,6 +104,8 @@ export type Channel = {
expired_at: Date
host: string
batch_no: string
filter_prov: string
filter_city: string
}
export type Proxy = {
id: number

View File

@@ -7,5 +7,6 @@ export type ProductSku = {
price_min: string
product_id: number
discount_id: number
discount?: number
status: number
}