优化数据库初始化,新增用户收货地址表以支持多地址管理;更新章节页面和我的页面,整合底部导航组件,提升用户体验;调整小程序设置页面,增加收货地址管理功能,优化样式与布局。

This commit is contained in:
乘风
2026-01-31 22:37:05 +08:00
parent 692397c997
commit c7b125535c
24 changed files with 1159 additions and 141 deletions

View File

@@ -154,6 +154,30 @@ export async function GET(request: NextRequest) {
results.push('✅ 创建system_config表')
}
// 6. 用户收货地址表(多地址,类似淘宝)
try {
await query('SELECT 1 FROM user_addresses LIMIT 1')
results.push('✅ user_addresses表已存在')
} catch (e) {
await query(`
CREATE TABLE IF NOT EXISTS user_addresses (
id VARCHAR(50) PRIMARY KEY,
user_id VARCHAR(50) NOT NULL,
name VARCHAR(50) NOT NULL,
phone VARCHAR(20) NOT NULL,
province VARCHAR(50) NOT NULL,
city VARCHAR(50) NOT NULL,
district VARCHAR(50) NOT NULL,
detail VARCHAR(200) NOT NULL,
is_default TINYINT(1) DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`)
results.push('✅ 创建user_addresses表')
}
console.log('[DB Init] 数据库升级完成')
return NextResponse.json({

View File

@@ -0,0 +1,112 @@
/**
* 用户收货地址 - 单条详情 / 编辑 / 删除 / 设为默认
* GET: 详情
* PUT: 更新name, phone, detail 等;省/市/区可选)
* DELETE: 删除
*/
import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'
async function getOne(id: string) {
const rows = await query(
`SELECT id, user_id, name, phone, province, city, district, detail, is_default, created_at, updated_at
FROM user_addresses WHERE id = ?`,
[id]
) as any[]
if (!rows || rows.length === 0) return null
const r = rows[0]
return {
id: r.id,
userId: r.user_id,
name: r.name,
phone: r.phone,
province: r.province,
city: r.city,
district: r.district,
detail: r.detail,
isDefault: !!r.is_default,
fullAddress: `${r.province}${r.city}${r.district}${r.detail}`,
createdAt: r.created_at,
updatedAt: r.updated_at,
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params
if (!id) {
return NextResponse.json({ success: false, message: '缺少地址 id' }, { status: 400 })
}
const item = await getOne(id)
if (!item) {
return NextResponse.json({ success: false, message: '地址不存在' }, { status: 404 })
}
return NextResponse.json({ success: true, item })
} catch (e) {
console.error('[Addresses] GET one error:', e)
return NextResponse.json({ success: false, message: '获取地址失败' }, { status: 500 })
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params
if (!id) {
return NextResponse.json({ success: false, message: '缺少地址 id' }, { status: 400 })
}
const body = await request.json()
const { name, phone, province, city, district, detail, isDefault } = body
const existing = await query('SELECT user_id FROM user_addresses WHERE id = ?', [id]) as any[]
if (!existing || existing.length === 0) {
return NextResponse.json({ success: false, message: '地址不存在' }, { status: 404 })
}
const userId = existing[0].user_id
const updates = []
const values = []
if (name !== undefined) { updates.push('name = ?'); values.push(name.trim()) }
if (phone !== undefined) { updates.push('phone = ?'); values.push(phone.trim()) }
if (province !== undefined) { updates.push('province = ?'); values.push((province == null ? '' : String(province)).trim()) }
if (city !== undefined) { updates.push('city = ?'); values.push((city == null ? '' : String(city)).trim()) }
if (district !== undefined) { updates.push('district = ?'); values.push((district == null ? '' : String(district)).trim()) }
if (detail !== undefined) { updates.push('detail = ?'); values.push(detail.trim()) }
if (isDefault === true) {
await query('UPDATE user_addresses SET is_default = 0 WHERE user_id = ?', [userId])
updates.push('is_default = 1')
} else if (isDefault === false) {
updates.push('is_default = 0')
}
if (updates.length > 0) {
values.push(id)
await query(`UPDATE user_addresses SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`, values)
}
const item = await getOne(id)
return NextResponse.json({ success: true, item, message: '更新成功' })
} catch (e) {
console.error('[Addresses] PUT error:', e)
return NextResponse.json({ success: false, message: '更新地址失败' }, { status: 500 })
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params
if (!id) {
return NextResponse.json({ success: false, message: '缺少地址 id' }, { status: 400 })
}
await query('DELETE FROM user_addresses WHERE id = ?', [id])
return NextResponse.json({ success: true, message: '删除成功' })
} catch (e) {
console.error('[Addresses] DELETE error:', e)
return NextResponse.json({ success: false, message: '删除地址失败' }, { status: 500 })
}
}

View File

@@ -0,0 +1,68 @@
/**
* 用户收货地址 - 列表与新建
* GET: 列表(需 userId
* POST: 新建(必填 userId, name, phone, detail省/市/区可选)
*/
import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'
import { randomUUID } from 'crypto'
export async function GET(request: NextRequest) {
try {
const userId = request.nextUrl.searchParams.get('userId')
if (!userId) {
return NextResponse.json({ success: false, message: '缺少 userId' }, { status: 400 })
}
const rows = await query(
`SELECT id, user_id, name, phone, province, city, district, detail, is_default, created_at, updated_at
FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC, updated_at DESC`,
[userId]
) as any[]
const list = (rows || []).map((r) => ({
id: r.id,
userId: r.user_id,
name: r.name,
phone: r.phone,
province: r.province,
city: r.city,
district: r.district,
detail: r.detail,
isDefault: !!r.is_default,
fullAddress: `${r.province}${r.city}${r.district}${r.detail}`,
createdAt: r.created_at,
updatedAt: r.updated_at,
}))
return NextResponse.json({ success: true, list })
} catch (e) {
console.error('[Addresses] GET error:', e)
return NextResponse.json({ success: false, message: '获取地址列表失败' }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { userId, name, phone, province, city, district, detail, isDefault } = body
if (!userId || !name || !phone || !detail) {
return NextResponse.json(
{ success: false, message: '缺少必填项userId, name, phone, detail' },
{ status: 400 }
)
}
const id = randomUUID().replace(/-/g, '').slice(0, 24)
const p = (v: string | undefined) => (v == null ? '' : String(v).trim())
if (isDefault) {
await query('UPDATE user_addresses SET is_default = 0 WHERE user_id = ?', [userId])
}
await query(
`INSERT INTO user_addresses (id, user_id, name, phone, province, city, district, detail, is_default)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[id, userId, name.trim(), phone.trim(), p(province), p(city), p(district), detail.trim(), isDefault ? 1 : 0]
)
return NextResponse.json({ success: true, id, message: '添加成功' })
} catch (e) {
console.error('[Addresses] POST error:', e)
return NextResponse.json({ success: false, message: '添加地址失败' }, { status: 500 })
}
}

View File

@@ -2,10 +2,11 @@
import { useState } from "react"
import { useRouter } from "next/navigation"
import { ChevronRight, Lock, Unlock, Book, BookOpen, Home, List, Sparkles, User, Users, Zap, Crown, Search } from "lucide-react"
import { ChevronRight, Lock, Unlock, Book, BookOpen, Sparkles, Zap, Crown, Search } from "lucide-react"
import { useStore } from "@/lib/store"
import { bookData, getTotalSectionCount, specialSections, getPremiumBookPrice, getExtraSectionsCount, BASE_SECTIONS_COUNT } from "@/lib/book-data"
import { SearchModal } from "@/components/search-modal"
import { BottomNav } from "@/components/bottom-nav"
export default function ChaptersPage() {
const router = useRouter()
@@ -209,31 +210,7 @@ export default function ChaptersPage() {
</div>
</main>
<nav className="fixed bottom-0 left-0 right-0 bg-[#1c1c1e]/95 backdrop-blur-xl border-t border-white/5 pb-safe-bottom">
<div className="px-4 py-2">
<div className="flex items-center justify-around">
<button onClick={() => router.push("/")} className="flex flex-col items-center py-2 px-4">
<Home className="w-5 h-5 text-gray-500 mb-1" />
<span className="text-gray-500 text-xs"></span>
</button>
<button className="flex flex-col items-center py-2 px-4">
<List className="w-5 h-5 text-[#00CED1] mb-1" />
<span className="text-[#00CED1] text-xs font-medium"></span>
</button>
{/* 找伙伴按钮 */}
<button onClick={() => router.push("/match")} className="flex flex-col items-center py-2 px-6 -mt-4">
<div className="w-14 h-14 rounded-full bg-gradient-to-br from-[#00CED1] to-[#20B2AA] flex items-center justify-center shadow-lg shadow-[#00CED1]/30">
<Users className="w-7 h-7 text-white" />
</div>
<span className="text-gray-500 text-xs mt-1"></span>
</button>
<button onClick={() => router.push("/my")} className="flex flex-col items-center py-2 px-4">
<User className="w-5 h-5 text-gray-500 mb-1" />
<span className="text-gray-500 text-xs"></span>
</button>
</div>
</div>
</nav>
<BottomNav />
</div>
)
}

View File

@@ -0,0 +1,196 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter, useParams } from "next/navigation"
import { ChevronLeft } from "lucide-react"
import { useStore } from "@/lib/store"
export default function EditAddressPage() {
const router = useRouter()
const params = useParams()
const id = params.id as string
const { user } = useStore()
const [loading, setLoading] = useState(false)
const [fetching, setFetching] = useState(true)
const [name, setName] = useState("")
const [phone, setPhone] = useState("")
const [province, setProvince] = useState("")
const [city, setCity] = useState("")
const [district, setDistrict] = useState("")
const [detail, setDetail] = useState("")
const [isDefault, setIsDefault] = useState(false)
useEffect(() => {
if (!id) {
setFetching(false)
return
}
fetch(`/api/user/addresses/${id}`)
.then((res) => res.json())
.then((data) => {
if (data.success && data.item) {
const item = data.item
setName(item.name)
setPhone(item.phone)
setProvince(item.province)
setCity(item.city)
setDistrict(item.district)
setDetail(item.detail)
setIsDefault(item.isDefault)
}
setFetching(false)
})
.catch(() => setFetching(false))
}, [id])
if (!user?.id) {
return (
<div className="min-h-screen bg-black text-white flex items-center justify-center">
<p className="text-white/60"></p>
</div>
)
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!name.trim()) {
alert("请输入收货人姓名")
return
}
if (!/^1[3-9]\d{9}$/.test(phone)) {
alert("请输入正确的手机号")
return
}
// 省/市/区为选填
if (!detail.trim()) {
alert("请输入详细地址")
return
}
setLoading(true)
try {
const res = await fetch(`/api/user/addresses/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: name.trim(),
phone: phone.trim(),
province: (province ?? "").trim(),
city: (city ?? "").trim(),
district: (district ?? "").trim(),
detail: detail.trim(),
isDefault,
}),
})
const data = await res.json()
if (data.success) {
router.push("/my/addresses")
} else {
alert(data.message || "保存失败")
}
} catch {
alert("保存失败")
} finally {
setLoading(false)
}
}
if (fetching) {
return (
<div className="min-h-screen bg-black text-white flex items-center justify-center">
<div className="text-white/40 text-sm">...</div>
</div>
)
}
return (
<div className="min-h-screen bg-black text-white pb-24">
<header className="sticky top-0 z-40 bg-black/90 backdrop-blur-xl border-b border-white/5">
<div className="px-4 py-3 flex items-center">
<button onClick={() => router.back()} className="w-8 h-8 rounded-full bg-white/10 flex items-center justify-center">
<ChevronLeft className="w-5 h-5 text-white" />
</button>
<h1 className="flex-1 text-center text-lg font-semibold text-white"></h1>
<div className="w-8" />
</div>
</header>
<form onSubmit={handleSubmit} className="px-4 py-4 space-y-4">
<div className="rounded-2xl bg-[#1c1c1e] border border-white/5 overflow-hidden">
<div className="flex items-center justify-between p-4 border-b border-white/5">
<label className="text-white text-sm w-24"></label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="请输入收货人姓名"
className="flex-1 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
</div>
<div className="flex items-center justify-between p-4 border-b border-white/5">
<label className="text-white text-sm w-24"></label>
<input
type="tel"
maxLength={11}
value={phone}
onChange={(e) => setPhone(e.target.value.replace(/\D/g, ""))}
placeholder="请输入手机号"
className="flex-1 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
</div>
<div className="flex items-center justify-between p-4 border-b border-white/5">
<label className="text-white text-sm w-24"></label>
<div className="flex-1 flex gap-2 justify-end">
<input
type="text"
value={province}
onChange={(e) => setProvince(e.target.value)}
placeholder="省"
className="flex-1 max-w-24 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="市"
className="flex-1 max-w-24 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
<input
type="text"
value={district}
onChange={(e) => setDistrict(e.target.value)}
placeholder="区"
className="flex-1 max-w-24 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
</div>
</div>
<div className="flex items-start justify-between p-4">
<label className="text-white text-sm w-24 pt-2"></label>
<textarea
value={detail}
onChange={(e) => setDetail(e.target.value)}
placeholder="街道、楼栋、门牌号等"
rows={3}
className="flex-1 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none resize-none"
/>
</div>
<div className="flex items-center justify-between p-4 border-t border-white/5">
<span className="text-white text-sm"></span>
<input
type="checkbox"
checked={isDefault}
onChange={(e) => setIsDefault(e.target.checked)}
className="w-5 h-5 rounded accent-[#00CED1]"
/>
</div>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-3 rounded-xl bg-[#00CED1] text-black font-medium disabled:opacity-50"
>
{loading ? "保存中..." : "保存"}
</button>
</form>
</div>
)
}

