'城市详情'

This commit is contained in:
eric
2026-03-08 23:20:16 -05:00
parent e36d533a31
commit 41487dc22e
53 changed files with 3417 additions and 1206 deletions

5
app/lib/env.ts Normal file
View File

@@ -0,0 +1,5 @@
const isDev = process.env.NODE_ENV === "development";
export const SITE_URL =
process.env.NEXT_PUBLIC_SITE_URL ||
(isDev ? "http://localhost:3000" : "https://nomadcna.cn");

22
app/lib/locale-link.tsx Normal file
View File

@@ -0,0 +1,22 @@
"use client";
import NextLink from "next/link";
import { usePathname as useNextPathname } from "next/navigation";
import { useLocale } from "../context/LocaleContext";
type LocaleLinkProps = React.ComponentProps<typeof NextLink>;
export function LocaleLink({ href, ...props }: LocaleLinkProps) {
const locale = useLocale();
const hrefStr = typeof href === "string" ? href : href.pathname ?? "/";
const localeHref = hrefStr.startsWith("/")
? `/${locale}${hrefStr === "/" ? "" : hrefStr}`
: hrefStr;
return <NextLink href={localeHref} {...props} />;
}
export function usePathname() {
const path = useNextPathname();
const match = path?.match(/^\/(zh|en)(\/.*)?$/);
return match ? (match[2] ?? "/") : path ?? "/";
}

51
app/lib/minio/client.ts Normal file
View File

