Next.js房产中介管理系统源码实战开发高效解决房源信息管理客户跟进与合同签约难题

引言:现代房产中介管理的数字化转型
在当今竞争激烈的房地产市场中,传统的纸质记录和分散的Excel表格管理方式已经无法满足高效运营的需求。房产中介公司面临着房源信息更新不及时、客户跟进容易遗漏、合同签约流程繁琐等痛点。基于Next.js构建的现代化房产中介管理系统正是解决这些难题的最佳方案。
Next.js作为React生态中最流行的全栈框架,凭借其服务端渲染(SSR)、静态站点生成(SSG)、API路由以及内置的TypeScript支持等特性,为构建高性能、SEO友好的Web应用提供了完美基础。结合现代数据库如PostgreSQL和Prisma ORM,我们可以打造一个功能完整、开发效率高、用户体验优秀的房产管理系统。
本文将通过实战开发的角度,详细讲解如何使用Next.js构建一个涵盖房源信息管理、客户跟进和合同签约三大核心模块的房产中介管理系统。我们将从技术选型开始,逐步深入到数据库设计、核心功能实现、代码优化和部署上线的全过程。
技术栈选择与项目架构设计
核心技术栈
前端框架
: Next.js 14 (App Router模式)
服务端渲染确保SEO友好,房源信息能被搜索引擎快速收录
API路由提供完整的后端能力,无需单独部署后端服务
内置优化的图片处理,房源图片加载更快
数据库
: PostgreSQL + Prisma ORM
PostgreSQL的JSONB字段支持灵活的房源属性存储
Prisma提供类型安全的数据库操作,减少运行时错误
迁移系统方便团队协作开发
UI组件库
: Shadcn UI + Tailwind CSS
专业的企业级组件,快速构建美观界面
响应式设计,支持移动端客户自助看房
状态管理
: Zustand + React Query
轻量级状态管理,避免过度复杂化
React Query处理服务端状态,缓存和自动重试机制完善
认证
: NextAuth.js
支持多种登录方式(邮箱、Google、微信)
基于角色的访问控制(经纪人、管理员、客户)
项目目录结构设计
/src
/app
/(main)
/admin # 管理后台路由
/broker # 经纪人工作台
/client # 客户自助页面
/api # API路由
/webhook # Stripe等支付回调
/cron # 定时任务
/login # 登录页面
/components # 通用组件
/ui # 基础UI组件
/features # 业务组件
/property # 房源相关
/customer # 客户相关
/contract # 合同相关
/lib
/db # 数据库连接
/utils # 工具函数
/validations # 数据验证
/types # TypeScript类型定义
/hooks # 自定义Hooks
/styles # 全局样式
数据库设计与Prisma Schema实现
核心数据模型
房产中介系统的核心在于数据关系的复杂性。我们需要设计能够处理房源、客户、经纪人、合同等多对多关系的数据库结构。
// prisma/schema.prisma

generator client {
provider = “prisma-client-js”
}

datasource db {
provider = “postgresql”
url = env(“DATABASE_URL”)
}