View File

@@ -0,0 +1,163 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft } from "lucide-react"
import { useStore } from "@/lib/store"
export default function NewAddressPage() {
const router = useRouter()
const { user } = useStore()
const [loading, setLoading] = useState(false)
const [name, setName] = useState("")
const [phone, setPhone] = useState("")
const [province, setProvince] = useState("")
const [city, setCity] = useState("")
const [district, setDistrict] = useState("")
const [detail, setDetail] = useState("")
const [isDefault, setIsDefault] = useState(false)
if (!user?.id) {
return (
<div className="min-h-screen bg-black text-white flex items-center justify-center">
<p className="text-white/60"></p>
</div>
)
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!name.trim()) {
alert("请输入收货人姓名")
return
}
if (!/^1[3-9]\d{9}$/.test(phone)) {
alert("请输入正确的手机号")
return
}
// 省/市/区为选填
if (!detail.trim()) {
alert("请输入详细地址")
return
}
setLoading(true)
try {
const res = await fetch("/api/user/addresses", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: user.id,
name: name.trim(),
phone: phone.trim(),
province: (province ?? "").trim(),
city: (city ?? "").trim(),
district: (district ?? "").trim(),
detail: detail.trim(),
isDefault,
}),
})
const data = await res.json()
if (data.success) {
router.push("/my/addresses")
} else {
alert(data.message || "添加失败")
}
} catch {
alert("添加失败")
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen bg-black text-white pb-24">
<header className="sticky top-0 z-40 bg-black/90 backdrop-blur-xl border-b border-white/5">
<div className="px-4 py-3 flex items-center">
<button onClick={() => router.back()} className="w-8 h-8 rounded-full bg-white/10 flex items-center justify-center">
<ChevronLeft className="w-5 h-5 text-white" />
</button>
<h1 className="flex-1 text-center text-lg font-semibold text-white"></h1>
<div className="w-8" />
</div>
</header>
<form onSubmit={handleSubmit} className="px-4 py-4 space-y-4">
<div className="rounded-2xl bg-[#1c1c1e] border border-white/5 overflow-hidden">
<div className="flex items-center justify-between p-4 border-b border-white/5">
<label className="text-white text-sm w-24"></label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="请输入收货人姓名"
className="flex-1 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
</div>
<div className="flex items-center justify-between p-4 border-b border-white/5">
<label className="text-white text-sm w-24"></label>
<input
type="tel"
maxLength={11}
value={phone}
onChange={(e) => setPhone(e.target.value.replace(/\D/g, ""))}
placeholder="请输入手机号"
className="flex-1 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
</div>
<div className="flex items-center justify-between p-4 border-b border-white/5">
<label className="text-white text-sm w-24"></label>
<div className="flex-1 flex gap-2 justify-end">
<input
type="text"
value={province}
onChange={(e) => setProvince(e.target.value)}
placeholder="省"
className="flex-1 max-w-24 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="市"
className="flex-1 max-w-24 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
<input
type="text"
value={district}
onChange={(e) => setDistrict(e.target.value)}
placeholder="区"
className="flex-1 max-w-24 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none"
/>
</div>
</div>
<div className="flex items-start justify-between p-4">
<label className="text-white text-sm w-24 pt-2"></label>
<textarea
value={detail}
onChange={(e) => setDetail(e.target.value)}
placeholder="街道、楼栋、门牌号等"
rows={3}
className="flex-1 bg-transparent text-white text-sm text-right placeholder-white/30 outline-none resize-none"
/>
</div>
<div className="flex items-center justify-between p-4 border-t border-white/5">
<span className="text-white text-sm"></span>
<input
type="checkbox"
checked={isDefault}
onChange={(e) => setIsDefault(e.target.checked)}
className="w-5 h-5 rounded accent-[#00CED1]"
/>
</div>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-3 rounded-xl bg-[#00CED1] text-black font-medium disabled:opacity-50"
>
{loading ? "保存中..." : "保存"}
</button>
</form>
</div>
)
}

