feat: 新增「喝什么」场景,支持奶茶/咖啡/酒吧等饮品店搜索

引入场景系统(SceneType),首页增加「吃什么」「喝什么」切换 Tab,
不同场景使用不同的高德 POI 类型、热门标签、价格区间和全链路文案。
场景信息存储在房间数据中,邀请/分享/匹配结果等页面自动适配。
This commit is contained in:
2026-02-25 01:12:44 +08:00
parent 6866b70278
commit c86a6c0909
13 changed files with 197 additions and 47 deletions
+20 -11
View File
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { createRoom } from "@/lib/store";
import { Restaurant } from "@/types";
import { Restaurant, SceneType } from "@/types";
import { getSceneConfig } from "@/lib/sceneConfig";
interface AmapPoiV5 {
id: string;
@@ -20,9 +21,6 @@ interface AmapPoiV5 {
photos?: { url: string }[];
}
const DEFAULT_IMAGE =
"https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=800&q=80";
function extractCategory(type?: string): string {
if (!type) return "";
const parts = type.split(";");
@@ -35,7 +33,7 @@ function cleanField(val: unknown): string {
return String(val);
}
function mapPoiToRestaurant(poi: AmapPoiV5): Restaurant {
function mapPoiToRestaurant(poi: AmapPoiV5, defaultImage: string): Restaurant {
const ratingStr = poi.business?.rating;
const rating =
ratingStr && ratingStr !== "[]" ? parseFloat(ratingStr) || 4.0 : 4.0;
@@ -47,7 +45,7 @@ function mapPoiToRestaurant(poi: AmapPoiV5): Restaurant {
const image =
poi.photos && poi.photos.length > 0 && poi.photos[0].url
? poi.photos[0].url
: DEFAULT_IMAGE;
: defaultImage;
const openTime =
cleanField(poi.business?.opentime_week) ||
@@ -81,10 +79,16 @@ function filterByPrice(
if (isNaN(cost)) return true;
switch (priceRange) {
case "under20":
return cost < 20;
case "under50":
return cost < 50;
case "20to50":
return cost >= 20 && cost <= 50;
case "50to100":
return cost >= 50 && cost <= 100;
case "over50":
return cost > 50;
case "over100":
return cost > 100;
default:
@@ -103,8 +107,11 @@ export async function POST(req: Request) {
priceRange = "any",
cuisine = "不限",
userId = "",
scene = "eat" as SceneType,
} = body;
const sceneConfig = getSceneConfig(scene === "drink" ? "drink" : "eat");
if (!lat || !lng) {
return NextResponse.json(
{ error: "无法获取位置信息,请允许定位权限后重试" },
@@ -125,7 +132,7 @@ export async function POST(req: Request) {
url.searchParams.set("key", apiKey);
url.searchParams.set("location", `${lng},${lat}`);
url.searchParams.set("radius", String(radius));
url.searchParams.set("types", "050000");
url.searchParams.set("types", sceneConfig.poiTypes);
url.searchParams.set("show_fields", "business,photos");
url.searchParams.set("sortrule", "weight");
@@ -141,24 +148,26 @@ export async function POST(req: Request) {
let restaurants: Restaurant[] = [];
if (amapData.status === "1" && amapData.pois?.length > 0) {
let results: Restaurant[] = amapData.pois.map(mapPoiToRestaurant);
let results: Restaurant[] = amapData.pois.map(
(poi: AmapPoiV5) => mapPoiToRestaurant(poi, sceneConfig.defaultImage),
);
results = filterByPrice(results, priceRange);
restaurants = results.slice(0, 15);
}
if (restaurants.length === 0) {
return NextResponse.json(
{ error: "附近没有找到餐厅,试试扩大搜索范围或换个菜系" },
{ error: sceneConfig.emptyError },
{ status: 404 },
);
}
const roomId = await createRoom(restaurants, userId);
const roomId = await createRoom(restaurants, userId, sceneConfig.key);
return NextResponse.json({ roomId, restaurants });
} catch (e) {
console.error("Failed to create room:", e);
return NextResponse.json(
{ error: "搜索餐厅失败,请检查网络后重试" },
{ error: "搜索失败,请检查网络后重试" },
{ status: 500 },
);
}
+9 -2
View File
@@ -10,8 +10,11 @@ import {
Sparkles,
ChevronRight,
Loader2,
Coffee,
} from "lucide-react";
import { getUserId } from "@/lib/userId";
import { getSceneConfig } from "@/lib/sceneConfig";
import type { SceneType } from "@/types";
export default function InvitePage() {
const params = useParams<{ id: string }>();
@@ -22,8 +25,11 @@ export default function InvitePage() {
"loading",
);
const [userCount, setUserCount] = useState(0);
const [scene, setScene] = useState<SceneType>("eat");
const [joining, setJoining] = useState(false);
const sceneConfig = getSceneConfig(scene);
useEffect(() => {
fetch(`/api/room/${roomId}`)
.then((res) => {
@@ -32,6 +38,7 @@ export default function InvitePage() {
})
.then((data) => {
setUserCount(data.userCount ?? 0);
if (data.scene) setScene(data.scene);
setStatus("ready");
})
.catch(() => setStatus("not_found"));
@@ -89,7 +96,7 @@ export default function InvitePage() {
transition={{ duration: 0.5 }}
>
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-emerald-500 shadow-lg shadow-emerald-200">
<Utensils size={28} className="text-white" />
{scene === "drink" ? <Coffee size={28} className="text-white" /> : <Utensils size={28} className="text-white" />}
</div>
<h1 className="mt-5 text-3xl font-black tracking-tight text-zinc-900">
@@ -107,7 +114,7 @@ export default function InvitePage() {
transition={{ duration: 0.5, delay: 0.1 }}
>
<p className="text-center text-lg font-bold text-zinc-800">
{sceneConfig.inviteText}
</p>
<div className="flex items-center gap-2 text-sm text-zinc-500">
<span className="rounded-full bg-white px-2.5 py-0.5 font-mono text-base font-bold tracking-widest text-emerald-600 shadow-sm">
+46 -18
View File
@@ -7,7 +7,8 @@ import { Plus, LogIn, Loader2, MapPin, Navigation, X, Users, Heart, Sparkles, Ch
import { getUserId, getCachedProfile, getCachedPreferences } from "@/lib/userId";
import { getAvatarBg } from "@/lib/avatars";
import AuthModal from "@/components/AuthModal";
import type { UserProfile } from "@/types";
import { SCENES, getSceneConfig } from "@/lib/sceneConfig";
import type { UserProfile, SceneType } from "@/types";
interface LocationSuggestion {
id: string;
@@ -26,15 +27,6 @@ const DISTANCE_OPTIONS = [
{ label: "5km", value: 5000 },
] as const;
const PRICE_OPTIONS = [
{ label: "不限", value: "any" },
{ label: "¥50以下", value: "under50" },
{ label: "¥50-100", value: "50to100" },
{ label: "¥100+", value: "over100" },
] as const;
const HOT_CUISINES = ["火锅", "日料", "烧烤", "西餐", "川菜", "咖啡甜品", "小吃快餐"] as const;
type GpsResult =
| { ok: true; lat: number; lng: number }
| { ok: false; reason: "unsupported" | "denied" | "timeout" | "unknown" };
@@ -95,6 +87,9 @@ export default function LandingPage() {
const [gpsCoords, setGpsCoords] = useState<{ lat: number; lng: number } | null>(null);
const [gpsLocationName, setGpsLocationName] = useState<string | null>(null);
const [scene, setScene] = useState<SceneType>("eat");
const sceneConfig = getSceneConfig(scene);
const [profile, setProfile] = useState<UserProfile | null>(null);
const [authModalOpen, setAuthModalOpen] = useState(false);
@@ -108,6 +103,12 @@ export default function LandingPage() {
if (prefs.radius) setRadius(prefs.radius);
}, []);
const handleSceneChange = useCallback((s: SceneType) => {
setScene(s);
setCuisine("");
setPriceRange("any");
}, []);
const doGpsLocate = useCallback(async () => {
setGpsStatus("locating");
const result = await requestGps();
@@ -208,12 +209,12 @@ export default function LandingPage() {
setLoading(true);
try {
setLoadingText("正在搜索周边美食...");
setLoadingText(sceneConfig.loadingText);
const res = await fetch("/api/room/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...coords, radius, priceRange, cuisine, userId: getUserId() }),
body: JSON.stringify({ ...coords, radius, priceRange, cuisine, userId: getUserId(), scene }),
});
const data = await res.json();
@@ -289,7 +290,7 @@ export default function LandingPage() {
便
</p>
<p className="mt-3 max-w-xs text-center text-sm leading-relaxed text-zinc-500">
{sceneConfig.subtitle}
</p>
</motion.div>
@@ -329,7 +330,34 @@ export default function LandingPage() {
</motion.div>
<motion.div
className="mt-10 flex w-full max-w-xs flex-col gap-3"
className="mt-8 flex items-center justify-center gap-2"
initial={{ y: 10, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ duration: 0.4, delay: 0.12 }}
>
{SCENES.map((s) => {
const cfg = getSceneConfig(s);
const active = scene === s;
return (
<button
key={s}
onClick={() => handleSceneChange(s)}
disabled={loading}
className={`flex items-center gap-1.5 rounded-full px-4 py-2 text-sm font-semibold transition-all disabled:opacity-50 ${
active
? "bg-emerald-500 text-white shadow-md shadow-emerald-200"
: "bg-zinc-100 text-zinc-500 hover:bg-zinc-200"
}`}
>
<span className="text-base leading-none">{cfg.emoji}</span>
{cfg.label}
</button>
);
})}
</motion.div>
<motion.div
className="mt-5 flex w-full max-w-xs flex-col gap-3"
initial={{ y: 20, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ duration: 0.5, delay: 0.15 }}
@@ -438,11 +466,11 @@ export default function LandingPage() {
<div className="flex flex-col gap-2 rounded-xl border border-zinc-100 bg-zinc-50/50 px-3 py-2.5">
<div className="flex items-center gap-3">
<span className="w-8 shrink-0 text-xs font-medium text-zinc-400"></span>
<span className="w-8 shrink-0 text-xs font-medium text-zinc-400">{sceneConfig.tagLabel}</span>
<div className="relative flex flex-1 items-center">
<input
type="text"
placeholder="想吃什么?(留空则不限)"
placeholder={sceneConfig.tagPlaceholder}
value={cuisine}
onChange={(e) => setCuisine(e.target.value)}
disabled={loading}
@@ -463,7 +491,7 @@ export default function LandingPage() {
<span className="w-8 shrink-0 text-xs font-medium text-zinc-400"></span>
<div className="flex flex-wrap items-center gap-1.5">
<Flame size={11} className="shrink-0 text-orange-400" />
{HOT_CUISINES.map((tag) => (
{sceneConfig.hotTags.map((tag) => (
<button
key={tag}
type="button"
@@ -505,7 +533,7 @@ export default function LandingPage() {
<div className="flex items-center gap-3">
<span className="w-8 shrink-0 text-xs font-medium text-zinc-400"></span>
<div className="flex flex-wrap gap-1.5">
{PRICE_OPTIONS.map((opt) => (
{sceneConfig.priceOptions.map((opt) => (
<button
key={opt.value}
type="button"
+7 -2
View File
@@ -7,6 +7,7 @@ import SwipeDeck from "@/components/SwipeDeck";
import LeaveConfirmModal from "@/components/LeaveConfirmModal";
import { useRoomPolling } from "@/hooks/useRoomPolling";
import { getUserId } from "@/lib/userId";
import { getSceneConfig } from "@/lib/sceneConfig";
export default function RoomPage() {
const params = useParams<{ id: string }>();
@@ -21,7 +22,7 @@ export default function RoomPage() {
const {
userCount, match, matchType, matchLikes, runnerUps, likeCounts, swipeCounts,
restaurants, notFound, mutate, creatorId, locked, users, userProfiles,
restaurants, notFound, mutate, creatorId, locked, users, userProfiles, scene,
} = useRoomPolling(roomId);
useEffect(() => {
@@ -107,11 +108,13 @@ export default function RoomPage() {
const initialIndex = swipeCounts[userId] ?? 0;
const ready = joined && userId && restaurants.length > 0;
const sceneConfig = getSceneConfig(scene);
if (!ready) {
return (
<div className="flex h-dvh flex-col items-center justify-center gap-3 bg-background">
<div className="h-6 w-6 animate-spin rounded-full border-2 border-zinc-300 border-t-emerald-500" />
<p className="text-sm text-zinc-400">...</p>
<p className="text-sm text-zinc-400">...</p>
</div>
);
}
@@ -129,6 +132,7 @@ export default function RoomPage() {
swipeCounts={swipeCounts}
totalCards={restaurants.length}
userProfiles={userProfiles}
scene={scene}
/>
<SwipeDeck
restaurants={restaurants}
@@ -145,6 +149,7 @@ export default function RoomPage() {
userProfiles={userProfiles}
onReset={handleReset}
onNarrow={handleNarrow}
scene={scene}
/>
<LeaveConfirmModal
open={showLeaveConfirm}