// 用户表(包含经纪人、管理员、客户)
model User {
id String @id @default(cuid())
email String @unique
name String?
phone String?
password String? // 仅用于邮箱登录
role Role @default(BROKER) // BROKER, ADMIN, CLIENT
image String?

// 关系
properties Property[] @relation(“BrokerProperties”)
customers Customer[] @relation(“BrokerCustomers”)
contracts Contract[] @relation(“BrokerContracts”)
createdContracts Contract[] @relation(“CreatorContracts”)

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

// 房源表
model Property {
id String @id @default(cuid())
title String // 房源标题
description String?
price Decimal // 价格(万元)
area Decimal // 面积(平方米)
bedrooms Int? // 卧室数量
bathrooms Int? // 卫生间数量
address String // 详细地址
city String // 城市
district String // 区域
type PropertyType // 住宅、商铺、写字楼
status PropertyStatus @default(AVAILABLE) // 可售、已售、已租

// 图片和多媒体
images String[] // 图片URL数组
videoUrl String?
virtualTour String? // VR看房链接

// 房源属性(JSONB存储灵活属性)
attributes Json? // 如:朝向、楼层、装修情况

// 关系
brokerId String
broker User @relation(“BrokerProperties”, fields: [brokerId], references: [id])

customers Customer[] // 收藏该房源的客户

contracts Contract[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

// 客户表
model Customer {
id String @id @default(cuid())
name String
phone String @unique
email String?

// 客户需求
budgetMin Decimal?
budgetMax Decimal?
areaMin Decimal?
areaMax Decimal?
requirements Json? // 需求详情(JSON)

// 关系
brokerId String
broker User @relation(“BrokerCustomers”, fields: [brokerId], references: [id])

properties Property[] @relation(“FavoriteProperties”) // 收藏的房源

// 跟进记录
followUps FollowUp[]

contracts Contract[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

// 跟进记录表
model FollowUp {
id String @id @default(cuid())
customerId String
customer Customer @relation(fields: [customerId], references: [id])

brokerId String
broker User @relation(fields: [brokerId], references: [id])

type FollowUpType // CALL, VISIT, MEETING, MESSAGE
notes String
nextAction String?
nextDate DateTime?

createdAt DateTime @default(now())
}

// 合同表
model Contract {
id String @id @default(cuid())
contractNo String @unique // 合同编号

// 合同主体
propertyId String
property Property @relation(fields: [propertyId], references: [id])

customerId String
customer Customer @relation(fields: [customerId], references: [id])

brokerId String
broker User @relation(fields: [brokerId], references: [id])

// 合同条款
price Decimal // 成交价
deposit Decimal // 定金
commission Decimal // 佣金
startDate Date // 起租/起售日期
endDate Date? // 结束日期(租赁)

// 状态和文件
status ContractStatus @default(PENDING) // 待审核、已签约、已支付、已取消
files String[] // 合同文件URL

// 审批流程
approvedBy String? // 审批人ID
approvedAt DateTime?

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

// 枚举定义
enum Role {
BROKER
ADMIN
CLIENT
}

enum PropertyType {
APARTMENT
VILLA
COMMERCIAL
OFFICE
LAND
}

enum PropertyStatus {
AVAILABLE
SOLD
RENTED
PENDING
}

enum FollowUpType {
CALL
VISIT
MEETING
MESSAGE
EMAIL
}

enum ContractStatus {
PENDING
APPROVED
SIGNED
PAID
COMPLETED
CANCELLED
}
数据库迁移与初始化
在完成schema设计后,执行以下命令生成并应用迁移:
# 生成迁移文件
npx prisma migrate dev –name init

# 生成Prisma Client
npx prisma generate

# 可选:填充测试数据
npx prisma db seed
Next.js API路由实现后端逻辑
认证系统实现
使用NextAuth.js实现基于角色的认证系统:
// src/app/api/auth/[…nextauth]/route.ts
import NextAuth from “next-auth”
import CredentialsProvider from “next-auth/providers/credentials”
import GoogleProvider from “next-auth/providers/google”
import { PrismaAdapter } from “@next-auth/prisma-adapter”
import { prisma } from “@/lib/db”
import bcrypt from “bcryptjs”

export const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
name: “credentials”,
credentials: {
email: { label: “Email”, type: “email” },
password: { label: “Password”, type: “password” }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null

const user = await prisma.user.findUnique({
where: { email: credentials.email }
})

if (!user || !user.password) return null

const isValid = await bcrypt.compare(credentials.password, user.password)
if (!isValid) return null

return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
phone: user.phone
}
}
}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
})
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role
token.phone = user.phone
}
return token
},
async session({ session, token }) {
if (session.user) {
session.user.role = token.role
session.user.phone = token.phone
session.user.id = token.sub
}
return session
}
},
pages: {
signIn: “/login”,
},
session: {
strategy: “jwt”,
},
secret: process.env.NEXTAUTH_SECRET,
}

