feat(catalog): fetch players, services, shops

This commit is contained in:
zetaloop
2026-02-28 16:37:15 +08:00
parent f4365668ab
commit f1ae3e04bb
11 changed files with 234 additions and 57 deletions
+39 -14
View File
@@ -6,18 +6,49 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress" import { Progress } from "@/components/ui/progress"
import { listOrders, listPlayers, listServices, listShops } from "@/lib/api" import { listOrders, listPlayers, listServices, listShops } from "@/lib/api"
import { statusLabels } from "@/lib/constants" import { statusLabels } from "@/lib/constants"
import type { Player, PlayerService, Shop } from "@/lib/types"
import { useAuthStore } from "@/store/auth" import { useAuthStore } from "@/store/auth"
import { CheckCircle, Clock, DollarSign, ListOrdered, Star, TrendingUp, Users } from "lucide-react" import { CheckCircle, Clock, DollarSign, ListOrdered, Star, TrendingUp, Users } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { useEffect, useState } from "react"
export default function DashboardPage() { export default function DashboardPage() {
const { currentRole } = useAuthStore() const { currentRole } = useAuthStore()
const isOwner = currentRole === "owner" const isOwner = currentRole === "owner"
const player = listPlayers()[0] const [player, setPlayer] = useState<Player | null>(null)
const shop = listShops()[0] const [shop, setShop] = useState<Shop | null>(null)
const [services, setServices] = useState<PlayerService[]>([])
const recentOrders = listOrders().slice(0, 3) 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 ( return (
<div className="container mx-auto max-w-6xl px-4 py-8 space-y-8"> <div className="container mx-auto max-w-6xl px-4 py-8 space-y-8">
<h1 className="text-2xl font-bold"></h1> <h1 className="text-2xl font-bold"></h1>
@@ -29,9 +60,7 @@ export default function DashboardPage() {
<ListOrdered className="h-4 w-4 text-muted-foreground" /> <ListOrdered className="h-4 w-4 text-muted-foreground" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold"> <div className="text-2xl font-bold">{totalOrders}</div>
{isOwner ? shop.totalOrders : player.totalOrders}
</div>
</CardContent> </CardContent>
</Card> </Card>
<Card className="hover:shadow-card-hover"> <Card className="hover:shadow-card-hover">
@@ -40,7 +69,7 @@ export default function DashboardPage() {
<Star className="h-4 w-4 text-muted-foreground" /> <Star className="h-4 w-4 text-muted-foreground" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold">{isOwner ? shop.rating : player.rating}</div> <div className="text-2xl font-bold">{rating}</div>
</CardContent> </CardContent>
</Card> </Card>
<Card className="hover:shadow-card-hover"> <Card className="hover:shadow-card-hover">
@@ -54,13 +83,11 @@ export default function DashboardPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{isOwner ? ( {isOwner ? (
<div className="text-2xl font-bold">{shop.playerCount}</div> <div className="text-2xl font-bold">{playerCount}</div>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
<div className="text-2xl font-bold"> <div className="text-2xl font-bold">{(completionRate * 100).toFixed(0)}%</div>
{(player.completionRate * 100).toFixed(0)}% <Progress value={completionRate * 100} className="h-1.5" />
</div>
<Progress value={player.completionRate * 100} className="h-1.5" />
</div> </div>
)} )}
</CardContent> </CardContent>
@@ -75,9 +102,7 @@ export default function DashboardPage() {
)} )}
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold"> <div className="text-2xl font-bold">{isOwner ? "¥12,800" : serviceCount}</div>
{isOwner ? "¥12,800" : listServices().filter((s) => s.playerId === player.id).length}
</div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
+7 -5
View File
@@ -6,16 +6,16 @@ import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card" import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card"
import { listGames, listOrders, listPlayers, listPosts } from "@/lib/api" import { listGames, listOrders, listPlayers, listPosts } from "@/lib/api"
import { roleLabels } from "@/lib/constants" 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 { ClipboardList, Heart, MessageCircle, PenSquare, Pin } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { useEffect, useState } from "react" import { useEffect, useState } from "react"
export default function CommunityPage() { export default function CommunityPage() {
const [games, setGames] = useState<Game[]>([]) const [games, setGames] = useState<Game[]>([])
const [players, setPlayers] = useState<Player[]>([])
const posts = listPosts() const posts = listPosts()
const orders = listOrders() const orders = listOrders()
const players = listPlayers()
const [sortMode, setSortMode] = useState<"latest" | "hot">("latest") const [sortMode, setSortMode] = useState<"latest" | "hot">("latest")
const [selectedGame, setSelectedGame] = useState<string | null>(null) const [selectedGame, setSelectedGame] = useState<string | null>(null)
@@ -23,14 +23,16 @@ export default function CommunityPage() {
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
listGames() Promise.all([listGames(), listPlayers()])
.then((items) => { .then(([gamesItems, playersItems]) => {
if (cancelled) return if (cancelled) return
setGames(items) setGames(gamesItems)
setPlayers(playersItems)
}) })
.catch(() => { .catch(() => {
if (cancelled) return if (cancelled) return
setGames([]) setGames([])
setPlayers([])
}) })
return () => { return () => {
+1 -3
View File
@@ -9,9 +9,7 @@ import { ArrowRight, Search, ShoppingBag, Star } from "lucide-react"
import Link from "next/link" import Link from "next/link"
export default async function HomePage() { export default async function HomePage() {
const games = await listGames() const [games, players, shops] = await Promise.all([listGames(), listPlayers(), listShops()])
const players = listPlayers()
const shops = listShops()
return ( return (
<div className="container mx-auto py-8 px-4 space-y-12"> <div className="container mx-auto py-8 px-4 space-y-12">
+3 -3
View File
@@ -12,14 +12,14 @@ import {
} from "@/components/ui/card" } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator" import { Separator } from "@/components/ui/separator"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" 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 { CheckCircle, Clock, MapPin, MessageSquare, ShoppingBag, Star } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { notFound } from "next/navigation" import { notFound } from "next/navigation"
export default async function PlayerDetailPage({ params }: { params: Promise<{ id: string }> }) { export default async function PlayerDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params const { id } = await params
const player = listPlayers().find((p) => p.id === id) const player = await getPlayerById(id)
if (!player) { if (!player) {
notFound() notFound()
@@ -29,7 +29,7 @@ export default async function PlayerDetailPage({ params }: { params: Promise<{ i
const playerServices = const playerServices =
player.services && player.services.length > 0 player.services && player.services.length > 0
? player.services ? player.services
: listServicesByPlayer(player.id) : await listServicesByPlayer(player.id)
return ( return (
<div className="container mx-auto py-8 px-4 max-w-5xl"> <div className="container mx-auto py-8 px-4 max-w-5xl">
<div className="flex flex-col md:flex-row gap-8 mb-8"> <div className="flex flex-col md:flex-row gap-8 mb-8">
+1 -1
View File
@@ -18,7 +18,7 @@ export default async function PostDetailPage({ params }: { params: Promise<{ id:
if (!post) notFound() if (!post) notFound()
const linkedOrder = post.linkedOrderId ? getOrderById(post.linkedOrderId) : null const linkedOrder = post.linkedOrderId ? getOrderById(post.linkedOrderId) : null
const linkedPlayer = linkedOrder ? getPlayerById(linkedOrder.playerId) : null const linkedPlayer = linkedOrder ? await getPlayerById(linkedOrder.playerId) : null
return ( return (
<div className="container mx-auto max-w-2xl px-4 py-8 space-y-6"> <div className="container mx-auto max-w-2xl px-4 py-8 space-y-6">
+3 -3
View File
@@ -16,15 +16,15 @@ interface PageProps {
export default async function ShopPage({ params }: PageProps) { export default async function ShopPage({ params }: PageProps) {
const { id } = await params const { id } = await params
const shop = getShopById(id) const shop = await getShopById(id)
if (!shop) { if (!shop) {
notFound() notFound()
} }
const shopPlayers = listPlayersByShop(shop.id) const [shopPlayers, allServices] = await Promise.all([listPlayersByShop(shop.id), listServices()])
const playerIds = shopPlayers.map((p) => p.id) 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 shopReviews = listReviews().filter((r) => playerIds.includes(r.toUserId))
const sortedSections = [...shop.templateConfig.sections] const sortedSections = [...shop.templateConfig.sections]
.filter((s) => s.enabled) .filter((s) => s.enabled)
+8 -4
View File
@@ -21,15 +21,19 @@ export default async function UserProfilePage({ params }: { params: Promise<{ id
notFound() notFound()
} }
const userPosts = listPostsByAuthor(user.id) const [userPosts, userFavorites, players, shops] = await Promise.all([
const userFavorites = listFavoritesByUser(user.id) listPostsByAuthor(user.id),
listFavoritesByUser(user.id),
listPlayers(),
listShops(),
])
const favoritePlayers = userFavorites const favoritePlayers = userFavorites
.filter((f) => f.targetType === "player") .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<typeof p> => p != null) .filter((p): p is NonNullable<typeof p> => p != null)
const favoriteShops = userFavorites const favoriteShops = userFavorites
.filter((f) => f.targetType === "shop") .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<typeof s> => s != null) .filter((s): s is NonNullable<typeof s> => s != null)
return ( return (
+51 -3
View File
@@ -10,6 +10,7 @@ import { Textarea } from "@/components/ui/textarea"
import type { Actor } from "@/lib/actor" import type { Actor } from "@/lib/actor"
import { getPlayerById, getServiceById } from "@/lib/api" import { getPlayerById, getServiceById } from "@/lib/api"
import { notifySuccess } from "@/lib/toast" import { notifySuccess } from "@/lib/toast"
import type { Player, PlayerService } from "@/lib/types"
import { useRequireAuth } from "@/lib/use-require-auth" import { useRequireAuth } from "@/lib/use-require-auth"
import { useAuthStore } from "@/store/auth" import { useAuthStore } from "@/store/auth"
import { useOrderStore } from "@/store/orders" import { useOrderStore } from "@/store/orders"
@@ -17,7 +18,7 @@ import { useWalletStore } from "@/store/wallet"
import { ArrowLeft, CheckCircle, CreditCard, ShieldCheck } from "lucide-react" import { ArrowLeft, CheckCircle, CreditCard, ShieldCheck } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation" import { useRouter, useSearchParams } from "next/navigation"
import { useState } from "react" import { useEffect, useState } from "react"
export default function NewOrderPage() { export default function NewOrderPage() {
const router = useRouter() const router = useRouter()
@@ -27,13 +28,60 @@ export default function NewOrderPage() {
const balance = useWalletStore((state) => state.balance) const balance = useWalletStore((state) => state.balance)
const serviceId = searchParams.get("serviceId") const serviceId = searchParams.get("serviceId")
const service = serviceId ? getServiceById(serviceId) : undefined const [service, setService] = useState<PlayerService | null>(null)
const player = service ? getPlayerById(service.playerId) : undefined const [player, setPlayer] = useState<Player | null>(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 [quantity, setQuantity] = useState(1)
const [note, setNote] = useState("") const [note, setNote] = useState("")
const [submitted, setSubmitted] = useState(false) const [submitted, setSubmitted] = useState(false)
if (loading) {
return (
<div className="container mx-auto py-8 px-4 text-center text-muted-foreground">...</div>
)
}
if (!service || !player) { if (!service || !player) {
return ( return (
<div className="container mx-auto py-8 px-4 text-center text-muted-foreground"> <div className="container mx-auto py-8 px-4 text-center text-muted-foreground">
+38 -7
View File
@@ -1,13 +1,44 @@
import { usePlayerStore } from "@/store/players" import { isApiError } from "@/lib/errors"
import type { Player } from "@/lib/types"
export function listPlayers() { import { httpJson } from "./http"
return usePlayerStore.getState().players
type Paginated<T> = {
items: T[]
meta: {
total: number
offset: number
limit: number
}
} }
export function getPlayerById(playerId: string) { export async function listPlayers(): Promise<Player[]> {
return usePlayerStore.getState().players.find((player) => player.id === playerId) const res = await httpJson<Paginated<Player>>("/api/v1/players?offset=0&limit=1000", {
cache: "no-store",
})
return res.items
} }
export function listPlayersByShop(shopId: string) { export async function getPlayerById(playerId: string): Promise<Player | undefined> {
return usePlayerStore.getState().players.filter((player) => player.shopId === shopId) try {
return await httpJson<Player>(`/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<Player[]> {
const res = await httpJson<Paginated<Player>>(
`/api/v1/shops/${encodeURIComponent(shopId)}/players?offset=0&limit=1000`,
{ cache: "no-store" },
)
return res.items
} }
+37 -7
View File
@@ -1,13 +1,43 @@
import { useServiceStore } from "@/store/services" import { isApiError } from "@/lib/errors"
import type { PlayerService } from "@/lib/types"
export function listServices() { import { httpJson } from "./http"
return useServiceStore.getState().services
type Paginated<T> = {
items: T[]
meta: {
total: number
offset: number
limit: number
}
} }
export function getServiceById(serviceId: string) { export async function listServices(): Promise<PlayerService[]> {
return useServiceStore.getState().services.find((service) => service.id === serviceId) const res = await httpJson<unknown>("/api/v1/services", { cache: "no-store" })
if (typeof res === "object" && res !== null && "items" in res) {
return (res as Paginated<PlayerService>).items
}
return res as PlayerService[]
} }
export function listServicesByPlayer(playerId: string) { export async function getServiceById(serviceId: string): Promise<PlayerService | undefined> {
return useServiceStore.getState().services.filter((service) => service.playerId === playerId) try {
return await httpJson<PlayerService>(`/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<PlayerService[]> {
return httpJson<PlayerService[]>(`/api/v1/players/${encodeURIComponent(playerId)}/services`, {
cache: "no-store",
})
} }
+46 -7
View File
@@ -1,13 +1,52 @@
import { useShopStore } from "@/store/shops" import { isApiError } from "@/lib/errors"
import type { Shop } from "@/lib/types"
export function listShops() { import { httpJson } from "./http"
return useShopStore.getState().shops
type Paginated<T> = {
items: T[]
meta: {
total: number
offset: number
limit: number
}
} }
export function getShopById(shopId: string) { export async function listShops(): Promise<Shop[]> {
return useShopStore.getState().shops.find((shop) => shop.id === shopId) const res = await httpJson<Paginated<Shop>>("/api/v1/shops?offset=0&limit=1000", {
cache: "no-store",
})
return res.items
} }
export function getShopByOwnerId(ownerId: string) { export async function getShopById(shopId: string): Promise<Shop | undefined> {
return useShopStore.getState().shops.find((shop) => shop.owner.id === ownerId) try {
return await httpJson<Shop>(`/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<Shop | undefined> {
try {
return await httpJson<Shop>(`/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
}
} }