@@ -0,0 +1,51 @@
/**
* MinIO 客户端封装 - 上传、下载
*/
import * as Minio from "minio";
import { getMinioConfig } from "./config";
export function getMinioClient(): Minio.Client {
const cfg = getMinioConfig();
return new Minio.Client({
endPoint: cfg.endPoint,
port: cfg.port,
useSSL: cfg.useSSL,
accessKey: cfg.accessKey,
secretKey: cfg.secretKey,
pathStyle: true,
region: cfg.region,
});
}
export interface UploadResult {
url: string;
objectKey: string;
}
export async function uploadBuffer(
buffer: Buffer,
objectKey: string,
contentType: string = "application/octet-stream"
): Promise<UploadResult> {
const cfg = getMinioConfig();
if (!cfg.enabled) {
throw new Error("MinIO 存储未启用");
}
const client = getMinioClient();
await client.putObject(cfg.bucket, objectKey, buffer, buffer.length, {
"Content-Type": contentType,
});
const url = `${cfg.publicUrl}/${objectKey}`;
return { url, objectKey };
}
export function generateObjectKey(ext: string): string {
const cfg = getMinioConfig();
const prefix = cfg.uploadPrefix.replace(/\/$/, "");
return `${prefix}/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
}

2
app/lib/minio/config.ts Normal file
View File

@@ -0,0 +1,2 @@
export { getMinioConfig } from "@/config/services.config";
export type { MinioConfig } from "@/config/services.config";

8
app/lib/minio/index.ts Normal file
View File

@@ -0,0 +1,8 @@
export { getMinioConfig } from "./config";
export type { MinioConfig } from "./config";
export {
getMinioClient,
uploadBuffer,
generateObjectKey,
} from "./client";
export type { UploadResult } from "./client";

39
app/lib/payEnv.ts Normal file
View File

@@ -0,0 +1,39 @@
/**
* 支付环境检测:PC / H5 / 微信浏览器
*/
export type PayEnv = "pc" | "h5" | "wechat";
export type PayChannel = "alipay" | "wxpay";
export function isWeChat(): boolean {
if (typeof navigator === "undefined") return false;
return /MicroMessenger/i.test(navigator.userAgent);
}
export function isAlipay(): boolean {
if (typeof navigator === "undefined") return false;
return /AlipayClient|Alipay/i.test(navigator.userAgent);
}
export function isMobile(): boolean {
if (typeof navigator === "undefined") return false;
return /AppleWebKit.*Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
);
}
export function getPayEnv(): PayEnv {
if (isWeChat()) return "wechat";
if (isMobile()) return "h5";
return "pc";
}
export function getRecommendedChannel(env: PayEnv): PayChannel {
if (env === "wechat") return "wxpay";
return "alipay";
}
export function mustUseWxPay(env: PayEnv): boolean {
return env === "wechat";
}

53
app/lib/payment/client.ts Normal file
View File

@@ -0,0 +1,53 @@
/**
* ZPay 支付客户端封装 - 发起支付、跳转支付页
*/
import { getPaymentConfig, getJoinPaymentConfig } from "@/config/services.config";
import type { PayChannel, PayEnv } from "./types";
export function redirectToPay(params: {
user_id: string;
return_url: string;
total_fee?: number;
type?: string;
channel: PayChannel;
device: "pc" | "h5" | "wechat";
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", params.device],
["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();
}
export function getDeviceFromEnv(env: PayEnv): "pc" | "h5" | "wechat" {
if (env === "wechat") return "wechat";
return env === "pc" ? "pc" : "h5";
}

View File

@@ -0,0 +1,2 @@
export { getPaymentConfig } from "@/config/services.config";
export type { PaymentConfig } from "@/config/services.config";

5
app/lib/payment/index.ts Normal file
View File

@@ -0,0 +1,5 @@
export { redirectToPay, getDeviceFromEnv } from "./client";
export { getPayEnv, getRecommendedChannel, mustUseWxPay } from "../payEnv";
export { usePayStatusPoll } from "./usePayStatusPoll";
export type { PayChannel, PayEnv, CreatePayParams } from "./types";
export { getPaymentConfig } from "./config";

11
app/lib/payment/types.ts Normal file
View File

@@ -0,0 +1,11 @@
export type PayChannel = "alipay" | "wxpay";
export type PayEnv = "pc" | "h5" | "wechat";
export interface CreatePayParams {
user_id: string;
return_url: string;
total_fee?: number;
type?: string;
channel?: PayChannel;
device?: "pc" | "h5" | "wechat";
}

View File

@@ -0,0 +1,74 @@
/**
* 微信 H5 支付完成后可能不跳转,通过 cookie 中的订单号轮询检测支付状态
*/
import { useEffect, useRef, useState } from "react";
const COOKIE_NAME = "join_pay_order";
const POLL_INTERVAL = 2000;
const MAX_POLLS = 150;
const MAX_AGE_MS = 15 * 60 * 1000;
function getCookie(name: string): string | null {
if (typeof document === "undefined") return null;
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
}
function clearCookie(name: string): void {
if (typeof document === "undefined") return;
document.cookie = `${name}=; path=/; max-age=0`;
}
function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
if (!raw?.trim()) return [null, false];
const parts = raw.split("|");
const orderId = parts[0]?.trim() || raw.trim();
const ts = parts[1] ? parseInt(parts[1], 10) : NaN;
if (!orderId) return [null, false];
if (Number.isNaN(ts)) return [orderId, false];
if (Date.now() - ts > MAX_AGE_MS) return [orderId, false];
return [orderId, true];
}
export function usePayStatusPoll(onPaid: () => void): boolean {
const [polling, setPolling] = useState(false);
const onPaidRef = useRef(onPaid);
onPaidRef.current = onPaid;
useEffect(() => {
const raw = getCookie(COOKIE_NAME);
const [orderId, isValid] = parsePayOrderCookie(raw);
if (!orderId || !isValid) {
if (raw) clearCookie(COOKIE_NAME);
return;
}
setPolling(true);
let count = 0;
const timer = setInterval(async () => {
count++;
if (count > MAX_POLLS) {
clearInterval(timer);
clearCookie(COOKIE_NAME);
setPolling(false);
return;
}
try {
const res = await fetch(`/api/pay/status?order_id=${encodeURIComponent(orderId)}`);
const data = await res.json();
if (data?.ok && data?.paid) {
clearInterval(timer);
clearCookie(COOKIE_NAME);
setPolling(false);
onPaidRef.current();
}
} catch {
// 继续轮询
}
}, POLL_INTERVAL);
return () => clearInterval(timer);
}, []);
return polling;
}

View File

@@ -0,0 +1,91 @@
/**
* PocketBase 认证服务 - 邮箱登录、注册
*/
import { getPocketBaseConfig } from "@/config/services.config";
import { PB_STORAGE_KEYS } from "./constants";
export interface AuthUser {
id: string;
email: string;
[key: string]: unknown;
}
export interface AuthResult {
token: string;
record: AuthUser;
}
function getPBUrl(): string {
return getPocketBaseConfig().url;
}
export async function pbLogin(
identity: string,
password: string
): Promise<AuthResult> {
const url = getPBUrl();
const res = await fetch(`${url}/api/collections/users/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity, password }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.message || "登录失败");
}
const data = await res.json();
if (!data?.token) throw new Error("登录响应异常");
return { token: data.token, record: data.record };
}
export async function pbRegister(
email: string,
password: string,
passwordConfirm: string
): Promise<AuthResult> {
const url = getPBUrl();
const config = getPocketBaseConfig();
const res = await fetch(
`${url}/api/collections/${config.usersCollection}/records`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, passwordConfirm }),
}
);
if (!res.ok) {
const err = await res.json();
throw new Error(err?.message || "注册失败");
}
return pbLogin(email, password);
}
export function pbSaveAuth(token: string, record: AuthUser): void {
if (typeof window === "undefined") return;
localStorage.setItem(PB_STORAGE_KEYS.token, token);
localStorage.setItem(PB_STORAGE_KEYS.user, JSON.stringify(record));
}
export function pbLogout(): void {
if (typeof window === "undefined") return;
localStorage.removeItem(PB_STORAGE_KEYS.token);
localStorage.removeItem(PB_STORAGE_KEYS.user);
}
export function getStoredUserEmail(): string | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem(PB_STORAGE_KEYS.user);
if (!raw) return null;
const user = JSON.parse(raw);
return user?.email ?? null;
} catch {
return null;
}
}
export function getStoredToken(): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem(PB_STORAGE_KEYS.token);
}

View File

@@ -0,0 +1,2 @@
export { getPocketBaseConfig } from "@/config/services.config";
export type { PocketBaseConfig } from "@/config/services.config";

View File

@@ -0,0 +1,4 @@
export const PB_STORAGE_KEYS = {
token: "pb_token",
user: "pb_user",
} as const;

View File

@@ -0,0 +1,11 @@
export {
pbLogin,
pbRegister,
pbSaveAuth,
pbLogout,
getStoredUserEmail,
getStoredToken,
} from "./auth";
export type { AuthUser, AuthResult } from "./auth";
export { PB_STORAGE_KEYS } from "./constants";
export { getPocketBaseConfig } from "./config";

15
app/lib/theme-data.ts Normal file
View File

@@ -0,0 +1,15 @@
/**
* 多语言消息加载
*/
export type Locale = "zh" | "en";
export async function getThemeMessages(
locale: Locale
): Promise<Record<string, unknown>> {
const mod =
locale === "zh"
? await import("@/messages/zh.json")
: await import("@/messages/en.json");
return mod.default as Record<string, unknown>;
}