const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }
房源管理API
实现完整的CRUD操作,包含权限验证和数据校验:
// src/app/api/properties/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { authOptions } from “../auth/[…nextauth]/route”
import { prisma } from “@/lib/db”
import { propertySchema } from “@/lib/validations/property”

// GET: 获取房源列表(支持筛选和分页)
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json({ error: “未授权” }, { status: 401 })
}

const { searchParams } = new URL(req.url)
const page = parseInt(searchParams.get(“page”) || “1”)
const limit = parseInt(searchParams.get(“limit”) || “10”)
const city = searchParams.get(“city”)
const type = searchParams.get(“type”)
const minPrice = searchParams.get(“minPrice”)
const maxPrice = searchParams.get(“maxPrice”)
const search = searchParams.get(“search”)

// 构建筛选条件
const where: any = {
AND: []
}

if (city) where.AND.push({ city })
if (type) where.AND.push({ type })
if (minPrice) where.AND.push({ price: { gte: parseFloat(minPrice) } })
if (maxPrice) where.AND.push({ price: { lte: parseFloat(maxPrice) } })
if (search) {
where.AND.push({
OR: [
{ title: { contains: search, mode: “insensitive” } },
{ address: { contains: search, mode: “insensitive” } },
{ district: { contains: search, mode: “insensitive” } }
]
})
}

// 如果是经纪人,只能看到自己的房源
if (session.user.role === “BROKER”) {
where.brokerId = session.user.id
}

const [properties, total] = await Promise.all([
prisma.property.findMany({
where,
include: {
broker: {
select: { name: true, phone: true, email: true }
},
customers: {
select: { id: true, name: true }
}
},
orderBy: { createdAt: “desc” },
skip: (page – 1) * limit,
take: limit
}),
prisma.property.count({ where })
])

return NextResponse.json({
data: properties,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit)
}
})
} catch (error) {
console.error(“获取房源失败:”, error)
return NextResponse.json({ error: “服务器错误” }, { status: 500 })
}
}

// POST: 创建房源
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== “BROKER”) {
return NextResponse.json({ error: “仅经纪人可创建房源” }, { status: 403 })
}

const body = await req.json()
const validated = propertySchema.parse(body)

const property = await prisma.property.create({
data: {
…validated,
price: parseFloat(validated.price.toString()),
area: parseFloat(validated.area.toString()),
brokerId: session.user.id,
attributes: validated.attributes || {}
},
include: {
broker: {
select: { name: true, phone: true }
}
}
})

return NextResponse.json(property, { status: 201 })
} catch (error) {
console.error(“创建房源失败:”, error)
return NextResponse.json({ error: “数据验证失败” }, { status: 400 })
}
}
单个房源操作API
// src/app/api/properties/[id]/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { authOptions } from “../../auth/[…nextauth]/route”
import { prisma } from “@/lib/db”

// GET: 获取单个房源详情
export async function GET(
req: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json({ error: “未授权” }, { status: 401 })
}

const property = await prisma.property.findUnique({
where: { id: params.id },
include: {
broker: {
select: { name: true, phone: true, email: true, image: true }
},
customers: {
select: { id: true, name: true, phone: true }
},
contracts: {
include: {
customer: { select: { name: true, phone: true } }
}
}
}
})

if (!property) {
return NextResponse.json({ error: “房源不存在” }, { status: 404 })
}

// 权限检查:经纪人只能访问自己的房源
if (session.user.role === “BROKER” && property.brokerId !== session.user.id) {
return NextResponse.json({ error: “无权访问该房源” }, { status: 403 })
}

return NextResponse.json(property)
} catch (error) {
console.error(“获取房源详情失败:”, error)
return NextResponse.json({ error: “服务器错误” }, { status: 500 })
}
}

// PUT: 更新房源
export async function PUT(
req: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== “BROKER”) {
return NextResponse.json({ error: “无权操作” }, { status: 403 })
}

const property = await prisma.property.findUnique({
where: { id: params.id }
})

if (!property || property.brokerId !== session.user.id) {
return NextResponse.json({ error: “房源不存在或无权修改” }, { status: 404 })
}

