feat: Implement subscription-based premium features, payment processing, and enhanced dashboard components.

This commit is contained in:
2569718930@qq.com
2026-03-13 06:41:33 +08:00
parent f7b649bb0a
commit 54c4a26162
19 changed files with 427 additions and 90 deletions
+3
View File
@@ -60,6 +60,9 @@ POLYWEATHER_PAYMENT_HTTP_TIMEOUT_SEC=10
POLYWEATHER_PAYMENT_POLL_INTERVAL_SEC=4 POLYWEATHER_PAYMENT_POLL_INTERVAL_SEC=4
POLYWEATHER_PAYMENT_MAX_WAIT_SEC=50 POLYWEATHER_PAYMENT_MAX_WAIT_SEC=50
POLYWEATHER_PAYMENT_TELEGRAM_NOTIFY_ENABLED=true POLYWEATHER_PAYMENT_TELEGRAM_NOTIFY_ENABLED=true
# Comma-separated allowed plans for checkout UI + backend validation.
# Default is monthly-only launch.
POLYWEATHER_PAYMENT_ALLOWED_PLAN_CODES=pro_monthly
# JSON object # JSON object
# Example: {"pro_monthly":{"plan_id":101,"amount_usdc":"29","duration_days":30}} # Example: {"pro_monthly":{"plan_id":101,"amount_usdc":"29","duration_days":30}}
POLYWEATHER_PAYMENT_PLAN_CATALOG_JSON= POLYWEATHER_PAYMENT_PLAN_CATALOG_JSON=
+1 -2
View File
@@ -24,7 +24,7 @@ export async function GET(req: NextRequest) {
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 300) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 300) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -38,4 +38,3 @@ export async function GET(req: NextRequest) {
); );
} }
} }
+1 -1
View File
@@ -23,7 +23,7 @@ export async function GET(req: NextRequest) {
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -36,7 +36,7 @@ export async function POST(
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -50,4 +50,3 @@ export async function POST(
); );
} }
} }
@@ -36,7 +36,7 @@ export async function POST(
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -50,4 +50,3 @@ export async function POST(
); );
} }
} }
+1 -1
View File
@@ -29,7 +29,7 @@ export async function POST(req: NextRequest) {
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -29,7 +29,7 @@ export async function POST(req: NextRequest) {
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -43,4 +43,3 @@ export async function POST(req: NextRequest) {
); );
} }
} }
+1 -1
View File
@@ -23,7 +23,7 @@ export async function GET(req: NextRequest) {
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
@@ -29,7 +29,7 @@ export async function POST(req: NextRequest) {
const raw = await res.text(); const raw = await res.text();
const response = NextResponse.json( const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) }, { error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 }, { status: res.status },
); );
return applyAuthResponseCookies(response, auth.response); return applyAuthResponseCookies(response, auth.response);
} }
+97 -34
View File
@@ -20,10 +20,10 @@ import {
LogIn, LogIn,
LogOut, LogOut,
Mail, Mail,
Wallet,
RefreshCw, RefreshCw,
Shield, Shield,
Sparkles, Sparkles,
Wallet,
User as UserIcon, User as UserIcon,
UserCheck, UserCheck,
} from "lucide-react"; } from "lucide-react";
@@ -134,6 +134,14 @@ function shortAddress(address: string) {
return `${text.slice(0, 8)}...${text.slice(-6)}`; return `${text.slice(0, 8)}...${text.slice(-6)}`;
} }
function planDisplayName(planCode: string) {
const code = String(planCode || "").trim().toLowerCase();
if (code === "pro_monthly") return "Pro 月付";
if (code === "pro_quarterly") return "Pro 季付";
if (code === "pro_yearly") return "Pro 年付";
return planCode || "--";
}
function toPaddedHex(value: bigint) { function toPaddedHex(value: bigint) {
return value.toString(16).padStart(64, "0"); return value.toString(16).padStart(64, "0");
} }
@@ -198,6 +206,31 @@ export function AccountCenter() {
const supabaseReady = hasSupabasePublicEnv(); const supabaseReady = hasSupabasePublicEnv();
const buildAuthedHeaders = useCallback(
async (withJson = false): Promise<Record<string, string>> => {
const headers: Record<string, string> = {};
if (withJson) {
headers["Content-Type"] = "application/json";
}
if (!supabaseReady) {
return headers;
}
try {
const {
data: { session },
} = await getSupabaseBrowserClient().auth.getSession();
const accessToken = String(session?.access_token || "").trim();
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
} catch {
// no-op: backend proxy may still succeed via cookie-based session.
}
return headers;
},
[supabaseReady],
);
const loadPaymentSnapshot = useCallback(async () => { const loadPaymentSnapshot = useCallback(async () => {
if (!backend?.authenticated) { if (!backend?.authenticated) {
setPaymentConfig(null); setPaymentConfig(null);
@@ -205,9 +238,16 @@ export function AccountCenter() {
return; return;
} }
try { try {
const authHeaders = await buildAuthedHeaders(false);
const [configRes, walletsRes] = await Promise.all([ const [configRes, walletsRes] = await Promise.all([
fetch("/api/payments/config", { cache: "no-store" }), fetch("/api/payments/config", {
fetch("/api/payments/wallets", { cache: "no-store" }), cache: "no-store",
headers: authHeaders,
}),
fetch("/api/payments/wallets", {
cache: "no-store",
headers: authHeaders,
}),
]); ]);
if (configRes.ok) { if (configRes.ok) {
const configJson = (await configRes.json()) as PaymentConfig; const configJson = (await configRes.json()) as PaymentConfig;
@@ -226,10 +266,13 @@ export function AccountCenter() {
setSelectedWallet(wallets[0].address); setSelectedWallet(wallets[0].address);
} }
} }
if (configRes.status === 401 || walletsRes.status === 401) {
setPaymentError("登录会话已过期,请重新登录后再进行钱包绑定或支付。");
}
} catch { } catch {
return; return;
} }
}, [backend?.authenticated, selectedPlanCode, selectedWallet]); }, [backend?.authenticated, buildAuthedHeaders, selectedPlanCode, selectedWallet]);
const loadSnapshot = useCallback(async () => { const loadSnapshot = useCallback(async () => {
setErrorText(""); setErrorText("");
@@ -237,7 +280,11 @@ export function AccountCenter() {
const userPromise = supabaseReady const userPromise = supabaseReady
? getSupabaseBrowserClient().auth.getUser() ? getSupabaseBrowserClient().auth.getUser()
: Promise.resolve({ data: { user: null as User | null } }); : Promise.resolve({ data: { user: null as User | null } });
const backendPromise = fetch("/api/auth/me", { cache: "no-store" }); const authHeaders = await buildAuthedHeaders(false);
const backendPromise = fetch("/api/auth/me", {
cache: "no-store",
headers: authHeaders,
});
const [userResult, backendResult] = await Promise.all([ const [userResult, backendResult] = await Promise.all([
userPromise, userPromise,
@@ -257,7 +304,7 @@ export function AccountCenter() {
} catch (error) { } catch (error) {
setErrorText(String(error)); setErrorText(String(error));
} }
}, [supabaseReady]); }, [buildAuthedHeaders, supabaseReady]);
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
@@ -372,7 +419,12 @@ export function AccountCenter() {
}; };
const planList = paymentConfig?.plans || []; const planList = paymentConfig?.plans || [];
const selectedPlan = planList.find((p) => p.plan_code === selectedPlanCode) || planList[0]; const monthlyPlanList = planList.filter(
(plan) => String(plan.plan_code || "").trim().toLowerCase() === "pro_monthly",
);
const effectivePlanList = monthlyPlanList.length ? monthlyPlanList : planList;
const selectedPlan =
effectivePlanList.find((p) => p.plan_code === selectedPlanCode) || effectivePlanList[0];
const paymentFeatureReady = Boolean(paymentConfig?.enabled && paymentConfig?.configured); const paymentFeatureReady = Boolean(paymentConfig?.enabled && paymentConfig?.configured);
const connectAndBindWallet = async () => { const connectAndBindWallet = async () => {
@@ -396,10 +448,14 @@ export function AccountCenter() {
if (!address) { if (!address) {
throw new Error("钱包账户为空"); throw new Error("钱包账户为空");
} }
const authHeaders = await buildAuthedHeaders(true);
if (!authHeaders.Authorization) {
throw new Error("登录会话失效,请重新登录后再绑定钱包。");
}
setWalletAddress(address); setWalletAddress(address);
const challengeRes = await fetch("/api/payments/wallets/challenge", { const challengeRes = await fetch("/api/payments/wallets/challenge", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: authHeaders,
body: JSON.stringify({ address }), body: JSON.stringify({ address }),
}); });
if (!challengeRes.ok) { if (!challengeRes.ok) {
@@ -421,7 +477,7 @@ export function AccountCenter() {
})) as string; })) as string;
const verifyRes = await fetch("/api/payments/wallets/verify", { const verifyRes = await fetch("/api/payments/wallets/verify", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: authHeaders,
body: JSON.stringify({ address, nonce, signature }), body: JSON.stringify({ address, nonce, signature }),
}); });
if (!verifyRes.ok) { if (!verifyRes.ok) {
@@ -453,7 +509,9 @@ export function AccountCenter() {
setPaymentError("未检测到 MetaMask。"); setPaymentError("未检测到 MetaMask。");
return; return;
} }
const payingWallet = (selectedWallet || walletAddress || "").toLowerCase(); const payingWallet = String(
selectedWallet || walletAddress || boundWallets[0]?.address || "",
).toLowerCase();
if (!payingWallet) { if (!payingWallet) {
setPaymentError("请先绑定钱包。"); setPaymentError("请先绑定钱包。");
return; return;
@@ -461,6 +519,10 @@ export function AccountCenter() {
setPaymentBusy(true); setPaymentBusy(true);
try { try {
const authHeaders = await buildAuthedHeaders(true);
if (!authHeaders.Authorization) {
throw new Error("登录会话失效,请重新登录后再支付。");
}
const currentChainIdHex = String( const currentChainIdHex = String(
(await eth.request({ method: "eth_chainId" })) || "", (await eth.request({ method: "eth_chainId" })) || "",
); );
@@ -475,9 +537,9 @@ export function AccountCenter() {
const createRes = await fetch("/api/payments/intents", { const createRes = await fetch("/api/payments/intents", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: authHeaders,
body: JSON.stringify({ body: JSON.stringify({
plan_code: selectedPlanCode || "pro_monthly", plan_code: selectedPlan?.plan_code || "pro_monthly",
payment_mode: "strict", payment_mode: "strict",
allowed_wallet: payingWallet, allowed_wallet: payingWallet,
metadata: { source: "account_center" }, metadata: { source: "account_center" },
@@ -548,7 +610,7 @@ export function AccountCenter() {
const submitRes = await fetch(`/api/payments/intents/${intentId}/submit`, { const submitRes = await fetch(`/api/payments/intents/${intentId}/submit`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: authHeaders,
body: JSON.stringify({ body: JSON.stringify({
tx_hash: txHashNorm, tx_hash: txHashNorm,
from_address: payingWallet, from_address: payingWallet,
@@ -561,7 +623,7 @@ export function AccountCenter() {
const confirmRes = await fetch(`/api/payments/intents/${intentId}/confirm`, { const confirmRes = await fetch(`/api/payments/intents/${intentId}/confirm`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: authHeaders,
body: JSON.stringify({ tx_hash: txHashNorm }), body: JSON.stringify({ tx_hash: txHashNorm }),
}); });
if (!confirmRes.ok) { if (!confirmRes.ok) {
@@ -581,31 +643,32 @@ export function AccountCenter() {
return ( return (
<div className="relative min-h-screen w-full overflow-hidden bg-[#0b0f1a] p-4 font-sans text-slate-200 md:p-8"> <div className="relative min-h-screen w-full overflow-hidden bg-[#0b0f1a] p-4 font-sans text-slate-200 md:p-8">
<div className="pointer-events-none absolute right-0 top-0 h-[500px] w-[500px] rounded-full bg-blue-600/10 blur-[120px]" /> <div className="pointer-events-none absolute -right-24 -top-20 h-[620px] w-[620px] rounded-full bg-blue-600/15 blur-[130px]" />
<div className="pointer-events-none absolute bottom-0 left-0 h-[500px] w-[500px] rounded-full bg-indigo-600/10 blur-[120px]" /> <div className="pointer-events-none absolute -bottom-24 -left-20 h-[620px] w-[620px] rounded-full bg-indigo-600/15 blur-[130px]" />
<div className="relative z-10 mx-auto max-w-5xl"> <div className="relative z-10 mx-auto flex w-full max-w-6xl flex-col">
<header className="mb-8 flex flex-col justify-between gap-4 md:flex-row md:items-center"> <header className="mb-8 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div> <div className="flex items-center gap-4">
<h1 className="bg-gradient-to-r from-white to-slate-400 bg-clip-text text-2xl font-bold text-transparent">
</h1>
<p className="mt-1 flex items-center gap-2 text-sm text-slate-500">
<Shield size={14} /> Bot
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Link <Link
href="/" href="/"
className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm transition-all active:scale-95 hover:bg-white/10" className="group rounded-full border border-white/10 bg-white/5 p-2 text-slate-400 transition-all hover:bg-white/10 hover:text-white"
title="返回首页"
> >
<ChevronLeft size={16} /> <ChevronLeft size={20} className="transition-transform group-hover:-translate-x-0.5" />
</Link> </Link>
<div>
<h1 className="text-2xl font-bold text-white"></h1>
<p className="text-sm text-slate-500">
v4.3 · Bot
</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<button <button
type="button" type="button"
onClick={() => void onRefresh()} onClick={() => void onRefresh()}
disabled={refreshing || loading} disabled={refreshing || loading}
className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm transition-all active:scale-95 hover:bg-white/10 disabled:opacity-70" className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm transition-all hover:bg-white/10 disabled:opacity-70"
> >
{refreshing || loading ? ( {refreshing || loading ? (
<Loader2 size={16} className="animate-spin" /> <Loader2 size={16} className="animate-spin" />
@@ -618,14 +681,14 @@ export function AccountCenter() {
<button <button
type="button" type="button"
onClick={() => void onSignOut()} onClick={() => void onSignOut()}
className="flex items-center gap-2 rounded-xl border border-red-500/20 bg-red-500/10 px-4 py-2 text-sm text-red-400 transition-all active:scale-95 hover:bg-red-500/20" className="flex items-center gap-2 rounded-xl border border-red-500/20 bg-red-500/10 px-4 py-2 text-sm text-red-400 transition hover:bg-red-500/20"
> >
<LogOut size={16} /> 退 <LogOut size={16} /> 退
</button> </button>
) : ( ) : (
<Link <Link
href="/auth/login?next=%2Faccount" href="/auth/login?next=%2Faccount"
className="flex items-center gap-2 rounded-xl border border-blue-500/20 bg-blue-500/10 px-4 py-2 text-sm text-blue-300 transition-all active:scale-95 hover:bg-blue-500/20" className="flex items-center gap-2 rounded-xl border border-blue-500/20 bg-blue-500/10 px-4 py-2 text-sm text-blue-300 transition hover:bg-blue-500/20"
> >
<LogIn size={16} /> / <LogIn size={16} /> /
</Link> </Link>
@@ -790,7 +853,7 @@ export function AccountCenter() {
</p> </p>
<div className="mb-3 space-y-2"> <div className="mb-3 space-y-2">
{planList.map((plan) => ( {effectivePlanList.map((plan) => (
<label <label
key={plan.plan_code} key={plan.plan_code}
className="flex cursor-pointer items-center justify-between rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm" className="flex cursor-pointer items-center justify-between rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
@@ -803,7 +866,7 @@ export function AccountCenter() {
checked={selectedPlanCode === plan.plan_code} checked={selectedPlanCode === plan.plan_code}
onChange={() => setSelectedPlanCode(plan.plan_code)} onChange={() => setSelectedPlanCode(plan.plan_code)}
/> />
{plan.plan_code} {planDisplayName(plan.plan_code)}
</span> </span>
<span className="text-cyan-200"> <span className="text-cyan-200">
{plan.amount_usdc} USDC / {plan.duration_days} {plan.amount_usdc} USDC / {plan.duration_days}
@@ -128,6 +128,7 @@ export function DetailPanel() {
const store = useDashboardStore(); const store = useDashboardStore();
const { locale, t } = useI18n(); const { locale, t } = useI18n();
const detail = store.selectedDetail; const detail = store.selectedDetail;
const isPro = store.proAccess.subscriptionActive;
const panelRef = useRef<HTMLElement | null>(null); const panelRef = useRef<HTMLElement | null>(null);
const isOverlayOpen = const isOverlayOpen =
Boolean(store.futureModalDate) || Boolean(store.futureModalDate) ||
@@ -201,26 +202,30 @@ export function DetailPanel() {
<button <button
type="button" type="button"
className="history-btn" className="history-btn"
title={t("detail.todayAnalysis")} title={
isPro
? t("detail.todayAnalysis")
: `${t("detail.todayAnalysis")} (Pro)`
}
onClick={() => { onClick={() => {
blurActiveElement(); blurActiveElement();
void store.openTodayModal(); void store.openTodayModal();
}} }}
disabled={!detail} disabled={!detail}
> >
{t("detail.todayAnalysis")} {isPro ? t("detail.todayAnalysis") : `${t("detail.todayAnalysis")} · Pro`}
</button> </button>
<button <button
type="button" type="button"
className="history-btn" className="history-btn"
title={t("detail.history")} title={isPro ? t("detail.history") : `${t("detail.history")} (Pro)`}
onClick={() => { onClick={() => {
blurActiveElement(); blurActiveElement();
void store.openHistory(); void store.openHistory();
}} }}
disabled={!detail} disabled={!detail}
> >
{t("detail.history")} {isPro ? t("detail.history") : `${t("detail.history")} · Pro`}
</button> </button>
</div> </div>
</div> </div>
@@ -18,6 +18,7 @@ import { CSSProperties } from "react";
import { useChart } from "@/hooks/useChart"; import { useChart } from "@/hooks/useChart";
import { useDashboardStore } from "@/hooks/useDashboardStore"; import { useDashboardStore } from "@/hooks/useDashboardStore";
import { useI18n } from "@/hooks/useI18n"; import { useI18n } from "@/hooks/useI18n";
import { ProFeaturePaywall } from "@/components/dashboard/ProFeaturePaywall";
import { import {
ModelForecast, ModelForecast,
ProbabilityDistribution, ProbabilityDistribution,
@@ -438,6 +439,8 @@ export function FutureForecastModal() {
const detail = store.selectedDetail; const detail = store.selectedDetail;
const marketScan = store.selectedMarketScan; const marketScan = store.selectedMarketScan;
const dateStr = store.futureModalDate; const dateStr = store.futureModalDate;
const isPro = store.proAccess.subscriptionActive;
const isProLoading = store.proAccess.loading;
if (!detail || !dateStr) return null; if (!detail || !dateStr) return null;
@@ -568,6 +571,7 @@ export function FutureForecastModal() {
"future-refresh-btn", "future-refresh-btn",
store.loadingState.marketScan && "spinning", store.loadingState.marketScan && "spinning",
)} )}
disabled={!isPro || isProLoading}
onClick={() => { onClick={() => {
if (isToday) { if (isToday) {
void store.openTodayModal(true); void store.openTodayModal(true);
@@ -575,7 +579,15 @@ export function FutureForecastModal() {
} }
store.openFutureModal(dateStr, true); store.openFutureModal(dateStr, true);
}} }}
title={locale === "en-US" ? "Refresh Data" : "刷新数据"} title={
!isPro
? locale === "en-US"
? "Pro subscription required"
: "需要 Pro 订阅"
: locale === "en-US"
? "Refresh Data"
: "刷新数据"
}
> >
<svg <svg
width="14" width="14"
@@ -605,7 +617,20 @@ export function FutureForecastModal() {
</div> </div>
<div className="modal-body future-modal-body"> <div className="modal-body future-modal-body">
{isToday ? ( {isProLoading ? (
<div
style={{
color: "var(--text-muted)",
display: "flex",
justifyContent: "center",
padding: "28px 0",
}}
>
{t("dashboard.loading")}
</div>
) : !isPro ? (
<ProFeaturePaywall feature={isToday ? "today" : "future"} />
) : isToday ? (
<div className="future-v2-layout"> <div className="future-v2-layout">
<aside className="future-v2-left"> <aside className="future-v2-left">
<section className="future-v2-card future-v2-hero-card"> <section className="future-v2-card future-v2-hero-card">
+54 -28
View File
@@ -5,6 +5,7 @@ import { useMemo } from "react";
import { useChart } from "@/hooks/useChart"; import { useChart } from "@/hooks/useChart";
import { useDashboardStore, useHistoryData } from "@/hooks/useDashboardStore"; import { useDashboardStore, useHistoryData } from "@/hooks/useDashboardStore";
import { useI18n } from "@/hooks/useI18n"; import { useI18n } from "@/hooks/useI18n";
import { ProFeaturePaywall } from "@/components/dashboard/ProFeaturePaywall";
import { getHistorySummary } from "@/lib/dashboard-utils"; import { getHistorySummary } from "@/lib/dashboard-utils";
function HistoryChart() { function HistoryChart() {
@@ -128,6 +129,8 @@ export function HistoryModal() {
const store = useDashboardStore(); const store = useDashboardStore();
const { t } = useI18n(); const { t } = useI18n();
const { data, error, isLoading, isOpen } = useHistoryData(); const { data, error, isLoading, isOpen } = useHistoryData();
const isPro = store.proAccess.subscriptionActive;
const isProLoading = store.proAccess.loading;
const summary = useMemo( const summary = useMemo(
() => getHistorySummary(data, store.selectedDetail?.local_date), () => getHistorySummary(data, store.selectedDetail?.local_date),
[data, store.selectedDetail?.local_date], [data, store.selectedDetail?.local_date],
@@ -162,37 +165,60 @@ export function HistoryModal() {
</button> </button>
</div> </div>
<div className="modal-body"> <div className="modal-body">
<div className="history-stats"> {isProLoading ? (
{isLoading ? ( <div
<span style={{ color: "var(--text-muted)" }}>{t("history.loading")}</span> style={{
) : error ? ( color: "var(--text-muted)",
<span style={{ color: "var(--accent-red)" }}>{t("history.error")}</span> display: "flex",
) : !summary.recentData.length ? ( justifyContent: "center",
<span style={{ color: "var(--text-muted)" }}>{t("history.empty")}</span> padding: "28px 0",
) : ( }}
<> >
<div className="h-stat-card"> {t("dashboard.loading")}
<span className="label">{t("history.hitRate")}</span> </div>
<span className="val"> ) : !isPro ? (
{summary.hitRate != null ? `${summary.hitRate}%` : "--"} <ProFeaturePaywall feature="history" />
) : (
<>
<div className="history-stats">
{isLoading ? (
<span style={{ color: "var(--text-muted)" }}>
{t("history.loading")}
</span> </span>
</div> ) : error ? (
<div className="h-stat-card"> <span style={{ color: "var(--accent-red)" }}>
<span className="label">{t("history.mae")}</span> {t("history.error")}
<span className="val">
{summary.debMae != null ? `${summary.debMae}°` : "--"}
</span> </span>
</div> ) : !summary.recentData.length ? (
<div className="h-stat-card"> <span style={{ color: "var(--text-muted)" }}>
<span className="label">{t("history.sample")}</span> {t("history.empty")}
<span className="val">
{t("history.sampleDays", { count: summary.settledCount })}
</span> </span>
</div> ) : (
</> <>
)} <div className="h-stat-card">
</div> <span className="label">{t("history.hitRate")}</span>
{!isLoading && !error && <HistoryChart />} <span className="val">
{summary.hitRate != null ? `${summary.hitRate}%` : "--"}
</span>
</div>
<div className="h-stat-card">
<span className="label">{t("history.mae")}</span>
<span className="val">
{summary.debMae != null ? `${summary.debMae}°` : "--"}
</span>
</div>
<div className="h-stat-card">
<span className="label">{t("history.sample")}</span>
<span className="val">
{t("history.sampleDays", { count: summary.settledCount })}
</span>
</div>
</>
)}
</div>
{!isLoading && !error && <HistoryChart />}
</>
)}
</div> </div>
</div> </div>
</div> </div>
@@ -0,0 +1,105 @@
"use client";
import Link from "next/link";
import {
ArrowRight,
BarChart3,
Crown,
Lock,
ShieldCheck,
Sparkles,
Zap,
} from "lucide-react";
import { useI18n } from "@/hooks/useI18n";
type ProFeaturePaywallProps = {
feature: "today" | "history" | "future";
};
function getFeatureLabel(
locale: "zh-CN" | "en-US",
feature: "today" | "history" | "future",
) {
if (locale === "en-US") {
if (feature === "today") return "Intraday Analysis";
if (feature === "history") return "History Reconciliation";
return "Future-date Analysis";
}
if (feature === "today") return "今日日内分析";
if (feature === "history") return "历史对账";
return "未来日期分析";
}
export function ProFeaturePaywall({ feature }: ProFeaturePaywallProps) {
const { locale } = useI18n();
const featureLabel = getFeatureLabel(locale, feature);
const isEn = locale === "en-US";
return (
<div className="mx-auto w-full max-w-4xl rounded-[2rem] border border-white/10 bg-gradient-to-b from-slate-800/95 to-slate-950/95 p-8 md:p-10">
<div className="mx-auto mb-5 flex h-16 w-16 -translate-y-12 items-center justify-center rounded-2xl bg-gradient-to-tr from-amber-500 to-orange-400 text-white shadow-xl shadow-amber-500/20">
<Crown size={28} />
</div>
<div className="-mt-6 text-center">
<h3 className="text-3xl font-bold text-white">
{isEn ? "Unlock PolyWeather Pro" : "开启 PolyWeather Pro"}
</h3>
<p className="mx-auto mt-4 max-w-2xl text-base text-slate-300">
{isEn
? `This module (${featureLabel}) is available for subscribers only. Upgrade to unlock advanced weather intelligence.`
: `当前模块(${featureLabel})仅对订阅用户开放。升级后可解锁更完整的气象分析能力。`}
</p>
</div>
<div className="mt-8 grid grid-cols-1 gap-3 md:grid-cols-2">
{[
{
icon: Zap,
text: isEn ? "Real-time radar and lightning tracking" : "实时雷达与闪电追踪",
},
{
icon: ShieldCheck,
text: isEn ? "15-day high-precision trend analysis" : "15 天高精度趋势分析",
},
{
icon: BarChart3,
text: isEn ? "Pro-grade station raw data" : "专业级气象站原始数据",
},
{
icon: Sparkles,
text: isEn ? "Ad-free experience across all surfaces" : "全平台无广告体验",
},
].map((item) => (
<div
key={item.text}
className="flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3"
>
<item.icon size={17} className="text-cyan-300" />
<span className="text-sm text-slate-200">{item.text}</span>
</div>
))}
</div>
<div className="mt-8">
<Link
href="/account"
className="group flex w-full items-center justify-center rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 px-5 py-4 text-lg font-semibold text-white shadow-lg shadow-blue-600/20 transition hover:from-blue-500 hover:to-indigo-500"
>
{isEn ? "Upgrade now - $5 / month" : "立即升级 - $5 / 月"}
<ArrowRight
size={19}
className="ml-2 transition-transform group-hover:translate-x-1"
/>
</Link>
</div>
<div className="mt-6 border-t border-white/10 pt-4 text-center text-xs text-slate-400">
<span className="inline-flex items-center gap-1.5">
<Lock size={12} />
{isEn ? "Payments are secured with AES-256 encryption" : "所有交易均经过 AES-256 加密保护"}
</span>
</div>
</div>
);
}
+74 -1
View File
@@ -22,6 +22,7 @@ import {
HistoryState, HistoryState,
LoadingState, LoadingState,
MarketScan, MarketScan,
ProAccessState,
} from "@/lib/dashboard-types"; } from "@/lib/dashboard-types";
interface DashboardStoreValue extends DashboardState { interface DashboardStoreValue extends DashboardState {
@@ -39,6 +40,7 @@ interface DashboardStoreValue extends DashboardState {
openTodayModal: (forceRefresh?: boolean) => Promise<void>; openTodayModal: (forceRefresh?: boolean) => Promise<void>;
registerMapStopMotion: (stopMotion: () => void) => void; registerMapStopMotion: (stopMotion: () => void) => void;
refreshAll: () => Promise<void>; refreshAll: () => Promise<void>;
refreshProAccess: () => Promise<void>;
refreshSelectedCity: () => Promise<void>; refreshSelectedCity: () => Promise<void>;
selectedMarketScan: MarketScan | null; selectedMarketScan: MarketScan | null;
selectedDetail: CityDetail | null; selectedDetail: CityDetail | null;
@@ -68,6 +70,15 @@ function getInitialHistoryState(): HistoryState {
}; };
} }
function getInitialProAccessState(): ProAccessState {
return {
loading: true,
authenticated: false,
subscriptionActive: false,
error: null,
};
}
const AI_EMPTY_PATTERNS = [ const AI_EMPTY_PATTERNS = [
/暂无\s*AI\s*分析/i, /暂无\s*AI\s*分析/i,
/当前以结构化气象与模型数据为主/i, /当前以结构化气象与模型数据为主/i,
@@ -205,6 +216,9 @@ export function DashboardStoreProvider({
getInitialHistoryState, getInitialHistoryState,
); );
const [isGuideOpen, setIsGuideOpen] = useState(false); const [isGuideOpen, setIsGuideOpen] = useState(false);
const [proAccess, setProAccess] = useState<ProAccessState>(
getInitialProAccessState,
);
const mapStopMotionRef = useRef<() => void>(() => {}); const mapStopMotionRef = useRef<() => void>(() => {});
const hydratedSelectionRef = useRef(false); const hydratedSelectionRef = useRef(false);
@@ -369,10 +383,50 @@ export function DashboardStoreProvider({
} }
}; };
const refreshProAccess = async () => {
setProAccess((current) => ({
...current,
loading: true,
error: null,
}));
try {
const response = await fetch("/api/auth/me", {
cache: "no-store",
headers: {
Accept: "application/json",
},
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const payload = (await response.json()) as {
authenticated?: boolean;
subscription_active?: boolean | null;
};
setProAccess({
loading: false,
authenticated: Boolean(payload.authenticated),
subscriptionActive: payload.subscription_active === true,
error: null,
});
} catch (error) {
setProAccess({
loading: false,
authenticated: false,
subscriptionActive: false,
error: String(error),
});
}
};
useEffect(() => { useEffect(() => {
void loadCities(); void loadCities();
}, []); }, []);
useEffect(() => {
void refreshProAccess();
}, []);
useEffect(() => { useEffect(() => {
if (!cities.length) return; if (!cities.length) return;
@@ -514,6 +568,15 @@ export function DashboardStoreProvider({
const openHistory = async () => { const openHistory = async () => {
if (!selectedCity) return; if (!selectedCity) return;
if (!proAccess.subscriptionActive) {
setHistoryState((current) => ({
...current,
error: null,
isOpen: true,
loading: false,
}));
return;
}
setHistoryState((current) => ({ setHistoryState((current) => ({
...current, ...current,
error: null, error: null,
@@ -558,10 +621,11 @@ export function DashboardStoreProvider({
isGuideOpen, isGuideOpen,
loadCities, loadCities,
loadingState, loadingState,
proAccess,
openFutureModal: (dateStr: string, forceRefresh = false) => { openFutureModal: (dateStr: string, forceRefresh = false) => {
mapStopMotionRef.current(); mapStopMotionRef.current();
setFutureModalDate(dateStr); setFutureModalDate(dateStr);
if (!selectedCity) return; if (!selectedCity || !proAccess.subscriptionActive) return;
const cacheKey = getMarketScanCacheKey(selectedCity, dateStr); const cacheKey = getMarketScanCacheKey(selectedCity, dateStr);
setLoadingState((current) => ({ ...current, marketScan: true })); setLoadingState((current) => ({ ...current, marketScan: true }));
void ensureCityMarketScan( void ensureCityMarketScan(
@@ -584,6 +648,13 @@ export function DashboardStoreProvider({
mapStopMotionRef.current(); mapStopMotionRef.current();
const cachedDetail = cityDetailsByName[selectedCity]; const cachedDetail = cityDetailsByName[selectedCity];
if (cachedDetail?.local_date) {
setSelectedForecastDate(cachedDetail.local_date);
setFutureModalDate(cachedDetail.local_date);
}
if (!proAccess.subscriptionActive) {
return;
}
// 乐观 UI: 有缓存则立刻秒开 modal,不阻塞显示 // 乐观 UI: 有缓存则立刻秒开 modal,不阻塞显示
if (cachedDetail?.local_date) { if (cachedDetail?.local_date) {
@@ -633,6 +704,7 @@ export function DashboardStoreProvider({
mapStopMotionRef.current = stopMotion; mapStopMotionRef.current = stopMotion;
}, },
refreshAll, refreshAll,
refreshProAccess,
refreshSelectedCity, refreshSelectedCity,
selectedMarketScan, selectedMarketScan,
selectedCity, selectedCity,
@@ -652,6 +724,7 @@ export function DashboardStoreProvider({
isPanelOpen, isPanelOpen,
isGuideOpen, isGuideOpen,
loadingState, loadingState,
proAccess,
marketScanByCityName, marketScanByCityName,
selectedMarketScan, selectedMarketScan,
selectedCity, selectedCity,
+8
View File
@@ -314,6 +314,13 @@ export interface HistoryState {
dataByCity: Record<string, HistoryPoint[]>; dataByCity: Record<string, HistoryPoint[]>;
} }
export interface ProAccessState {
loading: boolean;
authenticated: boolean;
subscriptionActive: boolean;
error: string | null;
}
export interface DashboardState { export interface DashboardState {
cities: CityListItem[]; cities: CityListItem[];
cityDetailsByName: Record<string, CityDetail>; cityDetailsByName: Record<string, CityDetail>;
@@ -323,4 +330,5 @@ export interface DashboardState {
selectedForecastDate: string | null; selectedForecastDate: string | null;
loadingState: LoadingState; loadingState: LoadingState;
historyState: HistoryState; historyState: HistoryState;
proAccess: ProAccessState;
} }
+11 -7
View File
@@ -134,15 +134,11 @@ class SupabaseEntitlementService:
logger.warning(f"supabase auth user check failed: {exc}") logger.warning(f"supabase auth user check failed: {exc}")
return None return None
def has_active_subscription(self, user_id: str) -> bool: def _query_active_subscription(self, user_id: str) -> bool:
if not self.require_subscription:
return True
if not user_id: if not user_id:
return False return False
if not self.service_role_key: if not self.service_role_key:
logger.warning( logger.warning("SUPABASE_SERVICE_ROLE_KEY is missing")
"POLYWEATHER_AUTH_REQUIRE_SUBSCRIPTION=true but SUPABASE_SERVICE_ROLE_KEY is missing",
)
return False return False
now_ts = time.time() now_ts = time.time()
@@ -188,6 +184,14 @@ class SupabaseEntitlementService:
logger.warning(f"supabase subscription query error user_id={user_id}: {exc}") logger.warning(f"supabase subscription query error user_id={user_id}: {exc}")
return False return False
def has_active_subscription(
self,
user_id: str,
respect_requirement: bool = True,
) -> bool:
if respect_requirement and not self.require_subscription:
return True
return self._query_active_subscription(user_id)
SUPABASE_ENTITLEMENT = SupabaseEntitlementService() SUPABASE_ENTITLEMENT = SupabaseEntitlementService()
+27
View File
@@ -159,6 +159,18 @@ def _parse_plan_catalog(raw: str) -> Dict[str, Dict[str, Any]]:
return out or dict(DEFAULT_PLAN_CATALOG) return out or dict(DEFAULT_PLAN_CATALOG)
def _parse_allowed_plan_codes(raw: str) -> List[str]:
text = str(raw or "").strip()
if not text:
return ["pro_monthly"]
out: List[str] = []
for part in text.split(","):
code = str(part or "").strip().lower()
if code and code not in out:
out.append(code)
return out or ["pro_monthly"]
@dataclass @dataclass
class WalletBindingRecord: class WalletBindingRecord:
chain_id: int chain_id: int
@@ -224,6 +236,21 @@ class PaymentContractCheckoutService:
self.plan_catalog = _parse_plan_catalog( self.plan_catalog = _parse_plan_catalog(
os.getenv("POLYWEATHER_PAYMENT_PLAN_CATALOG_JSON") or "" os.getenv("POLYWEATHER_PAYMENT_PLAN_CATALOG_JSON") or ""
) )
self.allowed_plan_codes = _parse_allowed_plan_codes(
os.getenv("POLYWEATHER_PAYMENT_ALLOWED_PLAN_CODES") or ""
)
filtered_catalog = {
code: row
for code, row in self.plan_catalog.items()
if code in self.allowed_plan_codes
}
if filtered_catalog:
self.plan_catalog = filtered_catalog
elif "pro_monthly" in self.plan_catalog:
self.plan_catalog = {"pro_monthly": self.plan_catalog["pro_monthly"]}
elif self.plan_catalog:
first_code = sorted(self.plan_catalog.keys())[0]
self.plan_catalog = {first_code: self.plan_catalog[first_code]}
self.notify_telegram = _env_bool( self.notify_telegram = _env_bool(
"POLYWEATHER_PAYMENT_TELEGRAM_NOTIFY_ENABLED", True "POLYWEATHER_PAYMENT_TELEGRAM_NOTIFY_ENABLED", True
) )
+4 -2
View File
@@ -1082,8 +1082,10 @@ async def auth_me(request: Request):
subscription_active = None subscription_active = None
if SUPABASE_ENTITLEMENT.enabled and user_id: if SUPABASE_ENTITLEMENT.enabled and user_id:
try: try:
if SUPABASE_ENTITLEMENT.require_subscription: subscription_active = SUPABASE_ENTITLEMENT.has_active_subscription(
subscription_active = SUPABASE_ENTITLEMENT.has_active_subscription(user_id) user_id,
respect_requirement=False,
)
except Exception: except Exception:
subscription_active = None subscription_active = None