Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
894150d1fa | ||
|
|
2f73b2ee23 | ||
|
|
5b26c3c907 | ||
|
|
6873bd8f70 | ||
|
|
bf10b5d7e4 | ||
|
|
742c293e14 | ||
|
|
4d4ca04167 | ||
|
|
fd2e424897 | ||
|
|
9d45fede7f | ||
|
|
473fa1a1cf | ||
|
|
c93eb7b2ee | ||
|
|
e30d4ad950 | ||
|
|
3ba00e9a93 | ||
|
|
b8fa250897 | ||
|
|
c5e057f0ed | ||
|
|
3e73917ad1 | ||
|
|
14b0cd2429 | ||
|
|
c54c236d1b | ||
|
|
c54d46517c | ||
|
|
ff31ef8001 | ||
|
|
ff135563fb | ||
|
|
91d56fa086 | ||
|
|
501e5b7987 | ||
|
|
4ed10176e7 | ||
|
|
39803739bb | ||
|
|
aff82b4fc2 | ||
|
|
de02b45199 |
@@ -1 +1,2 @@
|
||||
PAYMENT_API_URL=https://api.hackrobot.cn
|
||||
PAYMENT_API_URL=https://salonapi.hackrobot.cn
|
||||
PAYMENT_JOIN_AMOUNT=2900
|
||||
|
||||
23
README.md
23
README.md
@@ -13,22 +13,24 @@
|
||||
|
||||
### 前端 (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://salonapi.hackrobot.cn`)
|
||||
- `ROOT_DOMAIN`: 根域名(兼容变量),默认 `hackrobot.cn`;生产 salonapi 主机为 `salonapi.hackrobot.cn`
|
||||
- `NEXT_PUBLIC_SITE_URL`: 前端站点地址,线上 `https://salon.hackrobot.cn`
|
||||
- `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)
|
||||
|
||||
### 后端 (payjsapi)
|
||||
|
||||
- 与 cnomadcna 相同,需配置 PocketBase、支付渠道等
|
||||
- **PocketBase 需创建 `solanRed` 集合**(可克隆自 solan),字段:user_id, nickname, occupation, reason, wechatId, gender, education, gradYear, phone, single, media, type, order_id, amount
|
||||
- **PocketBase 需创建 `solanRed` 集合**(可克隆自 solan),字段:user_id, nickname, occupation, reason, wechatId, gender, education, gradYear, phone, single, media, type, order_id, amount, is_volunteer(布尔), is_approved(布尔,审核通过), is_rejected(布尔,审核拒绝), is_wechat_friend(布尔,是否微信好友,默认 false), xiaohongshu_url, vip(布尔)
|
||||
|
||||
## 启动
|
||||
|
||||
```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.
|
||||
|
||||
99
app/api/join/by-wechat/route.ts
Normal file
99
app/api/join/by-wechat/route.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
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";
|
||||
|
||||
/** 用户状态必须实时从数据库获取,禁止缓存 */
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const NO_CACHE_HEADERS = {
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
|
||||
Pragma: "no-cache",
|
||||
Expires: "0",
|
||||
};
|
||||
|
||||
const empty = {
|
||||
hasRecord: false,
|
||||
record: null,
|
||||
isComplete: false,
|
||||
isWechatFriend: false,
|
||||
isApproved: false,
|
||||
isRejected: false,
|
||||
vip: false,
|
||||
};
|
||||
|
||||
async function getPocketBaseJoinByWechat(wechatId: string) {
|
||||
const token = await getAdminToken();
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const base = pb.url.replace(/\/$/, "");
|
||||
const escaped = wechatId.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
const filter = encodeURIComponent(`wechatId = "${escaped}"`);
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 4000);
|
||||
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 null;
|
||||
const data = await res.json();
|
||||
const items = Array.isArray(data?.items) ? data.items : [];
|
||||
const rec = items[0] ?? null;
|
||||
const hasRecord = !!rec;
|
||||
const amount = rec ? Number(rec.amount) || 0 : 0;
|
||||
const isComplete = hasRecord && !!rec.order_id && amount > 0;
|
||||
const isWechatFriend = !!rec?.is_wechat_friend;
|
||||
const isApproved = !!rec?.is_approved;
|
||||
const isRejected = !!rec?.is_rejected;
|
||||
const vip = !!rec?.vip;
|
||||
|
||||
return {
|
||||
hasRecord,
|
||||
record: rec,
|
||||
isComplete,
|
||||
isWechatFriend,
|
||||
isApproved,
|
||||
isRejected,
|
||||
vip,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 按 wechatId 查询 solanRed 记录。优先 salonapi(记录由其创建,线上部署时更可靠),失败时回退直连 PocketBase */
|
||||
export async function GET(request: NextRequest) {
|
||||
const wechatId = request.nextUrl.searchParams.get("wechat_id")?.trim();
|
||||
if (!wechatId) {
|
||||
return NextResponse.json(empty, { headers: NO_CACHE_HEADERS });
|
||||
}
|
||||
|
||||
try {
|
||||
const { status, data } = await getSalonApi(
|
||||
request,
|
||||
`/api/salon/join/by-wechat?wechat_id=${encodeURIComponent(wechatId)}&_=${Date.now()}`,
|
||||
{ timeoutMs: 6000 }
|
||||
);
|
||||
if (status === 200 && data && typeof data === "object") {
|
||||
return NextResponse.json(data, { headers: NO_CACHE_HEADERS });
|
||||
}
|
||||
} catch {
|
||||
/* salonapi 不可用,回退直连 PocketBase */
|
||||
}
|
||||
|
||||
const pbData = await getPocketBaseJoinByWechat(wechatId);
|
||||
if (pbData) {
|
||||
return NextResponse.json(pbData, { headers: NO_CACHE_HEADERS });
|
||||
}
|
||||
|
||||
return NextResponse.json(empty, { headers: NO_CACHE_HEADERS });
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { postSalonApi } from "@/app/lib/salonApi";
|
||||
import { getNowChinaStr } from "@/app/lib/dates";
|
||||
import { getAdminToken } from "@/app/lib/pocketbase/admin";
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
import { COOKIE_NAME } from "@/app/lib/auth-cookie";
|
||||
|
||||
function getUserIdFromCookie(request: NextRequest): string | null {
|
||||
@@ -13,42 +16,125 @@ function getUserIdFromCookie(request: NextRequest): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function generateAnonId(): string {
|
||||
return "anon_" + crypto.randomUUID().replace(/-/g, "");
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const userId = getUserIdFromCookie(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ ok: false, error: "请先登录" }, { status: 401 });
|
||||
}
|
||||
const body = await request.json();
|
||||
const formData = body && typeof body === "object" ? body : {};
|
||||
|
||||
const record = {
|
||||
user_id: userId,
|
||||
nickname: formData.nickname || "",
|
||||
occupation: formData.profession || "",
|
||||
reason: formData.intro || "",
|
||||
single: formData.single || "",
|
||||
wechatId: formData.wechat || "",
|
||||
gender: formData.gender || "",
|
||||
education: formData.education || "",
|
||||
gradYear: formData.graduationYear || "",
|
||||
phone: formData.phone || "",
|
||||
media: formData.media || "",
|
||||
};
|
||||
|
||||
const { status, data } = await postSalonApi(request, "/api/salon/join", record);
|
||||
if (status >= 500) {
|
||||
const payload = typeof data === "object" && data !== null ? (data as Record<string, unknown>) : {};
|
||||
const nickname = String(formData.nickname || "").trim();
|
||||
const city = String(formData.city || "").trim();
|
||||
const session = String(formData.session || "").trim();
|
||||
const ageRange = String(formData.age_range || "").trim();
|
||||
const wechatOrPhone = String(formData.wechat_or_phone || formData.wechat || "").trim();
|
||||
const wechat = String(formData.wechat || "").trim();
|
||||
const phone = String(formData.phone || "").trim();
|
||||
const profession = String(formData.profession || "").trim();
|
||||
const education = String(formData.education || "").trim();
|
||||
const graduationYear = String(formData.graduation_year || formData.gradYear || "").trim();
|
||||
const xiaohongshuUrl = String(formData.xiaohongshu_url || "").trim();
|
||||
const xiaohongshuAvatarUrl = String(formData.xiaohongshu_avatar_url || formData.media || "").trim();
|
||||
const gender = String(formData.gender || "").trim() || "\u65e0";
|
||||
let intro = String(formData.intro || formData.reason || "").trim();
|
||||
const firstTime = String(formData.first_time || "").trim();
|
||||
const agreeRules = !!formData.agree_rules;
|
||||
const status = String(formData.status || "").trim();
|
||||
const activityType = String(formData.activity_type || "").trim();
|
||||
const whyJoin = String(formData.why_join || "").trim();
|
||||
const region = String(formData.region || "").trim();
|
||||
const availableTime = String(formData.available_time || "").trim();
|
||||
const meetupdate = String(formData.meetupdate || "").trim();
|
||||
const isVolunteer = !!formData.is_volunteer;
|
||||
const qualify = !!formData.qualify; // 女性且小红书帖子>10 时自动通过审核
|
||||
/** reason 仅存自我介绍,不合并其他字段 */
|
||||
const contact = wechatOrPhone || wechat || phone;
|
||||
if (!nickname || !session || !agreeRules) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: (payload.detail as string) || (payload.error as string) || "提交失败" },
|
||||
{ status: 503 }
|
||||
{ ok: false, error: "请填写必填项" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (status >= 400) {
|
||||
return NextResponse.json(data, { status });
|
||||
if (!contact) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "请填写微信号" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (!xiaohongshuUrl) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "请填写小红书主页链接或笔记链接" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (!intro) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "请填写自我介绍" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (intro.length < 20) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "自我介绍不少于20字" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const userId = getUserIdFromCookie(request) || generateAnonId();
|
||||
|
||||
const ageRangeForRecord = ageRange || "";
|
||||
/** occupation: 职业/城市,reason: 仅自我介绍 */
|
||||
const occupationValue = profession || city;
|
||||
|
||||
const userInfo = String(formData.userInfo || "").trim();
|
||||
const record: Record<string, unknown> = {
|
||||
user_id: userId,
|
||||
nickname,
|
||||
occupation: occupationValue,
|
||||
reason: intro,
|
||||
wechatId: wechat || wechatOrPhone,
|
||||
xiaohongshu_url: xiaohongshuUrl,
|
||||
gender,
|
||||
education: education,
|
||||
gradYear: graduationYear,
|
||||
single: "",
|
||||
media: xiaohongshuAvatarUrl,
|
||||
type: session,
|
||||
order_id: "",
|
||||
amount: 0,
|
||||
age_range: ageRangeForRecord,
|
||||
first_time: firstTime,
|
||||
is_volunteer: isVolunteer,
|
||||
qualify,
|
||||
userInfo: userInfo || "",
|
||||
meetupdate: meetupdate || "",
|
||||
};
|
||||
if (phone.trim()) {
|
||||
record.phone = phone.trim();
|
||||
}
|
||||
try {
|
||||
const { status, data } = await postSalonApi(request, "/api/salon/join", record);
|
||||
if (status >= 500) {
|
||||
const payload = typeof data === "object" && data !== null ? (data as Record<string, unknown>) : {};
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: (payload.detail as string) || (payload.error as string) || "提交失败" },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
if (status >= 400) {
|
||||
const payload = typeof data === "object" && data !== null ? (data as Record<string, unknown>) : {};
|
||||
const errMsg = (payload.error as string) || (payload.detail as string) || "提交失败";
|
||||
if (status === 401) {
|
||||
return tryPocketBaseDirect(record, errMsg);
|
||||
}
|
||||
return NextResponse.json({ ok: false, error: errMsg }, { status });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch {
|
||||
return tryPocketBaseDirect(record, "服务暂时不可用");
|
||||
}
|
||||
const payload = typeof data === "object" && data !== null ? (data as Record<string, unknown>) : {};
|
||||
return NextResponse.json({ ok: true, user_id: payload.user_id ?? userId });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
console.error("Join API error:", e);
|
||||
@@ -58,3 +144,93 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function tryPocketBaseDirect(
|
||||
record: Record<string, unknown>,
|
||||
fallbackError: string
|
||||
): Promise<NextResponse> {
|
||||
const token = await getAdminToken();
|
||||
if (!token) {
|
||||
return NextResponse.json({ ok: false, error: fallbackError }, { status: 503 });
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const base = pb.url.replace(/\/$/, "");
|
||||
const wechatId = String(record.wechatId ?? "").trim();
|
||||
if (wechatId) {
|
||||
const escaped = wechatId.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
const filter = encodeURIComponent(`wechatId = "${escaped}"`);
|
||||
const checkRes = await fetch(
|
||||
`${base}/api/collections/${pb.joinCollection}/records?filter=${filter}&perPage=1`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
if (checkRes.ok) {
|
||||
const checkData = await checkRes.json();
|
||||
if (Array.isArray((checkData as { items?: unknown[] }).items) && (checkData as { items: unknown[] }).items.length > 0) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "该微信号已报名,请勿重复提交" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const url = `${base}/api/collections/${pb.joinCollection}/records`;
|
||||
|
||||
const qualify = !!(record.qualify ?? false);
|
||||
const body: Record<string, unknown> = {
|
||||
user_id: record.user_id,
|
||||
nickname: record.nickname,
|
||||
occupation: record.occupation ?? "",
|
||||
reason: record.reason ?? "",
|
||||
wechatId: record.wechatId ?? "",
|
||||
gender: record.gender ?? "",
|
||||
education: record.education ?? "",
|
||||
gradYear: record.gradYear ?? "",
|
||||
single: record.single ?? "",
|
||||
media: record.media ?? "",
|
||||
type: record.type ?? "",
|
||||
order_id: record.order_id ?? "",
|
||||
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 ?? "",
|
||||
userInfo: record.userInfo ?? "",
|
||||
};
|
||||
if (record.meetupdate != null && String(record.meetupdate).trim()) {
|
||||
body.meetupdate = String(record.meetupdate).trim();
|
||||
}
|
||||
body.submitted_at_cn = getNowChinaStr();
|
||||
if (record.phone != null && String(record.phone).trim()) {
|
||||
body.phone = record.phone;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errData = await res.json().catch(() => ({}));
|
||||
const msg = (errData as { message?: string }).message || fallbackError;
|
||||
return NextResponse.json({ ok: false, error: msg }, { status: res.status });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error("PocketBase direct write error:", e);
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: fallbackError },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
110
app/api/join/stats/route.ts
Normal file
110
app/api/join/stats/route.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getAdminToken } from "@/app/lib/pocketbase/admin";
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
import { SESSIONS } from "@/config/home.config";
|
||||
import { getThisWeekRangeChinaStr, getThisWeekRangeISO } from "@/app/lib/dates";
|
||||
import { getSalonApi } from "@/app/lib/salonApi";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** 按场次返回报名人数和最近报名者,仅限中国日历本周(周一到周日)报名的记录。优先 salonapi,失败时回退直连 PocketBase */
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { status, data } = await getSalonApi(request, "/api/salon/join/stats", {
|
||||
timeoutMs: 8000,
|
||||
});
|
||||
if (status === 200 && data && typeof data === "object") {
|
||||
const payload = data as { ok?: boolean; stats?: Record<string, { count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] }> };
|
||||
if (payload?.stats && typeof payload.stats === "object") {
|
||||
return NextResponse.json({ ok: true, stats: payload.stats });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* salonapi 不可用,回退直连 PocketBase */
|
||||
}
|
||||
|
||||
const token = await getAdminToken();
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ ok: true, stats: getEmptyStats() },
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const base = pb.url.replace(/\/$/, "");
|
||||
|
||||
const stats: Record<string, { count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] }> = {};
|
||||
|
||||
const { start: weekStartCn, end: weekEndCn } = getThisWeekRangeChinaStr();
|
||||
const { start: weekStartUtc, end: weekEndUtc } = getThisWeekRangeISO();
|
||||
|
||||
const results = await Promise.all(
|
||||
SESSIONS.map(async (s) => {
|
||||
try {
|
||||
// session-1 周六 / session-2 周日;meetupdate 含关键词或为空(兼容旧记录)
|
||||
const dayKeyword = s.id === "session-1" ? "周六" : "周日";
|
||||
const meetupdatePart = s.id === "session-1"
|
||||
? `(meetupdate ~ "${dayKeyword}" || meetupdate = "")`
|
||||
: `meetupdate ~ "${dayKeyword}"`;
|
||||
// 本周:submitted_at_cn(中国公历)或 created(UTC 兼容旧记录),两路查询合并
|
||||
const filterSubmitted = encodeURIComponent(
|
||||
`${meetupdatePart} && submitted_at_cn >= "${weekStartCn}" && submitted_at_cn <= "${weekEndCn}"`
|
||||
);
|
||||
const filterCreated = encodeURIComponent(
|
||||
`${meetupdatePart} && created >= "${weekStartUtc}" && created <= "${weekEndUtc}"`
|
||||
);
|
||||
const [res1, res2] = await Promise.all([
|
||||
fetch(`${base}/api/collections/${pb.joinCollection}/records?filter=${filterSubmitted}&sort=-created&perPage=6`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
}),
|
||||
fetch(`${base}/api/collections/${pb.joinCollection}/records?filter=${filterCreated}&sort=-created&perPage=6`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
}),
|
||||
]);
|
||||
const data1 = res1.ok ? await res1.json() : { items: [], totalItems: 0 };
|
||||
const data2 = res2.ok ? await res2.json() : { items: [], totalItems: 0 };
|
||||
const seen = new Set<string>();
|
||||
const merged: typeof data1.items = [];
|
||||
for (const r of [...(data1.items || []), ...(data2.items || [])]) {
|
||||
if (r?.id && !seen.has(r.id)) {
|
||||
seen.add(r.id);
|
||||
merged.push(r);
|
||||
}
|
||||
}
|
||||
merged.sort((a: { created?: string }, b: { created?: string }) => (b?.created || "").localeCompare(a?.created || ""));
|
||||
const items = merged.slice(0, 6);
|
||||
const total = Math.max(data1.totalItems || 0, data2.totalItems || 0, merged.length);
|
||||
return {
|
||||
id: s.id,
|
||||
stat: {
|
||||
count: total,
|
||||
joiners: items.map((r: { nickname?: string; xiaohongshu_nickname?: string; xiaohongshu_avatar?: string; xiaohongshu_url?: string; media?: string }) => ({
|
||||
nickname: String(r?.xiaohongshu_nickname || r?.nickname || "").trim() || "匿名",
|
||||
avatar: String(r?.xiaohongshu_avatar || r?.media || "").trim() || undefined,
|
||||
xiaohongshu_url: String(r?.xiaohongshu_url || "").trim() || undefined,
|
||||
})),
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return { id: s.id, stat: { count: 0, joiners: [] } };
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
for (const { id, stat } of results) {
|
||||
stats[id] = stat;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, stats });
|
||||
}
|
||||
|
||||
function getEmptyStats() {
|
||||
const stats: Record<string, { count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] }> = {};
|
||||
for (const s of SESSIONS) {
|
||||
stats[s.id] = { count: 0, joiners: [] };
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
55
app/api/join/volunteers/route.ts
Normal file
55
app/api/join/volunteers/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
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
|
||||
}
|
||||
|
||||
const token = await getAdminToken();
|
||||
if (!token) {
|
||||
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 res = await fetch(
|
||||
`${base}/api/collections/${pb.joinCollection}/records?filter=${filter}&sort=-created&perPage=20`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
if (!res.ok) {
|
||||
return NextResponse.json({ ok: true, volunteer: null }, { status: 200 });
|
||||
}
|
||||
const data = await res.json();
|
||||
const items = Array.isArray(data?.items) ? data.items : [];
|
||||
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, volunteer: null }, { status: 200 });
|
||||
}
|
||||
}
|
||||
151
app/api/pay/complete-order/route.ts
Normal file
151
app/api/pay/complete-order/route.ts
Normal file
@@ -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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
} from "@/config/services.config";
|
||||
import { SITE_URL } from "@/app/lib/env";
|
||||
|
||||
/** ZPAY 创建订单较慢(约 6–10s),需延长超时避免手机浏览器发起支付超时 */
|
||||
export const maxDuration = 30;
|
||||
|
||||
const ORDER_COOKIE = "join_pay_order";
|
||||
const SALON_PAY_PREFIX = "/salon";
|
||||
|
||||
@@ -66,14 +69,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 `<!DOCTYPE html>
|
||||
@@ -96,14 +98,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;}
|
||||
</style></head>
|
||||
@@ -129,12 +123,6 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
|
||||
</div>
|
||||
<p class="tip pulse" id="tip">等待支付中...</p>
|
||||
</div>
|
||||
<div class="success-wrap" id="successWrap">
|
||||
<div class="success-icon">✅</div>
|
||||
<div class="success-title">支付成功</div>
|
||||
<div class="success-desc">${esc(successDesc)}</div>
|
||||
<div class="success-countdown" id="successCountdown">3 秒后跳转</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function(){
|
||||
@@ -143,11 +131,9 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
|
||||
var returnUrl=${JSON.stringify(returnUrl)};
|
||||
if(!orderId){return;}
|
||||
var waitWrap=document.getElementById("waitWrap");
|
||||
var successWrap=document.getElementById("successWrap");
|
||||
var tip=document.getElementById("tip");
|
||||
var countdownNum=document.getElementById("countdownNum");
|
||||
var progressCircle=document.getElementById("progressCircle");
|
||||
var successCountdown=document.getElementById("successCountdown");
|
||||
var maxT=300,left=maxT;
|
||||
var circumference=2*Math.PI*32;
|
||||
function fmt(t){var m=Math.floor(t/60),s=t%60;return m+":"+(s<10?"0":"")+s;}
|
||||
@@ -159,34 +145,32 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
|
||||
},1000);
|
||||
function showSuccess(){
|
||||
clearInterval(countdownTimer);
|
||||
waitWrap.classList.add("hide");
|
||||
successWrap.classList.add("show");
|
||||
var s=3;
|
||||
var t=setInterval(function(){
|
||||
s--;
|
||||
successCountdown.textContent=s>0?s+" 秒后跳转":"跳转中…";
|
||||
if(s<=0){clearInterval(t);window.location.href=returnUrl;}
|
||||
},1000);
|
||||
window.location.href=returnUrl;
|
||||
}
|
||||
var confirmUrl=${JSON.stringify(confirmUrl)};
|
||||
var confirmTimeoutMs=8000;
|
||||
function doConfirm(attempt){
|
||||
if(attempt>=3){showSuccess();return;}
|
||||
fetch(confirmUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order_id:orderId})})
|
||||
if(tip){tip.textContent="检测到支付,正在确认…";}
|
||||
var ctrl=new AbortController();
|
||||
var tid=setTimeout(function(){ctrl.abort();},confirmTimeoutMs);
|
||||
fetch(confirmUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order_id:orderId}),signal:ctrl.signal})
|
||||
.then(function(r){return r.json();})
|
||||
.then(function(cd){
|
||||
clearTimeout(tid);
|
||||
if(cd&&cd.ok){showSuccess();}
|
||||
else{setTimeout(function(){doConfirm(attempt+1);},800);}
|
||||
})
|
||||
.catch(function(){setTimeout(function(){doConfirm(attempt+1);},800);});
|
||||
.catch(function(){clearTimeout(tid);if(tip){tip.textContent="确认失败,重试中…";}setTimeout(function(){doConfirm(attempt+1);},800);});
|
||||
}
|
||||
function check(){
|
||||
fetch("/api/pay/status?order_id="+encodeURIComponent(orderId),{cache:"no-store"})
|
||||
fetch("/api/pay/status?order_id="+encodeURIComponent(orderId),{cache:"no-store",credentials:"same-origin"})
|
||||
.then(function(r){return r.json();})
|
||||
.then(function(d){
|
||||
if(d.ok&&d.paid){doConfirm(0);return;}
|
||||
setTimeout(check,500);
|
||||
if(d&&d.paid){doConfirm(0);return;}
|
||||
setTimeout(check,800);
|
||||
})
|
||||
.catch(function(){setTimeout(check,500);});
|
||||
.catch(function(){setTimeout(check,1500);});
|
||||
}
|
||||
setTimeout(check,500);
|
||||
})();
|
||||
@@ -250,7 +234,7 @@ async function requestRedirect(
|
||||
payload: Record<string, unknown>
|
||||
) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 12000);
|
||||
const timeout = setTimeout(() => controller.abort(), 25000);
|
||||
try {
|
||||
return await fetch(`${apiUrl}${path}`, {
|
||||
method: "POST",
|
||||
@@ -316,30 +300,33 @@ export async function POST(request: NextRequest) {
|
||||
device
|
||||
);
|
||||
|
||||
const created = await createPayOrder(
|
||||
apiUrl,
|
||||
userId,
|
||||
returnUrl,
|
||||
totalFee,
|
||||
type,
|
||||
channel,
|
||||
forcedProvider,
|
||||
clientIp
|
||||
);
|
||||
// 微信内:xorpay 收银台,需先 createPayOrder
|
||||
// PC/手机浏览器:zpay,参考 nomadvip 直接走 redirect,跳过 payh5 避免重复建单
|
||||
const isWechat = device === "wechat";
|
||||
let created: Awaited<ReturnType<typeof createPayOrder>> | null = null;
|
||||
|
||||
if (!wantHtml) {
|
||||
const response = NextResponse.json({
|
||||
ok: true,
|
||||
params: created.params,
|
||||
payUrl: created.payUrl,
|
||||
provider: created.provider,
|
||||
order_id: created.orderId,
|
||||
});
|
||||
if (created.orderId) setPayOrderCookie(response, created.orderId);
|
||||
return response;
|
||||
}
|
||||
|
||||
if (created.provider === "xorpay") {
|
||||
if (isWechat) {
|
||||
created = await createPayOrder(
|
||||
apiUrl,
|
||||
userId,
|
||||
returnUrl,
|
||||
totalFee,
|
||||
type,
|
||||
channel,
|
||||
"xorpay",
|
||||
clientIp
|
||||
);
|
||||
if (!wantHtml) {
|
||||
const response = NextResponse.json({
|
||||
ok: true,
|
||||
params: created.params,
|
||||
payUrl: created.payUrl,
|
||||
provider: created.provider,
|
||||
order_id: created.orderId,
|
||||
});
|
||||
if (created.orderId) setPayOrderCookie(response, created.orderId);
|
||||
return response;
|
||||
}
|
||||
const html = buildPayHtml(created.payUrl, created.params, {
|
||||
directToCashier: true,
|
||||
orderId: created.orderId,
|
||||
@@ -352,6 +339,7 @@ export async function POST(request: NextRequest) {
|
||||
return response;
|
||||
}
|
||||
|
||||
// PC/手机:zpay 直接 redirect(手机 h5 得 302 跳转支付页,PC 得二维码页)
|
||||
const redirectPayload: Record<string, unknown> = {
|
||||
user_id: userId,
|
||||
site_id: SITE_ID,
|
||||
@@ -373,10 +361,18 @@ export async function POST(request: NextRequest) {
|
||||
if (redirectRes.status >= 301 && redirectRes.status <= 308) {
|
||||
const location = redirectRes.headers.get("location");
|
||||
if (location) {
|
||||
const orderId = redirectRes.headers.get("x-pay-order-id")?.trim();
|
||||
if (!wantHtml) {
|
||||
const res = NextResponse.json({
|
||||
ok: true,
|
||||
order_id: orderId,
|
||||
redirect_url: location,
|
||||
provider: "zpay",
|
||||
});
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
return res;
|
||||
}
|
||||
const response = NextResponse.redirect(location);
|
||||
const orderId =
|
||||
redirectRes.headers.get("x-pay-order-id")?.trim() ||
|
||||
created.orderId;
|
||||
if (orderId) setPayOrderCookie(response, orderId);
|
||||
return response;
|
||||
}
|
||||
@@ -398,11 +394,10 @@ export async function POST(request: NextRequest) {
|
||||
c
|
||||
] || c)
|
||||
);
|
||||
const rawOrderId = String(resData.order_id || created.orderId).trim();
|
||||
const rawOrderId = String(resData.order_id || "").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,
|
||||
@@ -413,6 +408,16 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (redirectRes.status === 200 && resData?.use_form) {
|
||||
created = await createPayOrder(
|
||||
apiUrl,
|
||||
userId,
|
||||
returnUrl,
|
||||
totalFee,
|
||||
type,
|
||||
channel,
|
||||
undefined,
|
||||
clientIp
|
||||
);
|
||||
const html = buildPayHtml(payConfig.zpaySubmitUrl, created.params, {
|
||||
directToCashier: true,
|
||||
orderId: String(resData.order_id || created.orderId).trim(),
|
||||
@@ -440,6 +445,17 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
// 兜底:redirect 失败时回退到 payh5
|
||||
created = await createPayOrder(
|
||||
apiUrl,
|
||||
userId,
|
||||
returnUrl,
|
||||
totalFee,
|
||||
type,
|
||||
channel,
|
||||
undefined,
|
||||
clientIp
|
||||
);
|
||||
const html = buildPayHtml(created.payUrl, created.params, {
|
||||
orderId: created.orderId,
|
||||
});
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
62
app/api/xiaohongshu/profile/route.ts
Normal file
62
app/api/xiaohongshu/profile/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { resolvePaymentApiUrl } from "@/config/domain.config";
|
||||
|
||||
export const maxDuration = 60;
|
||||
|
||||
/** 开发环境优先使用本地 salonapi,避免 PAYMENT_API_URL 指向远程时 404 */
|
||||
function getSalonApiBase(): string {
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
const port = process.env.PAYJSAPI_PORT || "8007";
|
||||
const host = process.env.SALONAPI_HOST || "127.0.0.1";
|
||||
return `http://${host}:${port}`;
|
||||
}
|
||||
return resolvePaymentApiUrl();
|
||||
}
|
||||
|
||||
/** 代理到 salonapi 获取小红书用户资料,支持主页链接、笔记链接 xhslink.com/o/ */
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const url = String(body?.url || body?.id || "").trim();
|
||||
|
||||
if (!url) {
|
||||
return NextResponse.json({ ok: false, error: "请输入小红书链接" }, { status: 400 });
|
||||
}
|
||||
const apiBase = getSalonApiBase();
|
||||
const res = await fetch(`${apiBase}/api/salon/xiaohongshu/profile`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ url }),
|
||||
signal: AbortSignal.timeout(50000),
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
if (res.ok && data?.ok) {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
nickname: data.nickname,
|
||||
gender: data.gender,
|
||||
avatarUrl: data.avatarUrl ?? undefined,
|
||||
followers: data.followersText ?? data.followers ?? 0,
|
||||
followersText: data.followersText ?? undefined,
|
||||
following: data.followingText ?? data.following ?? 0,
|
||||
followingText: data.followingText ?? undefined,
|
||||
likesAndCollects: data.likesAndCollectsText ?? data.likesAndCollects ?? 0,
|
||||
likesAndCollectsText: data.likesAndCollectsText ?? undefined,
|
||||
postCount: data.postCount ?? 0,
|
||||
postCountText: data.postCountText ?? undefined,
|
||||
redbookId: data.redbookId ?? undefined,
|
||||
ipLocation: data.ipLocation ?? undefined,
|
||||
personalLink: data.personalLink ?? undefined,
|
||||
resolvedUrl: data.resolvedUrl ?? undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const error = data?.detail ?? data?.error ?? "无法解析用户资料,请确认链接有效";
|
||||
return NextResponse.json({ ok: false, error }, { status: res.status >= 400 ? res.status : 400 });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : "获取资料失败";
|
||||
return NextResponse.json({ ok: false, error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
32
app/api/xiaohongshu/validate/route.ts
Normal file
32
app/api/xiaohongshu/validate/route.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
/** 支持:主页 xiaohongshu.com/user/profile/xxx、xhslink.com/m/xxx;笔记 xhslink.com/o/xxx、xiaohongshu.com/explore/xxx */
|
||||
const XH_PROFILE_PATTERN = /^https?:\/\/(www\.)?(xiaohongshu\.com|xhslink\.com)\/user\/profile\/[a-zA-Z0-9_-]+/i;
|
||||
const XH_SHORT_PATTERN = /^https?:\/\/xhslink\.com\/m\/[a-zA-Z0-9_-]+/i;
|
||||
const XH_NOTE_PATTERN = /^https?:\/\/(xhslink\.com\/o\/|(www\.)?xiaohongshu\.com\/explore\/)[a-zA-Z0-9_-]+/i;
|
||||
|
||||
function isValidUrl(url: string): boolean {
|
||||
const s = url.trim();
|
||||
if (!s) return false;
|
||||
if (XH_PROFILE_PATTERN.test(s) || XH_SHORT_PATTERN.test(s) || XH_NOTE_PATTERN.test(s)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const url = String(body?.url || body?.id || "").trim();
|
||||
|
||||
if (!url) {
|
||||
return NextResponse.json({ valid: false, error: "请输入小红书链接" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!isValidUrl(url)) {
|
||||
return NextResponse.json({ valid: false, error: "请输入有效的主页链接或笔记链接(xhslink.com/m/xxx 或 xhslink.com/o/xxx)" }, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ valid: true, url });
|
||||
} catch {
|
||||
return NextResponse.json({ valid: false, error: "校验失败" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
30
app/apple-icon.tsx
Normal file
30
app/apple-icon.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ImageResponse } from "next/og";
|
||||
|
||||
export const size = { width: 180, height: 180 };
|
||||
export const contentType = "image/png";
|
||||
|
||||
export default function AppleIcon() {
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: "linear-gradient(135deg, #b45309 0%, #d97706 50%, #f59e0b 100%)",
|
||||
borderRadius: 36,
|
||||
}}
|
||||
>
|
||||
<div style={{ position: "relative", width: 100, height: 100, display: "flex" }}>
|
||||
<div style={{ position: "absolute", left: 38, top: 28, width: 28, height: 28, borderRadius: "50%", background: "white", opacity: 0.95 }} />
|
||||
<div style={{ position: "absolute", left: 18, top: 58, width: 22, height: 22, borderRadius: "50%", background: "white", opacity: 0.95 }} />
|
||||
<div style={{ position: "absolute", left: 60, top: 58, width: 22, height: 22, borderRadius: "50%", background: "white", opacity: 0.95 }} />
|
||||
<div style={{ position: "absolute", left: 43, top: 72, width: 16, height: 16, borderRadius: "50%", background: "white", opacity: 0.95 }} />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
{ ...size }
|
||||
);
|
||||
}
|
||||
28
app/coming-soon/page.tsx
Normal file
28
app/coming-soon/page.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import Header from "../components/Header";
|
||||
import Footer from "../components/Footer";
|
||||
|
||||
export default function ComingSoonPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950 flex flex-col">
|
||||
<Header />
|
||||
<main className="flex-1 flex items-center justify-center px-4">
|
||||
<div className="text-center">
|
||||
<p className="text-4xl mb-4">✨</p>
|
||||
<h1 className="text-xl font-semibold text-stone-800 dark:text-stone-100 mb-2">
|
||||
功能开发中
|
||||
</h1>
|
||||
<p className="text-sm text-stone-500 dark:text-stone-400 mb-6">
|
||||
敬请期待~
|
||||
</p>
|
||||
<Link href="/" className="text-amber-600 dark:text-amber-400 text-sm">
|
||||
返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
45
app/components/AddressLink.tsx
Normal file
45
app/components/AddressLink.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import { HONGSHAN_COORDS } from "@/config/home.config";
|
||||
|
||||
interface AddressLinkProps {
|
||||
place: string;
|
||||
city: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** 红山地址展示:龙华区 | 🚇红山地铁站 | Loft民宿 */
|
||||
const HONGSHAN_DISPLAY = "龙华区 | 🚇 红山地铁站 | Loft民宿";
|
||||
|
||||
/** 可点击的地址,点击打开地图(使用 span 避免嵌套在 Link 内时的 a 标签冲突) */
|
||||
export default function AddressLink({ place, city, className = "" }: AddressLinkProps) {
|
||||
const isHongshan = place.includes("红山");
|
||||
const mapUrl = isHongshan
|
||||
? `https://api.map.baidu.com/marker?location=${HONGSHAN_COORDS.lat},${HONGSHAN_COORDS.lng}&title=${encodeURIComponent(place)}&output=html`
|
||||
: `https://map.baidu.com/search?query=${encodeURIComponent(`${city}${place}`)}`;
|
||||
const displayText = isHongshan ? HONGSHAN_DISPLAY : place;
|
||||
|
||||
return (
|
||||
<span
|
||||
role="link"
|
||||
tabIndex={0}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
window.open(mapUrl, "_blank", "noopener,noreferrer");
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
window.open(mapUrl, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
}}
|
||||
className={`inline-flex items-center gap-1 text-stone-500 dark:text-stone-400 hover:text-amber-600 dark:hover:text-amber-400 transition-colors cursor-pointer ${className}`}
|
||||
title="点击打开地图"
|
||||
>
|
||||
<span className="inline-block" aria-hidden>📍</span>
|
||||
{displayText}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
35
app/components/AvatarStack.tsx
Normal file
35
app/components/AvatarStack.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { RECENT_JOINERS } from "@/config/home.config";
|
||||
|
||||
export default function AvatarStack() {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-3 sm:gap-4">
|
||||
<div className="flex -space-x-2.5 shrink-0">
|
||||
{RECENT_JOINERS.slice(0, 6).map((u, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="relative w-10 h-10 rounded-full overflow-hidden border-2 border-[#faf8f5] dark:border-stone-950 shadow-sm ring-1 ring-stone-200/50 dark:ring-stone-700/50"
|
||||
title={u.name}
|
||||
>
|
||||
<Image
|
||||
src={u.avatar}
|
||||
alt={u.name}
|
||||
fill
|
||||
sizes="40px"
|
||||
className="object-cover"
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-sm text-stone-600 dark:text-stone-400 min-w-0">
|
||||
<span className="font-medium text-stone-800 dark:text-stone-200">
|
||||
{RECENT_JOINERS.slice(0, 3).map((u) => u.name).join("、")}
|
||||
</span>
|
||||
<span className="ml-1">等有报名意向</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
26
app/components/CitySelect.tsx
Normal file
26
app/components/CitySelect.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { CITIES } from "@/config/home.config";
|
||||
|
||||
interface CitySelectProps {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
className?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export default function CitySelect({ value, onChange, className = "", required }: CitySelectProps) {
|
||||
return (
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
required={required}
|
||||
className={`form-input appearance-none ${value ? "text-stone-800 dark:text-stone-100" : "text-stone-400 dark:text-stone-500"} ${className}`}
|
||||
>
|
||||
<option value="" disabled>请选择城市</option>
|
||||
{CITIES.map((c) => (
|
||||
<option key={c} value={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function Footer() {
|
||||
return (
|
||||
<footer className="border-t border-gray-200 dark:border-gray-800 mt-12 py-8">
|
||||
<div className="max-w-[1400px] mx-auto px-5 sm:px-10 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
<p>© {new Date().getFullYear()} Salon. 探索中国,远程工作,自由生活。</p>
|
||||
<footer className="border-t border-stone-200 dark:border-stone-800 mt-12 py-8">
|
||||
<div className="max-w-[900px] mx-auto px-5 sm:px-8 text-center text-sm text-stone-500 dark:text-stone-400">
|
||||
<Link
|
||||
href="/join?volunteer=1"
|
||||
className="inline-flex items-center gap-1.5 mb-4 text-amber-600 dark:text-amber-400 hover:text-amber-700 dark:hover:text-amber-300 font-medium"
|
||||
>
|
||||
<span aria-hidden>🙋</span> 招募志愿者
|
||||
</Link>
|
||||
<p>© {new Date().getFullYear()} Salon · 深圳 周末轻社交</p>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
|
||||
19
app/components/Header.tsx
Normal file
19
app/components/Header.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import ThemeToggle from "./ThemeToggle";
|
||||
|
||||
export default function Header() {
|
||||
return (
|
||||
<header className="sticky top-0 z-40 w-full border-b border-stone-200/80 dark:border-stone-800 bg-[#faf8f5]/95 dark:bg-stone-950/95 backdrop-blur">
|
||||
<div className="max-w-[900px] mx-auto px-4 sm:px-6 h-14 flex items-center justify-between">
|
||||
<Link href="/" className="font-semibold text-stone-800 dark:text-stone-100 text-base">
|
||||
Salon
|
||||
</Link>
|
||||
<nav className="flex items-center gap-4 sm:gap-6">
|
||||
<ThemeToggle />
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,271 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import JoinModal from "./JoinModal";
|
||||
import {
|
||||
getPayEnv,
|
||||
redirectToPay,
|
||||
getDeviceFromEnv,
|
||||
} from "@/app/lib/payment";
|
||||
import type { PayChannel } from "@/app/lib/payment";
|
||||
import SessionCoverImage from "./SessionCoverImage";
|
||||
import AddressLink from "./AddressLink";
|
||||
import { getSessionsWithDates, MOCK_JOINERS_SESSION1 } from "@/config/home.config";
|
||||
import { mergeJoiners, getUniqueDbCount } from "@/app/lib/joiners";
|
||||
import { useXhClickOpener } from "@/app/hooks/useXhClickOpener";
|
||||
|
||||
const avatarPhotos = [
|
||||
"https://i.pravatar.cc/150?img=32",
|
||||
"https://i.pravatar.cc/150?img=33",
|
||||
"https://i.pravatar.cc/150?img=25",
|
||||
"https://i.pravatar.cc/150?img=52",
|
||||
"https://i.pravatar.cc/150?img=44",
|
||||
];
|
||||
|
||||
function isPrivateDevHost(hostname: string): boolean {
|
||||
if (!hostname) return false;
|
||||
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") return true;
|
||||
if (/^10\./.test(hostname) || /^192\.168\./.test(hostname)) return true;
|
||||
const match = hostname.match(/^172\.(\d{1,2})\./);
|
||||
if (!match) return false;
|
||||
const secondOctet = Number(match[1]);
|
||||
return secondOctet >= 16 && secondOctet <= 31;
|
||||
}
|
||||
|
||||
function buildPendingUserId(email: string): string {
|
||||
function HeroAvatarItem({ joiner }: { joiner: { name?: string; nickname?: string; avatar?: string; xiaohongshu_url?: string } }) {
|
||||
const nickname = ("name" in joiner ? joiner.name : joiner.nickname) ?? "";
|
||||
const avatar = joiner.avatar;
|
||||
const xhUrl = joiner.xiaohongshu_url;
|
||||
const showAvatar = avatar && avatar.length > 0;
|
||||
const handleClick = useXhClickOpener(xhUrl);
|
||||
return (
|
||||
"pending_" +
|
||||
Array.from(new TextEncoder().encode(email))
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("")
|
||||
<span
|
||||
className={`relative w-6 h-6 sm:w-8 sm:h-8 rounded-full overflow-hidden border-2 border-white dark:border-stone-900 shrink-0 inline-block transition-transform hover:scale-110 cursor-default ${showAvatar ? "" : "bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center text-[10px] sm:text-xs font-medium text-amber-700 dark:text-amber-300"}`}
|
||||
{...(xhUrl && { "data-xiaohongshu-url": xhUrl })}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{showAvatar ? (
|
||||
<Image src={avatar} alt="" fill sizes="32px" className="object-cover" unoptimized />
|
||||
) : (
|
||||
<span className="flex items-center justify-center w-full h-full">{nickname.slice(0, 1) || "?"}</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function HeroSection() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [joinModalOpen, setJoinModalOpen] = useState(false);
|
||||
const [joinModalVipOnly, setJoinModalVipOnly] = useState(false);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const sessions = getSessionsWithDates();
|
||||
const mainSession = sessions[0];
|
||||
const [stats, setStats] = useState<{ count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] } | null>(null);
|
||||
|
||||
const pathname = usePathname();
|
||||
const fetchStats = useCallback(() => {
|
||||
if (!mainSession) return;
|
||||
fetch(`/api/join/stats?_=${Date.now()}`, { cache: "no-store" })
|
||||
.then((r) => r.json())
|
||||
.then((d) => d?.stats?.[mainSession.id] && setStats(d.stats[mainSession.id]))
|
||||
.catch(() => {});
|
||||
}, [mainSession?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me", { credentials: "include" });
|
||||
const data = await res.json();
|
||||
setIsLoggedIn(!!data?.user);
|
||||
} catch {
|
||||
setIsLoggedIn(false);
|
||||
}
|
||||
if (!mainSession || pathname !== "/") return;
|
||||
fetchStats();
|
||||
const onVisible = () => fetchStats();
|
||||
const onPageShow = (e: PageTransitionEvent) => {
|
||||
if (e.persisted) fetchStats();
|
||||
};
|
||||
checkAuth();
|
||||
const onAuth = () => checkAuth();
|
||||
window.addEventListener("auth:updated", onAuth);
|
||||
return () => window.removeEventListener("auth:updated", onAuth);
|
||||
}, []);
|
||||
|
||||
const checkUserCacheRef = useRef<{ email: string; data: { exists: boolean; vip: boolean }; ts: number } | null>(null);
|
||||
const CACHE_TTL_MS = 60_000;
|
||||
|
||||
const handleCheckAndProceed = useCallback(
|
||||
async (em: string) => {
|
||||
if (checking) return;
|
||||
const trimmed = em.trim();
|
||||
if (!trimmed) {
|
||||
setError("请输入邮箱");
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setChecking(true);
|
||||
try {
|
||||
const cached = checkUserCacheRef.current;
|
||||
if (cached && cached.email === trimmed && Date.now() - cached.ts < CACHE_TTL_MS) {
|
||||
const { exists, vip } = cached.data;
|
||||
if (exists) {
|
||||
setJoinModalVipOnly(!!vip);
|
||||
setJoinModalOpen(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const checkRes = await fetch("/api/salon/check-user", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: trimmed }),
|
||||
credentials: "include",
|
||||
});
|
||||
const checkData = await checkRes.json();
|
||||
if (!checkRes.ok || !checkData?.ok) {
|
||||
throw new Error(checkData?.error || checkData?.detail || "操作失败");
|
||||
}
|
||||
if (checkData.exists) {
|
||||
checkUserCacheRef.current = { email: trimmed, data: { exists: true, vip: !!checkData.vip }, ts: Date.now() };
|
||||
setJoinModalVipOnly(!!checkData.vip);
|
||||
setJoinModalOpen(true);
|
||||
return;
|
||||
}
|
||||
const shouldPrecreateUser =
|
||||
typeof window !== "undefined" &&
|
||||
isPrivateDevHost(window.location.hostname);
|
||||
let user_id = buildPendingUserId(trimmed);
|
||||
if (shouldPrecreateUser) {
|
||||
const ensureRes = await fetch("/api/salon/ensure-user", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: trimmed }),
|
||||
credentials: "include",
|
||||
});
|
||||
const ensureData = await ensureRes.json();
|
||||
if (!ensureRes.ok || !ensureData?.ok || !ensureData?.user_id) {
|
||||
throw new Error(ensureData?.error || ensureData?.detail || "创建用户失败");
|
||||
}
|
||||
if (ensureData.is_new) {
|
||||
await fetch("/api/salon/set-needs-password-change", { method: "POST", credentials: "include" });
|
||||
}
|
||||
user_id = String(ensureData.user_id).trim();
|
||||
if (ensureData?.token && ensureData?.record) {
|
||||
await fetch("/api/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: ensureData.token, record: ensureData.record }),
|
||||
credentials: "include",
|
||||
});
|
||||
}
|
||||
}
|
||||
const returnUrl =
|
||||
typeof window !== "undefined" ? `${window.location.origin}/join/paid` : "/join/paid";
|
||||
const env = getPayEnv();
|
||||
const channel: PayChannel = "wxpay";
|
||||
redirectToPay({
|
||||
user_id,
|
||||
return_url: returnUrl,
|
||||
channel,
|
||||
device: getDeviceFromEnv(env),
|
||||
useJoinConfig: true,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "操作失败");
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
},
|
||||
[checking]
|
||||
);
|
||||
|
||||
const handleJoinClick = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
handleCheckAndProceed(email);
|
||||
};
|
||||
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
window.addEventListener("pageshow", onPageShow);
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
window.removeEventListener("pageshow", onPageShow);
|
||||
};
|
||||
}, [pathname, mainSession?.id, fetchStats]);
|
||||
return (
|
||||
<section className="relative overflow-hidden">
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-orange-50/70 via-white to-[#fafafa] dark:from-gray-950 dark:via-gray-900 dark:to-gray-950" />
|
||||
<section className="relative overflow-hidden bg-[#faf8f5] dark:bg-stone-950">
|
||||
<div
|
||||
className="absolute top-0 right-0 w-[500px] h-[500px] -translate-y-1/3 translate-x-1/4 opacity-40 rounded-full"
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
"radial-gradient(circle, rgba(249,115,22,0.25) 0%, transparent 70%)",
|
||||
backgroundImage: `radial-gradient(ellipse 80% 50% at 50% 0%, rgba(180,83,9,0.08) 0%, transparent 60%),
|
||||
radial-gradient(ellipse 60% 40% at 80% 80%, rgba(180,83,9,0.05) 0%, transparent 50%)`,
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="relative max-w-[1400px] mx-auto px-5 sm:px-10 py-10 sm:py-14 md:py-20">
|
||||
<div className="flex flex-col lg:flex-row lg:items-start lg:gap-10 xl:gap-16">
|
||||
<div className="relative max-w-[1200px] mx-auto px-4 sm:px-6 md:px-8 py-14 sm:py-20 md:py-28">
|
||||
<div className="flex flex-col lg:flex-row lg:items-center lg:gap-14 xl:gap-20">
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="inline-flex items-center gap-1.5 text-xs font-semibold text-orange-700 dark:text-orange-400 bg-orange-100 dark:bg-orange-900/30 px-3 py-1.5 rounded-full mb-5">
|
||||
🏆 数字游民首选
|
||||
</span>
|
||||
|
||||
<h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold tracking-tight leading-tight mb-5">
|
||||
<span className="hero-gradient-text">探索中国</span>
|
||||
<br />
|
||||
<span className="text-gray-900 dark:text-gray-100">远程工作,自由生活</span>
|
||||
<h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-[3rem] xl:text-[3.5rem] font-bold tracking-tight leading-[1.2]">
|
||||
<span className="hero-gradient-text">周末2小时</span>
|
||||
<span className="text-stone-800 dark:text-stone-100 whitespace-nowrap"> 认识更多有趣的人</span>
|
||||
</h1>
|
||||
|
||||
<p className="text-base sm:text-lg text-gray-500 dark:text-gray-400 max-w-2xl mb-7 leading-relaxed">
|
||||
加入全球数字游民社区,发现中国最适合远程工作和生活的城市
|
||||
<p className="mt-4 sm:mt-5 text-stone-600 dark:text-stone-400 text-sm sm:text-base max-w-lg leading-relaxed">
|
||||
深圳 · 4–8 人小圈子
|
||||
</p>
|
||||
|
||||
<div className="space-y-2.5 mb-8">
|
||||
{[
|
||||
{ icon: "🍹", text: "线下聚会与线上分享" },
|
||||
{ icon: "❤️", text: "结识志同道合的伙伴" },
|
||||
{ icon: "🧪", text: "探索新城市与新可能" },
|
||||
{ icon: "🌎", text: "全球数字游民网络" },
|
||||
{ icon: "💬", text: "社区互助与资源共享" },
|
||||
].map((f) => (
|
||||
<div key={f.icon} className="flex items-start gap-2.5">
|
||||
<span className="text-base sm:text-lg shrink-0 mt-0.5">{f.icon}</span>
|
||||
<span className="text-sm sm:text-base text-gray-600 dark:text-gray-400 underline decoration-gray-300 dark:decoration-gray-600 underline-offset-2">
|
||||
{f.text}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 mb-8">
|
||||
<div className="flex -space-x-2">
|
||||
{avatarPhotos.slice(0, 8).map((src, i) => (
|
||||
<img
|
||||
key={i}
|
||||
src={src}
|
||||
alt=""
|
||||
className="w-8 h-8 sm:w-9 sm:h-9 rounded-full border-2 border-white dark:border-gray-800 shadow-sm object-cover"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||
已有 5,000+ 成员加入
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="lg:w-[360px] xl:w-[400px] shrink-0 mt-10 lg:mt-4">
|
||||
<div className="bg-white dark:bg-gray-900 rounded-2xl shadow-xl overflow-hidden border border-gray-100 dark:border-gray-800">
|
||||
<div className="relative h-48 sm:h-56 bg-gradient-to-br from-emerald-400 via-teal-500 to-cyan-600 flex items-center justify-center overflow-hidden">
|
||||
<button className="relative w-16 h-16 rounded-full bg-white/95 flex items-center justify-center shadow-lg hover:scale-110 transition-transform">
|
||||
<svg className="w-7 h-7 text-emerald-600 ml-1" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!isLoggedIn ? (
|
||||
<form onSubmit={handleJoinClick} className="p-4 sm:p-5">
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => { setEmail(e.target.value); setError(null); }}
|
||||
placeholder="输入邮箱,加入社区"
|
||||
className="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-4 py-3 text-sm placeholder-gray-400 dark:placeholder-gray-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-[#ff4d4f]/20 focus:border-[#ff4d4f] transition-colors mb-3"
|
||||
/>
|
||||
{error && (
|
||||
<p className="mb-3 text-sm text-red-600 dark:text-red-400">{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={checking}
|
||||
className="w-full bg-[#ff4d4f] hover:bg-[#ff3333] dark:hover:bg-[#ff5c5e] text-white py-3 rounded-lg text-sm font-semibold transition-colors active:scale-[0.98] disabled:opacity-70"
|
||||
>
|
||||
{checking ? "处理中…" : "加入社区 →"}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="p-4 sm:p-5 text-center">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
您已登录,可前往社区参与互动
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<JoinModal
|
||||
isOpen={joinModalOpen}
|
||||
onClose={() => { setJoinModalOpen(false); setJoinModalVipOnly(false); }}
|
||||
initialEmail={email.trim()}
|
||||
vipOnly={joinModalVipOnly}
|
||||
/>
|
||||
|
||||
<div className="mt-4 flex flex-wrap gap-2 justify-center">
|
||||
<Link href="/join" className="text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 bg-white dark:bg-gray-800 rounded-full px-3 py-1.5 border border-gray-100 dark:border-gray-700 transition-colors min-h-[2rem] inline-flex items-center">
|
||||
💬 加入社区
|
||||
<p className="mt-1.5 text-stone-500 dark:text-stone-450 text-xs sm:text-sm max-w-lg">
|
||||
公开场地 · 填表申请 · 茶歇 · 不尬聊
|
||||
</p>
|
||||
<div className="mt-6 sm:mt-8 hidden sm:block">
|
||||
<Link
|
||||
href="/join"
|
||||
className="inline-flex items-center justify-center min-w-[180px] sm:min-w-[220px] bg-amber-600 hover:bg-amber-700 text-white px-8 py-2.5 sm:px-10 sm:py-3 rounded-xl text-sm font-medium shadow-lg shadow-amber-900/20 transition-all active:scale-[0.98]"
|
||||
>
|
||||
立即报名
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mainSession && (
|
||||
<div className="w-full max-w-[280px] sm:max-w-none lg:w-[520px] xl:w-[580px] shrink-0 mt-6 lg:mt-0 mx-auto lg:mx-0">
|
||||
<Link
|
||||
href={`/join?session=${mainSession.id}`}
|
||||
className="group flex flex-col lg:flex-row rounded-xl lg:rounded-2xl overflow-hidden bg-white dark:bg-stone-900 shadow-lg lg:shadow-xl shadow-stone-200/60 dark:shadow-stone-950/80 border border-stone-100 dark:border-stone-800 hover:shadow-xl lg:hover:shadow-2xl hover:shadow-amber-900/15 transition-all duration-300 hover:-translate-y-0.5 lg:hover:-translate-y-1"
|
||||
>
|
||||
{/* 图片区 - 左侧/上方 */}
|
||||
<div className="relative lg:w-[44%] aspect-[16/10] sm:aspect-[4/3] lg:aspect-auto lg:min-h-[180px] w-full bg-stone-100 dark:bg-stone-800 overflow-hidden shrink-0">
|
||||
{mainSession.coverImage ? (
|
||||
<SessionCoverImage
|
||||
src={mainSession.coverImage}
|
||||
alt={mainSession.title}
|
||||
type={mainSession.type}
|
||||
fill
|
||||
sizes="(max-width: 1024px) 100vw, 260px"
|
||||
className="object-cover transition-transform duration-500 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-4xl bg-stone-200 dark:bg-stone-700">
|
||||
☕
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-black/20 via-transparent to-transparent lg:from-transparent lg:via-transparent lg:to-black/30" aria-hidden />
|
||||
<div className="absolute bottom-1.5 left-1.5 sm:bottom-2 sm:left-2 lg:bottom-3 lg:left-3 flex flex-wrap gap-1 lg:gap-1.5">
|
||||
{["周末", "4人成行"].map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="inline-block text-[9px] sm:text-[10px] font-semibold bg-white/95 dark:bg-stone-900/95 backdrop-blur-sm px-2 sm:px-2.5 py-0.5 sm:py-1 rounded text-stone-700 dark:text-stone-200"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 内容区 - 右侧/下方 */}
|
||||
<div className="flex-1 flex flex-col justify-center p-3 sm:p-5 lg:p-6 lg:pl-6 min-w-0">
|
||||
<div className="inline-flex items-center gap-1.5 sm:gap-2 mb-2 sm:mb-3">
|
||||
<span className="w-0.5 sm:w-1 h-3 sm:h-4 rounded-full bg-amber-500 dark:bg-amber-500" aria-hidden />
|
||||
<p className="text-[9px] sm:text-[10px] font-semibold text-amber-600 dark:text-amber-400 uppercase tracking-[0.15em] sm:tracking-[0.2em]">
|
||||
本周场次
|
||||
</p>
|
||||
</div>
|
||||
<h3 className="font-bold text-stone-800 dark:text-stone-100 text-sm sm:text-lg lg:text-xl leading-tight tracking-tight">
|
||||
{mainSession.title}
|
||||
</h3>
|
||||
<div className="mt-2 sm:mt-3 space-y-1 sm:space-y-1.5">
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400">
|
||||
<span className="inline-block w-12 sm:w-14 text-stone-400 dark:text-stone-500">日期</span>
|
||||
{mainSession.date}
|
||||
</p>
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400">
|
||||
<span className="inline-block w-12 sm:w-14 text-stone-400 dark:text-stone-500">时间</span>
|
||||
{mainSession.time}
|
||||
</p>
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400">
|
||||
<span className="inline-block w-12 sm:w-14 text-stone-400 dark:text-stone-500">地点</span>
|
||||
<AddressLink place={mainSession.place} city={mainSession.city} />
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-3 sm:mt-4 pt-3 sm:pt-4 border-t border-stone-100 dark:border-stone-800 flex items-center justify-between gap-2 sm:gap-4">
|
||||
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
|
||||
<div className="flex -space-x-2 sm:-space-x-2.5 shrink-0">
|
||||
{mergeJoiners(MOCK_JOINERS_SESSION1, stats?.joiners).map((j, i) => (
|
||||
<HeroAvatarItem key={`${i}-${("name" in j ? j.name : j.nickname) || i}`} joiner={j} />
|
||||
))}
|
||||
</div>
|
||||
<span className="text-[10px] sm:text-xs text-stone-500 dark:text-stone-400 truncate">
|
||||
{3 + getUniqueDbCount(stats?.joiners)} 人已报名
|
||||
</span>
|
||||
</div>
|
||||
<span className="shrink-0 inline-flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1 sm:py-1.5 rounded-md sm:rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 font-semibold text-xs sm:text-sm group-hover:bg-amber-100 dark:group-hover:bg-amber-900/30 transition-all group-hover:gap-2">
|
||||
报名
|
||||
<span className="text-amber-500 dark:text-amber-400">→</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
271
app/components/HomeContent.tsx
Normal file
271
app/components/HomeContent.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
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";
|
||||
import { useCompleteOrderPolling } from "@/app/hooks/useCompleteOrderPolling";
|
||||
import { Check, X, ClipboardList, Calendar, Lightbulb, Users, HelpCircle } from "lucide-react";
|
||||
|
||||
export type JoinStatsMap = Record<string, { count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] }>;
|
||||
|
||||
interface HomeContentProps {
|
||||
initialVolunteer: { nickname: string; avatar?: string; xiaohongshu_url?: string } | null;
|
||||
}
|
||||
|
||||
const VOLUNTEER_BIO = "签到、茶歇准备、拍照摄像。";
|
||||
|
||||
function getPendingOrderId(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const cookie = document.cookie.split(";").find((c) => c.trim().startsWith("join_pay_order="));
|
||||
const raw = cookie?.split("=")[1]?.trim();
|
||||
const decoded = raw ? decodeURIComponent(raw) : "";
|
||||
const fromStorage = localStorage.getItem("join_pay_order") || "";
|
||||
const value = decoded || fromStorage;
|
||||
const orderId = value.split("|")[0]?.trim() || "";
|
||||
return orderId || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default function HomeContent({ initialVolunteer }: HomeContentProps) {
|
||||
const pathname = usePathname();
|
||||
const [volunteer, setVolunteer] = useState(initialVolunteer);
|
||||
const [stats, setStats] = useState<JoinStatsMap | null>(null);
|
||||
const [pendingOrderId] = useState<string | null>(() =>
|
||||
typeof window !== "undefined" ? getPendingOrderId() : null
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/join/volunteers")
|
||||
.then((r) => r.json())
|
||||
.then((d) => d?.volunteer && setVolunteer(d.volunteer))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const fetchStats = useCallback(() => {
|
||||
fetch(`/api/join/stats?_=${Date.now()}`, { cache: "no-store" })
|
||||
.then((r) => r.json())
|
||||
.then((d) => d?.stats && setStats(d.stats))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pathname !== "/") return;
|
||||
fetchStats();
|
||||
const onVisible = () => fetchStats();
|
||||
const onPageShow = (e: PageTransitionEvent) => {
|
||||
if (e.persisted) fetchStats();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
window.addEventListener("pageshow", onPageShow);
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
window.removeEventListener("pageshow", onPageShow);
|
||||
};
|
||||
}, [pathname, fetchStats]);
|
||||
|
||||
useCompleteOrderPolling({
|
||||
orderId: pendingOrderId,
|
||||
retryDelays: [500, 1000, 1500, 2500, 4000],
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950 pb-20 sm:pb-12">
|
||||
<Header />
|
||||
<HeroSection />
|
||||
|
||||
<main className="max-w-[900px] md:max-w-[1024px] mx-auto px-4 sm:px-6 md:px-8 py-8 sm:py-12 md:py-14 space-y-10 sm:space-y-14">
|
||||
<MyRegistrationStatus />
|
||||
{/* 是什么 / 不是什么 - 小红书风格 */}
|
||||
<section>
|
||||
<div className="rounded-xl sm:rounded-2xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 p-4 sm:p-6 overflow-hidden">
|
||||
<div className="grid sm:grid-cols-2 gap-6 sm:gap-8">
|
||||
<div>
|
||||
<h3 className="text-base sm:text-lg font-semibold text-stone-800 dark:text-stone-100 mb-3 flex items-center gap-2">
|
||||
<Check className="size-4 sm:size-5 text-amber-600 dark:text-amber-400 shrink-0" aria-hidden /> 是什么 · 适合谁
|
||||
</h3>
|
||||
<ul className="space-y-1.5 text-sm text-stone-600 dark:text-stone-400">
|
||||
<li>· 周末同城轻社交,loft民宿见~</li>
|
||||
<li>· 4–8 人小圈子,聊得来就多聊</li>
|
||||
<li>· 第一次来也完全 OK</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base sm:text-lg font-semibold text-stone-800 dark:text-stone-100 mb-3 flex items-center gap-2">
|
||||
<X className="size-4 sm:size-5 text-stone-400 dark:text-stone-500 shrink-0" aria-hidden /> 不是什么 · 不适合谁
|
||||
</h3>
|
||||
<ul className="space-y-1.5 text-sm text-stone-600 dark:text-stone-400">
|
||||
<li>· 不是相亲局、卖课、强制破冰</li>
|
||||
<li>· 只想线上聊、想加所有人微信的 pass</li>
|
||||
<li>· 想销售引流、不尊重边界的 pass</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 报名流程 */}
|
||||
<section>
|
||||
<h2 className="text-lg sm:text-xl font-semibold text-stone-800 dark:text-stone-100 mb-4 sm:mb-5 flex items-center gap-2">
|
||||
<ClipboardList className="size-5 text-amber-600 dark:text-amber-400 shrink-0" aria-hidden /> 怎么参加
|
||||
</h2>
|
||||
<div className="rounded-xl sm:rounded-2xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 p-4 sm:p-6 md:p-8">
|
||||
<div className="grid grid-cols-3 gap-3 sm:gap-6 md:gap-8">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<div className="w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 font-bold text-sm sm:text-lg flex items-center justify-center mb-2 sm:mb-3">1</div>
|
||||
<h4 className="font-semibold text-stone-800 dark:text-stone-100 text-xs sm:text-base">填表</h4>
|
||||
</div>
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<div className="w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 font-bold text-sm sm:text-lg flex items-center justify-center mb-2 sm:mb-3">2</div>
|
||||
<h4 className="font-semibold text-stone-800 dark:text-stone-100 text-xs sm:text-base">审核</h4>
|
||||
</div>
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<div className="w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 font-bold text-sm sm:text-lg flex items-center justify-center mb-2 sm:mb-3">3</div>
|
||||
<h4 className="font-semibold text-stone-800 dark:text-stone-100 text-xs sm:text-base leading-tight">通过后联系你确认</h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 信任标签 */}
|
||||
<div className="flex flex-wrap justify-center gap-x-6 gap-y-1.5 sm:gap-x-8 text-xs sm:text-sm text-stone-600 dark:text-stone-400">
|
||||
<span>📍 公开场地</span>
|
||||
<span>👥 4–8 人</span>
|
||||
<span>✍️ 填表申请</span>
|
||||
<span>☕ 茶歇</span>
|
||||
</div>
|
||||
|
||||
{/* 本周场次 */}
|
||||
<section>
|
||||
<h2 className="text-lg sm:text-xl font-semibold text-stone-800 dark:text-stone-100 mb-4 sm:mb-5 flex items-center gap-2">
|
||||
<Calendar className="size-5 text-amber-600 dark:text-amber-400 shrink-0" aria-hidden /> 本周活动
|
||||
</h2>
|
||||
<div className="grid gap-3 sm:gap-4 sm:grid-cols-2 animate-fade-in-stagger">
|
||||
{getSessionsWithDates().map((s, i) => (
|
||||
<SessionCard key={s.id} session={s} index={i} stats={stats?.[s.id] ?? null} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 活动亮点 */}
|
||||
<section>
|
||||
<h2 className="text-lg sm:text-xl font-semibold text-stone-800 dark:text-stone-100 mb-4 sm:mb-5 flex items-center gap-2">
|
||||
<Lightbulb className="size-5 text-amber-600 dark:text-amber-400 shrink-0" aria-hidden /> 活动亮点
|
||||
</h2>
|
||||
<div className="rounded-xl sm:rounded-2xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 p-4 sm:p-6 md:p-8">
|
||||
<div className="grid sm:grid-cols-2 gap-4 sm:gap-6">
|
||||
{[
|
||||
{ icon: "😌", title: "氛围轻松", desc: "loft民宿里的小聚,不用尬聊,聊得来就多聊~" },
|
||||
{ icon: "🛡️", title: "安全靠谱", desc: "公开场地,地址提前说。尊重边界,不追问隐私。" },
|
||||
{ icon: "👍", title: "第一次也 OK", desc: "很多人都是第一次来,小圈子人数可控~" },
|
||||
{ icon: "✍️", title: "填表就行", desc: "不用注册、不用先付,填个表就好。" },
|
||||
].map((item) => (
|
||||
<div key={item.title} className="flex gap-2.5 sm:gap-3">
|
||||
<span className="text-xl sm:text-2xl shrink-0">{item.icon}</span>
|
||||
<div>
|
||||
<p className="font-medium text-stone-800 dark:text-stone-100 text-sm sm:text-base">{item.title}</p>
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400 mt-0.5 leading-relaxed">{item.desc}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 发起人 + 志愿者(有志愿者时替换 host-2 卡片) */}
|
||||
<section>
|
||||
<h2 className="text-lg sm:text-xl font-semibold text-stone-800 dark:text-stone-100 mb-4 sm:mb-5 flex items-center gap-2">
|
||||
<Users className="size-5 text-amber-600 dark:text-amber-400 shrink-0" aria-hidden /> 发起人
|
||||
</h2>
|
||||
<div className="grid sm:grid-cols-2 gap-3 sm:gap-4 mb-4">
|
||||
{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,
|
||||
link: volunteer.xiaohongshu_url || host.link,
|
||||
}
|
||||
: host;
|
||||
return (
|
||||
<HostLink
|
||||
key={host.id}
|
||||
host={displayHost}
|
||||
{...(isHost2 && !volunteer && {
|
||||
ctaText: "立即申请",
|
||||
showFreeBadge: true,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* FAQ */}
|
||||
<section id="faq">
|
||||
<h2 className="text-lg sm:text-xl font-semibold text-stone-800 dark:text-stone-100 mb-4 sm:mb-5 flex items-center gap-2">
|
||||
<HelpCircle className="size-5 text-amber-600 dark:text-amber-400 shrink-0" aria-hidden /> 常见问题
|
||||
</h2>
|
||||
<div className="space-y-2 sm:space-y-3">
|
||||
{[
|
||||
{ q: "提交后多久会收到确认?", a: "活动前 1–2 天会联系,微信/短信确认。不匹配不会反复打扰~", icon: "⏱️" },
|
||||
{ q: "第一次参加可以吗?", a: "可以呀!很多人都是第一次来。4–8 人小圈子、公开场地,聊得来就多聊~", icon: "✨" },
|
||||
{ q: "临时有事怎么办?", a: "随时可以退出,提前说一声就行~", icon: "🔄" },
|
||||
].map((faq) => (
|
||||
<details
|
||||
key={faq.q}
|
||||
className="group rounded-lg sm:rounded-xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 overflow-hidden"
|
||||
>
|
||||
<summary className="flex items-center gap-2.5 sm:gap-3 p-3 sm:p-4 cursor-pointer list-none [&::-webkit-details-marker]:hidden select-none">
|
||||
<span className="text-base sm:text-lg shrink-0">{faq.icon}</span>
|
||||
<p className="font-medium text-stone-800 dark:text-stone-100 text-xs sm:text-sm flex-1">{faq.q}</p>
|
||||
<span className="shrink-0 text-stone-400 text-xs transition-transform duration-200 group-open:rotate-180">▼</span>
|
||||
</summary>
|
||||
<div className="px-3 pb-3 sm:px-4 sm:pb-4 pt-0 flex gap-2.5 sm:gap-3">
|
||||
<span className="w-[1.25rem] sm:w-[1.5rem] shrink-0" aria-hidden />
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400 leading-relaxed">{faq.a}</p>
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* CTA - 移动端隐藏,只保留底部悬浮去报名 */}
|
||||
<section className="pt-2 sm:pt-4 hidden sm:block">
|
||||
<Link
|
||||
href="/join"
|
||||
className="block w-full min-w-[200px] bg-amber-600 hover:bg-amber-700 text-white text-center py-3.5 sm:py-4 rounded-xl font-semibold text-sm sm:text-base shadow-lg shadow-amber-900/20 transition-all"
|
||||
>
|
||||
立即报名
|
||||
</Link>
|
||||
<p className="mt-3 text-center text-xs sm:text-sm text-stone-500 dark:text-stone-400">
|
||||
先填表,我们会根据场次联系你~
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
{/* 移动端悬浮 CTA */}
|
||||
<div className="fixed bottom-0 left-0 right-0 p-3 sm:p-4 bg-white/95 dark:bg-stone-900/95 backdrop-blur border-t border-stone-200 dark:border-stone-800 sm:hidden z-50 safe-area-pb">
|
||||
<Link
|
||||
href="/join"
|
||||
className="block w-full bg-amber-600 hover:bg-amber-700 text-white text-center py-3 rounded-xl font-medium text-sm"
|
||||
>
|
||||
去报名
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
78
app/components/HostLink.tsx
Normal file
78
app/components/HostLink.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
|
||||
interface HostLinkProps {
|
||||
host: { id: string; name: string; avatar: string; bio: string; link?: string };
|
||||
/** 志愿者招募:无审核通过时显示「立即申请」+ 免费标识 */
|
||||
ctaText?: string;
|
||||
showFreeBadge?: boolean;
|
||||
/** 卡片有 link 样式但不可点击跳转 */
|
||||
noLink?: boolean;
|
||||
}
|
||||
|
||||
/** 移动端优先尝试唤醒小红书 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) {
|
||||
e.preventDefault();
|
||||
// 移动端:同窗口打开,xhslink.com 会尝试唤起小红书 app,未安装则打开网页
|
||||
window.location.assign(href);
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof href !== "string") return null;
|
||||
|
||||
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 = (
|
||||
<>
|
||||
<div className="relative w-14 h-14 sm:w-16 sm:h-16 shrink-0 rounded-full overflow-hidden border-2 border-amber-100 dark:border-amber-900/30">
|
||||
<Image src={host.avatar} alt={host.name} fill sizes="64px" className="object-cover" unoptimized />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h3 className="font-semibold text-stone-800 dark:text-stone-100 text-sm sm:text-base">{host.name}</h3>
|
||||
{showFreeBadge && (
|
||||
<span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300">
|
||||
FREE
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-0.5 text-xs sm:text-sm text-stone-500 dark:text-stone-400 line-clamp-2">{host.bio}</p>
|
||||
<span className="inline-flex items-center gap-1 mt-2 text-amber-600 dark:text-amber-400 text-xs font-medium">
|
||||
{ctaText ?? "查看主页"} →
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
if (noLink) {
|
||||
return (
|
||||
<div className={`${cardClassName} cursor-default`}>
|
||||
{cardContent}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
target={href.startsWith("http") ? "_blank" : undefined}
|
||||
rel={href.startsWith("http") ? "noopener noreferrer" : undefined}
|
||||
onClick={handleClick}
|
||||
className={cardClassName}
|
||||
>
|
||||
{cardContent}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import { createPortal } from "react-dom";
|
||||
import {
|
||||
getPayEnv,
|
||||
redirectToPay,
|
||||
redirectToPayH5,
|
||||
payWechatXorpaySync,
|
||||
getDeviceFromEnv,
|
||||
} from "@/app/lib/payment";
|
||||
import type { PayChannel } from "@/app/lib/payment";
|
||||
@@ -70,15 +72,20 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly
|
||||
return;
|
||||
}
|
||||
const returnUrl = typeof window !== "undefined" ? `${window.location.origin}/join/paid` : "/join/paid";
|
||||
const env = getPayEnv();
|
||||
const channel: PayChannel = "wxpay";
|
||||
redirectToPay({
|
||||
const device = getDeviceFromEnv(getPayEnv());
|
||||
const base = {
|
||||
user_id: data.user_id,
|
||||
return_url: returnUrl,
|
||||
channel,
|
||||
device: getDeviceFromEnv(env),
|
||||
channel: "wxpay" as PayChannel,
|
||||
useJoinConfig: true,
|
||||
});
|
||||
};
|
||||
if (device === "wechat") {
|
||||
payWechatXorpaySync(base);
|
||||
} else if (device === "h5") {
|
||||
await redirectToPayH5(base);
|
||||
} else {
|
||||
redirectToPay({ ...base, device });
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "操作失败");
|
||||
} finally {
|
||||
|
||||
174
app/components/MyRegistrationStatus.tsx
Normal file
174
app/components/MyRegistrationStatus.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
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<UserRecord | null>(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)}&_=${Date.now()}`, { cache: "no-store" })
|
||||
.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);
|
||||
}
|
||||
};
|
||||
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
let cancelled = false;
|
||||
fetchStatus();
|
||||
const onUpdate = () => {
|
||||
if (!cancelled) fetchStatus();
|
||||
};
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible" && !cancelled) fetchStatus();
|
||||
};
|
||||
const onPageShow = (e: PageTransitionEvent) => {
|
||||
if (e.persisted && !cancelled) fetchStatus();
|
||||
};
|
||||
window.addEventListener("vip:updated", onUpdate);
|
||||
window.addEventListener("registration:refresh", onUpdate);
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
window.addEventListener("pageshow", onPageShow);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener("vip:updated", onUpdate);
|
||||
window.removeEventListener("registration:refresh", onUpdate);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
window.removeEventListener("pageshow", onPageShow);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 每次进入首页时强制重新拉取,避免预取/缓存导致显示旧状态
|
||||
useEffect(() => {
|
||||
if (pathname === "/") fetchStatus();
|
||||
}, [pathname]);
|
||||
|
||||
if (loading || !data?.hasRecord || !data.record) return null;
|
||||
|
||||
const rec = data.record;
|
||||
const status = getStatusLabel(data);
|
||||
const statusColor = getStatusColor(status);
|
||||
|
||||
return (
|
||||
<section className="mb-8 sm:mb-10">
|
||||
<div className="rounded-xl sm:rounded-2xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 p-4 sm:p-6 overflow-hidden">
|
||||
<h3 className="text-sm font-medium text-stone-500 dark:text-stone-400 mb-3 flex items-center gap-2">
|
||||
<span>👤</span> 我的报名
|
||||
</h3>
|
||||
<div className="flex items-center gap-3 sm:gap-4">
|
||||
<div className="relative shrink-0">
|
||||
<div className="relative w-12 h-12 sm:w-14 sm:h-14 rounded-full overflow-hidden border-2 border-stone-200 dark:border-stone-600">
|
||||
{rec.media ? (
|
||||
<Image
|
||||
src={rec.media}
|
||||
alt=""
|
||||
fill
|
||||
sizes="56px"
|
||||
className="object-cover"
|
||||
unoptimized
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center bg-amber-100 dark:bg-amber-900/40 text-xl sm:text-2xl">
|
||||
👤
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{rec.is_volunteer && (
|
||||
<span className="absolute -bottom-1 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded text-[10px] font-medium bg-amber-500 text-white whitespace-nowrap">
|
||||
志愿者
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-semibold text-stone-800 dark:text-stone-100 truncate">
|
||||
{rec.nickname || "—"}
|
||||
</p>
|
||||
{rec.wechatId && (
|
||||
<p className="text-xs text-stone-500 dark:text-stone-400 font-mono truncate mt-0.5">
|
||||
微信号: {rec.wechatId}
|
||||
</p>
|
||||
)}
|
||||
<span
|
||||
className={`inline-block mt-2 px-2.5 py-1 rounded-lg text-xs font-medium ${statusColor}`}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
<Link
|
||||
href="/join"
|
||||
className="shrink-0 text-sm font-medium text-amber-600 dark:text-amber-400 hover:text-amber-700 dark:hover:text-amber-300"
|
||||
>
|
||||
查看详情 →
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
145
app/components/SessionCard.tsx
Normal file
145
app/components/SessionCard.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { RefreshCw, Coffee } from "lucide-react";
|
||||
import SessionCoverImage from "./SessionCoverImage";
|
||||
import AddressLink from "./AddressLink";
|
||||
import { ACTIVITY_TYPES, SESSION_TAGS, MOCK_JOINERS_SESSION1, MOCK_JOINERS_SESSION2 } from "@/config/home.config";
|
||||
import { mergeJoiners, getUniqueDbCount } from "@/app/lib/joiners";
|
||||
import { useXhClickOpener } from "@/app/hooks/useXhClickOpener";
|
||||
|
||||
interface JoinStats {
|
||||
count: number;
|
||||
joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[];
|
||||
}
|
||||
|
||||
function getMockForSession(sessionId: string) {
|
||||
return sessionId === "session-1" ? MOCK_JOINERS_SESSION1 : MOCK_JOINERS_SESSION2;
|
||||
}
|
||||
|
||||
function AvatarItem({ joiner }: { joiner: { name?: string; nickname?: string; avatar?: string; xiaohongshu_url?: string } }) {
|
||||
const [imgError, setImgError] = useState(false);
|
||||
const nickname = ("name" in joiner ? joiner.name : joiner.nickname) ?? "";
|
||||
const avatar = joiner.avatar;
|
||||
const xhUrl = joiner.xiaohongshu_url;
|
||||
const showAvatar = avatar && avatar.length > 0 && !imgError;
|
||||
const handleClick = useXhClickOpener(xhUrl);
|
||||
|
||||
return (
|
||||
<span
|
||||
className="relative w-7 h-7 rounded-full overflow-hidden border-2 border-white dark:border-stone-900 ring-1 ring-stone-200/50 dark:ring-stone-700/50 shrink-0 inline-block cursor-default"
|
||||
{...(xhUrl && { "data-xiaohongshu-url": xhUrl })}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{showAvatar ? (
|
||||
<Image src={avatar} alt="" fill sizes="28px" className="object-cover" unoptimized onError={() => setImgError(true)} />
|
||||
) : (
|
||||
<span className="flex items-center justify-center w-full h-full text-xs font-medium bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300">
|
||||
{nickname.slice(0, 1) || "?"}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
type SessionTag = keyof typeof SESSION_TAGS;
|
||||
|
||||
interface SessionItem {
|
||||
id: string;
|
||||
type: "skill-exchange" | "side-hustle" | "loft" | "light-chat";
|
||||
title: string;
|
||||
date: string;
|
||||
time: string;
|
||||
place: string;
|
||||
city: string;
|
||||
coverImage?: string;
|
||||
tags?: readonly SessionTag[];
|
||||
}
|
||||
|
||||
export default function SessionCard({
|
||||
session,
|
||||
index,
|
||||
stats,
|
||||
}: {
|
||||
session: SessionItem;
|
||||
index: number;
|
||||
stats: JoinStats | null;
|
||||
}) {
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col sm:flex-row 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 hover:shadow-amber-900/5 transition-all duration-200 ease-out">
|
||||
<div className="relative w-full sm:w-36 md:w-40 sm:min-w-[144px] md:min-w-[160px] shrink-0 aspect-[16/10] rounded-lg sm:rounded-xl overflow-hidden bg-stone-100 dark:bg-stone-800">
|
||||
{session.coverImage ? (
|
||||
<SessionCoverImage
|
||||
src={session.coverImage}
|
||||
alt={session.title}
|
||||
type={session.type}
|
||||
fill
|
||||
sizes="(max-width: 640px) 100vw, (max-width: 768px) 144px, 160px"
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-amber-500/70 dark:text-amber-400/50">
|
||||
{session.type === "skill-exchange" ? <RefreshCw className="size-8" aria-hidden /> : <Coffee className="size-8" aria-hidden />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap gap-1 mb-1.5 min-h-[1.5rem]">
|
||||
{session.tags?.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="inline-block text-[9px] sm:text-[10px] font-medium text-amber-600 dark:text-amber-400/90 bg-amber-50 dark:bg-amber-900/20 px-1.5 py-0.5 rounded"
|
||||
>
|
||||
{SESSION_TAGS[tag]}
|
||||
</span>
|
||||
))}
|
||||
{!session.tags?.includes("light-topic") && (
|
||||
<span className="inline-block text-[9px] sm:text-[10px] font-medium px-1.5 py-0.5 rounded opacity-0" aria-hidden>
|
||||
{SESSION_TAGS["light-topic"]}
|
||||
</span>
|
||||
)}
|
||||
{index === 0 ? (
|
||||
<span className="inline-block text-[9px] sm:text-[10px] font-medium text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 px-1.5 py-0.5 rounded">
|
||||
主推
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-block text-[9px] sm:text-[10px] font-medium px-1.5 py-0.5 rounded opacity-0" aria-hidden>
|
||||
主推
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[10px] sm:text-xs text-amber-600 dark:text-amber-400/90">
|
||||
{ACTIVITY_TYPES[session.type]} · {session.city}
|
||||
</span>
|
||||
<h3 className="font-semibold text-stone-800 dark:text-stone-100 text-sm sm:text-base group-hover:text-amber-700 dark:group-hover:text-amber-400 mt-0.5">
|
||||
{session.title}
|
||||
</h3>
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400 mt-0.5">
|
||||
{session.date} {session.time}
|
||||
</p>
|
||||
<p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400 mt-0.5">
|
||||
<AddressLink place={session.place} city={session.city} />
|
||||
</p>
|
||||
<Link
|
||||
href={`/join?session=${encodeURIComponent(session.id)}`}
|
||||
className="inline-flex items-center gap-1 mt-2 sm:mt-3 text-amber-600 dark:text-amber-400 text-xs sm:text-sm font-medium hover:text-amber-700 dark:hover:text-amber-300 transition-colors"
|
||||
>
|
||||
报名这场 →
|
||||
</Link>
|
||||
<div className="mt-3 flex items-center gap-2 min-w-0 overflow-hidden">
|
||||
<div className="flex -space-x-2 shrink-0">
|
||||
{mergeJoiners(getMockForSession(session.id), stats?.joiners).map((j, i) => (
|
||||
<AvatarItem key={`${i}-${(j.nickname || j.name) || i}`} joiner={j} />
|
||||
))}
|
||||
</div>
|
||||
<span className="text-xs text-stone-500 dark:text-stone-400">
|
||||
{3 + getUniqueDbCount(stats?.joiners)} 人已报名
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
app/components/SessionCoverImage.tsx
Normal file
37
app/components/SessionCoverImage.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Image from "next/image";
|
||||
|
||||
interface SessionCoverImageProps {
|
||||
src: string;
|
||||
alt: string;
|
||||
type?: "skill-exchange" | "side-hustle" | "loft" | "light-chat";
|
||||
className?: string;
|
||||
fill?: boolean;
|
||||
sizes?: string;
|
||||
}
|
||||
|
||||
export default function SessionCoverImage({ src, alt, type, className = "", fill, sizes }: SessionCoverImageProps) {
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-stone-200 dark:bg-stone-700 text-2xl sm:text-3xl">
|
||||
{type === "loft" ? "🏠" : type === "skill-exchange" ? "🔄" : "☕"}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Image
|
||||
src={src}
|
||||
alt={alt}
|
||||
fill={fill}
|
||||
sizes={sizes}
|
||||
className={className}
|
||||
unoptimized
|
||||
onError={() => setError(true)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
18
app/components/ThemeProvider.tsx
Normal file
18
app/components/ThemeProvider.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||
|
||||
export default function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<NextThemesProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
enableSystem
|
||||
enableColorScheme
|
||||
storageKey="salon-theme"
|
||||
disableTransitionOnChange
|
||||
>
|
||||
{children}
|
||||
</NextThemesProvider>
|
||||
);
|
||||
}
|
||||
45
app/components/ThemeToggle.tsx
Normal file
45
app/components/ThemeToggle.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function ThemeToggle() {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="切换主题"
|
||||
className="p-2.5 rounded-lg text-stone-500 hover:bg-stone-100 dark:hover:bg-stone-800 transition-colors"
|
||||
>
|
||||
<span className="w-5 h-5 block" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const isDark = theme === "dark";
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={isDark ? "切换到日间模式" : "切换到夜间模式"}
|
||||
onClick={() => setTheme(isDark ? "light" : "dark")}
|
||||
className="p-2.5 rounded-lg text-stone-500 hover:text-stone-700 hover:bg-stone-100 dark:text-stone-400 dark:hover:text-stone-200 dark:hover:bg-stone-800 transition-colors"
|
||||
>
|
||||
{isDark ? (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,19 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* 使 Tailwind dark: 变体响应 class="dark",与 next-themes 配合 */
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
:root {
|
||||
--background: #fafafa;
|
||||
--foreground: #171717;
|
||||
--background: #faf8f5;
|
||||
--foreground: #1c1917;
|
||||
--accent: #b45309;
|
||||
--accent-hover: #92400e;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
html.dark {
|
||||
--background: #0c0a09;
|
||||
--foreground: #fafaf9;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
@@ -17,13 +21,23 @@ body {
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
.safe-area-pb {
|
||||
padding-bottom: env(safe-area-inset-bottom, 0);
|
||||
}
|
||||
|
||||
.hero-gradient-text {
|
||||
background: linear-gradient(135deg, #f97316 0%, #ea580c 50%, #c2410c 100%);
|
||||
background: linear-gradient(135deg, #b45309 0%, #d97706 50%, #f59e0b 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: #b45309;
|
||||
box-shadow: 0 0 0 2px rgba(180, 83, 9, 0.2);
|
||||
}
|
||||
|
||||
.items-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
@@ -67,16 +81,20 @@ body {
|
||||
|
||||
.form-input {
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.75rem;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.9375rem;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: #ff4d4f;
|
||||
box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
|
||||
.form-input:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.form-input::placeholder {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.dark .form-input {
|
||||
@@ -84,6 +102,10 @@ body {
|
||||
background: #1f2937;
|
||||
}
|
||||
|
||||
.dark .form-input::placeholder {
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.dark .right-item,
|
||||
.dark .community-card {
|
||||
background: #111827;
|
||||
@@ -105,3 +127,35 @@ body {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(20px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.animate-fade-in {
|
||||
animation: fadeIn 0.4s cubic-bezier(0.22, 1, 0.36, 1) forwards;
|
||||
}
|
||||
|
||||
/* 卡片依次淡入,用于列表 */
|
||||
.animate-fade-in-stagger > * {
|
||||
opacity: 0;
|
||||
animation: fadeIn 0.4s cubic-bezier(0.22, 1, 0.36, 1) forwards;
|
||||
}
|
||||
|
||||
.animate-fade-in-stagger > *:nth-child(1) { animation-delay: 0ms; }
|
||||
.animate-fade-in-stagger > *:nth-child(2) { animation-delay: 80ms; }
|
||||
.animate-fade-in-stagger > *:nth-child(3) { animation-delay: 160ms; }
|
||||
.animate-fade-in-stagger > *:nth-child(4) { animation-delay: 240ms; }
|
||||
.animate-fade-in-stagger > *:nth-child(5) { animation-delay: 320ms; }
|
||||
.animate-fade-in-stagger > *:nth-child(6) { animation-delay: 400ms; }
|
||||
|
||||
/* 骨架屏脉冲 */
|
||||
@keyframes pulse-subtle {
|
||||
0%, 100% { opacity: 0.6; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
.animate-pulse-subtle {
|
||||
animation: pulse-subtle 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
92
app/history/[id]/page.tsx
Normal file
92
app/history/[id]/page.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import SessionCoverImage from "../../components/SessionCoverImage";
|
||||
import AddressLink from "../../components/AddressLink";
|
||||
import Header from "../../components/Header";
|
||||
import Footer from "../../components/Footer";
|
||||
import { PAST_SESSIONS } from "@/config/home.config";
|
||||
import { ACTIVITY_TYPES } from "@/config/home.config";
|
||||
|
||||
export default function HistoryDetailPage() {
|
||||
const params = useParams();
|
||||
const id = typeof params.id === "string" ? params.id : "";
|
||||
const session = PAST_SESSIONS.find((s) => s.id === id);
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950 flex items-center justify-center">
|
||||
<div className="text-center px-4">
|
||||
<p className="text-stone-500 dark:text-stone-400 mb-4">活动不存在</p>
|
||||
<Link href="/history" className="text-amber-600 dark:text-amber-400">
|
||||
返回历史活动
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950">
|
||||
<Header />
|
||||
<main className="max-w-[600px] mx-auto px-4 sm:px-6 py-8 sm:py-12">
|
||||
<Link
|
||||
href="/history"
|
||||
className="inline-flex items-center gap-1 text-sm text-stone-500 dark:text-stone-400 hover:text-amber-600 dark:hover:text-amber-400 mb-6"
|
||||
>
|
||||
← 历史活动
|
||||
</Link>
|
||||
|
||||
<article className="rounded-2xl overflow-hidden bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700">
|
||||
<div className="relative aspect-[16/10] w-full bg-stone-100 dark:bg-stone-800">
|
||||
{session.coverImage ? (
|
||||
<SessionCoverImage
|
||||
src={session.coverImage}
|
||||
alt={session.title}
|
||||
type={session.type}
|
||||
fill
|
||||
sizes="600px"
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-4xl">☕</div>
|
||||
)}
|
||||
<div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/60 to-transparent">
|
||||
<span className="text-xs text-white/90">{ACTIVITY_TYPES[session.type]} · {session.city}</span>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-white mt-0.5">{session.title}</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-5 sm:p-6">
|
||||
<dl className="space-y-3 text-sm">
|
||||
<div>
|
||||
<dt className="text-stone-500 dark:text-stone-400">时间</dt>
|
||||
<dd className="font-medium text-stone-800 dark:text-stone-100">{session.date} {session.time}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-stone-500 dark:text-stone-400">地点</dt>
|
||||
<dd className="font-medium text-stone-800 dark:text-stone-100">
|
||||
<AddressLink place={session.place} city={session.city} className="text-stone-800 dark:text-stone-100" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-stone-500 dark:text-stone-400">城市</dt>
|
||||
<dd className="font-medium text-stone-800 dark:text-stone-100">{session.city}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="mt-4 pt-4 border-t border-stone-100 dark:border-stone-700 text-sm text-stone-600 dark:text-stone-400">
|
||||
这是一场已结束的活动。想参加本周活动?去首页看看~
|
||||
</p>
|
||||
<Link
|
||||
href="/"
|
||||
className="mt-4 inline-flex items-center justify-center w-full sm:w-auto bg-amber-600 hover:bg-amber-700 text-white px-6 py-2.5 rounded-xl text-sm font-medium"
|
||||
>
|
||||
看看本周活动
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
84
app/history/page.tsx
Normal file
84
app/history/page.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import SessionCoverImage from "../components/SessionCoverImage";
|
||||
import AddressLink from "../components/AddressLink";
|
||||
import Header from "../components/Header";
|
||||
import Footer from "../components/Footer";
|
||||
import { PAST_SESSIONS } from "@/config/home.config";
|
||||
import { ACTIVITY_TYPES } from "@/config/home.config";
|
||||
|
||||
export default function HistoryPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950">
|
||||
<Header />
|
||||
<main className="max-w-[700px] mx-auto px-4 sm:px-6 py-8 sm:py-12">
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-stone-800 dark:text-stone-100 mb-2">
|
||||
历史活动
|
||||
</h1>
|
||||
<p className="text-sm text-stone-500 dark:text-stone-400 mb-8">
|
||||
看看之前都举办了什么~
|
||||
</p>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute left-[11px] sm:left-[15px] top-0 bottom-0 w-px bg-stone-200 dark:bg-stone-700" />
|
||||
<div className="space-y-0">
|
||||
{PAST_SESSIONS.map((s, i) => (
|
||||
<Link
|
||||
key={s.id}
|
||||
href={`/history/${s.id}`}
|
||||
className="group flex gap-4 sm:gap-6 py-6 sm:py-8 relative"
|
||||
>
|
||||
<div className="relative z-10 w-6 h-6 sm:w-8 sm:h-8 rounded-full bg-amber-500 shrink-0 mt-1 flex items-center justify-center text-white text-[10px] sm:text-xs font-bold">
|
||||
{PAST_SESSIONS.length - i}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-col sm:flex-row sm:items-start gap-3 sm:gap-4">
|
||||
<div className="relative w-full sm:w-28 sm:h-28 shrink-0 aspect-[4/3] sm:aspect-square rounded-xl overflow-hidden bg-stone-100 dark:bg-stone-800">
|
||||
{s.coverImage ? (
|
||||
<SessionCoverImage
|
||||
src={s.coverImage}
|
||||
alt={s.title}
|
||||
type={s.type}
|
||||
fill
|
||||
sizes="(max-width: 640px) 100vw, 112px"
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-2xl">☕</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-[10px] sm:text-xs text-amber-600 dark:text-amber-400/90">
|
||||
{ACTIVITY_TYPES[s.type]} · {s.city}
|
||||
</span>
|
||||
<h2 className="font-semibold text-stone-800 dark:text-stone-100 text-base sm:text-lg mt-0.5 group-hover:text-amber-600 dark:group-hover:text-amber-400">
|
||||
{s.title}
|
||||
</h2>
|
||||
<p className="text-sm text-stone-500 dark:text-stone-400 mt-0.5">
|
||||
{s.date} {s.time} · <AddressLink place={s.place} city={s.city} />
|
||||
</p>
|
||||
<span className="inline-flex items-center gap-1 mt-2 text-amber-600 dark:text-amber-400 text-xs font-medium">
|
||||
查看主页 →
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-12 pt-8 border-t border-stone-200 dark:border-stone-800">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-sm text-stone-500 dark:text-stone-400 hover:text-amber-600 dark:hover:text-amber-400"
|
||||
>
|
||||
← 返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
64
app/hooks/useCompleteOrderPolling.ts
Normal file
64
app/hooks/useCompleteOrderPolling.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { tryCompleteOrder, applyCompleteSuccess } from "@/app/lib/complete-order";
|
||||
|
||||
const DEFAULT_RETRY_DELAYS = [1500, 2500, 3500, 4500, 5500];
|
||||
|
||||
export interface UseCompleteOrderPollingOptions {
|
||||
/** 待完成订单 ID,null 则不轮询 */
|
||||
orderId: string | null;
|
||||
/** 成功后的额外回调(用 ref 存储避免 deps 变化) */
|
||||
onSuccess?: (data: { token: string; record?: { wechatId?: string } }) => void;
|
||||
/** 重试间隔(毫秒) */
|
||||
retryDelays?: number[];
|
||||
}
|
||||
|
||||
/** 清除 pending order 的 cookie 和 localStorage */
|
||||
export function clearPendingOrder(): void {
|
||||
try {
|
||||
localStorage.removeItem("join_pay_order");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
document.cookie = "join_pay_order=; path=/; max-age=0";
|
||||
}
|
||||
|
||||
/** 支付完成后轮询 complete-order,成功后同步 session 并清除 pending */
|
||||
export function useCompleteOrderPolling({
|
||||
orderId,
|
||||
onSuccess,
|
||||
retryDelays = DEFAULT_RETRY_DELAYS,
|
||||
}: UseCompleteOrderPollingOptions): void {
|
||||
const onSuccessRef = useRef(onSuccess);
|
||||
onSuccessRef.current = onSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
if (!orderId || typeof window === "undefined") return;
|
||||
|
||||
let cancelled = false;
|
||||
const run = async () => {
|
||||
for (let i = 0; i <= retryDelays.length; i++) {
|
||||
if (cancelled) return;
|
||||
const result = await tryCompleteOrder(orderId);
|
||||
if (result.ok) {
|
||||
if (result.token && result.record) {
|
||||
applyCompleteSuccess({ token: result.token, record: result.record });
|
||||
} else if (result.record) {
|
||||
applyCompleteSuccess({ token: "", record: result.record });
|
||||
}
|
||||
clearPendingOrder();
|
||||
onSuccessRef.current?.({ token: result.token || "", record: result.record });
|
||||
return;
|
||||
}
|
||||
if (i < retryDelays.length && !cancelled) {
|
||||
await new Promise((r) => setTimeout(r, retryDelays[i]));
|
||||
}
|
||||
}
|
||||
};
|
||||
void run();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orderId, retryDelays]);
|
||||
}
|
||||
29
app/hooks/useXhClickOpener.ts
Normal file
29
app/hooks/useXhClickOpener.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useRef, useCallback } from "react";
|
||||
|
||||
const RESET_MS = 1000;
|
||||
const CLICK_THRESHOLD = 5;
|
||||
|
||||
/** 连续点击 5 次打开小红书主页 */
|
||||
export function useXhClickOpener(xhUrl: string | undefined) {
|
||||
const countRef = useRef(0);
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
|
||||
return useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!xhUrl) return;
|
||||
clearTimeout(timerRef.current);
|
||||
countRef.current++;
|
||||
if (countRef.current >= CLICK_THRESHOLD) {
|
||||
window.open(xhUrl, "_blank", "noopener,noreferrer");
|
||||
countRef.current = 0;
|
||||
} else {
|
||||
timerRef.current = setTimeout(() => {
|
||||
countRef.current = 0;
|
||||
}, RESET_MS);
|
||||
}
|
||||
},
|
||||
[xhUrl]
|
||||
);
|
||||
}
|
||||
97
app/host/[id]/page.tsx
Normal file
97
app/host/[id]/page.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import Header from "../../components/Header";
|
||||
import Footer from "../../components/Footer";
|
||||
import { HOSTS } from "@/config/home.config";
|
||||
|
||||
export default function HostDetailPage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const id = typeof params.id === "string" ? params.id : "";
|
||||
const host = HOSTS.find((h) => h.id === id);
|
||||
|
||||
useEffect(() => {
|
||||
if (host && "link" in host && host.link) {
|
||||
if (host.link.startsWith("http")) {
|
||||
window.location.href = host.link;
|
||||
} else {
|
||||
router.replace(host.link);
|
||||
}
|
||||
}
|
||||
}, [host, router]);
|
||||
|
||||
if (!host) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950 flex items-center justify-center">
|
||||
<div className="text-center px-4">
|
||||
<p className="text-stone-500 dark:text-stone-400 mb-4">主理人不存在</p>
|
||||
<Link href="/" className="text-amber-600 dark:text-amber-400">
|
||||
返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if ("link" in host && host.link) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950 flex items-center justify-center">
|
||||
<p className="text-stone-500 dark:text-stone-400">跳转中…</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#faf8f5] dark:bg-stone-950">
|
||||
<Header />
|
||||
<main className="max-w-[600px] mx-auto px-4 sm:px-6 py-8 sm:py-12">
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-1 text-sm text-stone-500 dark:text-stone-400 hover:text-amber-600 dark:hover:text-amber-400 mb-6"
|
||||
>
|
||||
← 返回首页
|
||||
</Link>
|
||||
|
||||
<article className="rounded-2xl overflow-hidden bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700">
|
||||
<div className="p-6 sm:p-8 text-center">
|
||||
<div className="relative w-24 h-24 sm:w-28 sm:h-28 mx-auto rounded-full overflow-hidden border-4 border-amber-100 dark:border-amber-900/30">
|
||||
<Image
|
||||
src={host.avatar}
|
||||
alt={host.name}
|
||||
fill
|
||||
sizes="112px"
|
||||
className="object-cover"
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
<h1 className="mt-4 text-xl sm:text-2xl font-bold text-stone-800 dark:text-stone-100">
|
||||
{host.name}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-amber-600 dark:text-amber-400">
|
||||
{host.bio}
|
||||
</p>
|
||||
{"intro" in host && typeof host.intro === "string" && (
|
||||
<div className="mt-6 pt-6 border-t border-stone-100 dark:border-stone-700 text-left">
|
||||
<p className="text-sm text-stone-600 dark:text-stone-400 leading-relaxed">
|
||||
{host.intro}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<Link
|
||||
href="/"
|
||||
className="mt-6 inline-flex justify-center w-full sm:w-auto bg-amber-600 hover:bg-amber-700 text-white px-6 py-2.5 rounded-xl text-sm font-medium"
|
||||
>
|
||||
看看本周活动
|
||||
</Link>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
16
app/icon.svg
Normal file
16
app/icon.svg
Normal file
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
|
||||
<rect width="32" height="32" rx="8" fill="url(#a)"/>
|
||||
<g fill="white" opacity=".95">
|
||||
<circle cx="16" cy="14" r="2.5"/>
|
||||
<circle cx="10" cy="20" r="2"/>
|
||||
<circle cx="22" cy="20" r="2"/>
|
||||
<circle cx="16" cy="22" r="1.5"/>
|
||||
</g>
|
||||
<defs>
|
||||
<linearGradient id="a" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#b45309"/>
|
||||
<stop offset=".5" stop-color="#d97706"/>
|
||||
<stop offset="1" stop-color="#f59e0b"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 580 B |
1404
app/join/page.tsx
1404
app/join/page.tsx
File diff suppressed because it is too large
Load Diff
@@ -2,47 +2,20 @@
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { tryCompleteOrder, applyCompleteSuccess } from "@/app/lib/complete-order";
|
||||
import { clearPendingOrder } from "@/app/hooks/useCompleteOrderPolling";
|
||||
|
||||
function clearPendingOrder(): void {
|
||||
try {
|
||||
localStorage.removeItem("join_pay_order");
|
||||
} catch {}
|
||||
document.cookie = "join_pay_order=; path=/; max-age=0";
|
||||
}
|
||||
const WECHAT_STORAGE_KEY = "salon_join_wechat";
|
||||
|
||||
export default function JoinPaidPage() {
|
||||
const [completeStatus, setCompleteStatus] = useState<"pending" | "success" | "error">("pending");
|
||||
const [errorDetail, setErrorDetail] = useState<string | null>(null);
|
||||
const [countdown, setCountdown] = useState<number | null>(null);
|
||||
const [wechatId, setWechatId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const tryComplete = async (orderId: string): Promise<{ ok: boolean; error?: string }> => {
|
||||
const r = await fetch("/api/salon/complete-order", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ order_id: orderId }),
|
||||
credentials: "include",
|
||||
});
|
||||
const d = await r.json();
|
||||
if (!d?.ok) return { ok: false, error: d?.error || d?.detail || `HTTP ${r.status}` };
|
||||
|
||||
if (d?.token && d?.record) {
|
||||
await fetch("/api/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: d.token, record: d.record }),
|
||||
credentials: "include",
|
||||
});
|
||||
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
|
||||
pbSaveAuth(d.token, d.record);
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent("auth:updated"));
|
||||
window.dispatchEvent(new CustomEvent("vip:updated"));
|
||||
return { ok: true };
|
||||
};
|
||||
|
||||
const run = async () => {
|
||||
const urlOrderId = typeof window !== "undefined"
|
||||
? new URLSearchParams(window.location.search).get("order_id") || ""
|
||||
@@ -65,15 +38,23 @@ export default function JoinPaidPage() {
|
||||
}
|
||||
|
||||
const maxClientRetries = 5;
|
||||
const retryDelays = [2000, 3000, 4000, 5000, 6000];
|
||||
const retryDelays = [800, 1500, 2500, 4000, 6000];
|
||||
let lastError = "";
|
||||
for (let i = 0; i <= maxClientRetries; i++) {
|
||||
if (cancelled) return;
|
||||
try {
|
||||
const result = await tryComplete(orderId);
|
||||
const result = await tryCompleteOrder(orderId);
|
||||
if (result.ok) {
|
||||
if (result.token && result.record) {
|
||||
applyCompleteSuccess({ token: result.token, record: result.record });
|
||||
} else if (result.record) {
|
||||
applyCompleteSuccess({ token: "", record: result.record });
|
||||
}
|
||||
clearPendingOrder();
|
||||
if (!cancelled) setCompleteStatus("success");
|
||||
if (!cancelled) {
|
||||
setCompleteStatus("success");
|
||||
if (result.record?.wechatId) setWechatId(result.record.wechatId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
lastError = result.error || "unknown";
|
||||
@@ -94,19 +75,28 @@ export default function JoinPaidPage() {
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem(WECHAT_STORAGE_KEY)?.trim();
|
||||
if (stored) setWechatId(stored);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, []);
|
||||
|
||||
const COUNTDOWN_SECONDS = 5;
|
||||
useEffect(() => {
|
||||
if (completeStatus !== "success") return;
|
||||
setCountdown(COUNTDOWN_SECONDS);
|
||||
const timer = setInterval(() => {
|
||||
setCountdown((prev) => {
|
||||
if (prev == null || prev <= 1) {
|
||||
clearInterval(timer);
|
||||
window.location.replace("/");
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
setCountdown((prev) => {
|
||||
if (prev == null || prev <= 1) {
|
||||
clearInterval(timer);
|
||||
window.location.replace("/join?paid=1");
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [completeStatus]);
|
||||
@@ -123,12 +113,15 @@ export default function JoinPaidPage() {
|
||||
<p className="mt-3 text-slate-500 dark:text-slate-400">
|
||||
{completeStatus === "success"
|
||||
? countdown != null
|
||||
? `${countdown} 秒后返回首页`
|
||||
? `${countdown} 秒后跳转报名成功页`
|
||||
: "感谢您的支持"
|
||||
: completeStatus === "error"
|
||||
? "请稍后刷新页面重试"
|
||||
: "正在确认支付状态…"}
|
||||
</p>
|
||||
{wechatId && (
|
||||
<p className="mt-2 text-xs text-slate-400 dark:text-slate-500 font-mono">微信号: {wechatId}</p>
|
||||
)}
|
||||
{completeStatus === "error" && errorDetail && (
|
||||
<p className="mt-1 text-xs text-slate-400 dark:text-slate-500">{errorDetail}</p>
|
||||
)}
|
||||
@@ -141,12 +134,18 @@ export default function JoinPaidPage() {
|
||||
刷新重试
|
||||
</button>
|
||||
)}
|
||||
<Link
|
||||
href="/"
|
||||
className="mt-8 inline-flex items-center gap-2 rounded-full bg-[#ff4d4f] px-8 py-3 font-semibold text-white transition-colors hover:bg-[#ff7a45]"
|
||||
>
|
||||
← 返回首页
|
||||
</Link>
|
||||
{completeStatus === "pending" ? (
|
||||
<span className="mt-8 inline-flex items-center gap-2 rounded-full bg-stone-200 dark:bg-stone-700 px-8 py-3 font-semibold text-stone-400 dark:text-stone-500 cursor-not-allowed">
|
||||
← 查看报名状态
|
||||
</span>
|
||||
) : (
|
||||
<Link
|
||||
href="/join?paid=1"
|
||||
className="mt-8 inline-flex items-center gap-2 rounded-full bg-[#ff4d4f] px-8 py-3 font-semibold text-white transition-colors hover:bg-[#ff7a45]"
|
||||
>
|
||||
← 查看报名状态
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
import ThemeProvider from "./components/ThemeProvider";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Salon - 探索中国",
|
||||
description: "加入数字游民社区,探索中国最适合远程工作的城市",
|
||||
title: "深圳|同城活动·技能交换·副业沙龙",
|
||||
description: "技能交换、副业沙龙茶话会,认识同城新朋友。公开场地,填表报名,无需注册。",
|
||||
keywords: "深圳活动,技能交换,副业沙龙,同城活动,loft民宿",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -12,8 +14,10 @@ export default function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh">
|
||||
<body className="antialiased">{children}</body>
|
||||
<html lang="zh" suppressHydrationWarning>
|
||||
<body className="antialiased">
|
||||
<ThemeProvider>{children}</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
51
app/lib/complete-order.ts
Normal file
51
app/lib/complete-order.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/** 共享:完成订单 API 调用与成功后的 session 同步 */
|
||||
|
||||
import type { AuthUser } from "@/app/lib/pocketbase";
|
||||
|
||||
const WECHAT_STORAGE_KEY = "salon_join_wechat";
|
||||
|
||||
export interface CompleteOrderResult {
|
||||
ok: boolean;
|
||||
token?: string;
|
||||
record?: { wechatId?: string; [k: string]: unknown };
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 调用 complete-order API */
|
||||
export async function tryCompleteOrder(orderId: string): Promise<CompleteOrderResult> {
|
||||
const r = await fetch("/api/salon/complete-order", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ order_id: orderId }),
|
||||
credentials: "include",
|
||||
});
|
||||
const d = await r.json();
|
||||
if (!d?.ok) return { ok: false, error: d?.error || d?.detail || `HTTP ${r.status}` };
|
||||
return { ok: true, token: d.token, record: d.record };
|
||||
}
|
||||
|
||||
/** 成功后的通用处理:sync-session、pbSaveAuth、dispatch 事件、localStorage wechatId。token 为空时仅 dispatch 和保存 wechatId(非 pending 用户) */
|
||||
export function applyCompleteSuccess(data: { token?: string; record?: { wechatId?: string; [k: string]: unknown } }): void {
|
||||
const { token, record } = data;
|
||||
if (token) {
|
||||
fetch("/api/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token, record }),
|
||||
credentials: "include",
|
||||
}).catch(() => {});
|
||||
if (record && "id" in record && "email" in record) {
|
||||
import("@/app/lib/pocketbase").then(({ pbSaveAuth }) => pbSaveAuth(token, record as AuthUser));
|
||||
}
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent("auth:updated"));
|
||||
window.dispatchEvent(new CustomEvent("vip:updated"));
|
||||
window.dispatchEvent(new CustomEvent("registration:refresh"));
|
||||
if (record?.wechatId) {
|
||||
try {
|
||||
localStorage.setItem(WECHAT_STORAGE_KEY, record.wechatId);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
132
app/lib/dates.ts
Normal file
132
app/lib/dates.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
/** 中国星期名称 */
|
||||
const WEEKDAY_CN = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"] as const;
|
||||
|
||||
/** 中国时区 */
|
||||
const TZ = "Asia/Shanghai";
|
||||
|
||||
/**
|
||||
* 获取中国时区下的日期数字(月、日、星期)
|
||||
* 无论服务器/客户端在何地,均返回中国公历
|
||||
*/
|
||||
function getChinaDateParts(): { year: number; month: number; day: number; weekday: number } {
|
||||
const now = new Date();
|
||||
const formatter = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: TZ,
|
||||
year: "numeric",
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
weekday: "short",
|
||||
});
|
||||
const parts = formatter.formatToParts(now);
|
||||
const get = (type: string) => parseInt(parts.find((p) => p.type === type)?.value ?? "0", 10);
|
||||
const weekdayStr = parts.find((p) => p.type === "weekday")?.value ?? "Sun";
|
||||
const weekdayMap: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
||||
return {
|
||||
year: get("year"),
|
||||
month: get("month"),
|
||||
day: get("day"),
|
||||
weekday: weekdayMap[weekdayStr] ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前中国公历时间字符串,用于上传
|
||||
* 格式:YYYY-MM-DD HH:mm:ss(中国时区)
|
||||
*/
|
||||
export function getNowChinaStr(): string {
|
||||
const formatter = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: TZ,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
hour12: false,
|
||||
});
|
||||
const parts = formatter.formatToParts(new Date());
|
||||
const pad = (s: string) => s.padStart(2, "0");
|
||||
const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "0";
|
||||
return `${get("year")}-${pad(get("month"))}-${pad(get("day"))} ${pad(get("hour"))}:${pad(get("minute"))}:${pad(get("second"))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化为中文日期:M月D日 周X
|
||||
*/
|
||||
function formatDateCN(month: number, day: number, weekday: number): string {
|
||||
return `${month}月${day}日 ${WEEKDAY_CN[weekday]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一个周六、周日的日期(中国公历)
|
||||
* 使用 +08:00 显式构造,避免服务器/客户端时区影响
|
||||
*/
|
||||
export function getNextWeekendDates(): { saturday: string; sunday: string } {
|
||||
const { year, month, day, weekday } = getChinaDateParts();
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const todayStr = `${year}-${pad(month)}-${pad(day)}T12:00:00+08:00`;
|
||||
const today = new Date(todayStr);
|
||||
|
||||
const daysToSat = weekday === 0 ? 6 : weekday === 6 ? 0 : 6 - weekday;
|
||||
const saturday = new Date(today);
|
||||
saturday.setUTCDate(saturday.getUTCDate() + daysToSat);
|
||||
const sunday = new Date(saturday);
|
||||
sunday.setUTCDate(sunday.getUTCDate() + 1);
|
||||
|
||||
return {
|
||||
saturday: formatDateCN(saturday.getUTCMonth() + 1, saturday.getUTCDate(), 6),
|
||||
sunday: formatDateCN(sunday.getUTCMonth() + 1, sunday.getUTCDate(), 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取中国公历本周一 00:00 至周日 23:59:59 的 UTC 时间范围
|
||||
* 用于 PocketBase created 过滤。PocketBase 要求 Y-m-d H:i:s.uZ 格式(空格非 T)
|
||||
*/
|
||||
export function getThisWeekRangeISO(): { start: string; end: string } {
|
||||
const { year, month, day, weekday } = getChinaDateParts();
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const todayStr = `${year}-${pad(month)}-${pad(day)}T12:00:00+08:00`;
|
||||
const today = new Date(todayStr);
|
||||
const daysToMonday = weekday === 0 ? 6 : weekday - 1;
|
||||
const monday = new Date(today);
|
||||
monday.setUTCDate(monday.getUTCDate() - daysToMonday);
|
||||
const sunday = new Date(monday);
|
||||
sunday.setUTCDate(sunday.getUTCDate() + 6);
|
||||
const mondayStr = `${monday.getUTCFullYear()}-${pad(monday.getUTCMonth() + 1)}-${pad(monday.getUTCDate())}T00:00:00+08:00`;
|
||||
const sundayStr = `${sunday.getUTCFullYear()}-${pad(sunday.getUTCMonth() + 1)}-${pad(sunday.getUTCDate())}T23:59:59.999+08:00`;
|
||||
const startDate = new Date(mondayStr);
|
||||
const endDate = new Date(sundayStr);
|
||||
const fmt = (d: Date, ms: string) => {
|
||||
const y = d.getUTCFullYear();
|
||||
const m = pad(d.getUTCMonth() + 1);
|
||||
const day = pad(d.getUTCDate());
|
||||
const h = pad(d.getUTCHours());
|
||||
const min = pad(d.getUTCMinutes());
|
||||
const s = pad(d.getUTCSeconds());
|
||||
return `${y}-${m}-${day} ${h}:${min}:${s}.${ms}Z`;
|
||||
};
|
||||
return {
|
||||
start: fmt(startDate, "000"),
|
||||
end: fmt(endDate, "999"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取中国公历本周一、周日的日期字符串(YYYY-MM-DD),用于 submitted_at_cn 过滤
|
||||
*/
|
||||
export function getThisWeekRangeChinaStr(): { start: string; end: string } {
|
||||
const { year, month, day, weekday } = getChinaDateParts();
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const todayStr = `${year}-${pad(month)}-${pad(day)}T12:00:00+08:00`;
|
||||
const today = new Date(todayStr);
|
||||
const daysToMonday = weekday === 0 ? 6 : weekday - 1;
|
||||
const monday = new Date(today);
|
||||
monday.setUTCDate(monday.getUTCDate() - daysToMonday);
|
||||
const sunday = new Date(monday);
|
||||
sunday.setUTCDate(sunday.getUTCDate() + 6);
|
||||
return {
|
||||
start: `${monday.getUTCFullYear()}-${pad(monday.getUTCMonth() + 1)}-${pad(monday.getUTCDate())} 00:00:00`,
|
||||
end: `${sunday.getUTCFullYear()}-${pad(sunday.getUTCMonth() + 1)}-${pad(sunday.getUTCDate())} 23:59:59`,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
const isDev = process.env.NODE_ENV === "development";
|
||||
|
||||
/** 前端站点地址。线上 salon.hackrobot.cn,开发 localhost:3002 */
|
||||
export const SITE_URL =
|
||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||
(isDev ? "http://localhost:3002" : "http://localhost:3002");
|
||||
(isDev ? "http://localhost:3002" : "https://salon.hackrobot.cn");
|
||||
|
||||
55
app/lib/joiners.ts
Normal file
55
app/lib/joiners.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/** 报名者项(mock 用 name,DB 用 nickname) */
|
||||
export type JoinerItem = {
|
||||
name?: string;
|
||||
nickname?: string;
|
||||
avatar?: string;
|
||||
xiaohongshu_url?: string;
|
||||
};
|
||||
|
||||
/** 去重 key:小红书 url 相同视为 1 人,无 url 时用 avatar,再 fallback nickname */
|
||||
function dedupeKey(j: JoinerItem, useAvatarForMock: boolean): string {
|
||||
const xh = (j.xiaohongshu_url || "").trim();
|
||||
if (xh && !useAvatarForMock) return `xh:${xh}`;
|
||||
const avatar = (j.avatar || "").trim();
|
||||
if (avatar) return `av:${avatar}`;
|
||||
return `_${(j.nickname || j.name || "").trim()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 mock 与数据库报名者:mock 固定 3 个在左,DB 在右
|
||||
* 小红书 url 相同视为 1 人,avatar 相同也只显示 1 个
|
||||
* 最多显示 8 个,保证 PC/H5 排版合理
|
||||
*/
|
||||
export function mergeJoiners(
|
||||
mock: JoinerItem[],
|
||||
db: JoinerItem[] | undefined
|
||||
): JoinerItem[] {
|
||||
const seen = new Set<string>();
|
||||
const result: JoinerItem[] = [];
|
||||
mock.forEach((j) => {
|
||||
const key = dedupeKey(j, true);
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push(j);
|
||||
}
|
||||
});
|
||||
(db || []).forEach((j) => {
|
||||
const key = dedupeKey(j, false);
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push(j);
|
||||
}
|
||||
});
|
||||
return result.slice(0, 8);
|
||||
}
|
||||
|
||||
/** 数据库报名者按小红书 url 去重后的数量(用于显示报名人数) */
|
||||
export function getUniqueDbCount(db: JoinerItem[] | undefined): number {
|
||||
if (!db?.length) return 0;
|
||||
const seen = new Set<string>();
|
||||
for (const j of db) {
|
||||
const key = dedupeKey(j, false);
|
||||
seen.add(key);
|
||||
}
|
||||
return seen.size;
|
||||
}
|
||||
@@ -2,6 +2,18 @@ import { getPaymentConfig, getJoinPaymentConfig } from "@/config/services.config
|
||||
|
||||
export type PayChannel = "wxpay" | "alipay";
|
||||
|
||||
const ORDER_COOKIE = "join_pay_order";
|
||||
|
||||
function savePendingOrder(orderId: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
try {
|
||||
const v = `${orderId}|${Date.now()}`;
|
||||
document.cookie = `${ORDER_COOKIE}=${encodeURIComponent(v)}; path=/; max-age=900`;
|
||||
localStorage.setItem(ORDER_COOKIE, v);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** 同步表单 POST,用于 PC 和微信内(微信内避免异步 fetch 导致手势失效) */
|
||||
export function redirectToPay(params: {
|
||||
user_id: string;
|
||||
return_url: string;
|
||||
@@ -44,6 +56,121 @@ export function redirectToPay(params: {
|
||||
payForm.submit();
|
||||
}
|
||||
|
||||
/** 微信内:同步表单 POST 到 /api/pay,避免异步 fetch 后 form.submit 被微信拦截(参考 nomadvip) */
|
||||
export function payWechatXorpaySync(params: {
|
||||
user_id: string;
|
||||
return_url: string;
|
||||
total_fee?: number;
|
||||
type?: string;
|
||||
channel: PayChannel;
|
||||
useJoinConfig?: boolean;
|
||||
}): void {
|
||||
const baseConfig = getPaymentConfig();
|
||||
const joinConfig = params.useJoinConfig ? getJoinPaymentConfig() : null;
|
||||
const total_fee = params.total_fee ?? joinConfig?.amount ?? baseConfig.defaultAmount;
|
||||
const type = params.type ?? joinConfig?.type ?? baseConfig.defaultType;
|
||||
|
||||
const payForm = document.createElement("form");
|
||||
payForm.method = "POST";
|
||||
payForm.action = "/api/pay";
|
||||
payForm.target = "_self";
|
||||
payForm.style.display = "none";
|
||||
|
||||
const fields: [string, string][] = [
|
||||
["user_id", params.user_id],
|
||||
["return_url", params.return_url],
|
||||
["total_fee", String(total_fee)],
|
||||
["type", type],
|
||||
["channel", params.channel],
|
||||
["device", "wechat"],
|
||||
["html", "1"],
|
||||
];
|
||||
|
||||
fields.forEach(([k, v]) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = k;
|
||||
input.value = v;
|
||||
payForm.appendChild(input);
|
||||
});
|
||||
|
||||
document.body.appendChild(payForm);
|
||||
payForm.submit();
|
||||
}
|
||||
|
||||
/** 手机浏览器 H5:异步 fetch 获取 redirect_url 后跳转,支持 ZPAY 微信 H5 唤醒(参考 nomadvip + payjsapi) */
|
||||
export async function redirectToPayH5(params: {
|
||||
user_id: string;
|
||||
return_url: string;
|
||||
total_fee?: number;
|
||||
type?: string;
|
||||
channel: PayChannel;
|
||||
useJoinConfig?: boolean;
|
||||
}): Promise<void> {
|
||||
const baseConfig = getPaymentConfig();
|
||||
const joinConfig = params.useJoinConfig ? getJoinPaymentConfig() : null;
|
||||
const total_fee = params.total_fee ?? joinConfig?.amount ?? baseConfig.defaultAmount;
|
||||
const type = params.type ?? joinConfig?.type ?? baseConfig.defaultType;
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 28000);
|
||||
const res = await fetch("/api/pay", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
user_id: params.user_id,
|
||||
return_url: params.return_url,
|
||||
total_fee,
|
||||
type,
|
||||
channel: params.channel,
|
||||
device: "h5",
|
||||
html: "0",
|
||||
}),
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeoutId));
|
||||
|
||||
if (res.status >= 301 && res.status <= 308) {
|
||||
const location = res.headers.get("location");
|
||||
if (location) {
|
||||
const orderId = res.headers.get("x-pay-order-id")?.trim();
|
||||
if (orderId) savePendingOrder(orderId);
|
||||
window.location.href = location;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!data?.ok) {
|
||||
alert(data?.error || "支付发起失败");
|
||||
return;
|
||||
}
|
||||
if (data?.order_id) savePendingOrder(data.order_id);
|
||||
if (data?.redirect_url) {
|
||||
window.location.href = data.redirect_url;
|
||||
return;
|
||||
}
|
||||
if (data?.params && data?.payUrl) {
|
||||
const form = document.createElement("form");
|
||||
form.method = "POST";
|
||||
form.action = data.payUrl;
|
||||
form.target = "_self";
|
||||
form.style.display = "none";
|
||||
for (const [k, v] of Object.entries(data.params as Record<string, string>)) {
|
||||
if (v == null) continue;
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = k;
|
||||
input.value = String(v);
|
||||
form.appendChild(input);
|
||||
}
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
return;
|
||||
}
|
||||
alert("支付发起失败");
|
||||
}
|
||||
|
||||
export function getDeviceFromEnv(env: "pc" | "h5" | "wechat"): "pc" | "h5" | "wechat" {
|
||||
if (env === "wechat") return "wechat";
|
||||
return env === "pc" ? "pc" : "h5";
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
export { redirectToPay, getDeviceFromEnv } from "./client";
|
||||
export {
|
||||
redirectToPay,
|
||||
redirectToPayH5,
|
||||
payWechatXorpaySync,
|
||||
getDeviceFromEnv,
|
||||
} from "./client";
|
||||
export { getPayEnv } from "../payEnv";
|
||||
export { usePayStatusPoll } from "./usePayStatusPoll";
|
||||
export type { PayChannel } from "./client";
|
||||
|
||||
@@ -28,7 +28,7 @@ function getApiCandidates(request: NextRequest): string[] {
|
||||
return urls.filter((u, i) => u && urls.indexOf(u) === i);
|
||||
}
|
||||
|
||||
const TIMEOUT_MS = 20000;
|
||||
const TIMEOUT_MS = 15000;
|
||||
|
||||
export async function postSalonApi(
|
||||
request: NextRequest,
|
||||
@@ -67,16 +67,18 @@ export async function postSalonApi(
|
||||
|
||||
export async function getSalonApi(
|
||||
request: NextRequest,
|
||||
path: string
|
||||
path: string,
|
||||
options?: { timeoutMs?: number }
|
||||
): Promise<{ status: number; data: unknown }> {
|
||||
const candidates = getApiCandidates(request);
|
||||
if (!candidates.length) throw new Error("PAYMENT_API_URL 未配置");
|
||||
|
||||
const timeoutMs = options?.timeoutMs ?? TIMEOUT_MS;
|
||||
let lastError: unknown = null;
|
||||
for (const apiUrl of candidates) {
|
||||
const url = `${apiUrl}${path}`;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const res = await fetch(url, { cache: "no-store", signal: controller.signal });
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
21
app/lib/volunteers.ts
Normal file
21
app/lib/volunteers.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { headers } from "next/headers";
|
||||
|
||||
/** 服务端获取第一个志愿者,用于替换发起人志愿者卡片。调用内部 API(API 优先走 salonapi 后端) */
|
||||
export async function getVolunteer(): Promise<{
|
||||
nickname: string;
|
||||
avatar?: string;
|
||||
xiaohongshu_url?: string;
|
||||
} | null> {
|
||||
try {
|
||||
const headersList = await headers();
|
||||
const host = headersList.get("host") || headersList.get("x-forwarded-host") || "localhost:3002";
|
||||
const proto = headersList.get("x-forwarded-proto") || (host.includes("localhost") ? "http" : "https");
|
||||
const base = `${proto}://${host}`;
|
||||
const res = await fetch(`${base}/api/join/volunteers`, { cache: "no-store" });
|
||||
const data = await res.json();
|
||||
const v = data?.volunteer;
|
||||
return v && typeof v === "object" && v.nickname ? v : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
76
app/lib/xorpayStatus.ts
Normal file
76
app/lib/xorpayStatus.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* XorPay 订单状态直接查询(兜底)
|
||||
* salonapi 不可用时,前端直接向 xorpay 查询,保证本地支付能检测到
|
||||
*/
|
||||
import { createHash } from "crypto";
|
||||
|
||||
/** 与 salonapi 保持一致,用于直接查询 xorpay 兜底 */
|
||||
const XORPAY_AID = process.env.XORPAY_AID || process.env.NEXT_PUBLIC_XORPAY_AID || "8220";
|
||||
const XORPAY_SECRET =
|
||||
process.env.XORPAY_SECRET || process.env.NEXT_PUBLIC_XORPAY_SECRET || "afcacd99570945f88de62624aaa3578e";
|
||||
const XORPAY_QUERY_URL =
|
||||
process.env.XORPAY_QUERY_URL || process.env.NEXT_PUBLIC_XORPAY_QUERY_URL || "https://xorpay.com/api/query2";
|
||||
const XORPAY_QUERY_TIMEOUT_MS = Number(
|
||||
process.env.XORPAY_QUERY_TIMEOUT_MS || 5000
|
||||
);
|
||||
|
||||
export type XorPayStatusResult = {
|
||||
ok: boolean;
|
||||
paid: boolean;
|
||||
status?: string;
|
||||
payPrice?: string;
|
||||
error?: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
function buildXorPaySign(orderId: string): string {
|
||||
return createHash("md5")
|
||||
.update(`${orderId}${XORPAY_SECRET}`, "utf8")
|
||||
.digest("hex")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export async function queryXorPayOrderStatus(
|
||||
orderId: string,
|
||||
timeoutMs = XORPAY_QUERY_TIMEOUT_MS
|
||||
): Promise<XorPayStatusResult | null> {
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId || !XORPAY_AID || !XORPAY_SECRET) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(
|
||||
`${XORPAY_QUERY_URL.replace(/\/$/, "")}/${encodeURIComponent(XORPAY_AID)}`
|
||||
);
|
||||
url.searchParams.set("order_id", normalizedOrderId);
|
||||
url.searchParams.set("sign", buildXorPaySign(normalizedOrderId));
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const res = await fetch(url.toString(), {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeout));
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const status = String(data?.status ?? "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
|
||||
return {
|
||||
ok: res.ok,
|
||||
paid: res.ok && (status === "payed" || status === "success"),
|
||||
status,
|
||||
payPrice: String(data?.pay_price ?? data?.price ?? "").trim() || undefined,
|
||||
url: url.toString(),
|
||||
error: res.ok ? undefined : `status=${res.status}`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
paid: false,
|
||||
url: url.toString(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
68
app/lib/zpayStatus.ts
Normal file
68
app/lib/zpayStatus.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* ZPAY 订单状态直接查询(兜底)
|
||||
* salonapi 不可用时,前端直接向 zpayz.cn 查询,保证本地支付能检测到
|
||||
*/
|
||||
/** 与 salonapi 保持一致,用于直接查询 zpay 兜底 */
|
||||
const ZPAY_PID = process.env.ZPAY_PID || process.env.NEXT_PUBLIC_ZPAY_PID || "2025121809351743";
|
||||
const ZPAY_KEY = process.env.ZPAY_KEY || process.env.NEXT_PUBLIC_ZPAY_KEY || "tpEi7wWIWI2kXiYVTpIG6j7it0mjVW89";
|
||||
const ZPAY_QUERY_URL =
|
||||
process.env.ZPAY_QUERY_URL || process.env.NEXT_PUBLIC_ZPAY_QUERY_URL || "https://zpayz.cn/api.php";
|
||||
const ZPAY_QUERY_TIMEOUT_MS = Number(
|
||||
process.env.ZPAY_QUERY_TIMEOUT_MS || 5000
|
||||
);
|
||||
|
||||
export type ZPayStatusResult = {
|
||||
ok: boolean;
|
||||
paid: boolean;
|
||||
status?: string;
|
||||
money?: string;
|
||||
error?: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export async function queryZPayOrderStatus(
|
||||
orderId: string,
|
||||
timeoutMs = ZPAY_QUERY_TIMEOUT_MS
|
||||
): Promise<ZPayStatusResult | null> {
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId || !ZPAY_PID || !ZPAY_KEY) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(ZPAY_QUERY_URL);
|
||||
url.searchParams.set("act", "order");
|
||||
url.searchParams.set("pid", ZPAY_PID);
|
||||
url.searchParams.set("key", ZPAY_KEY);
|
||||
url.searchParams.set("out_trade_no", normalizedOrderId);
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const res = await fetch(url.toString(), {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeout));
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const code = String(data?.code ?? "").trim();
|
||||
const status = String(data?.status ?? "").trim();
|
||||
|
||||
return {
|
||||
ok: res.ok,
|
||||
paid: res.ok && code === "1" && status === "1",
|
||||
status,
|
||||
money: String(data?.money ?? "").trim() || undefined,
|
||||
url: url.toString(),
|
||||
error:
|
||||
res.ok && code === "1"
|
||||
? undefined
|
||||
: String(data?.msg || `status=${res.status}`),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
paid: false,
|
||||
url: url.toString(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
34
app/page.tsx
34
app/page.tsx
@@ -1,34 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import HeroSection from "./components/HeroSection";
|
||||
import Footer from "./components/Footer";
|
||||
import { COMMUNITY_STATS } from "@/config/home.config";
|
||||
import HomeContent from "./components/HomeContent";
|
||||
|
||||
/** 首页:志愿者由客户端加载,避免 SSR 阻塞首屏 */
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#fafafa] dark:bg-gray-950">
|
||||
<HeroSection />
|
||||
|
||||
<div className="max-w-[1400px] mx-auto px-5 sm:px-10 py-8">
|
||||
<Link href="/join" className="right-item block max-w-md">
|
||||
<div className="right-item-header">加入社区</div>
|
||||
<div className="flex flex-col items-center justify-center text-center p-2 sm:p-5 h-[calc(100%-38px)] sm:h-[calc(100%-42px)]">
|
||||
<span className="text-2xl sm:text-5xl mb-1 sm:mb-3">💬</span>
|
||||
<p className="text-[10px] sm:text-sm text-gray-600 dark:text-gray-400 mb-0.5">
|
||||
加入数字游民社区,结识志同道合的伙伴
|
||||
</p>
|
||||
<p className="text-[9px] sm:text-xs text-gray-400 dark:text-gray-500 mb-1.5 sm:mb-4">
|
||||
{COMMUNITY_STATS.onlineMembers} 人在线
|
||||
</p>
|
||||
<span className="bg-[#ff4d4f] text-white px-2.5 sm:px-6 py-1 sm:py-2 rounded-lg text-[10px] sm:text-sm font-semibold whitespace-nowrap">
|
||||
加入社区 →
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
return <HomeContent initialVolunteer={null} />;
|
||||
}
|
||||
|
||||
17
app/volunteer/page.tsx
Normal file
17
app/volunteer/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
/** 志愿者报名跳转到 /join 页面,带 volunteer=1 参数 */
|
||||
export default function VolunteerPage() {
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
window.location.replace("/join?volunteer=1");
|
||||
}
|
||||
}, []);
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-[#faf8f5] dark:bg-stone-950">
|
||||
<span className="text-stone-400">跳转中…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +1,28 @@
|
||||
/**
|
||||
* 域名与 payjsapi 地址配置
|
||||
* 生产环境必须设置 PAYMENT_API_URL 或 ROOT_DOMAIN,否则无法连接 payjsapi
|
||||
* 域名配置(腾讯云生产)
|
||||
* - 前端: https://salon.hackrobot.cn
|
||||
* - salonapi: https://salonapi.hackrobot.cn(join、支付等)
|
||||
*/
|
||||
|
||||
const isDev = process.env.NODE_ENV === "development";
|
||||
|
||||
/** 生产环境 salonapi 主机(非 api.根域名 模式) */
|
||||
const DEFAULT_PROD_PAYMENT_API_HOST = "salonapi.hackrobot.cn";
|
||||
|
||||
/** 兼容旧逻辑:未单独设 PAYMENT_API_URL 时用于文档/兜底 */
|
||||
export const ROOT_DOMAIN =
|
||||
process.env.ROOT_DOMAIN || process.env.NEXT_PUBLIC_ROOT_DOMAIN || "hackrobot.cn";
|
||||
|
||||
/** 支付 API 默认地址。生产环境使用 api 子域,避免 127.0.0.1 导致连接失败 */
|
||||
/** salonapi 默认地址。开发连本地 8007,生产连 salonapi.hackrobot.cn */
|
||||
export const DEFAULT_PAYMENT_API_URL = isDev
|
||||
? "http://127.0.0.1:8007"
|
||||
: `https://api.${ROOT_DOMAIN}`;
|
||||
: `https://${DEFAULT_PROD_PAYMENT_API_HOST}`;
|
||||
|
||||
/** 若 PAYMENT_API_URL 指向 localhost,生产环境自动使用 api 子域 */
|
||||
/** 解析 salonapi 公网地址 */
|
||||
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)) {
|
||||
return `https://api.${ROOT_DOMAIN}`;
|
||||
return `https://${DEFAULT_PROD_PAYMENT_API_HOST}`;
|
||||
}
|
||||
return url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
@@ -1,43 +1,81 @@
|
||||
export const HOME_STATS = {
|
||||
cities: "18",
|
||||
nomads: "5,000+",
|
||||
meetups: "8+",
|
||||
homeMeetups: "50+",
|
||||
cost: "¥3,000",
|
||||
};
|
||||
import { getNextWeekendDates } from "@/app/lib/dates";
|
||||
|
||||
export const COMMUNITY_STATS = {
|
||||
onlineMembers: "3,200+",
|
||||
messagesPerMonth: "3,200+",
|
||||
};
|
||||
/** 开放城市 - 仅深圳 */
|
||||
export const CITIES = ["深圳"] as const;
|
||||
|
||||
export const MEMBER_PHOTOS = [
|
||||
{ name: "林晓", photo: "https://i.pravatar.cc/150?img=5" },
|
||||
{ name: "张浩", photo: "https://i.pravatar.cc/150?img=3" },
|
||||
{ name: "陈悦", photo: "https://i.pravatar.cc/150?img=9" },
|
||||
{ name: "周杰", photo: "https://i.pravatar.cc/150?img=7" },
|
||||
{ name: "吴婷", photo: "https://i.pravatar.cc/150?img=1" },
|
||||
/** 活动类型 */
|
||||
export const ACTIVITY_TYPES = {
|
||||
"skill-exchange": "技能交换",
|
||||
"side-hustle": "副业沙龙/茶话会",
|
||||
"loft": "loft民宿",
|
||||
"light-chat": "轻话题",
|
||||
} as const;
|
||||
|
||||
/** 活动标签 */
|
||||
export const SESSION_TAGS = {
|
||||
"first-friendly": "首次友好",
|
||||
"public-venue": "公开场地",
|
||||
"min-4": "4人成行",
|
||||
"weekend-pm": "周末",
|
||||
"loft": "loft民宿",
|
||||
"light-topic": "轻话题",
|
||||
} as const;
|
||||
|
||||
/** loft民宿 占位图 - Unsplash 室内/loft 风格 */
|
||||
const IMG_LOFT_1 = "https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=400&h=300&fit=crop";
|
||||
const IMG_LOFT_2 = "https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?w=400&h=300&fit=crop";
|
||||
|
||||
/** 龙华区红山地铁站 GPS */
|
||||
export const HONGSHAN_COORDS = { lat: 22.6569, lng: 114.0297 };
|
||||
|
||||
/** 本周活动场次(日期占位,实际由 getSessionsWithDates 动态计算) */
|
||||
const SESSIONS_BASE = [
|
||||
{ id: "session-1", time: "15:00-18:00", place: "龙华区红山地铁站", city: "深圳", type: "skill-exchange" as const, title: "周末轻社交", coverImage: IMG_LOFT_1, tags: ["first-friendly", "public-venue", "min-4", "weekend-pm", "loft", "light-topic"] as const },
|
||||
{ id: "session-2", time: "09:00-12:00", place: "龙华区红山地铁站", city: "深圳", type: "side-hustle" as const, title: "数字游民沙龙", coverImage: IMG_LOFT_2, tags: ["first-friendly", "public-venue", "min-4", "weekend-pm", "loft"] as const },
|
||||
] as const;
|
||||
|
||||
/** 获取带动态日期的本周场次(周六/周日自动计算,中国时区) */
|
||||
export function getSessionsWithDates() {
|
||||
const { saturday, sunday } = getNextWeekendDates();
|
||||
return [
|
||||
{ ...SESSIONS_BASE[0], date: saturday },
|
||||
{ ...SESSIONS_BASE[1], date: sunday },
|
||||
];
|
||||
}
|
||||
|
||||
/** 本周活动场次(静态引用,用于 API 等不需要日期的场景) */
|
||||
export const SESSIONS = SESSIONS_BASE;
|
||||
|
||||
/** 历史活动(用于时间轴展示) */
|
||||
export const PAST_SESSIONS = [
|
||||
{ id: "past-1", date: "3月9日 周六", time: "15:00-18:00", place: "龙华区红山地铁站", city: "深圳", type: "skill-exchange" as const, title: "周末轻社交", coverImage: IMG_LOFT_1, tags: ["loft", "light-topic"] as const },
|
||||
{ id: "past-2", date: "3月10日 周日", time: "09:00-12:00", place: "龙华区红山地铁站", city: "深圳", type: "side-hustle" as const, title: "数字游民沙龙", coverImage: IMG_LOFT_2, tags: ["loft"] as const },
|
||||
{ id: "past-3", date: "3月2日 周六", time: "15:00-18:00", place: "龙华区红山地铁站", city: "深圳", type: "skill-exchange" as const, title: "周末轻社交", coverImage: IMG_LOFT_1, tags: ["loft"] as const },
|
||||
{ id: "past-4", date: "3月3日 周日", time: "09:00-12:00", place: "龙华区红山地铁站", city: "深圳", type: "side-hustle" as const, title: "数字游民沙龙", coverImage: IMG_LOFT_2, tags: ["loft"] as const },
|
||||
{ id: "past-5", date: "2月24日 周六", time: "15:00-18:00", place: "龙华区红山地铁站", city: "深圳", type: "skill-exchange" as const, title: "周末轻社交", coverImage: IMG_LOFT_1, tags: ["loft"] as const },
|
||||
];
|
||||
|
||||
export const MEETUPS = [
|
||||
{ city: "大理", emoji: "🏯", date: "3月9日", count: 12 },
|
||||
{ city: "成都", emoji: "🐼", date: "3月12日", count: 8 },
|
||||
{ city: "深圳", emoji: "🌃", date: "3月14日", count: 15 },
|
||||
/** 发起人 - 点击跳转小红书 */
|
||||
export const HOSTS = [
|
||||
{ id: "host-1", name: "发起人", avatar: "/images/11.webp", bio: "数字游民社区发起人,热爱连接同频的人。", link: "https://xhslink.com/m/2GxEJ4eeTNS" },
|
||||
{ id: "host-2", name: "志愿者", avatar: "/images/volunteer-mystery.svg", bio: "签到、茶歇准备、拍照摄像。", link: "/join?volunteer=1" },
|
||||
];
|
||||
|
||||
export const ROUTES = [
|
||||
{
|
||||
titleZh: "云南慢生活线",
|
||||
titleEn: "Yunnan Slow Life",
|
||||
citiesZh: ["昆明", "大理", "丽江"],
|
||||
citiesEn: ["Kunming", "Dali", "Lijiang"],
|
||||
emojis: ["🌸", "🏯", "🏔️"],
|
||||
durationZh: "3-6个月",
|
||||
durationEn: "3-6 months",
|
||||
costZh: "¥3,200/月起",
|
||||
costEn: "From ¥3,200/month",
|
||||
descZh: "从春城昆明出发,感受最纯粹的慢生活",
|
||||
descEn: "From Kunming, experience the purest slow life",
|
||||
gradient: "from-purple-500 to-pink-500",
|
||||
},
|
||||
/** 数字游民社区 - 符合条件时显示的微信二维码 */
|
||||
export const DIGITAL_NOMAD_WECHAT_QR = "/images/QR.png";
|
||||
|
||||
/** 最近报名意向 - mock 数据,中国女性头像,含小红书昵称与主页链接 */
|
||||
export const RECENT_JOINERS = [
|
||||
{ name: "晓琪", avatar: "https://images.unsplash.com/photo-1589553009868-c7b2bb474531?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "雨晴", avatar: "https://images.unsplash.com/photo-1617187703472-9508e9d3d198?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "子豪", avatar: "https://images.unsplash.com/photo-1624803642337-2639de804c57?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "林晓", avatar: "https://images.unsplash.com/photo-1534751516642-a1af1ef26a56?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "佳琪", avatar: "https://images.unsplash.com/photo-1593519544233-57d84925abb4?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "浩然", avatar: "https://images.unsplash.com/photo-1623512083603-5068ca8290f4?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "心怡", avatar: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
{ name: "阿杰", avatar: "https://images.unsplash.com/photo-1627008320558-9d59b27cb732?w=80&h=80&fit=crop&crop=face", xiaohongshu_url: "https://www.xiaohongshu.com/user/profile/xxx" },
|
||||
];
|
||||
/** 周六场 mock 头像(晓琪、雨晴、子豪) */
|
||||
export const MOCK_JOINERS_SESSION1 = RECENT_JOINERS.slice(0, 3);
|
||||
/** 周日场 mock 头像(林晓、佳琪、浩然),与周六完全不重复 */
|
||||
export const MOCK_JOINERS_SESSION2 = RECENT_JOINERS.slice(3, 6);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* salon 服务配置 - PocketBase、支付
|
||||
* 使用 site_id=salon,支付调用 payjsapi /salon/*
|
||||
* 前端 salon.hackrobot.cn,后端 salonapi.hackrobot.cn
|
||||
*/
|
||||
|
||||
import { resolvePaymentApiUrl } from "./domain.config";
|
||||
@@ -58,9 +58,12 @@ export function getPaymentConfig(): PaymentConfig {
|
||||
};
|
||||
}
|
||||
|
||||
/** 茶歇费 29元/人(单位:分,2900=29元) */
|
||||
export const JOIN_TEA_FEE = 2900;
|
||||
|
||||
export function getJoinPaymentConfig(): { amount: number; type: string } {
|
||||
return {
|
||||
amount: Number(process.env.PAYMENT_JOIN_AMOUNT) || MEETUP_JOIN_AMOUNT,
|
||||
amount: Number(process.env.PAYMENT_JOIN_AMOUNT) || JOIN_TEA_FEE,
|
||||
type: "salon",
|
||||
};
|
||||
}
|
||||
|
||||
53
deploy/nginx.hackrobot.cn.conf
Normal file
53
deploy/nginx.hackrobot.cn.conf
Normal file
@@ -0,0 +1,53 @@
|
||||
# 腾讯云:将 salon.hackrobot.cn、salonapi.hackrobot.cn 解析到本机公网 IP 后,
|
||||
# 复制到 /etc/nginx/sites-available/ 并 ln -s 到 sites-enabled,再 nginx -t && systemctl reload nginx。
|
||||
# 需先申请 SSL(certbot 或腾讯云 SSL 证书),把证书路径替换为实际路径。
|
||||
|
||||
# ---------- salon 前端(Next.js 建议 Node 监听 127.0.0.1:3002,由 Nginx 反代)----------
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name salon.hackrobot.cn;
|
||||
|
||||
ssl_certificate /etc/nginx/ssl/salon.hackrobot.cn/fullchain.pem;
|
||||
ssl_certificate_key /etc/nginx/ssl/salon.hackrobot.cn/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3002;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name salon.hackrobot.cn;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
# ---------- salonapi 后端(uvicorn 建议 127.0.0.1:8007)----------
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name salonapi.hackrobot.cn;
|
||||
|
||||
ssl_certificate /etc/nginx/ssl/salonapi.hackrobot.cn/fullchain.pem;
|
||||
ssl_certificate_key /etc/nginx/ssl/salonapi.hackrobot.cn/privkey.pem;
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8007;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name salonapi.hackrobot.cn;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
@@ -2,6 +2,27 @@ import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
reactStrictMode: true,
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/:path*",
|
||||
headers: [
|
||||
{ key: "Cache-Control", value: "no-store, no-cache, must-revalidate, proxy-revalidate" },
|
||||
{ key: "Pragma", value: "no-cache" },
|
||||
{ key: "Expires", value: "0" },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{ protocol: "https", hostname: "picsum.photos", pathname: "/**" },
|
||||
{ protocol: "https", hostname: "i.pravatar.cc", pathname: "/**" },
|
||||
{ protocol: "https", hostname: "images.unsplash.com", pathname: "/**" },
|
||||
{ protocol: "https", hostname: "sns-webpic-qc.xhscdn.com", pathname: "/**" },
|
||||
{ protocol: "https", hostname: "sns-avatar-qc.xhscdn.com", pathname: "/**" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^0.577.0",
|
||||
"next": "16.1.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"pocketbase": "^0.26.8",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3"
|
||||
|
||||
26
pnpm-lock.yaml
generated
26
pnpm-lock.yaml
generated
@@ -8,9 +8,15 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
lucide-react:
|
||||
specifier: ^0.577.0
|
||||
version: 0.577.0(react@19.2.3)
|
||||
next:
|
||||
specifier: 16.1.6
|
||||
version: 16.1.6(@babel/core@7.29.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
next-themes:
|
||||
specifier: ^0.4.6
|
||||
version: 0.4.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
pocketbase:
|
||||
specifier: ^0.26.8
|
||||
version: 0.26.8
|
||||
@@ -1463,6 +1469,11 @@ packages:
|
||||
lru-cache@5.1.1:
|
||||
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
|
||||
|
||||
lucide-react@0.577.0:
|
||||
resolution: {integrity: sha512-4LjoFv2eEPwYDPg/CUdBJQSDfPyzXCRrVW1X7jrx/trgxnxkHFjnVZINbzvzxjN70dxychOfg+FTYwBiS3pQ5A==}
|
||||
peerDependencies:
|
||||
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
|
||||
magic-string@0.30.21:
|
||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
||||
|
||||
@@ -1504,6 +1515,12 @@ packages:
|
||||
natural-compare@1.4.0:
|
||||
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
|
||||
|
||||
next-themes@0.4.6:
|
||||
resolution: {integrity: sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==}
|
||||
peerDependencies:
|
||||
react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc
|
||||
|
||||
next@16.1.6:
|
||||
resolution: {integrity: sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
@@ -3453,6 +3470,10 @@ snapshots:
|
||||
dependencies:
|
||||
yallist: 3.1.1
|
||||
|
||||
lucide-react@0.577.0(react@19.2.3):
|
||||
dependencies:
|
||||
react: 19.2.3
|
||||
|
||||
magic-string@0.30.21:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
@@ -3484,6 +3505,11 @@ snapshots:
|
||||
|
||||
natural-compare@1.4.0: {}
|
||||
|
||||
next-themes@0.4.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3):
|
||||
dependencies:
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3(react@19.2.3)
|
||||
|
||||
next@16.1.6(@babel/core@7.29.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3):
|
||||
dependencies:
|
||||
'@next/env': 16.1.6
|
||||
|
||||
BIN
public/images/11.webp
Normal file
BIN
public/images/11.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
BIN
public/images/QR.png
Normal file
BIN
public/images/QR.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 109 KiB |
6
public/images/volunteer-mystery.svg
Normal file
6
public/images/volunteer-mystery.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" fill="none">
|
||||
<circle cx="60" cy="60" r="55" fill="#f5f5f4" stroke="#d6d3d1" stroke-width="2"/>
|
||||
<circle cx="60" cy="45" r="18" fill="#d6d3d1"/>
|
||||
<path d="M30 95 Q60 75 90 95" stroke="#d6d3d1" stroke-width="4" fill="none" stroke-linecap="round"/>
|
||||
<text x="60" y="115" text-anchor="middle" font-size="10" fill="#78716c">?</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 402 B |
5
public/images/wechat-qr-placeholder.svg
Normal file
5
public/images/wechat-qr-placeholder.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">
|
||||
<rect width="200" height="200" fill="#f5f5f5"/>
|
||||
<text x="100" y="95" text-anchor="middle" font-size="14" fill="#999">®áŒô</text>
|
||||
<text x="100" y="115" text-anchor="middle" font-size="12" fill="#bbb">÷ÿb:žEþG</text>
|
||||
</svg>
|
||||
313
scripts/deploy-neko-dual.sh
Normal file
313
scripts/deploy-neko-dual.sh
Normal file
@@ -0,0 +1,313 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
require_cmd() {
|
||||
if ! command -v "$1" >/dev/null 2>&1; then
|
||||
echo "missing required command: $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
require_cmd docker
|
||||
require_cmd getent
|
||||
require_cmd ip
|
||||
require_cmd awk
|
||||
require_cmd sudo
|
||||
|
||||
ufw_udp_range() {
|
||||
echo "${1//-/:}/udp"
|
||||
}
|
||||
|
||||
if [[ "${EUID}" -ne 0 ]]; then
|
||||
sudo -v
|
||||
fi
|
||||
|
||||
if [[ "$(id -u)" -eq 0 && -n "${SUDO_USER:-}" ]]; then
|
||||
DEFAULT_HOME="$(getent passwd "$SUDO_USER" | awk -F: '{print $6}')"
|
||||
else
|
||||
DEFAULT_HOME="$HOME"
|
||||
fi
|
||||
|
||||
HOME_DIR="${HOME_DIR:-$DEFAULT_HOME}"
|
||||
LAN_IP="${LAN_IP:-$(ip route get 1 | awk '{print $7; exit}')}"
|
||||
|
||||
NEKO_USER_PASSWORD="${NEKO_USER_PASSWORD:-user123}"
|
||||
NEKO_ADMIN_PASSWORD="${NEKO_ADMIN_PASSWORD:-admin123}"
|
||||
|
||||
PROFILE_UID="${PROFILE_UID:-1000}"
|
||||
PROFILE_GID="${PROFILE_GID:-1000}"
|
||||
|
||||
CHROMIUM_DIR="${CHROMIUM_DIR:-$HOME_DIR/neko-browser}"
|
||||
GOOGLE_CHROME_DIR="${GOOGLE_CHROME_DIR:-$HOME_DIR/neko-google-chrome}"
|
||||
|
||||
CHROMIUM_PROFILE_DIR="${CHROMIUM_PROFILE_DIR:-/root/neko-chromium-profile}"
|
||||
GOOGLE_CHROME_PROFILE_DIR="${GOOGLE_CHROME_PROFILE_DIR:-/root/neko-google-chrome-profile}"
|
||||
|
||||
CHROMIUM_HTTP_PORT="${CHROMIUM_HTTP_PORT:-8080}"
|
||||
GOOGLE_CHROME_HTTP_PORT="${GOOGLE_CHROME_HTTP_PORT:-8081}"
|
||||
|
||||
CHROMIUM_UDP_RANGE="${CHROMIUM_UDP_RANGE:-56000-56100}"
|
||||
GOOGLE_CHROME_UDP_RANGE="${GOOGLE_CHROME_UDP_RANGE:-56200-56300}"
|
||||
|
||||
CHROMIUM_DISPLAY="${CHROMIUM_DISPLAY:-:99.0}"
|
||||
GOOGLE_CHROME_DISPLAY="${GOOGLE_CHROME_DISPLAY:-:100.0}"
|
||||
|
||||
mkdir -p \
|
||||
"$CHROMIUM_DIR/policies" \
|
||||
"$GOOGLE_CHROME_DIR/policies"
|
||||
|
||||
sudo mkdir -p \
|
||||
"$CHROMIUM_PROFILE_DIR" \
|
||||
"$GOOGLE_CHROME_PROFILE_DIR"
|
||||
|
||||
sudo chown -R "${PROFILE_UID}:${PROFILE_GID}" \
|
||||
"$CHROMIUM_PROFILE_DIR" \
|
||||
"$GOOGLE_CHROME_PROFILE_DIR"
|
||||
|
||||
cat >"$CHROMIUM_DIR/docker-compose.yaml" <<EOF
|
||||
services:
|
||||
neko-browser:
|
||||
image: ghcr.io/m1k1o/neko/chromium:latest
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
shm_size: "8gb"
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
environment:
|
||||
DISPLAY: "${CHROMIUM_DISPLAY}"
|
||||
NEKO_DESKTOP_SCREEN: "1920x1080@60"
|
||||
NEKO_SERVER_BIND: ":${CHROMIUM_HTTP_PORT}"
|
||||
NEKO_MEMBER_PROVIDER: "multiuser"
|
||||
NEKO_MEMBER_MULTIUSER_USER_PASSWORD: "${NEKO_USER_PASSWORD}"
|
||||
NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: "${NEKO_ADMIN_PASSWORD}"
|
||||
NEKO_WEBRTC_EPR: "${CHROMIUM_UDP_RANGE}"
|
||||
NEKO_WEBRTC_ICELITE: "1"
|
||||
NEKO_WEBRTC_NAT1TO1: "${LAN_IP}"
|
||||
NEKO_PLUGINS_ENABLED: "true"
|
||||
NEKO_PLUGINS_DIR: "/etc/neko/plugins/"
|
||||
volumes:
|
||||
- ${CHROMIUM_PROFILE_DIR}:/home/neko/.config/chromium
|
||||
- ${CHROMIUM_DIR}/policies:/etc/chromium/policies/managed:ro
|
||||
- ${CHROMIUM_DIR}/chromium.conf:/etc/neko/supervisord/chromium.conf:ro
|
||||
EOF
|
||||
|
||||
cat >"$CHROMIUM_DIR/chromium.conf" <<'EOF'
|
||||
[program:chromium]
|
||||
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
|
||||
command=/usr/bin/chromium
|
||||
--window-position=0,0
|
||||
--display=%(ENV_DISPLAY)s
|
||||
--user-data-dir=/home/neko/.config/chromium
|
||||
--password-store=basic
|
||||
--no-first-run
|
||||
--start-maximized
|
||||
--force-dark-mode
|
||||
--disable-file-system
|
||||
--disable-gpu
|
||||
--disable-software-rasterizer
|
||||
--disable-dev-shm-usage
|
||||
--disable-background-timer-throttling
|
||||
--disable-backgrounding-occluded-windows
|
||||
--disable-renderer-backgrounding
|
||||
stopsignal=INT
|
||||
autorestart=true
|
||||
priority=800
|
||||
user=%(ENV_USER)s
|
||||
stdout_logfile=/var/log/neko/chromium.log
|
||||
stdout_logfile_maxbytes=100MB
|
||||
stdout_logfile_backups=10
|
||||
redirect_stderr=true
|
||||
|
||||
[program:openbox]
|
||||
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
|
||||
command=/usr/bin/openbox --config-file /etc/neko/openbox.xml
|
||||
autorestart=true
|
||||
priority=300
|
||||
user=%(ENV_USER)s
|
||||
stdout_logfile=/var/log/neko/openbox.log
|
||||
stdout_logfile_maxbytes=100MB
|
||||
stdout_logfile_backups=10
|
||||
redirect_stderr=true
|
||||
EOF
|
||||
|
||||
cat >"$CHROMIUM_DIR/policies/policies.json" <<'EOF'
|
||||
{
|
||||
"ExtensionInstallForcelist": [
|
||||
"dhdgffkkebhmkfjojejmpbldmpobfkfo;https://clients2.google.com/service/update2/crx"
|
||||
],
|
||||
"ExtensionInstallAllowlist": [
|
||||
"*"
|
||||
],
|
||||
"ExtensionInstallBlocklist": [],
|
||||
"DownloadRestrictions": 0,
|
||||
"AllowFileSelectionDialogs": true,
|
||||
"URLAllowlist": ["file:///home/neko/Downloads/*"],
|
||||
"DefaultCookiesSetting": 1,
|
||||
"RestoreOnStartup": 1
|
||||
}
|
||||
EOF
|
||||
|
||||
cat >"$GOOGLE_CHROME_DIR/docker-compose.yaml" <<EOF
|
||||
services:
|
||||
neko-google-chrome:
|
||||
image: ghcr.io/m1k1o/neko/google-chrome:latest
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
shm_size: "8gb"
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
environment:
|
||||
DISPLAY: "${GOOGLE_CHROME_DISPLAY}"
|
||||
NEKO_DESKTOP_SCREEN: "1920x1080@60"
|
||||
NEKO_SERVER_BIND: ":${GOOGLE_CHROME_HTTP_PORT}"
|
||||
NEKO_MEMBER_PROVIDER: "multiuser"
|
||||
NEKO_MEMBER_MULTIUSER_USER_PASSWORD: "${NEKO_USER_PASSWORD}"
|
||||
NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: "${NEKO_ADMIN_PASSWORD}"
|
||||
NEKO_WEBRTC_EPR: "${GOOGLE_CHROME_UDP_RANGE}"
|
||||
NEKO_WEBRTC_ICELITE: "1"
|
||||
NEKO_WEBRTC_NAT1TO1: "${LAN_IP}"
|
||||
NEKO_PLUGINS_ENABLED: "true"
|
||||
NEKO_PLUGINS_DIR: "/etc/neko/plugins/"
|
||||
volumes:
|
||||
- ${GOOGLE_CHROME_PROFILE_DIR}:/home/neko/.config/google-chrome
|
||||
- ${GOOGLE_CHROME_DIR}/policies:/etc/opt/chrome/policies/managed:ro
|
||||
- ${GOOGLE_CHROME_DIR}/google-chrome.conf:/etc/neko/supervisord/google-chrome.conf:ro
|
||||
EOF
|
||||
|
||||
cat >"$GOOGLE_CHROME_DIR/google-chrome.conf" <<'EOF'
|
||||
[program:google-chrome]
|
||||
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
|
||||
command=/usr/bin/google-chrome
|
||||
--window-position=0,0
|
||||
--display=%(ENV_DISPLAY)s
|
||||
--user-data-dir=/home/neko/.config/google-chrome
|
||||
--password-store=basic
|
||||
--no-first-run
|
||||
--start-maximized
|
||||
--force-dark-mode
|
||||
--disable-file-system
|
||||
--disable-gpu
|
||||
--disable-software-rasterizer
|
||||
--disable-dev-shm-usage
|
||||
--disable-background-timer-throttling
|
||||
--disable-backgrounding-occluded-windows
|
||||
--disable-renderer-backgrounding
|
||||
stopsignal=INT
|
||||
autorestart=true
|
||||
priority=800
|
||||
user=%(ENV_USER)s
|
||||
stdout_logfile=/var/log/neko/google-chrome.log
|
||||
stdout_logfile_maxbytes=100MB
|
||||
stdout_logfile_backups=10
|
||||
redirect_stderr=true
|
||||
|
||||
[program:openbox]
|
||||
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
|
||||
command=/usr/bin/openbox --config-file /etc/neko/openbox.xml
|
||||
autorestart=true
|
||||
priority=300
|
||||
user=%(ENV_USER)s
|
||||
stdout_logfile=/var/log/neko/openbox.log
|
||||
stdout_logfile_maxbytes=100MB
|
||||
stdout_logfile_backups=10
|
||||
redirect_stderr=true
|
||||
EOF
|
||||
|
||||
cat >"$GOOGLE_CHROME_DIR/policies/policies.json" <<'EOF'
|
||||
{
|
||||
"ExtensionInstallForcelist": [
|
||||
"dhdgffkkebhmkfjojejmpbldmpobfkfo;https://clients2.google.com/service/update2/crx"
|
||||
],
|
||||
"ExtensionInstallAllowlist": [
|
||||
"*"
|
||||
],
|
||||
"ExtensionInstallBlocklist": [],
|
||||
"DownloadRestrictions": 0,
|
||||
"AllowFileSelectionDialogs": true,
|
||||
"URLAllowlist": ["file:///home/neko/Downloads/*"],
|
||||
"DefaultCookiesSetting": 1,
|
||||
"RestoreOnStartup": 1
|
||||
}
|
||||
EOF
|
||||
|
||||
sudo ufw allow "${CHROMIUM_HTTP_PORT}" >/dev/null 2>&1 || true
|
||||
sudo ufw allow "${GOOGLE_CHROME_HTTP_PORT}" >/dev/null 2>&1 || true
|
||||
sudo ufw allow "$(ufw_udp_range "${CHROMIUM_UDP_RANGE}")" >/dev/null 2>&1 || true
|
||||
sudo ufw allow "$(ufw_udp_range "${GOOGLE_CHROME_UDP_RANGE}")" >/dev/null 2>&1 || true
|
||||
|
||||
recreate_compose_service() {
|
||||
local compose_dir="$1"
|
||||
local service="$2"
|
||||
local name_pattern="$3"
|
||||
local existing_id=""
|
||||
local pid=""
|
||||
|
||||
existing_id="$(cd "$compose_dir" && docker compose ps -q "$service" 2>/dev/null || true)"
|
||||
if [[ -n "$existing_id" ]]; then
|
||||
docker update --restart=no "$existing_id" >/dev/null 2>&1 || true
|
||||
pid="$(docker inspect -f '{{.State.Pid}}' "$existing_id" 2>/dev/null || true)"
|
||||
if [[ -n "$pid" && "$pid" != "0" ]]; then
|
||||
sudo kill -TERM "$pid" >/dev/null 2>&1 || true
|
||||
sleep 3
|
||||
sudo kill -KILL "$pid" >/dev/null 2>&1 || true
|
||||
sleep 2
|
||||
fi
|
||||
docker rm -f "$existing_id" >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
docker ps -a --format '{{.ID}} {{.Names}}' \
|
||||
| awk -v pat="$name_pattern" '$2 ~ pat {print $1}' \
|
||||
| xargs -r docker rm -f >/dev/null 2>&1 || true
|
||||
|
||||
(cd "$compose_dir" && docker compose up -d)
|
||||
}
|
||||
|
||||
wait_for_healthy() {
|
||||
local compose_dir="$1"
|
||||
local service="$2"
|
||||
local container_id=""
|
||||
local health_status=""
|
||||
local state_status=""
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
container_id="$(cd "$compose_dir" && docker compose ps -q "$service" 2>/dev/null || true)"
|
||||
[[ -z "$container_id" ]] && sleep 2 && continue
|
||||
|
||||
health_status="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container_id" 2>/dev/null || true)"
|
||||
state_status="$(docker inspect -f '{{.State.Status}}' "$container_id" 2>/dev/null || true)"
|
||||
|
||||
if [[ "$state_status" == "running" && ( "$health_status" == "healthy" || "$health_status" == "none" ) ]]; then
|
||||
echo "$container_id"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ "$health_status" == "unhealthy" ]]; then
|
||||
echo "service ${service} became unhealthy" >&2
|
||||
docker logs --tail 200 "$container_id" >&2 || true
|
||||
return 1
|
||||
fi
|
||||
|
||||
sleep 2
|
||||
done
|
||||
|
||||
echo "timed out waiting for ${service}" >&2
|
||||
[[ -n "$container_id" ]] && docker logs --tail 200 "$container_id" >&2 || true
|
||||
return 1
|
||||
}
|
||||
|
||||
recreate_compose_service "$CHROMIUM_DIR" "neko-browser" "neko-browser"
|
||||
recreate_compose_service "$GOOGLE_CHROME_DIR" "neko-google-chrome" "neko-google-chrome"
|
||||
|
||||
CHROMIUM_ID="$(wait_for_healthy "$CHROMIUM_DIR" "neko-browser")"
|
||||
GOOGLE_CHROME_ID="$(wait_for_healthy "$GOOGLE_CHROME_DIR" "neko-google-chrome")"
|
||||
|
||||
echo
|
||||
echo "chromium:"
|
||||
echo " url: http://${LAN_IP}:${CHROMIUM_HTTP_PORT}/"
|
||||
echo " container: ${CHROMIUM_ID}"
|
||||
echo " compose: ${CHROMIUM_DIR}"
|
||||
echo
|
||||
echo "google-chrome:"
|
||||
echo " url: http://${LAN_IP}:${GOOGLE_CHROME_HTTP_PORT}/"
|
||||
echo " container: ${GOOGLE_CHROME_ID}"
|
||||
echo " compose: ${GOOGLE_CHROME_DIR}"
|
||||
205
scripts/deploy-neko-google-chrome-2.sh
Normal file
205
scripts/deploy-neko-google-chrome-2.sh
Normal file
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
require_cmd() {
|
||||
if ! command -v "$1" >/dev/null 2>&1; then
|
||||
echo "missing required command: $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
require_cmd docker
|
||||
require_cmd getent
|
||||
require_cmd ip
|
||||
require_cmd awk
|
||||
require_cmd sudo
|
||||
|
||||
ufw_udp_range() {
|
||||
echo "${1//-/:}/udp"
|
||||
}
|
||||
|
||||
if [[ "${EUID}" -ne 0 ]]; then
|
||||
sudo -v
|
||||
fi
|
||||
|
||||
if [[ "$(id -u)" -eq 0 && -n "${SUDO_USER:-}" ]]; then
|
||||
DEFAULT_HOME="$(getent passwd "$SUDO_USER" | awk -F: '{print $6}')"
|
||||
else
|
||||
DEFAULT_HOME="$HOME"
|
||||
fi
|
||||
|
||||
HOME_DIR="${HOME_DIR:-$DEFAULT_HOME}"
|
||||
LAN_IP="${LAN_IP:-$(ip route get 1 | awk '{print $7; exit}')}"
|
||||
|
||||
NEKO_USER_PASSWORD="${NEKO_USER_PASSWORD:-user123}"
|
||||
NEKO_ADMIN_PASSWORD="${NEKO_ADMIN_PASSWORD:-admin123}"
|
||||
|
||||
PROFILE_UID="${PROFILE_UID:-1000}"
|
||||
PROFILE_GID="${PROFILE_GID:-1000}"
|
||||
|
||||
GOOGLE_CHROME_DIR="${GOOGLE_CHROME_DIR:-$HOME_DIR/neko-google-chrome-2}"
|
||||
GOOGLE_CHROME_PROFILE_DIR="${GOOGLE_CHROME_PROFILE_DIR:-/root/neko-google-chrome-2-profile}"
|
||||
|
||||
GOOGLE_CHROME_HTTP_PORT="${GOOGLE_CHROME_HTTP_PORT:-8082}"
|
||||
GOOGLE_CHROME_UDP_RANGE="${GOOGLE_CHROME_UDP_RANGE:-56400-56500}"
|
||||
GOOGLE_CHROME_DISPLAY="${GOOGLE_CHROME_DISPLAY:-:101.0}"
|
||||
|
||||
mkdir -p "$GOOGLE_CHROME_DIR/policies"
|
||||
|
||||
sudo mkdir -p "$GOOGLE_CHROME_PROFILE_DIR"
|
||||
sudo chown -R "${PROFILE_UID}:${PROFILE_GID}" "$GOOGLE_CHROME_PROFILE_DIR"
|
||||
|
||||
cat >"$GOOGLE_CHROME_DIR/docker-compose.yaml" <<EOF
|
||||
services:
|
||||
neko-google-chrome-2:
|
||||
image: ghcr.io/m1k1o/neko/google-chrome:latest
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
shm_size: "8gb"
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
environment:
|
||||
DISPLAY: "${GOOGLE_CHROME_DISPLAY}"
|
||||
NEKO_DESKTOP_SCREEN: "1920x1080@60"
|
||||
NEKO_SERVER_BIND: ":${GOOGLE_CHROME_HTTP_PORT}"
|
||||
NEKO_MEMBER_PROVIDER: "multiuser"
|
||||
NEKO_MEMBER_MULTIUSER_USER_PASSWORD: "${NEKO_USER_PASSWORD}"
|
||||
NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: "${NEKO_ADMIN_PASSWORD}"
|
||||
NEKO_WEBRTC_EPR: "${GOOGLE_CHROME_UDP_RANGE}"
|
||||
NEKO_WEBRTC_ICELITE: "1"
|
||||
NEKO_WEBRTC_NAT1TO1: "${LAN_IP}"
|
||||
NEKO_PLUGINS_ENABLED: "true"
|
||||
NEKO_PLUGINS_DIR: "/etc/neko/plugins/"
|
||||
volumes:
|
||||
- ${GOOGLE_CHROME_PROFILE_DIR}:/home/neko/.config/google-chrome
|
||||
- ${GOOGLE_CHROME_DIR}/policies:/etc/opt/chrome/policies/managed:ro
|
||||
- ${GOOGLE_CHROME_DIR}/google-chrome.conf:/etc/neko/supervisord/google-chrome.conf:ro
|
||||
EOF
|
||||
|
||||
cat >"$GOOGLE_CHROME_DIR/google-chrome.conf" <<'EOF'
|
||||
[program:google-chrome]
|
||||
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
|
||||
command=/usr/bin/google-chrome
|
||||
--window-position=0,0
|
||||
--display=%(ENV_DISPLAY)s
|
||||
--user-data-dir=/home/neko/.config/google-chrome
|
||||
--password-store=basic
|
||||
--no-first-run
|
||||
--start-maximized
|
||||
--force-dark-mode
|
||||
--disable-file-system
|
||||
--disable-gpu
|
||||
--disable-software-rasterizer
|
||||
--disable-dev-shm-usage
|
||||
--disable-background-timer-throttling
|
||||
--disable-backgrounding-occluded-windows
|
||||
--disable-renderer-backgrounding
|
||||
stopsignal=INT
|
||||
autorestart=true
|
||||
priority=800
|
||||
user=%(ENV_USER)s
|
||||
stdout_logfile=/var/log/neko/google-chrome.log
|
||||
stdout_logfile_maxbytes=100MB
|
||||
stdout_logfile_backups=10
|
||||
redirect_stderr=true
|
||||
|
||||
[program:openbox]
|
||||
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
|
||||
command=/usr/bin/openbox --config-file /etc/neko/openbox.xml
|
||||
autorestart=true
|
||||
priority=300
|
||||
user=%(ENV_USER)s
|
||||
stdout_logfile=/var/log/neko/openbox.log
|
||||
stdout_logfile_maxbytes=100MB
|
||||
stdout_logfile_backups=10
|
||||
redirect_stderr=true
|
||||
EOF
|
||||
|
||||
cat >"$GOOGLE_CHROME_DIR/policies/policies.json" <<'EOF'
|
||||
{
|
||||
"ExtensionInstallForcelist": [
|
||||
"dhdgffkkebhmkfjojejmpbldmpobfkfo;https://clients2.google.com/service/update2/crx"
|
||||
],
|
||||
"ExtensionInstallAllowlist": [
|
||||
"*"
|
||||
],
|
||||
"ExtensionInstallBlocklist": [],
|
||||
"DownloadRestrictions": 0,
|
||||
"AllowFileSelectionDialogs": true,
|
||||
"URLAllowlist": ["file:///home/neko/Downloads/*"],
|
||||
"DefaultCookiesSetting": 1,
|
||||
"RestoreOnStartup": 1
|
||||
}
|
||||
EOF
|
||||
|
||||
sudo ufw allow "${GOOGLE_CHROME_HTTP_PORT}" >/dev/null 2>&1 || true
|
||||
sudo ufw allow "$(ufw_udp_range "${GOOGLE_CHROME_UDP_RANGE}")" >/dev/null 2>&1 || true
|
||||
|
||||
recreate_compose_service() {
|
||||
local compose_dir="$1"
|
||||
local service="$2"
|
||||
local name_pattern="$3"
|
||||
local existing_id=""
|
||||
local pid=""
|
||||
|
||||
existing_id="$(cd "$compose_dir" && docker compose ps -q "$service" 2>/dev/null || true)"
|
||||
if [[ -n "$existing_id" ]]; then
|
||||
docker update --restart=no "$existing_id" >/dev/null 2>&1 || true
|
||||
pid="$(docker inspect -f '{{.State.Pid}}' "$existing_id" 2>/dev/null || true)"
|
||||
if [[ -n "$pid" && "$pid" != "0" ]]; then
|
||||
sudo kill -TERM "$pid" >/dev/null 2>&1 || true
|
||||
sleep 3
|
||||
sudo kill -KILL "$pid" >/dev/null 2>&1 || true
|
||||
sleep 2
|
||||
fi
|
||||
docker rm -f "$existing_id" >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
docker ps -a --format '{{.ID}} {{.Names}}' \
|
||||
| awk -v pat="$name_pattern" '$2 ~ pat {print $1}' \
|
||||
| xargs -r docker rm -f >/dev/null 2>&1 || true
|
||||
|
||||
(cd "$compose_dir" && docker compose up -d)
|
||||
}
|
||||
|
||||
wait_for_healthy() {
|
||||
local compose_dir="$1"
|
||||
local service="$2"
|
||||
local container_id=""
|
||||
local health_status=""
|
||||
local state_status=""
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
container_id="$(cd "$compose_dir" && docker compose ps -q "$service" 2>/dev/null || true)"
|
||||
[[ -z "$container_id" ]] && sleep 2 && continue
|
||||
|
||||
health_status="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container_id" 2>/dev/null || true)"
|
||||
state_status="$(docker inspect -f '{{.State.Status}}' "$container_id" 2>/dev/null || true)"
|
||||
|
||||
if [[ "$state_status" == "running" && ( "$health_status" == "healthy" || "$health_status" == "none" ) ]]; then
|
||||
echo "$container_id"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ "$health_status" == "unhealthy" ]]; then
|
||||
echo "service ${service} became unhealthy" >&2
|
||||
docker logs --tail 200 "$container_id" >&2 || true
|
||||
return 1
|
||||
fi
|
||||
|
||||
sleep 2
|
||||
done
|
||||
|
||||
echo "timed out waiting for ${service}" >&2
|
||||
[[ -n "$container_id" ]] && docker logs --tail 200 "$container_id" >&2 || true
|
||||
return 1
|
||||
}
|
||||
|
||||
recreate_compose_service "$GOOGLE_CHROME_DIR" "neko-google-chrome-2" "neko-google-chrome-2"
|
||||
GOOGLE_CHROME_ID="$(wait_for_healthy "$GOOGLE_CHROME_DIR" "neko-google-chrome-2")"
|
||||
|
||||
echo
|
||||
echo "google-chrome-2:"
|
||||
echo " url: http://${LAN_IP}:${GOOGLE_CHROME_HTTP_PORT}/"
|
||||
echo " container: ${GOOGLE_CHROME_ID}"
|
||||
echo " compose: ${GOOGLE_CHROME_DIR}"
|
||||
50
tcp_forward_qwen.py
Normal file
50
tcp_forward_qwen.py
Normal file
@@ -0,0 +1,50 @@
|
||||
import socket
|
||||
import threading
|
||||
|
||||
|
||||
LISTEN_HOST = "127.0.0.1"
|
||||
LISTEN_PORT = 18007
|
||||
TARGET_HOST = "192.168.41.184"
|
||||
TARGET_PORT = 8007
|
||||
|
||||
|
||||
def pipe(src: socket.socket, dst: socket.socket) -> None:
|
||||
try:
|
||||
while True:
|
||||
data = src.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
dst.sendall(data)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for sock in (src, dst):
|
||||
try:
|
||||
sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def handle_client(client: socket.socket) -> None:
|
||||
upstream = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
upstream.connect((TARGET_HOST, TARGET_PORT))
|
||||
threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
|
||||
threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
server.bind((LISTEN_HOST, LISTEN_PORT))
|
||||
server.listen()
|
||||
while True:
|
||||
client, _ = server.accept()
|
||||
threading.Thread(target=handle_client, args=(client,), daemon=True).start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user