const body = await req.json()
const updated = await prisma.property.update({
where: { id: params.id },
data: {
…body,
price: body.price ? parseFloat(body.price) : undefined,
area: body.area ? parseFloat(body.area) : undefined
}
})

return NextResponse.json(updated)
} catch (error) {
console.error(“更新房源失败:”, error)
return NextResponse.json({ error: “更新失败” }, { status: 400 })
}
}

// DELETE: 删除房源
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== “BROKER”) {
return NextResponse.json({ error: “无权操作” }, { status: 403 })
}

// 检查是否有关联合同
const contractsCount = await prisma.contract.count({
where: { propertyId: params.id }
})

if (contractsCount > 0) {
return NextResponse.json({ error: “该房源已有合同关联,无法删除” }, { status: 400 })
}

await prisma.property.delete({
where: { id: params.id, brokerId: session.user.id }
})

return NextResponse.json({ message: “删除成功” })
} catch (error) {
console.error(“删除房源失败:”, error)
return NextResponse.json({ error: “删除失败” }, { status: 500 })
}
}
客户跟进API
// src/app/api/followups/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { authOptions } from “../auth/[…nextauth]/route”
import { prisma } from “@/lib/db”

// POST: 创建跟进记录
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== “BROKER”) {
return NextResponse.json({ error: “仅经纪人可创建跟进” }, { status: 403 })
}

const { customerId, type, notes, nextAction, nextDate } = await req.json()

// 验证客户归属
const customer = await prisma.customer.findFirst({
where: {
id: customerId,
brokerId: session.user.id
}
})

if (!customer) {
return NextResponse.json({ error: “客户不存在或无权访问” }, { status: 404 })
}

const followUp = await prisma.followUp.create({
data: {
customerId,
brokerId: session.user.id,
type,
notes,
nextAction,
nextDate: nextDate ? new Date(nextDate) : null
},
include: {
customer: {
select: { name: true, phone: true }
}
}
})

return NextResponse.json(followUp, { status: 201 })
} catch (error) {
console.error(“创建跟进失败:”, error)
return NextResponse.json({ error: “创建失败” }, { status: 400 })
}
}

// GET: 获取客户跟进历史
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json({ error: “未授权” }, { status: 401 })
}

const { searchParams } = new URL(req.url)
const customerId = searchParams.get(“customerId”)

if (!customerId) {
return NextResponse.json({ error: “缺少客户ID” }, { status: 400 })
}

// 验证客户归属
const customer = await prisma.customer.findFirst({
where: {
id: customerId,
brokerId: session.user.id
}
})

if (!customer && session.user.role !== “ADMIN”) {
return NextResponse.json({ error: “无权访问” }, { status: 403 })
}

const followUps = await prisma.followUp.findMany({
where: { customerId },
include: {
broker: {
select: { name: true }
}
},
orderBy: { createdAt: “desc” }
})

return NextResponse.json(followUps)
} catch (error) {
console.error(“获取跟进失败:”, error)
return NextResponse.json({ error: “服务器错误” }, { status: 500 })
}
}
合同签约API
// src/app/api/contracts/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { authOptions } from “../auth/[…nextauth]/route”
import { prisma } from “@/lib/db”
import { contractSchema } from “@/lib/validations/contract”