141
app/my/addresses/page.tsx Normal file
View File

@@ -0,0 +1,141 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft, MapPin, Plus, Pencil, Trash2 } from "lucide-react"
import { useStore } from "@/lib/store"
type AddressItem = {
id: string
name: string
phone: string
province: string
city: string
district: string
detail: string
fullAddress: string
isDefault: boolean
}
export default function AddressesPage() {
const router = useRouter()
const { user } = useStore()
const [list, setList] = useState<AddressItem[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!user?.id) {
setList([])
setLoading(false)
return
}
fetch(`/api/user/addresses?userId=${user.id}`)
.then((res) => res.json())
.then((data) => {
if (data.success && data.list) setList(data.list)
setLoading(false)
})
.catch(() => setLoading(false))
}, [user?.id])
const handleDelete = async (id: string) => {
if (!confirm("确定要删除该收货地址吗?")) return
try {
const res = await fetch(`/api/user/addresses/${id}`, { method: "DELETE" })
const data = await res.json()
if (data.success) {
setList((prev) => prev.filter((a) => a.id !== id))
} else {
alert(data.message || "删除失败")
}
} catch {
alert("删除失败")
}
}
if (!user) {
return (
<div className="min-h-screen bg-black text-white flex items-center justify-center">
<div className="text-center">
<p className="text-white/60 mb-4"></p>
<button
onClick={() => router.push("/my")}
className="px-4 py-2 rounded-xl bg-[#00CED1] text-black font-medium"
>
</button>
</div>
</div>
)
}
return (
<div className="min-h-screen bg-black text-white pb-24">
<header className="sticky top-0 z-40 bg-black/90 backdrop-blur-xl border-b border-white/5">
<div className="px-4 py-3 flex items-center">
<button
onClick={() => router.back()}
className="w-8 h-8 rounded-full bg-white/10 flex items-center justify-center"
>
<ChevronLeft className="w-5 h-5 text-white" />
</button>
<h1 className="flex-1 text-center text-lg font-semibold text-white"></h1>
<div className="w-8" />
</div>
</header>
<main className="px-4 py-4">
{loading ? (
<div className="py-12 text-center text-white/40 text-sm">...</div>
) : list.length === 0 ? (
<div className="py-12 text-center">
<MapPin className="w-12 h-12 text-white/30 mx-auto mb-3" />
<p className="text-white/60 text-sm"></p>
<p className="text-white/40 text-xs mt-1"></p>
</div>
) : (
<div className="space-y-3">
{list.map((item) => (
<div
key={item.id}
className="rounded-xl bg-[#1c1c1e] border border-white/5 p-4"
>
<div className="flex items-center justify-between mb-2">
<span className="text-white font-medium">{item.name}</span>
<span className="text-white/50 text-sm">{item.phone}</span>
{item.isDefault && (
<span className="text-xs px-2 py-0.5 rounded bg-[#00CED1]/20 text-[#00CED1]">
</span>
)}
</div>
<p className="text-white/60 text-sm leading-relaxed">{item.fullAddress}</p>
<div className="flex justify-end gap-4 mt-3 pt-3 border-t border-white/5">
<button
onClick={() => router.push(`/my/addresses/${item.id}`)}
className="flex items-center gap-1 text-[#00CED1] text-sm"
>
<Pencil className="w-4 h-4" />
</button>
<button
onClick={() => handleDelete(item.id)}
className="flex items-center gap-1 text-red-400 text-sm"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
))}
</div>
)}
<button
onClick={() => router.push("/my/addresses/new")}
className="mt-6 w-full py-3 rounded-xl bg-[#00CED1] text-black font-medium flex items-center justify-center gap-2"
>
<Plus className="w-5 h-5" />
</button>
</main>
</div>
)
}

