13 Commits

Author SHA1 Message Date
63f320fa6d 补足分支条件 2026-08-01 10:46:55 +08:00
Eamon-meng
3e99f2f66f 修复v2提取IP默认方式修改必填类型 2026-07-22 12:32:51 +08:00
397555bf50 更新提取文档 2026-07-22 12:01:59 +08:00
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
26 changed files with 686 additions and 219 deletions

View File

@@ -3,7 +3,7 @@
// For a full list of overridable settings, and general information on folder-specific settings, // For a full list of overridable settings, and general information on folder-specific settings,
// see the documentation: https://zed.dev/docs/configuring-zed#settings-files // see the documentation: https://zed.dev/docs/configuring-zed#settings-files
{ {
"language_servers": ["...", "!biome", "!typescript-language-server"], "language_servers": ["!biome", "!oxfmt", "!oxlint", "!typescript-language-server", "..."],
"formatter": { "formatter": {
"code_action": "source.fixAll.eslint" "code_action": "source.fixAll.eslint"
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "lanhu-web", "name": "lanhu-web",
"version": "1.13.1", "version": "1.14.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

@@ -37,6 +37,19 @@ export async function createChannels(params: {
return callPublic<CreateChannelsResp[]>('/api/channel/create', 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: { export async function createChannelsV3(params: {
resource_no: string resource_no: string
protocol: number protocol: number

View File

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

View File

@@ -22,50 +22,19 @@ export async function GET(req: NextRequest) {
if (!count) { if (!count) {
throw new Error('需要指定通道创建数量') throw new Error('需要指定通道创建数量')
} }
// const prov = params.get('a') || undefined
const area_id = params.get('b') || undefined const area_id = params.get('b') || undefined
const isp = params.get('s') || undefined const isp = params.get('s') || undefined
const hostFormat = params.get('rh') || 'domain' 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) { if (!result.success) {
throw new Error(result.message) throw new Error(result.message)
} }
@@ -78,6 +47,7 @@ export async function GET(req: NextRequest) {
const separator = rSeparator.split(',').map(code => String.fromCharCode(parseInt(code))).join('') const separator = rSeparator.split(',').map(code => String.fromCharCode(parseInt(code))).join('')
switch (format) { switch (format) {
case '2':
case 'json': case 'json':
if (hostFormat === 'domain') { if (hostFormat === 'domain') {
const domainFormatData = result.data.map(item => ({ const domainFormatData = result.data.map(item => ({
@@ -95,7 +65,9 @@ export async function GET(req: NextRequest) {
})) }))
return NextResponse.json(ipFormatData) return NextResponse.json(ipFormatData)
} }
case '1':
case 'text': case 'text':
default:
const text = result.data.map((item) => { const text = result.data.map((item) => {
let hostValue: string let hostValue: string
if (hostFormat === 'domain') { if (hostFormat === 'domain') {

View File

@@ -0,0 +1,98 @@
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 '2':
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 '1':
case 'text':
default:
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,23 +2,19 @@
## 请求方式 ## 请求方式
`GET https://lanhuip.com/api/extract` `GET https://lanhuip.com/proxies`
## 请求参数 ## 请求参数
| 参数名 | 类型 | 必填 | 描述 | | 参数名 | 类型 | 必填 | 描述 |
|--------|----------|------|----------------------------------------------------------------------------------------------------------------------------| |--------|----------|------|----------------------------------------------------------------------------------------------------------------------------|
| i | number | 是 | 用于提取的套餐 ID | | i | string | 是 | 用于提取的套餐 ID |
| n | number | 是 | 提取数量 |
| t | number | 是 | 认证类型1 - 白名单2 - 密码 | | t | number | 是 | 认证类型1 - 白名单2 - 密码 |
| a | string | 否 | 归属地省份。默认全局随机 | | b | string | 否 | 地区 ID具体地区编码见[地区编码表](https://lanhuip.com/docs/area) |
| b | string | 否 | 归属地城市。默认全局随机 | | rt | string | 否 | 返回类型1 - TXT2 - JSON。默认 TXT |
| s | string | 否 | 归属地运营商。默认全局随机 |
| d | string | 否 | 是否去重1 - 是0 - 否。默认为是 |
| rt | string | 否 | 返回类型1 - TXT2 - JSON。默认 TXT
| rh | string | 否 | 返回时主机字段的格式1 - 域名2 - IP。默认为域名 |
| rs | number[] | 否 | 返回时要使用的分隔符,值为该字符的 ascii 编码,可以有多个字符,多个字符用半角逗号连接。默认为 13,10即回车 + 换行(\r\n | | rs | number[] | 否 | 返回时要使用的分隔符,值为该字符的 ascii 编码,可以有多个字符,多个字符用半角逗号连接。默认为 13,10即回车 + 换行(\r\n |
| rb | number[] | 否 | 返回时要使用的换行符,值为该字符的 ascii 编码,可以有多个字符,多个字符用半角逗号连接。默认为 124即垂直线 \| | | rb | number[] | 否 | 返回时要使用的换行符,值为该字符的 ascii 编码,可以有多个字符,多个字符用半角逗号连接。默认为 124即垂直线 \| |
| n | number | 否 | 提取数量。默认为 1 |
## 响应参数 ## 响应参数
@@ -34,12 +30,12 @@
| password | string | 代理服务器密码(仅在认证类型为密码时返回) | | password | string | 代理服务器密码(仅在认证类型为密码时返回) |
## 示例1 ## 接口示例:
### 请求示例 ### 请求示例
```http ```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?i=1&t=2&b=105&rt=2&n=3
``` ```
### 响应示例 ### 响应示例
@@ -47,52 +43,19 @@ GET https://lanhuip.com/api/extract?i=1&t=2&a=广东省&b=广州市&s=移动&d=1
```json ```json
[ [
{ {
"host": "fwd1.lanhuip.com", "host": "43.226.59.241",
"port": 20000, "port": 20000,
"username": "user1", "username": "user1",
"password": "pass1" "password": "pass1"
}, },
{ {
"host": "fwd1.lanhuip.com", "host": "43.226.59.241",
"port": 20001, "port": 20001,
"username": "user2", "username": "user2",
"password": "pass2" "password": "pass2"
}, },
{ {
"host": "fwd1.lanhuip.com", "host": "43.226.59.241",
"port": 20002,
"username": "user3",
"password": "pass3"
}
]
```
## 示例2
### 请求示例
```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
```
### 响应示例
```json
[
{
"ip": "127.0.0.1",
"port": 20000,
"username": "user1",
"password": "pass1"
},
{
"ip": "127.0.0.1",
"port": 20001,
"username": "user2",
"password": "pass2"
},
{
"ip": "127.0.0.1",
"port": 20002, "port": 20002,
"username": "user3", "username": "user3",
"password": "pass3" "password": "pass3"

View File

@@ -0,0 +1,254 @@
# 地区编码表
| 编码 | 地区 | 类型 |
| ---- | -------------------- | ---- |
| 1 | 上海 | 省份 |
| 2 | 云南 | 省份 |
| 3 | 内蒙古 | 省份 |
| 4 | 北京 | 省份 |
| 5 | 吉林 | 省份 |
| 6 | 四川 | 省份 |
| 7 | 天津 | 省份 |
| 8 | 宁夏 | 省份 |
| 9 | 安徽 | 省份 |
| 10 | 山东 | 省份 |
| 11 | 山西 | 省份 |
| 12 | 广东 | 省份 |
| 13 | 广西 | 省份 |
| 14 | 新疆 | 省份 |
| 15 | 江苏 | 省份 |
| 16 | 江西 | 省份 |
| 17 | 河北 | 省份 |
| 18 | 河南 | 省份 |
| 19 | 浙江 | 省份 |
| 20 | 海南 | 省份 |
| 21 | 湖北 | 省份 |
| 22 | 湖南 | 省份 |
| 23 | 甘肃 | 省份 |
| 24 | 福建 | 省份 |
| 25 | 贵州 | 省份 |
| 26 | 辽宁 | 省份 |
| 27 | 重庆 | 省份 |
| 28 | 陕西 | 省份 |
| 29 | 黑龙江 | 省份 |
| 30 | 上海 | 城市 |
| 31 | 昆明 | 城市 |
| 32 | 包头 | 城市 |
| 33 | 呼伦贝尔 | 城市 |
| 34 | 呼和浩特 | 城市 |
| 35 | 赤峰 | 城市 |
| 36 | 通辽 | 城市 |
| 37 | 鄂尔多斯 | 城市 |
| 38 | 北京 | 城市 |
| 39 | 四平 | 城市 |
| 40 | 延边朝鲜族自治州 | 城市 |
| 41 | 松原 | 城市 |
| 42 | 白山 | 城市 |
| 43 | 通化 | 城市 |
| 44 | 长春 | 城市 |
| 45 | 乐山 | 城市 |
| 46 | 内江 | 城市 |
| 47 | 南充 | 城市 |
| 48 | 宜宾 | 城市 |
| 49 | 广元 | 城市 |
| 50 | 德阳 | 城市 |
| 51 | 成都 | 城市 |
| 52 | 攀枝花 | 城市 |
| 53 | 泸州 | 城市 |
| 54 | 绵阳 | 城市 |
| 55 | 自贡 | 城市 |
| 56 | 达州 | 城市 |
| 57 | 天津 | 城市 |
| 58 | 银川 | 城市 |
| 59 | 亳州 | 城市 |
| 60 | 六安 | 城市 |
| 61 | 合肥 | 城市 |
| 62 | 安庆 | 城市 |
| 63 | 宣城 | 城市 |
| 64 | 宿州 | 城市 |
| 65 | 池州 | 城市 |
| 66 | 淮北 | 城市 |
| 67 | 淮南 | 城市 |
| 68 | 滁州 | 城市 |
| 69 | 芜湖 | 城市 |
| 70 | 蚌埠 | 城市 |
| 71 | 铜陵 | 城市 |
| 72 | 阜阳 | 城市 |
| 73 | 马鞍山 | 城市 |
| 74 | 黄山 | 城市 |
| 75 | 东营 | 城市 |
| 76 | 临沂 | 城市 |
| 77 | 威海 | 城市 |
| 78 | 德州 | 城市 |
| 79 | 日照 | 城市 |
| 80 | 枣庄 | 城市 |
| 81 | 泰安 | 城市 |
| 82 | 济南 | 城市 |
| 83 | 济宁 | 城市 |
| 84 | 淄博 | 城市 |
| 85 | 滨州 | 城市 |
| 86 | 潍坊 | 城市 |
| 87 | 烟台 | 城市 |
| 88 | 聊城 | 城市 |
| 89 | 菏泽 | 城市 |
| 90 | 青岛 | 城市 |
| 91 | 临汾 | 城市 |
| 92 | 吕梁 | 城市 |
| 93 | 大同 | 城市 |
| 94 | 太原 | 城市 |
| 95 | 忻州 | 城市 |
| 96 | 晋城 | 城市 |
| 97 | 朔州 | 城市 |
| 98 | 运城 | 城市 |
| 99 | 长治 | 城市 |
| 100 | 阳泉 | 城市 |
| 101 | 东莞 | 城市 |
| 102 | 中山 | 城市 |
| 103 | 云浮 | 城市 |
| 104 | 佛山 | 城市 |
| 105 | 广州 | 城市 |
| 106 | 惠州 | 城市 |
| 107 | 揭阳 | 城市 |
| 108 | 梅州 | 城市 |
| 109 | 汕头 | 城市 |
| 110 | 汕尾 | 城市 |
| 111 | 江门 | 城市 |
| 112 | 河源 | 城市 |
| 113 | 深圳 | 城市 |
| 114 | 清远 | 城市 |
| 115 | 湛江 | 城市 |
| 116 | 潮州 | 城市 |
| 117 | 珠海 | 城市 |
| 118 | 肇庆 | 城市 |
| 119 | 茂名 | 城市 |
| 120 | 阳江 | 城市 |
| 121 | 韶关 | 城市 |
| 122 | 北海 | 城市 |
| 123 | 南宁 | 城市 |
| 124 | 柳州 | 城市 |
| 125 | 桂林 | 城市 |
| 126 | 玉林 | 城市 |
| 127 | 贵港 | 城市 |
| 128 | 钦州 | 城市 |
| 129 | 乌鲁木齐 | 城市 |
| 130 | 南京 | 城市 |
| 131 | 南通 | 城市 |
| 132 | 宿迁 | 城市 |
| 133 | 常州 | 城市 |
| 134 | 徐州 | 城市 |
| 135 | 扬州 | 城市 |
| 136 | 无锡 | 城市 |
| 137 | 泰州 | 城市 |
| 138 | 淮安 | 城市 |
| 139 | 盐城 | 城市 |
| 140 | 苏州 | 城市 |
| 141 | 连云港 | 城市 |
| 142 | 镇江 | 城市 |
| 143 | 上饶 | 城市 |
| 144 | 九江 | 城市 |
| 145 | 南昌 | 城市 |
| 146 | 吉安 | 城市 |
| 147 | 宜春 | 城市 |
| 148 | 抚州 | 城市 |
| 149 | 新余 | 城市 |
| 150 | 景德镇 | 城市 |
| 151 | 萍乡 | 城市 |
| 152 | 赣州 | 城市 |
| 153 | 鹰潭 | 城市 |
| 154 | 保定 | 城市 |
| 155 | 唐山 | 城市 |
| 156 | 廊坊 | 城市 |
| 157 | 张家口 | 城市 |
| 158 | 承德 | 城市 |
| 159 | 沧州 | 城市 |
| 160 | 石家庄 | 城市 |
| 161 | 秦皇岛 | 城市 |
| 162 | 衡水 | 城市 |
| 163 | 邢台 | 城市 |
| 164 | 邯郸 | 城市 |
| 165 | 信阳 | 城市 |
| 166 | 南阳 | 城市 |
| 167 | 周口 | 城市 |
| 168 | 商丘 | 城市 |
| 169 | 安阳 | 城市 |
| 170 | 开封 | 城市 |
| 171 | 新乡 | 城市 |
| 172 | 洛阳 | 城市 |
| 173 | 漯河 | 城市 |
| 174 | 焦作 | 城市 |
| 175 | 许昌 | 城市 |
| 176 | 郑州 | 城市 |
| 177 | 驻马店 | 城市 |
| 178 | 鹤壁 | 城市 |
| 179 | 丽水 | 城市 |
| 180 | 台州 | 城市 |
| 181 | 嘉兴 | 城市 |
| 182 | 宁波 | 城市 |
| 183 | 杭州 | 城市 |
| 184 | 温州 | 城市 |
| 185 | 湖州 | 城市 |
| 186 | 绍兴 | 城市 |
| 187 | 舟山 | 城市 |
| 188 | 衢州 | 城市 |
| 189 | 金华 | 城市 |
| 190 | 三亚 | 城市 |
| 191 | 文昌 | 城市 |
| 192 | 海口 | 城市 |
| 193 | 咸宁 | 城市 |
| 194 | 孝感 | 城市 |
| 195 | 宜昌 | 城市 |
| 196 | 武汉 | 城市 |
| 197 | 荆州 | 城市 |
| 198 | 荆门 | 城市 |
| 199 | 襄阳 | 城市 |
| 200 | 黄冈 | 城市 |
| 201 | 黄石 | 城市 |
| 202 | 岳阳 | 城市 |
| 203 | 株洲 | 城市 |
| 204 | 湘潭 | 城市 |
| 205 | 衡阳 | 城市 |
| 206 | 邵阳 | 城市 |
| 207 | 郴州 | 城市 |
| 208 | 长沙 | 城市 |
| 209 | 兰州 | 城市 |
| 210 | 三明 | 城市 |
| 211 | 南平 | 城市 |
| 212 | 厦门 | 城市 |
| 213 | 宁德 | 城市 |
| 214 | 泉州 | 城市 |
| 215 | 福州 | 城市 |
| 216 | 莆田 | 城市 |
| 217 | 龙岩 | 城市 |
| 218 | 六盘水 | 城市 |
| 219 | 贵阳 | 城市 |
| 220 | 遵义 | 城市 |
| 221 | 铜仁 | 城市 |
| 222 | 黔东南苗族侗族自治州 | 城市 |
| 223 | 大连 | 城市 |
| 224 | 抚顺 | 城市 |
| 225 | 朝阳 | 城市 |
| 226 | 沈阳 | 城市 |
| 227 | 盘锦 | 城市 |
| 228 | 营口 | 城市 |
| 229 | 葫芦岛 | 城市 |
| 230 | 铁岭 | 城市 |
| 231 | 鞍山 | 城市 |
| 232 | 重庆 | 城市 |
| 233 | 咸阳 | 城市 |
| 234 | 宝鸡 | 城市 |
| 235 | 渭南 | 城市 |
| 236 | 西安 | 城市 |
| 237 | 铜川 | 城市 |
| 238 | 七台河 | 城市 |
| 239 | 伊春 | 城市 |
| 240 | 佳木斯 | 城市 |
| 241 | 双鸭山 | 城市 |
| 242 | 哈尔滨 | 城市 |
| 243 | 大庆 | 城市 |
| 244 | 牡丹江 | 城市 |
| 245 | 绥化 | 城市 |
| 246 | 鸡西 | 城市 |
| 247 | 鹤岗 | 城市 |
| 248 | 黑河 | 城市 |
| 249 | 齐齐哈尔 | 城市 |
| 250 | 平顶山 | 城市 |

View File

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

View File

@@ -178,6 +178,21 @@ export default function ChannelsPage(props: ChannelsPageProps) {
header: '代理地址', header: '代理地址',
cell: ({row}) => <Addr channel={row.original}/>, 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: '认证方式', header: '认证方式',
cell: ({row}) => { cell: ({row}) => {

View File

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

View File

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

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

@@ -9,7 +9,7 @@ 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, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku' import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuDiscount, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
export default function Center({skuData}: { export default function Center({skuData}: {
skuData: PurchaseSkuData skuData: PurchaseSkuData
@@ -18,7 +18,7 @@ export default function Center({skuData}: {
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']
const {modeList, priceMap} = skuData const {modeList, priceMap, discountMap} = skuData
const liveList = type === '1' const liveList = type === '1'
? getAvailablePurchaseLives(skuData, {mode: type, expire}) ? getAvailablePurchaseLives(skuData, {mode: type, expire})
: getAvailablePurchaseLives(skuData, {mode: type}) : getAvailablePurchaseLives(skuData, {mode: type})
@@ -134,7 +134,7 @@ export default function Center({skuData}: {
setValue('expire', nextExpireList[0]) 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) => { {liveList.map((live) => {
const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire}) const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire})
? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0' ? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0'
@@ -144,6 +144,11 @@ export default function Center({skuData}: {
live, live,
expire: priceExpire, expire: priceExpire,
}) })
const discount = getPurchaseSkuDiscount(discountMap, {
mode: type,
live,
expire: priceExpire,
})
return ( return (
<FormOption <FormOption
key={live} key={live}
@@ -151,6 +156,8 @@ export default function Center({skuData}: {
value={live} value={live}
label={`${Number(live) / 60} 小时`} label={`${Number(live) / 60} 小时`}
description={price && `${price}/IP`} description={price && `${price}/IP`}
price={price}
discount={discount}
compare={field.value} compare={field.value}
/> />
) )

View File

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

View File

@@ -9,12 +9,37 @@ export type FormOptionProps = {
value: string value: string
label?: string label?: string
description?: string description?: string
price?: string
discount?: number
compare: string compare: string
className?: string className?: string
children?: ReactNode children?: ReactNode
} }
export default function FormOption(props: FormOptionProps) { 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 ( return (
<> <>
<FormLabel <FormLabel
@@ -28,7 +53,24 @@ export default function FormOption(props: FormOptionProps) {
{props.children ? props.children : ( {props.children ? props.children : (
<> <>
<span>{props.label}</span> <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> </FormLabel>

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,7 +9,7 @@ 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, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku' import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuDiscount, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'
export default function Center({ export default function Center({
skuData, skuData,
@@ -20,7 +20,7 @@ export default function Center({
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']
const {modeList, priceMap} = skuData const {modeList, priceMap, discountMap} = skuData
const liveList = type === '1' const liveList = type === '1'
? getAvailablePurchaseLives(skuData, {mode: type, expire}) ? getAvailablePurchaseLives(skuData, {mode: type, expire})
: getAvailablePurchaseLives(skuData, {mode: type}) : getAvailablePurchaseLives(skuData, {mode: type})
@@ -135,7 +135,7 @@ export default function Center({
setValue('expire', nextExpireList[0]) 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) => { {liveList.map((live) => {
const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire}) const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire})
? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0' ? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0'
@@ -145,6 +145,11 @@ export default function Center({
live, live,
expire: priceExpire, expire: priceExpire,
}) })
const discount = getPurchaseSkuDiscount(discountMap, {
mode: type,
live,
expire: priceExpire,
})
const minutes = Number(live) const minutes = Number(live)
const hours = minutes / 60 const hours = minutes / 60
const label = minutes % 60 === 0 ? `${hours} 小时` : `${minutes} 分钟` const label = minutes % 60 === 0 ? `${hours} 小时` : `${minutes} 分钟`
@@ -155,6 +160,8 @@ export default function Center({
value={live} value={live}
label={label} label={label}
description={price && `${price}/IP`} description={price && `${price}/IP`}
price={price}
discount={discount}
compare={field.value} compare={field.value}
/> />
) )

View File

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

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import * as React from 'react' 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 {merge} from '@/lib/utils'
import {Button} from '@/components/ui/button' import {Button} from '@/components/ui/button'
@@ -10,7 +10,7 @@ import {
PopoverContent, PopoverContent,
PopoverTrigger, PopoverTrigger,
} from '@/components/ui/popover' } from '@/components/ui/popover'
import {ReactNode, useRef, useState} from 'react' import {ReactNode, useState} from 'react'
import {Input} from '@/components/ui/input' import {Input} from '@/components/ui/input'
type ComboboxItem = { type ComboboxItem = {
@@ -28,6 +28,7 @@ type ComboboxProps = {
value?: string[] value?: string[]
onChange?: (value: string[]) => void onChange?: (value: string[]) => void
children?: React.ReactNode children?: React.ReactNode
searchPlaceholder?: string
} }
export function Combobox(props: ComboboxProps) { export function Combobox(props: ComboboxProps) {
@@ -56,22 +57,51 @@ export function Combobox(props: ComboboxProps) {
const [wait, setWait] = useState(false) const [wait, setWait] = useState(false)
const [filter, setFilter] = useState<string>('') const [filter, setFilter] = useState<string>('')
const [filtered, setFiltered] = useState<ComboboxItem[]>([]) 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 if (wait) return
const cond = filter.trim() const cond = filter.trim()
console.log('onFilter', cond)
setWait(true) setWait(true)
if (cond.length > 0) { 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 { else {
setFiltered(props.options) setFiltered(props.options)
setExpandedKeys(new Set())
} }
console.log('onFilter end')
setWait(false) 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 mapFilter = (items: ComboboxItem[], cond: string): ComboboxItem[] => {
const nItems: ComboboxItem[] = [] const nItems: ComboboxItem[] = []
items.forEach((item) => { items.forEach((item) => {
@@ -97,6 +127,7 @@ export function Combobox(props: ComboboxProps) {
if (status) { if (status) {
setFiltered(props.options) setFiltered(props.options)
setFilter('') setFilter('')
setExpandedKeys(new Set())
} }
}}> }}>
<PopoverTrigger asChild> <PopoverTrigger asChild>
@@ -117,18 +148,18 @@ export function Combobox(props: ComboboxProps) {
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent <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" align="start"
collisionPadding={6} collisionPadding={6}
> >
<div className="p-2 flex gap-2 flex-none"> <div className="p-2 flex gap-2 flex-none">
<Input <Input
className="h-9 placeholder:text-weak placeholder:text-sm" className="h-9 placeholder:text-weak placeholder:text-sm"
placeholder="搜索地区" placeholder={props.searchPlaceholder || '搜索地区'}
value={filter} value={filter}
onChange={event => setFilter(event.target.value)} onChange={event => setFilter(event.target.value)}
/> />
<Button className="h-9" onClick={onFilter} disabled={wait}> <Button className="h-9" onClick={onSearch} disabled={wait}>
</Button> </Button>
</div> </div>
@@ -136,11 +167,13 @@ export function Combobox(props: ComboboxProps) {
<OptionList <OptionList
options={filtered} options={filtered}
value={values} value={values}
onChange={(value) => { expandedKeys={expandedKeys}
console.log(value.map(item => item.value)) onToggleExpand={toggleExpand}
props.onChange?.(value.map(item => item.value)) onChange={(pathValue) => {
props.onChange?.(pathValue)
setOpen(false) setOpen(false)
}}/> }}
/>
</div> </div>
</PopoverContent> </PopoverContent>
</Popover> </Popover>
@@ -150,51 +183,76 @@ export function Combobox(props: ComboboxProps) {
function OptionList(props: { function OptionList(props: {
options: ComboboxItem[] options: ComboboxItem[]
value: string[] value: string[]
onChange: (value: ComboboxItem[]) => void expandedKeys: Set<string>
path?: ComboboxItem[] onToggleExpand: (key: string) => void
onChange: (value: string[]) => void
path?: string[]
depth?: number depth?: number
}) { }) {
const depth = props.depth || 0 const depth = props.depth || 0
const parent = props.path || [] const parentPath = props.path || []
const indent = depth * 16
return ( return (
<ul style={{ <ul>
marginLeft: `${indent}px`,
}}>
{props.options.map((item, i) => { {props.options.map((item, i) => {
const path = [...parent, item] const path = [...parentPath, item.value]
const pathValue = path.map(item => item.value) const hasChildren = !!item.children?.length
const equal = pathValue.join(`.`) === props.value?.join('.') 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 ( return (
<li key={i}> <li key={i}>
<OptionItem key={`${i}`} item={item} active={equal} onChange={() => props.onChange?.(path)}/> <div
{item.children?.length className={merge(
&& <OptionList depth={depth + 1} options={item.children} value={props.value} path={path} onChange={props.onChange}/> `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> </li>
) )
})} })}
</ul> </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 = { export const siteConfig = {
name: '蓝狐代理', name: '蓝狐代理',
shortName: '蓝狐代理', 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、爬虫代理等产品保护您的隐私畅游互联网', description: '蓝狐代理 - 稳定、高速、安全的代理服务提供HTTP代理、SOCKS5代理、动态IP、静态IP、爬虫代理等产品保护您的隐私畅游互联网',
keywords: ['代理ip', '国内代理ip', 'http代理', '动态ip', '静态ip', '爬虫代理', '独享代理', 'socks5代理'], keywords: ['代理ip', '国内代理ip', 'http代理', '动态ip', '静态ip', '爬虫代理', '独享代理', 'socks5代理'],
author: '蓝狐团队', author: '蓝狐团队',

View File

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

View File

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