// POST: 创建合同
export async function POST(req: NextRequest) {
try {
const session = session = await getServerSession(authOptions)
if (!session || session.user.role !== “BROKER”) {
return NextResponse.json({ error: “仅经纪人可创建合同” }, { status: 403 })
}

const body = await req.json()
const validated = contractSchema.parse(body)

// 验证房源和客户归属
const [property, customer] = await Promise.all([
prisma.property.findFirst({
where: { id: validated.propertyId, brokerId: session.user.id }
}),
prisma.customer.findFirst({
where: { id: validated.customerId, brokerId: session.user.id }
})
])

if (!property || !customer) {
return NextResponse.json({ error: “房源或客户不存在” }, { status: 404 })
}

// 检查房源状态
if (property.status !== “AVAILABLE”) {
return NextResponse.json({ error: “房源不可用” }, { status: 400 })
}

// 生成合同编号
const contractNo = `CTR${Date.now()}${Math.random().toString(36).substr(2, 6)}`.toUpperCase()

const contract = await prisma.$transaction(async (tx) => {
// 创建合同
const newContract = await tx.contract.create({
data: {
contractNo,
…validated,
price: parseFloat(validated.price.toString()),
deposit: parseFloat(validated.deposit.toString()),
commission: parseFloat(validated.commission.toString()),
brokerId: session.user.id,
startDate: new Date(validated.startDate)
},
include: {
property: true,
customer: true
}
})

// 更新房源状态为待定
await tx.property.update({
where: { id: validated.propertyId },
data: { status: “PENDING” }
})

return newContract
})

return NextResponse.json(contract, { status: 201 })
} catch (error) {
console.error(“创建合同失败:”, error)
return NextResponse.json({ error: “数据验证失败” }, { status: 400 })
}
}

// GET: 获取合同列表
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json({ error: “未授权” }, { status: 401 })
}

const { searchParams } = new URL(req.url)
const status = searchParams.get(“status”)
const page = parseInt(searchParams.get(“page”) || “1”)
const limit = parseInt(searchParams.get(“limit”) || “10”)

const where: any = {}

// 权限控制
if (session.user.role === “BROKER”) {
where.brokerId = session.user.id
}

if (status) {
where.status = status
}

const [contracts, total] = await Promise.all([
prisma.contract.findMany({
where,
include: {
property: {
select: { title: true, address: true, price: true }
},
customer: {
select: { name: true, phone: true }
},
broker: {
select: { name: true, phone: true }
}
},
orderBy: { createdAt: “desc” },
skip: (page – 1) * limit,
take: limit
}),
prisma.contract.count({ where })
])

return NextResponse.json({
data: contracts,
pagination: { page, limit, total, pages: Math.ceil(total / limit) }
})
} catch (error) {
console.error(“获取合同失败:”, error)
return NextResponse.json({ error: “服务器错误” }, { status: 500 })
}
}
前端页面与组件开发
经纪人工作台页面
// src/app/(main)/broker/page.tsx
import { getServerSession } from “next-auth”
import { authOptions } from “@/app/api/auth/[…nextauth]/route”
import { redirect } from “next/navigation”
import { PropertyList } from “@/components/features/property/PropertyList”
import { StatsCard } from “@/components/features/dashboard/StatsCard”
import { UpcomingFollowUps } from “@/components/features/followup/UpcomingFollowUps”

export default async function BrokerDashboard() {
const session = await getServerSession(authOptions)

if (!session || session.user.role !== “BROKER”) {
redirect(“/login”)
}

// 获取统计数据
const stats = await getStats(session.user.id)

return (

经纪人工作台

{/* 统计卡片 */}




{/* 待办跟进 */}

今日待跟进

{/* 最新房源 */}

最新房源

)
}

async function getStats(brokerId: string) {
const [properties, customers, pendingContracts, completedContracts] = await Promise.all([
prisma.property.count({ where: { brokerId, status: “AVAILABLE” } }),
prisma.customer.count({ where: { brokerId } }),
prisma.contract.count({ where: { brokerId, status: “PENDING” } }),
prisma.contract.count({
where: {
brokerId,
status: “COMPLETED”,
createdAt: {
gte: new Date(new Date().setDate(new Date().getDate() – 30))
}
}
})
])

return { properties, customers, pendingContracts, completedContracts }
}
房源列表组件(客户端组件)
// src/components/features/property/PropertyList.tsx
“use client”

import { useState, useEffect } from “react”
import { PropertyCard } from “./PropertyCard”
import { PropertyFilters } from “./PropertyFilters”
import { useQuery } from “@tanstack/react-query”
import { Button } from “@/components/ui/button”
import { Skeleton } from “@/components/ui/skeleton”
import { toast } from “sonner”

interface PropertyListProps {
brokerId?: string
}