View File

@@ -2,9 +2,10 @@
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { User, ChevronRight, Home, List, Gift, Star, Info, Users, Wallet, Footprints, Eye, BookOpen, Clock, ArrowUpRight, Phone, MessageCircle, CreditCard, X, Check, Loader2, Settings } from "lucide-react"
import { User, Users, ChevronRight, Gift, Star, Info, Wallet, Footprints, Eye, BookOpen, Clock, ArrowUpRight, Phone, MessageCircle, CreditCard, X, Check, Loader2, Settings } from "lucide-react"
import { useStore } from "@/lib/store"
import { AuthModal } from "@/components/modules/auth/auth-modal"
import { BottomNav } from "@/components/bottom-nav"
import { getFullBookPrice, getTotalSectionCount } from "@/lib/book-data"
export default function MyPage() {
@@ -92,35 +93,6 @@ export default function MyPage() {
setShowBindModal(true)
}
// 底部导航组件
const BottomNavBar = () => (
<nav className="fixed bottom-0 left-0 right-0 bg-[#1c1c1e]/95 backdrop-blur-xl border-t border-white/5 pb-safe-bottom">
<div className="px-4 py-2">
<div className="flex items-center justify-around">
<button onClick={() => router.push("/")} className="flex flex-col items-center py-2 px-4">
<Home className="w-5 h-5 text-gray-500 mb-1" />
<span className="text-gray-500 text-xs"></span>
</button>
<button onClick={() => router.push("/chapters")} className="flex flex-col items-center py-2 px-4">
<List className="w-5 h-5 text-gray-500 mb-1" />
<span className="text-gray-500 text-xs"></span>
</button>
{/* 找伙伴按钮 */}
<button onClick={() => router.push("/match")} className="flex flex-col items-center py-2 px-6 -mt-4">
<div className="w-14 h-14 rounded-full bg-gradient-to-br from-[#00CED1] to-[#20B2AA] flex items-center justify-center shadow-lg shadow-[#00CED1]/30">
<Users className="w-7 h-7 text-white" />
</div>
<span className="text-gray-500 text-xs mt-1"></span>
</button>
<button className="flex flex-col items-center py-2 px-4">
<User className="w-5 h-5 text-[#00CED1] mb-1" />
<span className="text-[#00CED1] text-xs font-medium"></span>
</button>
</div>
</div>
</nav>
)
// 未登录状态
if (!isLoggedIn) {
return (
@@ -206,7 +178,7 @@ export default function MyPage() {
</button>
</div>
<BottomNavBar />
<BottomNav />
<AuthModal isOpen={showAuthModal} onClose={() => setShowAuthModal(false)} />
</main>
)
@@ -484,8 +456,8 @@ export default function MyPage() {
</>
)}
<BottomNavBar />
<BottomNav />
{/* 绑定弹窗 */}
{showBindModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">

View File

@@ -2,7 +2,7 @@
import { useState } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft, Phone, MessageCircle, CreditCard, Check, X, Loader2, Shield } from "lucide-react"
import { ChevronLeft, Phone, MessageCircle, CreditCard, Check, X, Loader2, Shield, MapPin } from "lucide-react"
import { useStore } from "@/lib/store"
export default function SettingsPage() {
@@ -152,7 +152,7 @@ export default function SettingsPage() {
{/* 支付宝 */}
<button
onClick={() => openBindModal("alipay")}
className="w-full flex items-center justify-between p-4 active:bg-white/5"
className="w-full flex items-center justify-between p-4 border-b border-white/5 active:bg-white/5"
>
<div className="flex items-center gap-3">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
@@ -173,6 +173,23 @@ export default function SettingsPage() {
<span className="text-[#1677FF] text-xs"></span>
)}
</button>
{/* 收货地址 */}
<button
onClick={() => router.push("/my/addresses")}
className="w-full flex items-center justify-between p-4 active:bg-white/5"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full flex items-center justify-center bg-orange-500/20">
<MapPin className="w-4 h-4 text-orange-400" />
</div>
<div className="text-left">
<p className="text-white text-sm"></p>
<p className="text-white/40 text-xs"></p>
</div>
</div>
<span className="text-[#00CED1] text-xs"></span>
</button>
</div>
{/* 绑定提示 */}

View File

@@ -9,6 +9,8 @@
"pages/referral/referral",
"pages/purchases/purchases",
"pages/settings/settings",
"pages/address-list/address-list",
"pages/address-edit/address-edit",
"pages/search/search"
],
"window": {
@@ -52,8 +54,7 @@
}
},
"requiredPrivateInfos": [
"getLocation",
"chooseAddress"
"getLocation"
],
"lazyCodeLoading": "requiredComponents",
"style": "v2",

View File

@@ -0,0 +1,136 @@
/**
* Soul创业派对 - 收货地址新建/编辑
*/
const app = getApp()
Page({
data: {
statusBarHeight: 44,
id: '',
isEdit: false,
name: '',
phone: '',
region: ['广东省', '广州市', '天河区'],
province: '广东省',
city: '广州市',
district: '天河区',
detail: '',
isDefault: false,
loading: false
},
onLoad(options) {
this.setData({ statusBarHeight: app.globalData.statusBarHeight })
if (options.id) {
this.setData({ id: options.id, isEdit: true })
this.loadItem(options.id)
}
},
async loadItem(id) {
wx.showLoading({ title: '加载中...' })
try {
const res = await app.request('/api/user/addresses/' + id)
wx.hideLoading()
if (res.success && res.item) {
const item = res.item
this.setData({
name: item.name,
phone: item.phone,
province: item.province || '',
city: item.city || '',
district: item.district || '',
region: [item.province || '', item.city || '', item.district || ''],
detail: item.detail,
isDefault: item.isDefault
})
}
} catch (e) {
wx.hideLoading()
wx.showToast({ title: '加载失败', icon: 'none' })
}
},
onNameInput(e) {
this.setData({ name: e.detail.value.trim() })
},
onPhoneInput(e) {
this.setData({ phone: e.detail.value.replace(/\D/g, '').slice(0, 11) })
},
onRegionChange(e) {
const region = e.detail.value
this.setData({
region,
province: region[0] || '',
city: region[1] || '',
district: region[2] || ''
})
},
onDetailInput(e) {
this.setData({ detail: e.detail.value.trim() })
},
onDefaultChange(e) {
this.setData({ isDefault: e.detail.value })
},
async save() {
const { id, isEdit, name, phone, province, city, district, detail, isDefault } = this.data
if (!name) {
wx.showToast({ title: '请输入收货人姓名', icon: 'none' })
return
}
if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
wx.showToast({ title: '请输入正确的手机号', icon: 'none' })
return
}
// 省/市/区为选填,不校验
if (!detail) {
wx.showToast({ title: '请输入详细地址', icon: 'none' })
return
}
const userId = app.globalData.userInfo?.id
if (!userId) {
wx.showToast({ title: '请先登录', icon: 'none' })
return
}
this.setData({ loading: true })
try {
if (isEdit && id) {
const res = await app.request('/api/user/addresses/' + id, {
method: 'PUT',
data: { name, phone, province, city, district, detail, isDefault }
})
if (res.success) {
wx.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => wx.navigateBack(), 1500)
} else {
wx.showToast({ title: res.message || '保存失败', icon: 'none' })
this.setData({ loading: false })
}
} else {
const res = await app.request('/api/user/addresses', {
method: 'POST',
data: { userId, name, phone, province, city, district, detail, isDefault }
})
if (res.success) {
wx.showToast({ title: '添加成功', icon: 'success' })
setTimeout(() => wx.navigateBack(), 1500)
} else {
wx.showToast({ title: res.message || '添加失败', icon: 'none' })
this.setData({ loading: false })
}
}
} catch (e) {
this.setData({ loading: false })
wx.showToast({ title: '保存失败', icon: 'none' })
}
},
goBack() {
wx.navigateBack()
}
})

