diff --git a/README.md b/README.md index 64536c8..1d975e2 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,11 @@ ### 前端 (salon) -- `PAYMENT_API_URL`: payjsapi 公网地址,**生产环境必填**(如 `https://api.example.com`),否则会连不上 payjsapi 导致「服务不可用」 -- `ROOT_DOMAIN`: 根域名,未设 PAYMENT_API_URL 时用于推导 `https://api.${ROOT_DOMAIN}`,默认 `hackrobot.cn` -- `PAYJSAPI_PORT`: 开发时 payjsapi 端口,默认 `8007` +- `PAYMENT_API_URL`: salonapi 公网地址,**生产环境必填**(如 `https://api.nomadyt.com`) +- `ROOT_DOMAIN`: 根域名,未设 PAYMENT_API_URL 时用于推导 `https://api.${ROOT_DOMAIN}`,默认 `nomadyt.com` +- `NEXT_PUBLIC_SITE_URL`: 前端站点地址,线上 `https://nomadyt.com` +- `PAYJSAPI_PORT`: 开发时 salonapi 端口,默认 `8007` +- `ZPAY_PID` / `ZPAY_KEY`、`XORPAY_AID` / `XORPAY_SECRET`:支付平台凭证,与 salonapi 一致。用于 pay/status 兜底直接查询,**本地无回调时依赖此检测支付** - `NEXT_PUBLIC_POCKETBASE_URL` / `POCKETBASE_URL`: PocketBase 地址 - `POCKETBASE_EMAIL` / `POCKETBASE_PASSWORD`: PocketBase 管理员账号(用于 join API 写 solanRed) @@ -27,8 +29,8 @@ ## 启动 ```bash -# 1. 启动 payjsapi -cd C:\project\payjsapi +# 1. 启动 salonapi(后端,端口 8007) +cd C:\project\salonapi python run.py # 2. 启动 salon 前端 @@ -39,6 +41,15 @@ npm run dev 访问 http://localhost:3002 +## 本地支付测试 + +PC 扫码支付后自动检测逻辑(参考 nomadvip): +1. 优先 salonapi `/salon/order_status` +2. 失败时 **直接向 zpay/xorpay 查询** 兜底(不依赖回调) +3. 检测到 paid 后调用 complete-order → 跳转报名成功页 + +若仍无反应:点击「支付完成?点此手动检查」;确认 ZPAY_PID/KEY、XORPAY_AID/SECRET 与 salonapi 一致 + ## Getting started To make it easy for you to get started with GitLab, here's a list of recommended next steps. diff --git a/app/api/join/by-wechat/route.ts b/app/api/join/by-wechat/route.ts index b3c91d2..ddbd95e 100644 --- a/app/api/join/by-wechat/route.ts +++ b/app/api/join/by-wechat/route.ts @@ -21,7 +21,11 @@ export async function GET(request: NextRequest) { } try { - const { status, data } = await getSalonApi(request, `/api/salon/join/by-wechat?wechat_id=${encodeURIComponent(wechatId)}`); + const { status, data } = await getSalonApi( + request, + `/api/salon/join/by-wechat?wechat_id=${encodeURIComponent(wechatId)}`, + { timeoutMs: 8000 } + ); if (status === 200 && data && typeof data === "object") { return NextResponse.json(data); } @@ -40,13 +44,16 @@ export async function GET(request: NextRequest) { const filter = encodeURIComponent(`wechatId = "${escaped}"`); try { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 8000); const res = await fetch( `${base}/api/collections/${pb.joinCollection}/records?filter=${filter}&sort=-created&perPage=1`, { headers: { Authorization: `Bearer ${token}` }, cache: "no-store", + signal: controller.signal, } - ); + ).finally(() => clearTimeout(timeoutId)); if (!res.ok) return NextResponse.json(empty); const data = await res.json(); const items = Array.isArray(data?.items) ? data.items : []; diff --git a/app/api/join/route.ts b/app/api/join/route.ts index 61cbb49..0f696fe 100644 --- a/app/api/join/route.ts +++ b/app/api/join/route.ts @@ -46,6 +46,7 @@ export async function POST(request: NextRequest) { const region = String(formData.region || "").trim(); const availableTime = String(formData.available_time || "").trim(); const isVolunteer = !!formData.is_volunteer; + const qualify = !!formData.qualify; // 女性且小红书帖子>10 时自动通过审核 /** reason 仅存自我介绍,不合并其他字段 */ const contact = wechatOrPhone || wechat || phone; if (!nickname || !session || !agreeRules) { @@ -85,6 +86,7 @@ export async function POST(request: NextRequest) { age_range: ageRangeForRecord, first_time: firstTime, is_volunteer: isVolunteer, + qualify, }; if (phone.trim()) { record.phone = phone.trim(); @@ -133,6 +135,7 @@ async function tryPocketBaseDirect( const base = pb.url.replace(/\/$/, ""); const url = `${base}/api/collections/${pb.joinCollection}/records`; + const qualify = !!(record.qualify ?? false); const body: Record = { user_id: record.user_id, nickname: record.nickname, @@ -149,6 +152,7 @@ async function tryPocketBaseDirect( amount: record.amount ?? 0, xiaohongshu_url: record.xiaohongshu_url ?? "", is_volunteer: record.is_volunteer ?? false, + is_approved: qualify, age_range: record.age_range ?? "", first_time: record.first_time ?? "", }; diff --git a/app/api/join/volunteers/route.ts b/app/api/join/volunteers/route.ts index c56a190..218d0ee 100644 --- a/app/api/join/volunteers/route.ts +++ b/app/api/join/volunteers/route.ts @@ -1,19 +1,33 @@ -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { getAdminToken } from "@/app/lib/pocketbase/admin"; import { getPocketBaseConfig } from "@/config/services.config"; +import { getSalonApi } from "@/app/lib/salonApi"; + +/** 获取志愿者列表 - 优先 salonapi,回退直连 PocketBase */ +export async function GET(request: NextRequest) { + try { + const { status, data } = await getSalonApi(request, "/api/salon/join/volunteers", { + timeoutMs: 8000, + }); + if (status === 200 && data && typeof data === "object") { + const v = (data as { volunteer?: unknown }).volunteer; + const payload = v && typeof v === "object" ? { volunteer: v } : { volunteer: null }; + return NextResponse.json(payload); + } + } catch { + // salonapi 不可用,回退直连 PocketBase + } -/** 获取志愿者列表 - solanRed 中 is_volunteer=true 的记录 */ -export async function GET() { const token = await getAdminToken(); if (!token) { - return NextResponse.json({ ok: true, volunteers: [] }, { status: 200 }); + return NextResponse.json({ ok: true, volunteer: null }, { status: 200 }); } const pb = getPocketBaseConfig(); const base = pb.url.replace(/\/$/, ""); try { - const filter = encodeURIComponent('is_volunteer=true && is_approved=true'); + const filter = encodeURIComponent("is_volunteer = true && is_approved = true"); const res = await fetch( `${base}/api/collections/${pb.joinCollection}/records?filter=${filter}&sort=-created&perPage=20`, { @@ -22,19 +36,20 @@ export async function GET() { } ); if (!res.ok) { - return NextResponse.json({ ok: true, volunteers: [] }, { status: 200 }); + return NextResponse.json({ ok: true, volunteer: null }, { status: 200 }); } const data = await res.json(); const items = Array.isArray(data?.items) ? data.items : []; - const volunteers = items.map( - (r: { nickname?: string; xiaohongshu_nickname?: string; media?: string; xiaohongshu_url?: string }) => ({ - nickname: String(r?.xiaohongshu_nickname || r?.nickname || "").trim() || "志愿者", - avatar: String(r?.media || "").trim() || undefined, - xiaohongshu_url: String(r?.xiaohongshu_url || "").trim() || undefined, - }) - ); - return NextResponse.json({ ok: true, volunteers }); + const rec = items[0] ?? null; + const volunteer = rec + ? { + nickname: String(rec?.xiaohongshu_nickname || rec?.nickname || "").trim() || "志愿者", + avatar: String(rec?.media || "").trim() || undefined, + xiaohongshu_url: String(rec?.xiaohongshu_url || "").trim() || undefined, + } + : null; + return NextResponse.json({ ok: true, volunteer }); } catch { - return NextResponse.json({ ok: true, volunteers: [] }, { status: 200 }); + return NextResponse.json({ ok: true, volunteer: null }, { status: 200 }); } } diff --git a/app/api/pay/complete-order/route.ts b/app/api/pay/complete-order/route.ts new file mode 100644 index 0000000..6baf88a --- /dev/null +++ b/app/api/pay/complete-order/route.ts @@ -0,0 +1,151 @@ +/** + * 本地直接确认支付:检测到 paid 后立即写入 PocketBase,不依赖 salonapi + * 用于扫码页 doConfirm,避免「检测到支付,正在确认…」等待过久 + */ +import { NextRequest, NextResponse } from "next/server"; +import { getAdminToken } from "@/app/lib/pocketbase/admin"; +import { getPocketBaseConfig, SITE_ID } from "@/config/services.config"; +import { queryZPayOrderStatus } from "@/app/lib/zpayStatus"; +import { queryXorPayOrderStatus } from "@/app/lib/xorpayStatus"; + +function parseOrderId(orderId: string): { userId: string; payType: string } { + const id = (orderId || "").trim(); + if (!id.includes("_order_")) return { userId: "", payType: "unknown" }; + const prefix = id.split("_order_")[0]; + const lastUnderscore = prefix.lastIndexOf("_"); + if (lastUnderscore > 0) { + return { + userId: prefix.substring(0, lastUnderscore), + payType: prefix.substring(lastUnderscore + 1).toLowerCase(), + }; + } + return { userId: prefix, payType: "unknown" }; +} + +export async function POST(request: NextRequest) { + try { + const body = await request.json().catch(() => ({})); + const orderId = String(body?.order_id || "").trim(); + if (!orderId) { + return NextResponse.json({ ok: false, error: "缺少 order_id" }, { status: 400 }); + } + + const { userId, payType } = parseOrderId(orderId); + if (!userId || payType !== "salon") { + return NextResponse.json({ ok: false, error: "订单格式无效" }, { status: 400 }); + } + + const [zpay, xorpay] = await Promise.all([ + queryZPayOrderStatus(orderId, 5000), + queryXorPayOrderStatus(orderId, 5000), + ]); + + const paid = zpay?.paid || xorpay?.paid; + if (!paid) { + return NextResponse.json({ ok: false, error: "订单未支付" }, { status: 400 }); + } + + const moneyYuan = parseFloat(zpay?.money || xorpay?.payPrice || "0") || 0; + const amountCents = moneyYuan > 0 ? Math.round(moneyYuan * 100) : 100; + + const token = await getAdminToken(); + if (!token) { + return NextResponse.json({ ok: false, error: "PocketBase 未配置" }, { status: 503 }); + } + + const pb = getPocketBaseConfig(); + const base = pb.url.replace(/\/$/, ""); + + const escapedUserId = userId.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const filter = encodeURIComponent(`user_id = "${escapedUserId}"`); + + const listRes = await fetch( + `${base}/api/collections/${pb.joinCollection}/records?filter=${filter}&sort=-created&perPage=1`, + { + headers: { Authorization: `Bearer ${token}` }, + cache: "no-store", + } + ); + + if (!listRes.ok) { + return NextResponse.json({ ok: false, error: "查询记录失败" }, { status: 500 }); + } + + const listData = await listRes.json().catch(() => ({})); + const items = Array.isArray(listData?.items) ? listData.items : []; + const rec = items[0] ?? null; + + if (rec?.id) { + const patchRes = await fetch( + `${base}/api/collections/${pb.joinCollection}/records/${rec.id}`, + { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ + order_id: orderId, + amount: amountCents, + vip: true, + }), + } + ); + if (!patchRes.ok) { + const err = await patchRes.json().catch(() => ({})); + console.warn("[pay/complete-order] solanRed patch failed:", patchRes.status, err); + } + } + + const siteVipFilter = encodeURIComponent( + `user_id = "${escapedUserId}" && site_id = "${SITE_ID}"` + ); + const siteVipList = await fetch( + `${base}/api/collections/site_vip/records?filter=${siteVipFilter}&perPage=1`, + { + headers: { Authorization: `Bearer ${token}` }, + cache: "no-store", + } + ); + + if (siteVipList.ok) { + const svData = await siteVipList.json().catch(() => ({})); + const svItems = svData?.items ?? []; + if (svItems.length > 0) { + await fetch( + `${base}/api/collections/site_vip/records/${svItems[0].id}`, + { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ order_id: orderId }), + } + ); + } else { + await fetch(`${base}/api/collections/site_vip/records`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ + user_id: userId, + site_id: SITE_ID, + order_id: orderId, + expires_at: "", + }), + }); + } + } + + return NextResponse.json({ ok: true }); + } catch (error) { + console.error("[pay/complete-order] error:", error); + return NextResponse.json( + { ok: false, error: error instanceof Error ? error.message : "操作失败" }, + { status: 500 } + ); + } +} diff --git a/app/api/pay/route.ts b/app/api/pay/route.ts index 0d3bd91..4b9af83 100644 --- a/app/api/pay/route.ts +++ b/app/api/pay/route.ts @@ -66,14 +66,13 @@ function buildQrHtml( imgSrc: string, returnUrl: string, orderId: string, - opts?: { channel?: string; successDesc?: string; confirmUrl?: string } + opts?: { channel?: string; confirmUrl?: string } ): string { const ch = (opts?.channel || "wxpay").toLowerCase(); const isWx = ch === "wxpay" || ch === "wx" || ch === "wechat"; const title = isWx ? "微信扫码支付" : "支付宝扫码支付"; const hint = isWx ? "请使用微信扫描下方二维码完成支付" : "请使用支付宝扫描下方二维码完成支付"; - const successDesc = opts?.successDesc || "支付成功,即将跳转"; - const confirmUrl = opts?.confirmUrl || "/api/salon/complete-order"; + const confirmUrl = opts?.confirmUrl || "/api/pay/complete-order"; const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c); return ` @@ -96,14 +95,6 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;} .countdown-num{font-size:1rem;font-weight:700;color:#1e293b;line-height:1;} .countdown-unit{font-size:9px;color:#94a3b8;} .tip{font-size:13px;color:#64748b;margin-top:16px;} -.success-wrap{display:none;} -.success-wrap.show{display:block;} -.wait-wrap.hide{display:none;} -.success-icon{font-size:4rem;margin-bottom:16px;animation:scaleIn .4s ease;} -.success-title{font-size:1.25rem;color:#16a34a;font-weight:600;margin-bottom:8px;} -.success-desc{color:#64748b;font-size:14px;margin-bottom:24px;} -.success-countdown{font-size:1.5rem;font-weight:700;color:#667eea;} -@keyframes scaleIn{from{transform:scale(0);opacity:0;}to{transform:scale(1);opacity:1;}} @keyframes pulse{0%,100%{opacity:1;}50%{opacity:.7;}} .pulse{animation:pulse 2s ease-in-out infinite;} @@ -129,12 +120,6 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}