export function PropertyList({ brokerId }: PropertyListProps) {
const [filters, setFilters] = useState({
city: “”,
type: “”,
minPrice: “”,
maxPrice: “”,
search: “”
})
const [page, setPage] = useState(1)

const { data, isLoading, error, refetch } = useQuery({
queryKey: [“properties”, filters, page, brokerId],
queryFn: async () => {
const params = new URLSearchParams({
page: page.toString(),
limit: “10”,
…filters
})
if (brokerId) params.append(“brokerId”, brokerId)

const res = await fetch(`/api/properties?${params}`)
if (!res.ok) throw new Error(“获取房源失败”)
return res.json()
}
})

useEffect(() => {
if (error) {
toast.error(error.message)
}
}, [error])

if (isLoading) {
return (

{[…Array(5)].map((_, i) => (

))}

)
}

return (

{data?.data?.map((property: any) => (

))}

{data?.data?.length === 0 && (

暂无符合条件的房源

)}

{/* 分页 */}
{data?.pagination && data.pagination.pages > 1 && (



第 {page} / {data.pagination.pages} 页

)}

)
}
房源卡片组件
// src/components/features/property/PropertyCard.tsx
import { Card, CardContent, CardHeader, CardTitle } from “@/components/ui/card”
import { Badge } from “@/components/ui/badge”
import { Button } from “@/components/ui/button”
import { useRouter } from “next/navigation”
import { formatCurrency } from “@/lib/utils”

interface PropertyCardProps {
property: any
action?: React.ReactNode
}

export function PropertyCard({ property, action }: PropertyCardProps) {
const router = useRouter()

const statusColors = {
AVAILABLE: “bg-green-500”,
SOLD: “bg-red-500”,
RENTED: “bg-blue-500”,
PENDING: “bg-yellow-500”
}

return (

{property.title}

{property.status === “AVAILABLE” ? “在售” :
property.status === “SOLD” ? “已售” :
property.status === “RENTED” ? “已租” : “待定”}


{property.address}

{formatCurrency(property.price)}万

{property.area}㎡
{property.bedrooms && {property.bedrooms}室}
{property.bathrooms && {property.bathrooms}卫}

{action}



)
}
客户跟进表单组件
// src/components/features/followup/FollowUpForm.tsx
“use client”

import { useState } from “react”
import { useForm } from “react-hook-form”
import { zodResolver } from “@hookform/resolvers/zod”
import { z } from “zod”
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from “@/components/ui/form”
import { Input } from “@/components/ui/input”
import { Button } from “@/components/ui/button”
import { Textarea } from “@/components/ui/textarea”
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from “@/components/ui/select”
import { toast } from “sonner”
import { useRouter } from “next/navigation”

const followUpSchema = z.object({
customerId: z.string().min(1, “请选择客户”),
type: z.enum([“CALL”, “VISIT”, “MEETING”, “MESSAGE”, “EMAIL”]),
notes: z.string().min(1, “请填写跟进内容”),
nextAction: z.string().optional(),
nextDate: z.string().optional()
})

interface FollowUpFormProps {
customers: Array<{ id: string; name: string; phone: string }>
onSuccess?: () => void
}

export function FollowUpForm({ customers, onSuccess }: FollowUpFormProps) {
const [isSubmitting, setIsSubmitting] = useState(false)
const router = useRouter()

const form = useForm>({
resolver: zodResolver(followUpSchema),
defaultValues: {
customerId: “”,
type: “CALL”,
notes: “”,
nextAction: “”,
nextDate: “”
}
})

async function onSubmit(values: z.infer) {
setIsSubmitting(true)
try {
const res = await fetch(“/api/followups”, {
method: “POST”,
headers: { “Content-Type”: “application/json” },
body: JSON.stringify(values)
})

if (!res.ok) {
const error = await res.json()
throw new Error(error.error || “创建失败”)
}

toast.success(“跟进记录已创建”)
form.reset()
if (onSuccess) onSuccess()
router.refresh()
} catch (error: any) {
toast.error(error.message)
} finally {
setIsSubmitting(false)
}
}

return (

(

选择客户



)}
/>

(

跟进方式



)}
/>

(

跟进内容