View File

@@ -0,0 +1,4 @@
{
"navigationBarTitleText": "编辑地址",
"usingComponents": {}
}

View File

@@ -0,0 +1,40 @@
<!-- 收货地址 新建/编辑 -->
<view class="page">
<view class="nav-bar" style="padding-top: {{statusBarHeight}}px;">
<view class="nav-back" bindtap="goBack">
<text class="back-icon"></text>
</view>
<text class="nav-title">{{isEdit ? '编辑地址' : '新增地址'}}</text>
<view class="nav-placeholder"></view>
</view>
<view style="height: {{statusBarHeight + 44}}px;"></view>
<view class="form">
<view class="form-item">
<text class="label">收货人</text>
<input class="input" placeholder="请输入收货人姓名" value="{{name}}" bindinput="onNameInput" />
</view>
<view class="form-item">
<text class="label">手机号码</text>
<input class="input" type="number" maxlength="11" placeholder="请输入手机号" value="{{phone}}" bindinput="onPhoneInput" />
</view>
<view class="form-item">
<text class="label">所在地区(选填)</text>
<picker mode="region" value="{{region}}" bindchange="onRegionChange">
<view class="picker-value">
{{region[0] && region[1] && region[2] ? region[0] + ' ' + region[1] + ' ' + region[2] : '选填,可不选'}}
</view>
</picker>
</view>
<view class="form-item detail">
<text class="label">详细地址</text>
<textarea class="textarea" placeholder="街道、楼栋、门牌号等" value="{{detail}}" bindinput="onDetailInput" maxlength="200" />
</view>
<view class="form-item switch-row">
<text class="label">设为默认地址</text>
<switch checked="{{isDefault}}" bindchange="onDefaultChange" color="#00CED1" />
</view>
</view>
<view class="btn-save {{loading ? 'disabled' : ''}}" bindtap="save">保存</view>
</view>