等待支付中...

-
-
-
支付成功
-
${esc(successDesc)}
-
3 秒后跳转
-
`; @@ -401,8 +394,7 @@ export async function POST(request: NextRequest) { const rawOrderId = String(resData.order_id || created.orderId).trim(); const html = buildQrHtml(imgSrc, safeReturnUrl, rawOrderId, { channel: resData.channel || "wxpay", - successDesc: "支付成功,申请已提交", - confirmUrl: "/api/salon/complete-order", + confirmUrl: "/api/pay/complete-order", }); const response = new NextResponse(html, { status: 200, diff --git a/app/api/pay/status/route.ts b/app/api/pay/status/route.ts index a1ca926..59e26dc 100644 --- a/app/api/pay/status/route.ts +++ b/app/api/pay/status/route.ts @@ -1,5 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; import { getApiUrlFromRequest, getPaymentConfig } from "@/config/services.config"; +import { queryXorPayOrderStatus } from "@/app/lib/xorpayStatus"; +import { queryZPayOrderStatus } from "@/app/lib/zpayStatus"; function resolvePayApiUrl(request: NextRequest): string { const config = getPaymentConfig(); @@ -8,6 +10,10 @@ function resolvePayApiUrl(request: NextRequest): string { return (getApiUrlFromRequest(hostHeader) || config.apiUrl).replace(/\/$/, ""); } +/** + * 支付状态查询:salonapi 优先,失败时直接向 zpay/xorpay 查询兜底 + * 参考 nomadvip,保证本地无回调时也能检测到支付 + */ export async function GET(request: NextRequest) { const orderId = request.nextUrl.searchParams.get("order_id"); if (!orderId) { @@ -20,27 +26,36 @@ export async function GET(request: NextRequest) { const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); const apiUrl = resolvePayApiUrl(request); - const url = `${apiUrl}/salon/order_status?order_id=${encodeURIComponent(orderId)}`; + const salonUrl = `${apiUrl}/salon/order_status?order_id=${encodeURIComponent(orderId)}`; - try { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 3000); - const res = await fetch(url, { - cache: "no-store", - signal: controller.signal, - }).finally(() => clearTimeout(timeout)); - const data = await res.json().catch(() => ({})); - const paid = !!data?.paid; - if (paid) { - return NextResponse.json({ ok: true, paid: true }); + // 并行查询 salonapi、xorpay、zpay,任一返回 paid 即立即返回,避免串行阻塞 + const salonPaid = (async () => { + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 3000); + const res = await fetch(salonUrl, { + cache: "no-store", + signal: controller.signal, + }).finally(() => clearTimeout(timeout)); + const data = await res.json().catch(() => ({})); + return !!data?.paid; + } catch (error) { + console.warn( + "[pay/status] salonapi order_id=%s url=%s error=%s", + orderId, + salonUrl, + error instanceof Error ? error.message : String(error) + ); + return false; } - } catch (error) { - console.log( - "[pay/status] error order_id=%s error=%s", - orderId, - error instanceof Error ? error.message : String(error) - ); - } + })(); + const xorpayPaid = queryXorPayOrderStatus(orderId, 5000).then((r) => r?.paid ?? false); + const zpayPaid = queryZPayOrderStatus(orderId, 5000).then((r) => r?.paid ?? false); + + const [salon, xorpay, zpay] = await Promise.all([salonPaid, xorpayPaid, zpayPaid]); + if (salon || xorpay || zpay) { + return NextResponse.json({ ok: true, paid: true }); + } return NextResponse.json({ ok: true, paid: false }); } diff --git a/app/components/HomeContent.tsx b/app/components/HomeContent.tsx new file mode 100644 index 0000000..46e202d --- /dev/null +++ b/app/components/HomeContent.tsx @@ -0,0 +1,214 @@ +"use client"; + +import { useEffect, useState } from "react"; +import Link from "next/link"; +import HeroSection from "./HeroSection"; +import MyRegistrationStatus from "./MyRegistrationStatus"; +import SessionCard from "./SessionCard"; +import HostLink from "./HostLink"; +import Footer from "./Footer"; +import Header from "./Header"; +import { getSessionsWithDates, HOSTS } from "@/config/home.config"; + +interface HomeContentProps { + initialVolunteer: { nickname: string; avatar?: string; xiaohongshu_url?: string } | null; +} + +const VOLUNTEER_BIO = "签到、茶歇准备、拍照摄像。"; + +export default function HomeContent({ initialVolunteer }: HomeContentProps) { + const [volunteer, setVolunteer] = useState(initialVolunteer); + + useEffect(() => { + fetch("/api/join/volunteers") + .then((r) => r.json()) + .then((d) => d?.volunteer && setVolunteer(d.volunteer)) + .catch(() => {}); + }, []); + + return ( +
+
+ + +
+ + {/* 是什么 / 不是什么 - 小红书风格 */} +
+
+
+
+

+ 是什么 · 适合谁 +

+
    +
  • · 周末同城轻社交,loft民宿见~
  • +
  • · 4–8 人小圈子,聊得来就多聊
  • +
  • · 第一次来也完全 OK
  • +
+
+
+

+ 不是什么 · 不适合谁 +

+
    +
  • · 不是相亲局、卖课、强制破冰
  • +
  • · 只想线上聊、想加所有人微信的 pass
  • +
  • · 想销售引流、不尊重边界的 pass
  • +
+
+
+
+
+ + {/* 报名流程 */} +
+

+ 📋 怎么参加 +

+
+
+
+
1
+

填表

+
+
+
2
+

审核

+
+
+
3
+

通过后联系你确认

+
+
+
+
+ + {/* 信任标签 */} +
+ 📍 公开场地 + 👥 4–8 人 + ✍️ 填表申请 + ☕ 茶歇 +
+ + {/* 本周场次 */} +
+

+ 📅 本周活动 +

+
+ {getSessionsWithDates().map((s, i) => ( + + ))} +
+
+ + {/* 活动亮点 */} +
+

+ 💡 活动亮点 +

+
+
+ {[ + { icon: "😌", title: "氛围轻松", desc: "loft民宿里的小聚,不用尬聊,聊得来就多聊~" }, + { icon: "🛡️", title: "安全靠谱", desc: "公开场地,地址提前说。尊重边界,不追问隐私。" }, + { icon: "👍", title: "第一次也 OK", desc: "很多人都是第一次来,小圈子人数可控~" }, + { icon: "✍️", title: "填表就行", desc: "不用注册、不用先付,填个表就好。" }, + ].map((item) => ( +
+ {item.icon} +
+

{item.title}

+

{item.desc}

+
+
+ ))} +
+
+
+ + {/* 发起人 + 志愿者(有志愿者时替换 host-2 卡片) */} +
+

+ 👤 发起人 +

+
+ {HOSTS.map((host) => { + const isHost2 = host.id === "host-2"; + const displayHost = isHost2 && volunteer + ? { ...host, name: volunteer.nickname, avatar: volunteer.avatar || host.avatar, bio: VOLUNTEER_BIO } + : host; + return ( + + ); + })} +
+
+ + {/* FAQ */} +
+

+ 常见问题 +

+
+ {[ + { q: "提交后多久会收到确认?", a: "活动前 1–2 天会联系,微信/短信确认。不匹配不会反复打扰~", icon: "⏱️" }, + { q: "第一次参加可以吗?", a: "可以呀!很多人都是第一次来。4–8 人小圈子、公开场地,聊得来就多聊~", icon: "✨" }, + { q: "临时有事怎么办?", a: "随时可以退出,提前说一声就行~", icon: "🔄" }, + ].map((faq) => ( +
+ + {faq.icon} +

{faq.q}

+ +
+
+ +

{faq.a}

+
+
+ ))} +
+
+ + {/* CTA - 移动端隐藏,只保留底部悬浮去报名 */} +
+ + 立即报名 + +

+ 先填表,我们会根据场次联系你~ +

+
+
+ + {/* 移动端悬浮 CTA */} +
+ + 去报名 + +
+ +
+
+ ); +} diff --git a/app/components/HostLink.tsx b/app/components/HostLink.tsx index b0cd815..1d09757 100644 --- a/app/components/HostLink.tsx +++ b/app/components/HostLink.tsx @@ -8,14 +8,20 @@ interface HostLinkProps { /** 志愿者招募:无审核通过时显示「立即申请」+ 免费标识 */ ctaText?: string; showFreeBadge?: boolean; + /** 卡片有 link 样式但不可点击跳转 */ + noLink?: boolean; } -/** 移动端优先尝试唤醒小红书 app,PC 新窗口打开 */ -export default function HostLink({ host, ctaText, showFreeBadge }: HostLinkProps) { +/** 移动端优先尝试唤醒小红书 app,PC 新窗口打开。noLink 时仅展示,不跳转 */ +export default function HostLink({ host, ctaText, showFreeBadge, noLink }: HostLinkProps) { const href = "link" in host ? host.link : `/host/${host.id}`; const isXiaohongshu = typeof href === "string" && (href.includes("xhslink.com") || href.includes("xiaohongshu.com")); const handleClick = (e: React.MouseEvent) => { + if (noLink) { + e.preventDefault(); + return; + } if (!isXiaohongshu || typeof href !== "string") return; const isMobile = /Android|iPhone|iPad|iPod|webOS|Mobile/i.test(navigator.userAgent); if (isMobile) { @@ -27,14 +33,9 @@ export default function HostLink({ host, ctaText, showFreeBadge }: HostLinkProps if (typeof href !== "string") return null; - return ( - + const cardClassName = "flex gap-3 sm:gap-4 p-4 sm:p-5 rounded-xl sm:rounded-2xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 hover:border-amber-200 dark:hover:border-amber-900/50 hover:shadow-lg transition-all"; + const cardContent = ( + <>
{host.name}
@@ -52,6 +53,26 @@ export default function HostLink({ host, ctaText, showFreeBadge }: HostLinkProps {ctaText ?? "查看主页"} → + + ); + + if (noLink) { + return ( +
+ {cardContent} +
+ ); + } + + return ( + + {cardContent} ); } diff --git a/app/components/MyRegistrationStatus.tsx b/app/components/MyRegistrationStatus.tsx new file mode 100644 index 0000000..bad5a63 --- /dev/null +++ b/app/components/MyRegistrationStatus.tsx @@ -0,0 +1,154 @@ +"use client"; + +import { useEffect, useState } from "react"; +import Image from "next/image"; +import Link from "next/link"; + +const WECHAT_STORAGE_KEY = "salon_join_wechat"; + +interface RecordData { + id?: string; + wechatId?: string; + nickname?: string; + media?: string; + is_volunteer?: boolean; +} + +interface UserRecord { + hasRecord: boolean; + record: RecordData | null; + isComplete: boolean; + isApproved: boolean; + isRejected: boolean; + vip: boolean; +} + +function getStatusLabel(data: UserRecord): string { + if (data.isComplete || (data.vip && data.hasRecord)) return "报名成功"; + if (data.isRejected) return "审核拒绝"; + if (data.isApproved) return "审核通过"; + return "审核中"; +} + +function getStatusColor(status: string): string { + if (status === "报名成功") return "bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300"; + if (status === "审核通过") return "bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"; + if (status === "审核拒绝") return "bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400"; + return "bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400"; +} + +export default function MyRegistrationStatus() { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + + const fetchStatus = () => { + if (typeof window === "undefined") return; + try { + const stored = localStorage.getItem(WECHAT_STORAGE_KEY); + const wechatId = (stored || "").trim(); + if (!wechatId) { + setLoading(false); + setData(null); + return; + } + setLoading(true); + fetch(`/api/join/by-wechat?wechat_id=${encodeURIComponent(wechatId)}`) + .then((r) => r.json()) + .then((d) => { + if (d?.hasRecord) { + const rec = d.record ?? null; + setData({ + hasRecord: !!d.hasRecord, + record: rec ? { ...rec, wechatId: rec.wechatId || wechatId } : null, + isComplete: !!d.isComplete, + isApproved: !!d.isApproved, + isRejected: !!d.isRejected, + vip: !!d.vip, + }); + } else { + setData(null); + } + }) + .catch(() => setData(null)) + .finally(() => setLoading(false)); + } catch { + setLoading(false); + } + }; + + useEffect(() => { + if (typeof window === "undefined") return; + let cancelled = false; + fetchStatus(); + const onUpdate = () => { + if (!cancelled) fetchStatus(); + }; + window.addEventListener("vip:updated", onUpdate); + return () => { + cancelled = true; + window.removeEventListener("vip:updated", onUpdate); + }; + }, []); + + if (loading || !data?.hasRecord || !data.record) return null; + + const rec = data.record; + const status = getStatusLabel(data); + const statusColor = getStatusColor(status); + + return ( +
+
+

+ 👤 我的报名 +

+
+
+
+ {rec.media ? ( + + ) : ( +
+ 👤 +
+ )} +
+ {rec.is_volunteer && ( + + 志愿者 + + )} +
+
+

+ {rec.nickname || "—"} +

+ {rec.wechatId && ( +

+ 微信号: {rec.wechatId} +

+ )} + + {status} + +
+ + 查看详情 → + +
+
+
+ ); +} diff --git a/app/join/page.tsx b/app/join/page.tsx index 5629f1f..8af762e 100644 --- a/app/join/page.tsx +++ b/app/join/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState, useEffect, type FormEvent } from "react"; +import { useState, useEffect, useRef, type FormEvent } from "react"; import Link from "next/link"; import ThemeToggle from "../components/ThemeToggle"; import { DIGITAL_NOMAD_WECHAT_QR } from "@/config/home.config"; @@ -11,9 +11,21 @@ const ageRangeOptions = ["18-22", "23-27", "28-32", "33-37", "38+"]; /** 微信号仅允许英文字母、数字、下划线、连字符 */ const WECHAT_REGEX = /^[a-zA-Z0-9_-]*$/; +const WECHAT_STORAGE_KEY = "salon_join_wechat"; + interface UserRecord { hasRecord: boolean; - record: { user_id?: string; amount?: number; order_id?: string; vip?: boolean } | null; + record: { + id?: string; + wechatId?: string; + user_id?: string; + nickname?: string; + media?: string; + amount?: number; + order_id?: string; + vip?: boolean; + is_volunteer?: boolean; + } | null; isComplete: boolean; isWechatFriend: boolean; isApproved: boolean; @@ -21,6 +33,39 @@ interface UserRecord { vip: boolean; } +function UserProfileCard({ record, showVolunteerTag }: { record: UserRecord["record"]; showVolunteerTag?: boolean }) { + if (!record || (!record.nickname && !record.media && !record.wechatId)) return null; + const isVolunteer = showVolunteerTag && record.is_volunteer; + return ( +
+
+ {record.media ? ( + + ) : ( +
+ 👤 +
+ )} + {isVolunteer && ( + + 志愿者 + + )} +
+
+

{record.nickname || "—"}

+ {record.wechatId && ( +

微信号: {record.wechatId}

+ )} +
+
+ ); +} + export default function JoinPage() { const [wechat, setWechat] = useState(""); const [userRecord, setUserRecord] = useState(null); @@ -48,9 +93,9 @@ export default function JoinPage() { const [error, setError] = useState(null); const [hydrated, setHydrated] = useState(false); - const [fromPaid, setFromPaid] = useState(() => - typeof window !== "undefined" && new URLSearchParams(window.location.search).get("paid") === "1" - ); + const [fromPaid, setFromPaid] = useState(false); + const [fromVolunteer, setFromVolunteer] = useState(false); + const initialWechatCheckDone = useRef(false); const fetchByWechat = async (w: string) => { if (!w.trim()) return; @@ -79,6 +124,11 @@ export default function JoinPage() { const w = wechat.trim(); if (!w) { setUserRecord(null); + try { + typeof window !== "undefined" && localStorage.removeItem(WECHAT_STORAGE_KEY); + } catch { + /* ignore */ + } return; } if (!WECHAT_REGEX.test(w)) { @@ -86,6 +136,11 @@ export default function JoinPage() { return; } setError(null); + try { + typeof window !== "undefined" && localStorage.setItem(WECHAT_STORAGE_KEY, w); + } catch { + /* ignore */ + } fetchByWechat(w); }; @@ -181,7 +236,7 @@ export default function JoinPage() { intro: "", age_range: ageRange, city: "深圳", - session: "digital-nomad", + session: fromVolunteer ? "volunteer" : "digital-nomad", education: "", graduation_year: "", agree_rules: true, @@ -191,6 +246,8 @@ export default function JoinPage() { why_join: "", region: "", available_time: "", + qualify, // 女性且小红书帖子>10 时自动通过审核 + is_volunteer: fromVolunteer, }), }); const data = await res.json(); @@ -199,6 +256,8 @@ export default function JoinPage() { } setQualify(qualify); setSubmitted(true); + // 提交成功后立即按微信号查询,用真实记录状态展示(审核中/审核通过等),避免刷新后状态不一致 + fetchByWechat(wechat.trim()); } catch (err) { setError(err instanceof Error ? err.message : "网络错误,请重试"); } finally { @@ -206,6 +265,32 @@ export default function JoinPage() { } }; + const clearWechatAndRecord = () => { + setUserRecord(null); + setWechat(""); + setXiaohongshuUrl(""); + setProfession(""); + setGender(""); + setAgeRange(""); + setAgreeRules(true); + setUrlError(null); + setProfile(null); + setValidating(false); + setSubmitted(false); + setSubmitting(false); + setQualify(false); + setError(null); + try { + if (typeof window !== "undefined") { + localStorage.removeItem(WECHAT_STORAGE_KEY); + localStorage.removeItem("join_pay_order"); + document.cookie = "join_pay_order=; path=/; max-age=0"; + } + } catch { + /* ignore */ + } + }; + const handlePayNow = () => { const rec = userRecord?.record; if (!rec?.user_id) return; @@ -221,10 +306,27 @@ export default function JoinPage() { }; useEffect(() => { + if (typeof window === "undefined") return; + const params = new URLSearchParams(window.location.search); + setFromPaid(params.get("paid") === "1"); + setFromVolunteer(params.get("volunteer") === "1"); + if (!initialWechatCheckDone.current) { + initialWechatCheckDone.current = true; + try { + const stored = localStorage.getItem(WECHAT_STORAGE_KEY); + const w = (stored || "").trim(); + if (w && WECHAT_REGEX.test(w)) { + setWechat(w); + fetchByWechat(w); + } + } catch { + /* ignore */ + } + } setHydrated(true); }, []); - // 成功报名:已支付 或 支付成功跳转 或 (好友且vip) + // 成功报名:已支付 或 支付成功跳转 或 (好友且vip) —— 仅以数据库状态为准,不依赖 submitted const showSuccess = fromPaid || (userRecord?.hasRecord && userRecord.isComplete) || (userRecord?.hasRecord && userRecord.isWechatFriend && userRecord.vip); // 有数据、非好友 → 只展示状态页:审核中/审核通过/审核拒绝 @@ -233,18 +335,20 @@ export default function JoinPage() { // 有数据、好友、非vip、未支付 → 支付状态页 const showPayPage = userRecord?.hasRecord && userRecord.isWechatFriend && !userRecord.vip && !userRecord.isComplete; - if (submitted || showSuccess) { + if (showSuccess) { + const baseRecord = userRecord?.record ?? null; + const displayRecord = baseRecord + ? { ...baseRecord, wechatId: baseRecord.wechatId || wechat || undefined } + : (wechat ? { wechatId: wechat } : null); return (
🎉

报名成功

-

感谢报名,活动前会联系你确认~

-

- {`本场收取少量场地分摊费29/人 -用于覆盖民宿/场地基础成本。 -通过审核后再确认名额,未确认无需支付。`} +

+ {displayRecord?.is_volunteer ? "要提前到场,金额可退" : "感谢报名,活动前会联系你确认~"}

+ 🏠 返回首页 @@ -281,18 +385,16 @@ export default function JoinPage() {

⏰ 通常会在 24 小时内完成审核,通过后用微信联系你。

)} -

- {`本场收取少量场地分摊费29/人 -用于覆盖民宿/场地基础成本。 -通过审核后再确认名额,未确认无需支付。`} -

- + + {status !== "approved" && ( + + )} 🏠 返回首页 @@ -314,7 +416,14 @@ export default function JoinPage() {
💰

支付场地茶歇费

-

29元/人,用于覆盖民宿/场地基础成本

+

1元/人,用于覆盖民宿/场地基础成本

+ + {userRecord?.record?.is_volunteer && ( +

+ 🌿 志愿者预付活动结束可退
+ 用于防止临时爽约 +

+ )} -
@@ -419,6 +521,16 @@ export default function JoinPage() {
+ {fromVolunteer && ( +
+

🙌 志愿者工作内容

+
    +
  • · 签到:现场签到、引导参与者
  • +
  • · 茶歇准备:协助布置茶歇、收拾整理
  • +
  • · 拍照摄像:记录活动现场,分享精彩瞬间
  • +
+
+ )}
@@ -460,6 +572,14 @@ export default function JoinPage() {
+ {fromVolunteer && ( +
+ +
+ )}
{ setXiaohongshuUrl(e.target.value); setUrlError(null); }} - onBlur={handleUrlBlur} - placeholder="https://www.xiaohongshu.com/user/profile/xxx" - required - className="form-input" - /> - {validating &&

🔄 校验中…

} - {urlError && !validating &&

⚠️ {urlError}

} - {profile && !urlError && ( -

- 已验证 -

- )} -
- -
- - setProfession(e.target.value)} - required - className="form-input" - /> -
- -
- - setWechat(e.target.value.replace(/[^a-zA-Z0-9_-]/g, ""))} - required - className="form-input" - /> -
- -
-
- - -
-
- - -
-
- -
- -
- - {error && ( -

- ⚠️ {error} -

- )} - - -
-
- - -
- - 🏠 返回首页 - -
- +
+ 跳转中…
); } diff --git a/config/domain.config.ts b/config/domain.config.ts index 9226149..4a8c1d9 100644 --- a/config/domain.config.ts +++ b/config/domain.config.ts @@ -1,19 +1,21 @@ /** - * 域名与 payjsapi 地址配置 - * 生产环境必须设置 PAYMENT_API_URL 或 ROOT_DOMAIN,否则无法连接 payjsapi + * 域名配置 + * - salon 前端线上: nomadyt.com + * - salonapi 后端线上: api.nomadyt.com(join、支付等) */ const isDev = process.env.NODE_ENV === "development"; +/** 根域名。前端 nomadyt.com,后端 api.nomadyt.com */ export const ROOT_DOMAIN = - process.env.ROOT_DOMAIN || process.env.NEXT_PUBLIC_ROOT_DOMAIN || "hackrobot.cn"; + process.env.ROOT_DOMAIN || process.env.NEXT_PUBLIC_ROOT_DOMAIN || "nomadyt.com"; -/** 支付 API 默认地址。生产环境使用 api 子域,避免 127.0.0.1 导致连接失败 */ +/** salonapi 默认地址。开发连本地 8007,生产连 api.nomadyt.com */ export const DEFAULT_PAYMENT_API_URL = isDev ? "http://127.0.0.1:8007" : `https://api.${ROOT_DOMAIN}`; -/** 若 PAYMENT_API_URL 指向 localhost,生产环境自动使用 api 子域 */ +/** 解析 salonapi 地址(api.nomadyt.com) */ export function resolvePaymentApiUrl(): string { const url = process.env.PAYMENT_API_URL || DEFAULT_PAYMENT_API_URL; if (!isDev && /^(https?:\/\/)?(127\.0\.0\.1|localhost)(:\d+)?(\/|$)/i.test(url)) { diff --git a/config/services.config.ts b/config/services.config.ts index 2a4baea..b08fdb4 100644 --- a/config/services.config.ts +++ b/config/services.config.ts @@ -1,6 +1,6 @@ /** * salon 服务配置 - PocketBase、支付 - * 使用 site_id=salon,支付调用 payjsapi /salon/* + * 前端 nomadyt.com,后端 salonapi api.nomadyt.com */ import { resolvePaymentApiUrl } from "./domain.config"; @@ -58,8 +58,8 @@ export function getPaymentConfig(): PaymentConfig { }; } -/** 茶歇费 29元/人 */ -export const JOIN_TEA_FEE = 2900; +/** 茶歇费 1元/人(本地测试用,正式环境可改为 2900) */ +export const JOIN_TEA_FEE = 100; export function getJoinPaymentConfig(): { amount: number; type: string } { return {