diff --git a/app/(dashboard)/dashboard/page.tsx b/app/(dashboard)/dashboard/page.tsx index 50a9b44..87691dc 100644 --- a/app/(dashboard)/dashboard/page.tsx +++ b/app/(dashboard)/dashboard/page.tsx @@ -6,18 +6,49 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Progress } from "@/components/ui/progress" import { listOrders, listPlayers, listServices, listShops } from "@/lib/api" import { statusLabels } from "@/lib/constants" +import type { Player, PlayerService, Shop } from "@/lib/types" import { useAuthStore } from "@/store/auth" import { CheckCircle, Clock, DollarSign, ListOrdered, Star, TrendingUp, Users } from "lucide-react" import Link from "next/link" +import { useEffect, useState } from "react" export default function DashboardPage() { const { currentRole } = useAuthStore() const isOwner = currentRole === "owner" - const player = listPlayers()[0] - const shop = listShops()[0] + const [player, setPlayer] = useState(null) + const [shop, setShop] = useState(null) + const [services, setServices] = useState([]) const recentOrders = listOrders().slice(0, 3) + useEffect(() => { + let cancelled = false + + Promise.all([listPlayers(), listShops(), listServices()]) + .then(([players, shops, services]) => { + if (cancelled) return + setPlayer(players[0] ?? null) + setShop(shops[0] ?? null) + setServices(services) + }) + .catch(() => { + if (cancelled) return + setPlayer(null) + setShop(null) + setServices([]) + }) + + return () => { + cancelled = true + } + }, []) + + const totalOrders = isOwner ? (shop?.totalOrders ?? 0) : (player?.totalOrders ?? 0) + const rating = isOwner ? (shop?.rating ?? 0) : (player?.rating ?? 0) + const playerCount = shop?.playerCount ?? 0 + const completionRate = player?.completionRate ?? 0 + const serviceCount = player ? services.filter((s) => s.playerId === player.id).length : 0 + return (

概览

@@ -29,9 +60,7 @@ export default function DashboardPage() { -
- {isOwner ? shop.totalOrders : player.totalOrders} -
+
{totalOrders}
@@ -40,7 +69,7 @@ export default function DashboardPage() { -
{isOwner ? shop.rating : player.rating}
+
{rating}
@@ -54,13 +83,11 @@ export default function DashboardPage() { {isOwner ? ( -
{shop.playerCount}
+
{playerCount}
) : (
-
- {(player.completionRate * 100).toFixed(0)}% -
- +
{(completionRate * 100).toFixed(0)}%
+
)}
@@ -75,9 +102,7 @@ export default function DashboardPage() { )} -
- {isOwner ? "¥12,800" : listServices().filter((s) => s.playerId === player.id).length} -
+
{isOwner ? "¥12,800" : serviceCount}
diff --git a/app/(main)/community/page.tsx b/app/(main)/community/page.tsx index cc580ee..e2a3d17 100644 --- a/app/(main)/community/page.tsx +++ b/app/(main)/community/page.tsx @@ -6,16 +6,16 @@ import { Button } from "@/components/ui/button" import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card" import { listGames, listOrders, listPlayers, listPosts } from "@/lib/api" import { roleLabels } from "@/lib/constants" -import type { Game } from "@/lib/types" +import type { Game, Player } from "@/lib/types" import { ClipboardList, Heart, MessageCircle, PenSquare, Pin } from "lucide-react" import Link from "next/link" import { useEffect, useState } from "react" export default function CommunityPage() { const [games, setGames] = useState([]) + const [players, setPlayers] = useState([]) const posts = listPosts() const orders = listOrders() - const players = listPlayers() const [sortMode, setSortMode] = useState<"latest" | "hot">("latest") const [selectedGame, setSelectedGame] = useState(null) @@ -23,14 +23,16 @@ export default function CommunityPage() { useEffect(() => { let cancelled = false - listGames() - .then((items) => { + Promise.all([listGames(), listPlayers()]) + .then(([gamesItems, playersItems]) => { if (cancelled) return - setGames(items) + setGames(gamesItems) + setPlayers(playersItems) }) .catch(() => { if (cancelled) return setGames([]) + setPlayers([]) }) return () => { diff --git a/app/(main)/page.tsx b/app/(main)/page.tsx index 01a8c57..788ad2d 100644 --- a/app/(main)/page.tsx +++ b/app/(main)/page.tsx @@ -9,9 +9,7 @@ import { ArrowRight, Search, ShoppingBag, Star } from "lucide-react" import Link from "next/link" export default async function HomePage() { - const games = await listGames() - const players = listPlayers() - const shops = listShops() + const [games, players, shops] = await Promise.all([listGames(), listPlayers(), listShops()]) return (
diff --git a/app/(main)/player/[id]/page.tsx b/app/(main)/player/[id]/page.tsx index ba49907..43e8272 100644 --- a/app/(main)/player/[id]/page.tsx +++ b/app/(main)/player/[id]/page.tsx @@ -12,14 +12,14 @@ import { } from "@/components/ui/card" import { Separator } from "@/components/ui/separator" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" -import { listPlayers, listReviewsByTargetUser, listServicesByPlayer } from "@/lib/api" +import { getPlayerById, listReviewsByTargetUser, listServicesByPlayer } from "@/lib/api" import { CheckCircle, Clock, MapPin, MessageSquare, ShoppingBag, Star } from "lucide-react" import Link from "next/link" import { notFound } from "next/navigation" export default async function PlayerDetailPage({ params }: { params: Promise<{ id: string }> }) { const { id } = await params - const player = listPlayers().find((p) => p.id === id) + const player = await getPlayerById(id) if (!player) { notFound() @@ -29,7 +29,7 @@ export default async function PlayerDetailPage({ params }: { params: Promise<{ i const playerServices = player.services && player.services.length > 0 ? player.services - : listServicesByPlayer(player.id) + : await listServicesByPlayer(player.id) return (
diff --git a/app/(main)/post/[id]/page.tsx b/app/(main)/post/[id]/page.tsx index f532779..f36b202 100644 --- a/app/(main)/post/[id]/page.tsx +++ b/app/(main)/post/[id]/page.tsx @@ -18,7 +18,7 @@ export default async function PostDetailPage({ params }: { params: Promise<{ id: if (!post) notFound() const linkedOrder = post.linkedOrderId ? getOrderById(post.linkedOrderId) : null - const linkedPlayer = linkedOrder ? getPlayerById(linkedOrder.playerId) : null + const linkedPlayer = linkedOrder ? await getPlayerById(linkedOrder.playerId) : null return (
diff --git a/app/(main)/shop/[id]/page.tsx b/app/(main)/shop/[id]/page.tsx index 299f5a1..cf37509 100644 --- a/app/(main)/shop/[id]/page.tsx +++ b/app/(main)/shop/[id]/page.tsx @@ -16,15 +16,15 @@ interface PageProps { export default async function ShopPage({ params }: PageProps) { const { id } = await params - const shop = getShopById(id) + const shop = await getShopById(id) if (!shop) { notFound() } - const shopPlayers = listPlayersByShop(shop.id) + const [shopPlayers, allServices] = await Promise.all([listPlayersByShop(shop.id), listServices()]) const playerIds = shopPlayers.map((p) => p.id) - const shopServices = listServices().filter((s) => playerIds.includes(s.playerId)) + const shopServices = allServices.filter((s) => playerIds.includes(s.playerId)) const shopReviews = listReviews().filter((r) => playerIds.includes(r.toUserId)) const sortedSections = [...shop.templateConfig.sections] .filter((s) => s.enabled) diff --git a/app/(main)/user/[id]/page.tsx b/app/(main)/user/[id]/page.tsx index d35a9d7..16c11ef 100644 --- a/app/(main)/user/[id]/page.tsx +++ b/app/(main)/user/[id]/page.tsx @@ -21,15 +21,19 @@ export default async function UserProfilePage({ params }: { params: Promise<{ id notFound() } - const userPosts = listPostsByAuthor(user.id) - const userFavorites = listFavoritesByUser(user.id) + const [userPosts, userFavorites, players, shops] = await Promise.all([ + listPostsByAuthor(user.id), + listFavoritesByUser(user.id), + listPlayers(), + listShops(), + ]) const favoritePlayers = userFavorites .filter((f) => f.targetType === "player") - .map((f) => listPlayers().find((p) => p.id === f.targetId)) + .map((f) => players.find((p) => p.id === f.targetId)) .filter((p): p is NonNullable => p != null) const favoriteShops = userFavorites .filter((f) => f.targetType === "shop") - .map((f) => listShops().find((s) => s.id === f.targetId)) + .map((f) => shops.find((s) => s.id === f.targetId)) .filter((s): s is NonNullable => s != null) return ( diff --git a/app/(order)/order/new/page.tsx b/app/(order)/order/new/page.tsx index 41b3a88..4716bf8 100644 --- a/app/(order)/order/new/page.tsx +++ b/app/(order)/order/new/page.tsx @@ -10,6 +10,7 @@ import { Textarea } from "@/components/ui/textarea" import type { Actor } from "@/lib/actor" import { getPlayerById, getServiceById } from "@/lib/api" import { notifySuccess } from "@/lib/toast" +import type { Player, PlayerService } from "@/lib/types" import { useRequireAuth } from "@/lib/use-require-auth" import { useAuthStore } from "@/store/auth" import { useOrderStore } from "@/store/orders" @@ -17,7 +18,7 @@ import { useWalletStore } from "@/store/wallet" import { ArrowLeft, CheckCircle, CreditCard, ShieldCheck } from "lucide-react" import Link from "next/link" import { useRouter, useSearchParams } from "next/navigation" -import { useState } from "react" +import { useEffect, useState } from "react" export default function NewOrderPage() { const router = useRouter() @@ -27,13 +28,60 @@ export default function NewOrderPage() { const balance = useWalletStore((state) => state.balance) const serviceId = searchParams.get("serviceId") - const service = serviceId ? getServiceById(serviceId) : undefined - const player = service ? getPlayerById(service.playerId) : undefined + const [service, setService] = useState(null) + const [player, setPlayer] = useState(null) + const [loading, setLoading] = useState(true) + + useEffect(() => { + let cancelled = false + setLoading(true) + + if (!serviceId) { + setService(null) + setPlayer(null) + setLoading(false) + return + } + + ;(async () => { + try { + const s = await getServiceById(serviceId) + if (cancelled) return + if (!s) { + setService(null) + setPlayer(null) + setLoading(false) + return + } + + setService(s) + const p = await getPlayerById(s.playerId) + if (cancelled) return + setPlayer(p ?? null) + setLoading(false) + } catch { + if (cancelled) return + setService(null) + setPlayer(null) + setLoading(false) + } + })() + + return () => { + cancelled = true + } + }, [serviceId]) const [quantity, setQuantity] = useState(1) const [note, setNote] = useState("") const [submitted, setSubmitted] = useState(false) + if (loading) { + return ( +
加载中...
+ ) + } + if (!service || !player) { return (
diff --git a/lib/api/players.ts b/lib/api/players.ts index deac8b2..64adb44 100644 --- a/lib/api/players.ts +++ b/lib/api/players.ts @@ -1,13 +1,44 @@ -import { usePlayerStore } from "@/store/players" +import { isApiError } from "@/lib/errors" +import type { Player } from "@/lib/types" -export function listPlayers() { - return usePlayerStore.getState().players +import { httpJson } from "./http" + +type Paginated = { + items: T[] + meta: { + total: number + offset: number + limit: number + } } -export function getPlayerById(playerId: string) { - return usePlayerStore.getState().players.find((player) => player.id === playerId) +export async function listPlayers(): Promise { + const res = await httpJson>("/api/v1/players?offset=0&limit=1000", { + cache: "no-store", + }) + return res.items } -export function listPlayersByShop(shopId: string) { - return usePlayerStore.getState().players.filter((player) => player.shopId === shopId) +export async function getPlayerById(playerId: string): Promise { + try { + return await httpJson(`/api/v1/players/${encodeURIComponent(playerId)}`, { + cache: "no-store", + }) + } catch (error) { + if (error instanceof Error && error.message === "UNAUTHORIZED") { + throw error + } + if (isApiError(error) && error.code === 404) { + return undefined + } + throw error + } +} + +export async function listPlayersByShop(shopId: string): Promise { + const res = await httpJson>( + `/api/v1/shops/${encodeURIComponent(shopId)}/players?offset=0&limit=1000`, + { cache: "no-store" }, + ) + return res.items } diff --git a/lib/api/services.ts b/lib/api/services.ts index b12c6e5..930bdea 100644 --- a/lib/api/services.ts +++ b/lib/api/services.ts @@ -1,13 +1,43 @@ -import { useServiceStore } from "@/store/services" +import { isApiError } from "@/lib/errors" +import type { PlayerService } from "@/lib/types" -export function listServices() { - return useServiceStore.getState().services +import { httpJson } from "./http" + +type Paginated = { + items: T[] + meta: { + total: number + offset: number + limit: number + } } -export function getServiceById(serviceId: string) { - return useServiceStore.getState().services.find((service) => service.id === serviceId) +export async function listServices(): Promise { + const res = await httpJson("/api/v1/services", { cache: "no-store" }) + if (typeof res === "object" && res !== null && "items" in res) { + return (res as Paginated).items + } + return res as PlayerService[] } -export function listServicesByPlayer(playerId: string) { - return useServiceStore.getState().services.filter((service) => service.playerId === playerId) +export async function getServiceById(serviceId: string): Promise { + try { + return await httpJson(`/api/v1/services/${encodeURIComponent(serviceId)}`, { + cache: "no-store", + }) + } catch (error) { + if (error instanceof Error && error.message === "UNAUTHORIZED") { + throw error + } + if (isApiError(error) && error.code === 404) { + return undefined + } + throw error + } +} + +export async function listServicesByPlayer(playerId: string): Promise { + return httpJson(`/api/v1/players/${encodeURIComponent(playerId)}/services`, { + cache: "no-store", + }) } diff --git a/lib/api/shops.ts b/lib/api/shops.ts index 573c724..1e8e768 100644 --- a/lib/api/shops.ts +++ b/lib/api/shops.ts @@ -1,13 +1,52 @@ -import { useShopStore } from "@/store/shops" +import { isApiError } from "@/lib/errors" +import type { Shop } from "@/lib/types" -export function listShops() { - return useShopStore.getState().shops +import { httpJson } from "./http" + +type Paginated = { + items: T[] + meta: { + total: number + offset: number + limit: number + } } -export function getShopById(shopId: string) { - return useShopStore.getState().shops.find((shop) => shop.id === shopId) +export async function listShops(): Promise { + const res = await httpJson>("/api/v1/shops?offset=0&limit=1000", { + cache: "no-store", + }) + return res.items } -export function getShopByOwnerId(ownerId: string) { - return useShopStore.getState().shops.find((shop) => shop.owner.id === ownerId) +export async function getShopById(shopId: string): Promise { + try { + return await httpJson(`/api/v1/shops/${encodeURIComponent(shopId)}`, { + cache: "no-store", + }) + } catch (error) { + if (error instanceof Error && error.message === "UNAUTHORIZED") { + throw error + } + if (isApiError(error) && error.code === 404) { + return undefined + } + throw error + } +} + +export async function getShopByOwnerId(ownerId: string): Promise { + try { + return await httpJson(`/api/v1/users/${encodeURIComponent(ownerId)}/shop`, { + cache: "no-store", + }) + } catch (error) { + if (error instanceof Error && error.message === "UNAUTHORIZED") { + throw error + } + if (isApiError(error) && error.code === 404) { + return undefined + } + throw error + } }