View File

@@ -0,0 +1,21 @@
.page { min-height: 100vh; background: #000; padding-bottom: 120rpx; }
.nav-bar { position: fixed; top: 0; left: 0; right: 0; z-index: 100; background: rgba(0,0,0,0.9); backdrop-filter: blur(40rpx); display: flex; align-items: center; justify-content: space-between; padding: 0 32rpx; height: 88rpx; }
.nav-back { width: 64rpx; height: 64rpx; display: flex; align-items: center; justify-content: center; }
.back-icon { font-size: 40rpx; color: rgba(255,255,255,0.6); }
.nav-title { font-size: 34rpx; font-weight: 600; color: #fff; }
.nav-placeholder { width: 64rpx; }
.form { margin: 24rpx; background: #1c1c1e; border-radius: 24rpx; overflow: hidden; border: 2rpx solid rgba(0,206,209,0.2); }
.form-item { display: flex; align-items: center; padding: 28rpx 24rpx; border-bottom: 2rpx solid rgba(255,255,255,0.06); }
.form-item:last-child { border-bottom: none; }
.form-item.detail { align-items: flex-start; }
.form-item .label { width: 160rpx; font-size: 28rpx; color: rgba(255,255,255,0.8); flex-shrink: 0; }
.form-item .input { flex: 1; font-size: 28rpx; color: #fff; }
.form-item .picker-value { flex: 1; font-size: 28rpx; color: #fff; }
.form-item .picker-value:empty:before { content: '请选择省市区'; color: rgba(255,255,255,0.4); }
.form-item .textarea { flex: 1; font-size: 28rpx; color: #fff; min-height: 120rpx; }
.form-item.switch-row { justify-content: space-between; }
.form-item switch { transform: scale(0.9); }
.btn-save { margin: 48rpx 24rpx 0; height: 88rpx; line-height: 88rpx; text-align: center; background: #00CED1; color: #000; font-size: 30rpx; font-weight: 600; border-radius: 44rpx; }
.btn-save.disabled { opacity: 0.6; }

View File

@@ -0,0 +1,83 @@
/**
* Soul创业派对 - 收货地址列表(增删改查)
*/
const app = getApp()
Page({
data: {
statusBarHeight: 44,
list: [],
loading: true
},
onLoad() {
this.setData({ statusBarHeight: app.globalData.statusBarHeight })
this.loadList()
},
onShow() {
this.loadList()
},
async loadList() {
const userId = app.globalData.userInfo?.id
if (!userId) {
this.setData({ list: [], loading: false })
return
}
this.setData({ loading: true })
try {
const res = await app.request('/api/user/addresses', { data: { userId } })
if (res.success && res.list) {
this.setData({ list: res.list, loading: false })
} else {
this.setData({ list: [], loading: false })
}
} catch (e) {
this.setData({ list: [], loading: false })
}
},
goAdd() {
wx.navigateTo({ url: '/pages/address-edit/address-edit' })
},
goEdit(e) {
const id = e.currentTarget.dataset.id
wx.navigateTo({ url: '/pages/address-edit/address-edit?id=' + id })
},
async deleteAddress(e) {
const id = e.currentTarget.dataset.id
const that = this
wx.showModal({
title: '删除地址',
content: '确定要删除该收货地址吗?',
success(res) {
if (!res.confirm) return
that.doDelete(id)
}
})
},
async doDelete(id) {
wx.showLoading({ title: '删除中...' })
try {
const res = await app.request('/api/user/addresses/' + id, { method: 'DELETE' })
wx.hideLoading()
if (res.success) {
wx.showToast({ title: '已删除', icon: 'success' })
this.loadList()
} else {
wx.showToast({ title: res.message || '删除失败', icon: 'none' })
}
} catch (e) {
wx.hideLoading()
wx.showToast({ title: '删除失败', icon: 'none' })
}
},
goBack() {
wx.navigateBack()
}
})

View File

@@ -0,0 +1,4 @@
{
"navigationBarTitleText": "收货地址",
"usingComponents": {}
}

View File

@@ -0,0 +1,46 @@
<!-- 收货地址列表 - 类似淘宝 -->
<view class="page">
<view class="nav-bar" style="padding-top: {{statusBarHeight}}px;">
<view class="nav-back" bindtap="goBack">
<text class="back-icon"></text>
</view>
<text class="nav-title">收货地址</text>
<view class="nav-placeholder"></view>
</view>
<view style="height: {{statusBarHeight + 44}}px;"></view>
<view class="content">
<view wx:if="{{loading}}" class="loading-wrap">
<text class="loading-text">加载中...</text>
</view>
<view wx:elif="{{list.length === 0}}" class="empty-wrap">
<text class="empty-icon">📍</text>
<text class="empty-text">暂无收货地址</text>
<text class="empty-tip">点击下方按钮添加</text>
</view>
<view wx:else class="address-list">
<view
class="address-card"
wx:for="{{list}}"
wx:key="id"
data-id="{{item.id}}"
bindtap="goEdit"
>
<view class="card-header">
<text class="name">{{item.name}}</text>
<text class="phone">{{item.phone}}</text>
<view class="default-tag" wx:if="{{item.isDefault}}">默认</view>
</view>
<view class="card-address">{{item.fullAddress}}</view>
<view class="card-actions">
<view class="action-btn" catchtap="goEdit" data-id="{{item.id}}">编辑</view>
<view class="action-btn delete" catchtap="deleteAddress" data-id="{{item.id}}">删除</view>
</view>
</view>
</view>
<view class="btn-add" bindtap="goAdd">+ 新增收货地址</view>
</view>
</view>

View File

@@ -0,0 +1,44 @@
.page { min-height: 100vh; background: #000; padding-bottom: 120rpx; }
.nav-bar { position: fixed; top: 0; left: 0; right: 0; z-index: 100; background: rgba(0,0,0,0.9); backdrop-filter: blur(40rpx); display: flex; align-items: center; justify-content: space-between; padding: 0 32rpx; height: 88rpx; }
.nav-back { width: 64rpx; height: 64rpx; display: flex; align-items: center; justify-content: center; }
.back-icon { font-size: 40rpx; color: rgba(255,255,255,0.6); }
.nav-title { font-size: 34rpx; font-weight: 600; color: #fff; }
.nav-placeholder { width: 64rpx; }
.content { padding: 24rpx; }
.loading-wrap, .empty-wrap { text-align: center; padding: 80rpx 0; }
.loading-text { color: rgba(255,255,255,0.5); font-size: 28rpx; }
.empty-icon { font-size: 80rpx; display: block; margin-bottom: 24rpx; opacity: 0.6; }
.empty-text { color: #fff; font-size: 30rpx; display: block; }
.empty-tip { color: rgba(255,255,255,0.4); font-size: 26rpx; display: block; margin-top: 8rpx; }
.address-list { display: flex; flex-direction: column; gap: 24rpx; }
.address-card {
background: #1c1c1e;
border-radius: 24rpx;
padding: 28rpx;
border: 2rpx solid rgba(0,206,209,0.2);
}
.card-header { display: flex; align-items: center; gap: 16rpx; margin-bottom: 16rpx; }
.card-header .name { font-size: 30rpx; font-weight: 600; color: #fff; }
.card-header .phone { font-size: 26rpx; color: rgba(255,255,255,0.6); }
.default-tag { margin-left: auto; padding: 4rpx 12rpx; background: rgba(0,206,209,0.25); color: #00CED1; font-size: 22rpx; border-radius: 8rpx; }
.card-address { font-size: 26rpx; color: rgba(255,255,255,0.7); line-height: 1.5; margin-bottom: 20rpx; }
.card-actions { display: flex; justify-content: flex-end; gap: 24rpx; }
.action-btn { font-size: 26rpx; color: #00CED1; }
.action-btn.delete { color: rgba(255,107,107,0.9); }
.btn-add {
position: fixed;
bottom: 0;
left: 24rpx;
right: 24rpx;
height: 88rpx;
line-height: 88rpx;
text-align: center;
background: #00CED1;
color: #000;
font-size: 30rpx;
font-weight: 600;
border-radius: 44rpx;
}

View File

@@ -32,13 +32,13 @@ Page({
latestSection: null,
latestLabel: '最新更新',
// 内容概览
// 内容概览(与 Web lib/book-data.ts 一致)
partsList: [
{ id: 'part-1', number: '', title: '真实的人', subtitle: '人与人之间的底层逻辑' },
{ id: 'part-2', number: '', title: '真实的行业', subtitle: '电商、内容、传统行业解析' },
{ id: 'part-3', number: '', title: '真实的错误', subtitle: '我和别人犯过的错' },
{ id: 'part-4', number: '', title: '真实的赚钱', subtitle: '底层结构与真实案例' },
{ id: 'part-5', number: '', title: '真实的社会', subtitle: '未来职业与商业生态' }
{ id: 'part-1', number: '01', title: '真实的人', subtitle: '人性观察与社交逻辑' },
{ id: 'part-2', number: '02', title: '真实的行业', subtitle: '社会运作的底层规则' },
{ id: 'part-3', number: '03', title: '真实的错误', subtitle: '错过机会比失败更贵' },
{ id: 'part-4', number: '04', title: '真实的赚钱', subtitle: '所有行业的杠杆结构' },
{ id: 'part-5', number: '05', title: '真实的未来', subtitle: '人与系统的关系' }
],
// 加载状态

View File

@@ -30,7 +30,7 @@
<view class="search-circle"></view>
<view class="search-handle"></view>
</view>
<text class="search-placeholder">搜索章节标题或内容...</text>
<text class="search-placeholder">搜索章节...</text>
</view>
</view>

View File

@@ -15,7 +15,7 @@ Page({
phoneNumber: '',
wechatId: '',
alipayAccount: '',
address: '',
addressSummary: '管理收货地址',
// 自动提现(默认开启)
autoWithdrawEnabled: true,
@@ -47,7 +47,6 @@ Page({
const phoneNumber = wx.getStorageSync('user_phone') || userInfo.phone || ''
const wechatId = wx.getStorageSync('user_wechat') || userInfo.wechat || ''
const alipayAccount = wx.getStorageSync('user_alipay') || userInfo.alipay || ''
const address = wx.getStorageSync('user_address') || userInfo.address || ''
// 默认开启自动提现
const autoWithdrawEnabled = wx.getStorageSync('auto_withdraw_enabled') !== false
@@ -57,73 +56,37 @@ Page({
phoneNumber,
wechatId,
alipayAccount,
address,
autoWithdrawEnabled
})
this.loadAddressSummary()
}
},
// 一键获取收货地址
getAddress() {
wx.chooseAddress({
success: (res) => {
console.log('[Settings] 获取地址成功:', res)
const fullAddress = `${res.provinceName || ''}${res.cityName || ''}${res.countyName || ''}${res.detailInfo || ''}`
if (fullAddress.trim()) {
wx.setStorageSync('user_address', fullAddress)
this.setData({ address: fullAddress })
// 更新用户信息
if (app.globalData.userInfo) {
app.globalData.userInfo.address = fullAddress
wx.setStorageSync('userInfo', app.globalData.userInfo)
}
// 同步到服务器
this.syncAddressToServer(fullAddress)
wx.showToast({ title: '地址已获取', icon: 'success' })
}
},
fail: (e) => {
console.log('[Settings] 获取地址失败:', e)
if (e.errMsg?.includes('cancel')) {
// 用户取消,不提示
return
}
if (e.errMsg?.includes('auth deny') || e.errMsg?.includes('authorize')) {
wx.showModal({
title: '需要授权',
content: '请在设置中允许获取收货地址',
confirmText: '去设置',
success: (res) => {
if (res.confirm) wx.openSetting()
}
})
} else {
wx.showToast({ title: '获取失败,请重试', icon: 'none' })
}
}
})
},
// 同步地址到服务器
async syncAddressToServer(address) {
// 加载地址摘要(共 N 个地址
async loadAddressSummary() {
try {
const userId = app.globalData.userInfo?.id
if (!userId) return
await app.request('/api/user/update', {
method: 'POST',
data: { userId, address }
})
console.log('[Settings] 地址已同步到服务器')
const res = await app.request('/api/user/addresses', { data: { userId } })
if (res.success && res.list && res.list.length > 0) {
this.setData({ addressSummary: `${res.list.length}个收货地址` })
} else {
this.setData({ addressSummary: '管理收货地址' })
}
} catch (e) {
console.log('[Settings] 同步地址失败:', e)
this.setData({ addressSummary: '管理收货地址' })
}
},
// 跳转收货地址列表(增删改查),未登录时提示先登录
goToAddressList() {
if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
wx.showToast({ title: '请先登录', icon: 'none' })
return
}
wx.navigateTo({ url: '/pages/address-list/address-list' })
},
// 切换自动提现
async toggleAutoWithdraw(e) {
const enabled = e.detail.value

View File

@@ -58,20 +58,22 @@
</view>
</view>
<!-- 收货地址 - 微信一键获取 -->
<view class="bind-item" bindtap="getAddress">
<view class="bind-left">
<view class="bind-icon address-icon">📍</view>
<view class="bind-info">
<text class="bind-label">收货地址</text>
<text class="bind-value address-text">{{address || '未绑定'}}</text>
</view>
</view>
<view class="bind-right">
<text class="bind-check" wx:if="{{address}}">✓</text>
<text class="bind-btn" wx:else>一键获取</text>
</view>
</view>
<!-- 收货地址管理(始终显示,未登录点击提示先登录) -->
<view class="bind-card address-card">
<view class="bind-item" bindtap="goToAddressList">
<view class="bind-left">
<view class="bind-icon address-icon">📍</view>
<view class="bind-info">
<text class="bind-label">收货地址</text>
<text class="bind-value address-text">{{isLoggedIn ? (addressSummary || '管理收货地址') : '点击登录后管理'}}</text>
</view>
</view>
<view class="bind-right">
<text class="bind-arrow"></text>
</view>
</view>
</view>

View File

@@ -35,6 +35,7 @@
.bind-right { display: flex; align-items: center; }
.bind-check { color: #00CED1; font-size: 32rpx; }
.bind-btn { color: #00CED1; font-size: 26rpx; }
.bind-arrow { color: rgba(255,255,255,0.4); font-size: 36rpx; }
/* 一键获取手机号按钮 */
.get-phone-btn {
@@ -48,6 +49,9 @@
}
.get-phone-btn::after { border: none; }
/* 收货地址独立卡片(始终显示) */
.address-card { margin-top: 24rpx; }
/* 自动提现卡片 */
.auto-withdraw-card { margin-top: 24rpx; }
.auto-withdraw-content { padding-top: 16rpx; }

2
next-env.d.ts vendored
View File

@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.