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_MAX_WAIT_SEC=50
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
# Example: {"pro_monthly":{"plan_id":101,"amount_usdc":"29","duration_days":30}}
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 response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 300) },
{ status: 502 },
{ status: res.status },
);
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 response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
return applyAuthResponseCookies(response, auth.response);
}
@@ -36,7 +36,7 @@ export async function POST(
const raw = await res.text();
const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
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 response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
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 response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
return applyAuthResponseCookies(response, auth.response);
}
@@ -29,7 +29,7 @@ export async function POST(req: NextRequest) {
const raw = await res.text();
const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
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 response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
return applyAuthResponseCookies(response, auth.response);
}
@@ -29,7 +29,7 @@ export async function POST(req: NextRequest) {
const raw = await res.text();
const response = NextResponse.json(
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 350) },
{ status: 502 },
{ status: res.status },
);
return applyAuthResponseCookies(response, auth.response);
}
+97 -34
View File
@@ -20,10 +20,10 @@ import {
LogIn,
LogOut,
Mail,
Wallet,
RefreshCw,
Shield,
Sparkles,
Wallet,
User as UserIcon,
UserCheck,
} from "lucide-react";
@@ -134,6 +134,14 @@ function shortAddress(address: string) {
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) {
return value.toString(16).padStart(64, "0");
}
@@ -198,6 +206,31 @@ export function AccountCenter() {
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 () => {
if (!backend?.authenticated) {
setPaymentConfig(null);
@@ -205,9 +238,16 @@ export function AccountCenter() {
return;
}
try {
const authHeaders = await buildAuthedHeaders(false);
const [configRes, walletsRes] = await Promise.all([
fetch("/api/payments/config", { cache: "no-store" }),
fetch("/api/payments/wallets", { cache: "no-store" }),
fetch("/api/payments/config", {
cache: "no-store",
headers: authHeaders,
}),
fetch("/api/payments/wallets", {
cache: "no-store",
headers: authHeaders,
}),
]);
if (configRes.ok) {
const configJson = (await configRes.json()) as PaymentConfig;
@@ -226,10 +266,13 @@ export function AccountCenter() {
setSelectedWallet(wallets[0].address);
}
}
if (configRes.status === 401 || walletsRes.status === 401) {
setPaymentError("登录会话已过期,请重新登录后再进行钱包绑定或支付。");
}
} catch {
return;
}
}, [backend?.authenticated, selectedPlanCode, selectedWallet]);
}, [backend?.authenticated, buildAuthedHeaders, selectedPlanCode, selectedWallet]);
const loadSnapshot = useCallback(async () => {
setErrorText("");
@@ -237,7 +280,11 @@ export function AccountCenter() {
const userPromise = supabaseReady
? getSupabaseBrowserClient().auth.getUser()
: 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([
userPromise,
@@ -257,7 +304,7 @@ export function AccountCenter() {
} catch (error) {
setErrorText(String(error));
}
}, [supabaseReady]);
}, [buildAuthedHeaders, supabaseReady]);
useEffect(() => {
let cancelled = false;
@@ -372,7 +419,12 @@ export function AccountCenter() {
};
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 connectAndBindWallet = async () => {
@@ -396,10 +448,14 @@ export function AccountCenter() {
if (!address) {
throw new Error("钱包账户为空");
}
const authHeaders = await buildAuthedHeaders(true);
if (!authHeaders.Authorization) {
throw new Error("登录会话失效,请重新登录后再绑定钱包。");
}
setWalletAddress(address);
const challengeRes = await fetch("/api/payments/wallets/challenge", {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: authHeaders,
body: JSON.stringify({ address }),
});
if (!challengeRes.ok) {
@@ -421,7 +477,7 @@ export function AccountCenter() {
})) as string;
const verifyRes = await fetch("/api/payments/wallets/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: authHeaders,
body: JSON.stringify({ address, nonce, signature }),
});
if (!verifyRes.ok) {
@@ -453,7 +509,9 @@ export function AccountCenter() {
setPaymentError("未检测到 MetaMask。");
return;
}
const payingWallet = (selectedWallet || walletAddress || "").toLowerCase();
const payingWallet = String(
selectedWallet || walletAddress || boundWallets[0]?.address || "",
).toLowerCase();
if (!payingWallet) {
setPaymentError("请先绑定钱包。");
return;
@@ -461,6 +519,10 @@ export function AccountCenter() {
setPaymentBusy(true);
try {
const authHeaders = await buildAuthedHeaders(true);
if (!authHeaders.Authorization) {
throw new Error("登录会话失效,请重新登录后再支付。");
}
const currentChainIdHex = String(
(await eth.request({ method: "eth_chainId" })) || "",
);
@@ -475,9 +537,9 @@ export function AccountCenter() {
const createRes = await fetch("/api/payments/intents", {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: authHeaders,
body: JSON.stringify({
plan_code: selectedPlanCode || "pro_monthly",
plan_code: selectedPlan?.plan_code || "pro_monthly",
payment_mode: "strict",
allowed_wallet: payingWallet,
metadata: { source: "account_center" },
@@ -548,7 +610,7 @@ export function AccountCenter() {
const submitRes = await fetch(`/api/payments/intents/${intentId}/submit`, {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: authHeaders,
body: JSON.stringify({
tx_hash: txHashNorm,
from_address: payingWallet,
@@ -561,7 +623,7 @@ export function AccountCenter() {
const confirmRes = await fetch(`/api/payments/intents/${intentId}/confirm`, {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: authHeaders,
body: JSON.stringify({ tx_hash: txHashNorm }),
});
if (!confirmRes.ok) {
@@ -581,31 +643,32 @@ export function AccountCenter() {
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="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 bottom-0 left-0 h-[500px] w-[500px] rounded-full bg-indigo-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-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">
<div>
<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">
<div className="flex items-center gap-4">
<Link
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>
<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
type="button"
onClick={() => void onRefresh()}
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 ? (
<Loader2 size={16} className="animate-spin" />
@@ -618,14 +681,14 @@ export function AccountCenter() {
<button
type="button"
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>
) : (
<Link
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} /> /
</Link>
@@ -790,7 +853,7 @@ export function AccountCenter() {
</p>
<div className="mb-3 space-y-2">
{planList.map((plan) => (
{effectivePlanList.map((plan) => (
<label
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"
@@ -803,7 +866,7 @@ export function AccountCenter() {
checked={selectedPlanCode === plan.plan_code}
onChange={() => setSelectedPlanCode(plan.plan_code)}
/>
{plan.plan_code}
{planDisplayName(plan.plan_code)}
</span>
<span className="text-cyan-200">
{plan.amount_usdc} USDC / {plan.duration_days}
@@ -128,6 +128,7 @@ export function DetailPanel() {
const store = useDashboardStore();
const { locale, t } = useI18n();
const detail = store.selectedDetail;
const isPro = store.proAccess.subscriptionActive;
const panelRef = useRef<HTMLElement | null>(null);
const isOverlayOpen =
Boolean(store.futureModalDate) ||
@@ -201,26 +202,30 @@ export function DetailPanel() {
<button
type="button"
className="history-btn"
title={t("detail.todayAnalysis")}
title={
isPro
? t("detail.todayAnalysis")
: `${t("detail.todayAnalysis")} (Pro)`
}
onClick={() => {
blurActiveElement();
void store.openTodayModal();
}}
disabled={!detail}
>
{t("detail.todayAnalysis")}
{isPro ? t("detail.todayAnalysis") : `${t("detail.todayAnalysis")} · Pro`}
</button>
<button
type="button"
className="history-btn"
title={t("detail.history")}
title={isPro ? t("detail.history") : `${t("detail.history")} (Pro)`}
onClick={() => {
blurActiveElement();
void store.openHistory();
}}
disabled={!detail}
>
{t("detail.history")}
{isPro ? t("detail.history") : `${t("detail.history")} · Pro`}
</button>
</div>
</div>
@@ -18,6 +18,7 @@ import { CSSProperties } from "react";
import { useChart } from "@/hooks/useChart";
import { useDashboardStore } from "@/hooks/useDashboardStore";
import { useI18n } from "@/hooks/useI18n";
import { ProFeaturePaywall } from "@/components/dashboard/ProFeaturePaywall";
import {
ModelForecast,
ProbabilityDistribution,
@@ -438,6 +439,8 @@ export function FutureForecastModal() {
const detail = store.selectedDetail;
const marketScan = store.selectedMarketScan;
const dateStr = store.futureModalDate;
const isPro = store.proAccess.subscriptionActive;
const isProLoading = store.proAccess.loading;
if (!detail || !dateStr) return null;
@@ -568,6 +571,7 @@ export function FutureForecastModal() {
"future-refresh-btn",
store.loadingState.marketScan && "spinning",
)}
disabled={!isPro || isProLoading}
onClick={() => {
if (isToday) {
void store.openTodayModal(true);
@@ -575,7 +579,15 @@ export function FutureForecastModal() {
}
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
width="14"
@@ -605,7 +617,20 @@ export function FutureForecastModal() {
</div>
<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">
<aside className="future-v2-left">
<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 { useDashboardStore, useHistoryData } from "@/hooks/useDashboardStore";
import { useI18n } from "@/hooks/useI18n";
import { ProFeaturePaywall } from "@/components/dashboard/ProFeaturePaywall";
import { getHistorySummary } from "@/lib/dashboard-utils";
function HistoryChart() {
@@ -128,6 +129,8 @@ export function HistoryModal() {
const store = useDashboardStore();
const { t } = useI18n();
const { data, error, isLoading, isOpen } = useHistoryData();
const isPro = store.proAccess.subscriptionActive;
const isProLoading = store.proAccess.loading;
const summary = useMemo(
() => getHistorySummary(data, store.selectedDetail?.local_date),
[data, store.selectedDetail?.local_date],
@@ -162,37 +165,60 @@ export function HistoryModal() {
</button>
</div>
<div className="modal-body">
<div className="history-stats">
{isLoading ? (
<span style={{ color: "var(--text-muted)" }}>{t("history.loading")}</span>
) : error ? (
<span style={{ color: "var(--accent-red)" }}>{t("history.error")}</span>
) : !summary.recentData.length ? (
<span style={{ color: "var(--text-muted)" }}>{t("history.empty")}</span>
) : (
<>
<div className="h-stat-card">
<span className="label">{t("history.hitRate")}</span>
<span className="val">
{summary.hitRate != null ? `${summary.hitRate}%` : "--"}
{isProLoading ? (
<div
style={{
color: "var(--text-muted)",
display: "flex",
justifyContent: "center",
padding: "28px 0",
}}
>
{t("dashboard.loading")}
</div>
) : !isPro ? (
<ProFeaturePaywall feature="history" />
) : (
<>
<div className="history-stats">
{isLoading ? (
<span style={{ color: "var(--text-muted)" }}>
{t("history.loading")}
</span>
</div>
<div className="h-stat-card">
<span className="label">{t("history.mae")}</span>
<span className="val">
{summary.debMae != null ? `${summary.debMae}°` : "--"}
) : error ? (
<span style={{ color: "var(--accent-red)" }}>
{t("history.error")}
</span>
</div>
<div className="h-stat-card">
<span className="label">{t("history.sample")}</span>
<span className="val">
{t("history.sampleDays", { count: summary.settledCount })}
) : !summary.recentData.length ? (
<span style={{ color: "var(--text-muted)" }}>
{t("history.empty")}
</span>
</div>
</>
)}
</div>
{!isLoading && !error && <HistoryChart />}
) : (
<>
<div className="h-stat-card">
<span className="label">{t("history.hitRate")}</span>
<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>
@@ -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,
LoadingState,
MarketScan,
ProAccessState,
} from "@/lib/dashboard-types";
interface DashboardStoreValue extends DashboardState {
@@ -39,6 +40,7 @@ interface DashboardStoreValue extends DashboardState {
openTodayModal: (forceRefresh?: boolean) => Promise<void>;
registerMapStopMotion: (stopMotion: () => void) => void;
refreshAll: () => Promise<void>;
refreshProAccess: () => Promise<void>;
refreshSelectedCity: () => Promise<void>;
selectedMarketScan: MarketScan | 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 = [
/暂无\s*AI\s*分析/i,
/当前以结构化气象与模型数据为主/i,
@@ -205,6 +216,9 @@ export function DashboardStoreProvider({
getInitialHistoryState,
);
const [isGuideOpen, setIsGuideOpen] = useState(false);
const [proAccess, setProAccess] = useState<ProAccessState>(
getInitialProAccessState,
);
const mapStopMotionRef = useRef<() => void>(() => {});
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(() => {
void loadCities();
}, []);
useEffect(() => {
void refreshProAccess();
}, []);
useEffect(() => {
if (!cities.length) return;
@@ -514,6 +568,15 @@ export function DashboardStoreProvider({
const openHistory = async () => {
if (!selectedCity) return;
if (!proAccess.subscriptionActive) {
setHistoryState((current) => ({
...current,
error: null,
isOpen: true,
loading: false,
}));
return;
}
setHistoryState((current) => ({
...current,
error: null,
@@ -558,10 +621,11 @@ export function DashboardStoreProvider({
isGuideOpen,
loadCities,
loadingState,
proAccess,
openFutureModal: (dateStr: string, forceRefresh = false) => {
mapStopMotionRef.current();
setFutureModalDate(dateStr);
if (!selectedCity) return;
if (!selectedCity || !proAccess.subscriptionActive) return;
const cacheKey = getMarketScanCacheKey(selectedCity, dateStr);
setLoadingState((current) => ({ ...current, marketScan: true }));
void ensureCityMarketScan(
@@ -584,6 +648,13 @@ export function DashboardStoreProvider({
mapStopMotionRef.current();
const cachedDetail = cityDetailsByName[selectedCity];
if (cachedDetail?.local_date) {
setSelectedForecastDate(cachedDetail.local_date);
setFutureModalDate(cachedDetail.local_date);
}
if (!proAccess.subscriptionActive) {
return;
}
// 乐观 UI: 有缓存则立刻秒开 modal,不阻塞显示
if (cachedDetail?.local_date) {
@@ -633,6 +704,7 @@ export function DashboardStoreProvider({
mapStopMotionRef.current = stopMotion;
},
refreshAll,
refreshProAccess,
refreshSelectedCity,
selectedMarketScan,
selectedCity,
@@ -652,6 +724,7 @@ export function DashboardStoreProvider({
isPanelOpen,
isGuideOpen,
loadingState,
proAccess,
marketScanByCityName,
selectedMarketScan,
selectedCity,
+8
View File
@@ -314,6 +314,13 @@ export interface HistoryState {
dataByCity: Record<string, HistoryPoint[]>;
}
export interface ProAccessState {
loading: boolean;
authenticated: boolean;
subscriptionActive: boolean;
error: string | null;
}
export interface DashboardState {
cities: CityListItem[];
cityDetailsByName: Record<string, CityDetail>;
@@ -323,4 +330,5 @@ export interface DashboardState {
selectedForecastDate: string | null;
loadingState: LoadingState;
historyState: HistoryState;
proAccess: ProAccessState;
}
+11 -7
View File
@@ -134,15 +134,11 @@ class SupabaseEntitlementService:
logger.warning(f"supabase auth user check failed: {exc}")
return None
def has_active_subscription(self, user_id: str) -> bool:
if not self.require_subscription:
return True
def _query_active_subscription(self, user_id: str) -> bool:
if not user_id:
return False
if not self.service_role_key:
logger.warning(
"POLYWEATHER_AUTH_REQUIRE_SUBSCRIPTION=true but SUPABASE_SERVICE_ROLE_KEY is missing",
)
logger.warning("SUPABASE_SERVICE_ROLE_KEY is missing")
return False
now_ts = time.time()
@@ -188,6 +184,14 @@ class SupabaseEntitlementService:
logger.warning(f"supabase subscription query error user_id={user_id}: {exc}")
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()
+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)
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
class WalletBindingRecord:
chain_id: int
@@ -224,6 +236,21 @@ class PaymentContractCheckoutService:
self.plan_catalog = _parse_plan_catalog(
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(
"POLYWEATHER_PAYMENT_TELEGRAM_NOTIFY_ENABLED", True
)
+4 -2
View File
@@ -1082,8 +1082,10 @@ async def auth_me(request: Request):
subscription_active = None
if SUPABASE_ENTITLEMENT.enabled and user_id:
try:
if SUPABASE_ENTITLEMENT.require_subscription:
subscription_active = SUPABASE_ENTITLEMENT.has_active_subscription(user_id)
subscription_active = SUPABASE_ENTITLEMENT.has_active_subscription(
user_id,
respect_requirement=False,
)
except Exception:
subscription_active = None