finance-calculator/hooks/use-data-sync.ts

92 lines
2.7 KiB
TypeScript

"use client"
import { useState } from "react"
import { useSession } from "next-auth/react"
import { toast } from "sonner"
import { LocalFinanceProduct } from "./use-local-storage"
export function useDataSync() {
const { data: session } = useSession()
const [isSyncing, setIsSyncing] = useState(false)
// 将本地数据同步到服务器
const syncLocalToServer = async (localProducts: LocalFinanceProduct[]): Promise<boolean> => {
if (!session?.user?.id) {
throw new Error('用户未登录')
}
setIsSyncing(true)
try {
const syncPromises = localProducts.map(async (product) => {
const requestData = {
principal: product.principal,
depositDate: product.depositDate?.toISOString() || null,
endDate: product.endDate?.toISOString() || null,
currentNetValue: product.currentNetValue,
annualRate: product.annualRate,
currency: product.currency,
notes: product.notes,
}
const response = await fetch('/api/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestData),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(`同步产品失败: ${errorData.error || '未知错误'}`)
}
return response.json()
})
await Promise.all(syncPromises)
toast.success(`成功同步 ${localProducts.length} 条本地数据到服务器`)
return true
} catch (error) {
console.error('数据同步失败:', error)
toast.error('数据同步失败,请重试')
return false
} finally {
setIsSyncing(false)
}
}
// 从服务器获取数据
const fetchServerData = async () => {
if (!session?.user?.id) {
throw new Error('用户未登录')
}
try {
const response = await fetch('/api/products')
if (!response.ok) {
throw new Error('获取服务器数据失败')
}
const data = await response.json()
return data.map((product: any) => ({
...product,
depositDate: product.depositDate ? new Date(product.depositDate) : null,
endDate: product.endDate ? new Date(product.endDate) : null,
createdAt: product.createdAt ? new Date(product.createdAt) : undefined,
updatedAt: product.updatedAt ? new Date(product.updatedAt) : undefined,
}))
} catch (error) {
console.error('获取服务器数据失败:', error)
toast.error('获取服务器数据失败')
throw error
}
}
return {
isSyncing,
syncLocalToServer,
fetchServerData,
}
}