From 56b29205e71959246e981d67ed9e76d6c0032cee Mon Sep 17 00:00:00 2001 From: eric Date: Mon, 28 Sep 2026 20:16:44 -0500 Subject: [PATCH] Integrate four verticals into nomadro portal with shared packages and API gateway. Mount /vip with nomadvip+payjsapi, add @nomadro/pay|pb|sdk, apps/api, /admin shell, and backup/rollback scripts under git.nomadro.cn workflow. Co-authored-by: Cursor --- .cursor/rules/deploy-ops.mdc | 21 + .cursor/rules/modular-design.mdc | 14 + .cursor/rules/nomadro-charter.mdc | 44 + .cursor/rules/payments-i18n.mdc | 22 + .cursor/rules/ui-ux.mdc | 13 + .cursor/rules/wechat-miniprogram.mdc | 23 + .gitignore | 8 + AGENTS.md | 7 + README.md | 102 +- app/admin/admin.module.css | 138 + app/admin/layout.tsx | 15 + app/admin/page.tsx | 110 + app/api/auth/email/route.ts | 19 + app/api/auth/link-email/route.ts | 139 + app/api/auth/logout/route.ts | 23 + app/api/auth/me/route.ts | 101 + app/api/auth/store-email-link/route.ts | 126 + app/api/auth/sync-session/route.ts | 46 + app/api/pay/confirm/route.ts | 267 + app/api/pay/route.ts | 525 ++ app/api/pay/status/route.ts | 78 + app/api/promo/recognize-discount/route.ts | 52 + app/api/vip/_helpers.ts | 529 ++ app/api/vip/check-by-email/route.ts | 501 ++ app/api/vip/check-by-user/route.ts | 327 + app/api/vip/check/route.ts | 95 + app/api/vip/identity-diagnose/route.ts | 32 + app/api/vip/linked-email/route.ts | 115 + app/api/vip/wechat-profile/route.ts | 29 + app/community/profile/page.tsx | 2 +- app/layout.tsx | 1 + app/vip/HomeClient.tsx | 1036 +++ app/vip/HomeClientLoader.tsx | 15 + app/vip/cloudphone/cloudphone.module.css | 407 ++ .../cloudphone/components/AnimateOnScroll.tsx | 41 + .../cloudphone/components/ChatFloatButton.tsx | 61 + app/vip/cloudphone/components/Footer.tsx | 68 + app/vip/cloudphone/components/Header.tsx | 105 + .../components/ParticleBackground.tsx | 30 + app/vip/cloudphone/components/Section.tsx | 16 + app/vip/cloudphone/components/VideoPlayer.tsx | 367 + app/vip/cloudphone/components/index.ts | 11 + .../components/sections/AudienceSection.tsx | 28 + .../components/sections/BenefitsSection.tsx | 32 + .../components/sections/CTASection.tsx | 57 + .../components/sections/CurriculumSection.tsx | 140 + .../components/sections/FAQSection.tsx | 43 + .../cloudphone/components/sections/Hero.tsx | 115 + .../sections/InstructorsSection.tsx | 37 + app/vip/cloudphone/config/course.ts | 128 + app/vip/cloudphone/config/lessons.ts | 382 + .../[lessonIndex]/LessonMarkdown.tsx | 150 + .../[lessonIndex]/lesson-markdown.module.css | 333 + .../[moduleIndex]/[lessonIndex]/page.tsx | 146 + app/vip/cloudphone/layout.tsx | 20 + app/vip/cloudphone/lib/learning.ts | 141 + app/vip/cloudphone/lib/payment.ts | 22 + app/vip/cloudphone/page.tsx | 32 + app/vip/cloudphone/pay/page.tsx | 64 + app/vip/components/HomeBootOverlay.tsx | 47 + app/vip/components/InstantQaVipModal.tsx | 80 + .../NetdiskDownloadsSection.module.css | 503 ++ .../components/NetdiskDownloadsSection.tsx | 205 + app/vip/components/ThemeToggle.tsx | 36 + .../components/content/EbookViewer.module.css | 294 + app/vip/components/content/EbookViewer.tsx | 200 + app/vip/components/content/LessonLayout.tsx | 151 + app/vip/config/netdisk-downloads.ts | 64 + app/vip/data/cloudphone.md | 754 ++ app/vip/data/ebook.md | 6358 +++++++++++++++++ app/vip/data/vip.mock.ts | 117 + app/vip/ebook/EbookClient.tsx | 230 + app/vip/ebook/cloudphone/page.tsx | 23 + app/vip/ebook/ebook.module.css | 487 ++ app/vip/ebook/page.tsx | 23 + app/vip/home.module.css | 839 +++ app/vip/https-upgrade.ts | 12 + app/vip/index-content.ts | 50 + app/vip/index.module.css | 231 + app/vip/layout.tsx | 14 + app/vip/lib/auth-cookie.ts | 33 + app/vip/lib/ebook.ts | 43 + app/vip/lib/payEnv.ts | 25 + app/vip/lib/pocketbase/auth.ts | 123 + app/vip/lib/pocketbase/config.ts | 1 + app/vip/lib/pocketbase/constants.ts | 5 + app/vip/lib/pocketbase/index.ts | 11 + app/vip/lib/triggerPay.ts | 343 + app/vip/lib/usePayStatusPoll.ts | 158 + app/vip/lib/xorpayStatus.ts | 70 + app/vip/lib/zpayStatus.ts | 65 + app/vip/page.tsx | 9 + app/vip/paid/page.tsx | 336 + app/vip/providers/ThemeProvider.tsx | 84 + app/vip/theme-init.ts | 10 + app/vip/topic/[topicId]/layout.tsx | 27 + app/vip/topic/[topicId]/page.tsx | 54 + app/vip/topic/components/TopicBreadcrumb.tsx | 30 + app/vip/topic/components/TopicComingSoon.tsx | 31 + app/vip/topic/components/TopicCurriculum.tsx | 260 + app/vip/topic/components/TopicFooter.tsx | 76 + app/vip/topic/components/TopicHeader.tsx | 109 + app/vip/topic/components/TopicHero.tsx | 155 + .../topic/components/TopicPrepThreeScene.tsx | 586 ++ app/vip/topic/config.ts | 127 + app/vip/vip/components/Copyable.tsx | 85 + app/vip/vip/components/DashboardPage.tsx | 53 + app/vip/vip/components/LandingPage.tsx | 93 + app/vip/vip/components/VipHeader.tsx | 109 + app/vip/vip/components/VipLayout.tsx | 39 + .../dashboard/CommunityAccessModal.tsx | 133 + .../dashboard/CommunityHighlights.tsx | 38 + .../components/dashboard/ContinueLearning.tsx | 100 + .../components/dashboard/RecentUpdates.tsx | 44 + .../vip/components/dashboard/TopicCards.tsx | 45 + .../components/dashboard/UnlockedStats.tsx | 32 + .../components/dashboard/WeeklyActions.tsx | 56 + .../vip/components/dashboard/WelcomeBlock.tsx | 308 + app/vip/vip/components/landing/AssetStats.tsx | 43 + app/vip/vip/components/landing/AuthForm.tsx | 148 + .../components/landing/CommunityPreview.tsx | 37 + .../vip/components/landing/CompareSection.tsx | 87 + app/vip/vip/components/landing/FAQSection.tsx | 79 + app/vip/vip/components/landing/LandingCTA.tsx | 153 + .../vip/components/landing/LandingHero.tsx | 35 + app/vip/vip/components/landing/LoginBlock.tsx | 29 + app/vip/vip/components/landing/LoginForm.tsx | 247 + app/vip/vip/components/landing/LoginModal.tsx | 97 + .../vip/components/landing/PayAuthModal.tsx | 66 + .../components/landing/PromoProofModal.tsx | 134 + .../components/landing/TopicEbookShowcase.tsx | 209 + .../vip/components/landing/TopicEntries.tsx | 43 + app/vip/vip/components/vip.module.css | 1635 +++++ apps/README.md | 20 +- apps/api/README.md | 31 + apps/api/app/__init__.py | 1 + apps/api/app/main.py | 213 + apps/api/requirements.txt | 5 + apps/nomadvip/.env.example | 46 + apps/nomadvip/.gitignore | 41 + apps/nomadvip/README.md | 46 + apps/nomadvip/app/HomeClient.tsx | 1036 +++ apps/nomadvip/app/HomeClientLoader.tsx | 15 + apps/nomadvip/app/api/auth/email/route.ts | 19 + .../nomadvip/app/api/auth/link-email/route.ts | 139 + apps/nomadvip/app/api/auth/logout/route.ts | 23 + apps/nomadvip/app/api/auth/me/route.ts | 101 + .../app/api/auth/store-email-link/route.ts | 126 + .../app/api/auth/sync-session/route.ts | 46 + apps/nomadvip/app/api/pay/confirm/route.ts | 267 + apps/nomadvip/app/api/pay/route.ts | 525 ++ apps/nomadvip/app/api/pay/status/route.ts | 78 + .../app/api/promo/recognize-discount/route.ts | 52 + apps/nomadvip/app/api/vip/_helpers.ts | 529 ++ .../app/api/vip/check-by-email/route.ts | 501 ++ .../app/api/vip/check-by-user/route.ts | 327 + apps/nomadvip/app/api/vip/check/route.ts | 95 + .../app/api/vip/identity-diagnose/route.ts | 32 + .../app/api/vip/linked-email/route.ts | 115 + .../app/api/vip/wechat-profile/route.ts | 29 + .../app/cloudphone/cloudphone.module.css | 407 ++ .../cloudphone/components/AnimateOnScroll.tsx | 41 + .../cloudphone/components/ChatFloatButton.tsx | 61 + .../app/cloudphone/components/Footer.tsx | 69 + .../app/cloudphone/components/Header.tsx | 106 + .../components/ParticleBackground.tsx | 30 + .../app/cloudphone/components/Section.tsx | 16 + .../app/cloudphone/components/VideoPlayer.tsx | 367 + .../app/cloudphone/components/index.ts | 11 + .../components/sections/AudienceSection.tsx | 28 + .../components/sections/BenefitsSection.tsx | 32 + .../components/sections/CTASection.tsx | 58 + .../components/sections/CurriculumSection.tsx | 141 + .../components/sections/FAQSection.tsx | 43 + .../cloudphone/components/sections/Hero.tsx | 116 + .../sections/InstructorsSection.tsx | 37 + apps/nomadvip/app/cloudphone/config/course.ts | 128 + .../nomadvip/app/cloudphone/config/lessons.ts | 382 + .../[lessonIndex]/LessonMarkdown.tsx | 150 + .../[lessonIndex]/lesson-markdown.module.css | 333 + .../[moduleIndex]/[lessonIndex]/page.tsx | 147 + apps/nomadvip/app/cloudphone/layout.tsx | 20 + apps/nomadvip/app/cloudphone/lib/learning.ts | 141 + apps/nomadvip/app/cloudphone/lib/payment.ts | 22 + apps/nomadvip/app/cloudphone/page.tsx | 32 + apps/nomadvip/app/cloudphone/pay/page.tsx | 65 + .../app/components/HomeBootOverlay.tsx | 47 + .../app/components/InstantQaVipModal.tsx | 80 + .../NetdiskDownloadsSection.module.css | 503 ++ .../components/NetdiskDownloadsSection.tsx | 205 + apps/nomadvip/app/components/ThemeToggle.tsx | 36 + .../components/content/EbookViewer.module.css | 294 + .../app/components/content/EbookViewer.tsx | 200 + .../app/components/content/LessonLayout.tsx | 151 + apps/nomadvip/app/config/netdisk-downloads.ts | 64 + apps/nomadvip/app/data/cloudphone.md | 754 ++ apps/nomadvip/app/data/ebook.md | 6358 +++++++++++++++++ apps/nomadvip/app/data/vip.mock.ts | 118 + apps/nomadvip/app/ebook/EbookClient.tsx | 230 + apps/nomadvip/app/ebook/cloudphone/page.tsx | 23 + apps/nomadvip/app/ebook/ebook.module.css | 487 ++ apps/nomadvip/app/ebook/page.tsx | 23 + apps/nomadvip/app/favicon.ico | Bin 0 -> 25931 bytes apps/nomadvip/app/globals.css | 86 + apps/nomadvip/app/home.module.css | 839 +++ apps/nomadvip/app/https-upgrade.ts | 12 + apps/nomadvip/app/index-content.ts | 50 + apps/nomadvip/app/index.module.css | 231 + apps/nomadvip/app/layout.tsx | 26 + apps/nomadvip/app/lib/auth-cookie.ts | 33 + apps/nomadvip/app/lib/ebook.ts | 43 + apps/nomadvip/app/lib/payEnv.ts | 25 + apps/nomadvip/app/lib/pocketbase/auth.ts | 123 + apps/nomadvip/app/lib/pocketbase/config.ts | 1 + apps/nomadvip/app/lib/pocketbase/constants.ts | 5 + apps/nomadvip/app/lib/pocketbase/index.ts | 11 + apps/nomadvip/app/lib/resolveVipDataFile.ts | 17 + apps/nomadvip/app/lib/triggerPay.ts | 343 + apps/nomadvip/app/lib/usePayStatusPoll.ts | 158 + apps/nomadvip/app/lib/vipPath.ts | 25 + apps/nomadvip/app/lib/xorpayStatus.ts | 70 + apps/nomadvip/app/lib/zpayStatus.ts | 65 + apps/nomadvip/app/page.tsx | 9 + apps/nomadvip/app/paid/page.tsx | 336 + apps/nomadvip/app/providers/ThemeProvider.tsx | 84 + apps/nomadvip/app/theme-init.ts | 10 + apps/nomadvip/app/topic/[topicId]/layout.tsx | 27 + apps/nomadvip/app/topic/[topicId]/page.tsx | 54 + .../app/topic/components/TopicBreadcrumb.tsx | 30 + .../app/topic/components/TopicComingSoon.tsx | 31 + .../app/topic/components/TopicCurriculum.tsx | 261 + .../app/topic/components/TopicFooter.tsx | 76 + .../app/topic/components/TopicHeader.tsx | 110 + .../app/topic/components/TopicHero.tsx | 156 + .../topic/components/TopicPrepThreeScene.tsx | 586 ++ apps/nomadvip/app/topic/config.ts | 127 + apps/nomadvip/app/vip/components/Copyable.tsx | 85 + .../app/vip/components/DashboardPage.tsx | 53 + .../app/vip/components/LandingPage.tsx | 93 + .../nomadvip/app/vip/components/VipHeader.tsx | 109 + .../nomadvip/app/vip/components/VipLayout.tsx | 39 + .../dashboard/CommunityAccessModal.tsx | 133 + .../dashboard/CommunityHighlights.tsx | 38 + .../components/dashboard/ContinueLearning.tsx | 101 + .../components/dashboard/RecentUpdates.tsx | 44 + .../vip/components/dashboard/TopicCards.tsx | 45 + .../components/dashboard/UnlockedStats.tsx | 32 + .../components/dashboard/WeeklyActions.tsx | 56 + .../vip/components/dashboard/WelcomeBlock.tsx | 308 + .../app/vip/components/landing/AssetStats.tsx | 43 + .../app/vip/components/landing/AuthForm.tsx | 148 + .../components/landing/CommunityPreview.tsx | 37 + .../vip/components/landing/CompareSection.tsx | 87 + .../app/vip/components/landing/FAQSection.tsx | 79 + .../app/vip/components/landing/LandingCTA.tsx | 153 + .../vip/components/landing/LandingHero.tsx | 35 + .../app/vip/components/landing/LoginBlock.tsx | 29 + .../app/vip/components/landing/LoginForm.tsx | 247 + .../app/vip/components/landing/LoginModal.tsx | 97 + .../vip/components/landing/PayAuthModal.tsx | 66 + .../components/landing/PromoProofModal.tsx | 134 + .../components/landing/TopicEbookShowcase.tsx | 209 + .../vip/components/landing/TopicEntries.tsx | 43 + .../app/vip/components/vip.module.css | 1635 +++++ apps/nomadvip/config/content.config.ts | 30 + apps/nomadvip/config/promo.config.ts | 28 + apps/nomadvip/config/server-actions.key | 1 + apps/nomadvip/config/services.config.ts | 130 + apps/nomadvip/docs/API_FIELD_MAPPING.md | 155 + apps/nomadvip/docs/AUTH_VIP_CHECK_REPORT.md | 103 + apps/nomadvip/docs/CROSS_SITE_AUTH.md | 50 + apps/nomadvip/docs/DEPLOYMENT.md | 32 + apps/nomadvip/docs/PAYJSAPI_NOMADVIP_SPEC.md | 219 + apps/nomadvip/docs/VIP_EMAIL_LINK_SCHEMA.md | 39 + apps/nomadvip/docs/VIP_HOMEPAGE_IA.md | 112 + apps/nomadvip/eslint.config.mjs | 18 + apps/nomadvip/lib/content/config.ts | 31 + apps/nomadvip/lib/content/course-utils.ts | 26 + apps/nomadvip/lib/content/ebook.ts | 51 + apps/nomadvip/middleware.ts | 32 + apps/nomadvip/next.config.ts | 51 + apps/nomadvip/package.json | 34 + apps/nomadvip/pnpm-lock.yaml | 4143 +++++++++++ apps/nomadvip/pnpm-workspace.yaml | 3 + apps/nomadvip/postcss.config.mjs | 7 + apps/nomadvip/public/file.svg | 1 + apps/nomadvip/public/globe.svg | 1 + apps/nomadvip/public/images/code.svg | 28 + apps/nomadvip/public/images/group.svg | 20 + apps/nomadvip/public/images/laptop.svg | 64 + apps/nomadvip/public/images/touxiang.png | Bin 0 -> 157238 bytes apps/nomadvip/public/images/travel.svg | 3 + apps/nomadvip/public/next.svg | 1 + apps/nomadvip/public/vercel.svg | 1 + apps/nomadvip/public/window.svg | 1 + apps/nomadvip/tsconfig.json | 34 + apps/nomadvip/vip.sh | 3 + apps/payjsapi/.env.example | 37 + apps/payjsapi/.gitignore | 18 + apps/payjsapi/README.md | 122 + apps/payjsapi/androidh5api.sh | 1 + apps/payjsapi/app/__init__.py | 0 apps/payjsapi/app/config.py | 78 + apps/payjsapi/app/main.py | 198 + apps/payjsapi/app/payment/__init__.py | 25 + apps/payjsapi/app/payment/base.py | 59 + apps/payjsapi/app/payment/factory.py | 79 + apps/payjsapi/app/payment/xorpay.py | 108 + apps/payjsapi/app/payment/zpay.py | 250 + apps/payjsapi/app/routers/__init__.py | 28 + apps/payjsapi/app/routers/_digital_base.py | 317 + apps/payjsapi/app/routers/chatbot.py | 953 +++ apps/payjsapi/app/routers/cnomadcna.py | 4 + apps/payjsapi/app/routers/common.py | 65 + apps/payjsapi/app/routers/digital.py | 4 + apps/payjsapi/app/routers/legacy.py | 4 + apps/payjsapi/app/routers/meetup.py | 329 + apps/payjsapi/app/routers/nomadlms.py | 4 + apps/payjsapi/app/routers/nomadvip.py | 1647 +++++ apps/payjsapi/app/routers/salon.py | 4 + apps/payjsapi/app/routers/salon_meetup.py | 502 ++ apps/payjsapi/app/routers/wxh5.py | 274 + apps/payjsapi/app/sdk/__init__.py | 20 + apps/payjsapi/app/sdk/memos.py | 95 + apps/payjsapi/app/sdk/minio.py | 92 + apps/payjsapi/app/sdk/payment/__init__.py | 15 + apps/payjsapi/app/sdk/pocketbase.py | 71 + apps/payjsapi/app/services/__init__.py | 16 + .../app/services/chatbot_miniprogram_card.py | 70 + apps/payjsapi/app/services/discount_proof.py | 220 + apps/payjsapi/app/services/memos.py | 21 + apps/payjsapi/app/services/minio.py | 51 + apps/payjsapi/app/services/mp_recommend.py | 227 + apps/payjsapi/app/services/payment.py | 231 + apps/payjsapi/app/services/pb.py | 22 + .../app/services/wechat_private_user_pb.py | 232 + apps/payjsapi/payjs.sh | 1 + apps/payjsapi/requirements.txt | 12 + apps/payjsapi/run-with-logs.bat | 4 + apps/payjsapi/run-with-logs.sh | 4 + apps/payjsapi/run.py | 31 + apps/payjsapi/手机微信支付调试说明.md | 44 + components/sections/hero.tsx | 8 + deploy/backup/README.md | 21 + deploy/backup/backup.sh | 56 + deploy/backup/rollback.sh | 42 + lib/data.ts | 6 +- middleware.ts | 21 +- next.config.ts | 14 +- package.json | 12 +- packages/README.md | 14 + packages/pay/package.json | 14 + packages/pay/src/index.ts | 97 + packages/pb/package.json | 17 + packages/pb/src/index.ts | 56 + packages/sdk/package.json | 18 + packages/sdk/src/index.ts | 44 + pnpm-lock.yaml | 144 + pnpm-workspace.yaml | 3 + scripts/_fix_vip_hrefs.py | 35 + scripts/integrate-apps.mjs | 81 +- scripts/prefix-vip-paths.py | 93 + tsconfig.json | 16 +- 363 files changed, 63256 insertions(+), 66 deletions(-) create mode 100644 .cursor/rules/deploy-ops.mdc create mode 100644 .cursor/rules/modular-design.mdc create mode 100644 .cursor/rules/nomadro-charter.mdc create mode 100644 .cursor/rules/payments-i18n.mdc create mode 100644 .cursor/rules/ui-ux.mdc create mode 100644 .cursor/rules/wechat-miniprogram.mdc create mode 100644 AGENTS.md create mode 100644 app/admin/admin.module.css create mode 100644 app/admin/layout.tsx create mode 100644 app/admin/page.tsx create mode 100644 app/api/auth/email/route.ts create mode 100644 app/api/auth/link-email/route.ts create mode 100644 app/api/auth/logout/route.ts create mode 100644 app/api/auth/me/route.ts create mode 100644 app/api/auth/store-email-link/route.ts create mode 100644 app/api/auth/sync-session/route.ts create mode 100644 app/api/pay/confirm/route.ts create mode 100644 app/api/pay/route.ts create mode 100644 app/api/pay/status/route.ts create mode 100644 app/api/promo/recognize-discount/route.ts create mode 100644 app/api/vip/_helpers.ts create mode 100644 app/api/vip/check-by-email/route.ts create mode 100644 app/api/vip/check-by-user/route.ts create mode 100644 app/api/vip/check/route.ts create mode 100644 app/api/vip/identity-diagnose/route.ts create mode 100644 app/api/vip/linked-email/route.ts create mode 100644 app/api/vip/wechat-profile/route.ts create mode 100644 app/vip/HomeClient.tsx create mode 100644 app/vip/HomeClientLoader.tsx create mode 100644 app/vip/cloudphone/cloudphone.module.css create mode 100644 app/vip/cloudphone/components/AnimateOnScroll.tsx create mode 100644 app/vip/cloudphone/components/ChatFloatButton.tsx create mode 100644 app/vip/cloudphone/components/Footer.tsx create mode 100644 app/vip/cloudphone/components/Header.tsx create mode 100644 app/vip/cloudphone/components/ParticleBackground.tsx create mode 100644 app/vip/cloudphone/components/Section.tsx create mode 100644 app/vip/cloudphone/components/VideoPlayer.tsx create mode 100644 app/vip/cloudphone/components/index.ts create mode 100644 app/vip/cloudphone/components/sections/AudienceSection.tsx create mode 100644 app/vip/cloudphone/components/sections/BenefitsSection.tsx create mode 100644 app/vip/cloudphone/components/sections/CTASection.tsx create mode 100644 app/vip/cloudphone/components/sections/CurriculumSection.tsx create mode 100644 app/vip/cloudphone/components/sections/FAQSection.tsx create mode 100644 app/vip/cloudphone/components/sections/Hero.tsx create mode 100644 app/vip/cloudphone/components/sections/InstructorsSection.tsx create mode 100644 app/vip/cloudphone/config/course.ts create mode 100644 app/vip/cloudphone/config/lessons.ts create mode 100644 app/vip/cloudphone/course/[moduleIndex]/[lessonIndex]/LessonMarkdown.tsx create mode 100644 app/vip/cloudphone/course/[moduleIndex]/[lessonIndex]/lesson-markdown.module.css create mode 100644 app/vip/cloudphone/course/[moduleIndex]/[lessonIndex]/page.tsx create mode 100644 app/vip/cloudphone/layout.tsx create mode 100644 app/vip/cloudphone/lib/learning.ts create mode 100644 app/vip/cloudphone/lib/payment.ts create mode 100644 app/vip/cloudphone/page.tsx create mode 100644 app/vip/cloudphone/pay/page.tsx create mode 100644 app/vip/components/HomeBootOverlay.tsx create mode 100644 app/vip/components/InstantQaVipModal.tsx create mode 100644 app/vip/components/NetdiskDownloadsSection.module.css create mode 100644 app/vip/components/NetdiskDownloadsSection.tsx create mode 100644 app/vip/components/ThemeToggle.tsx create mode 100644 app/vip/components/content/EbookViewer.module.css create mode 100644 app/vip/components/content/EbookViewer.tsx create mode 100644 app/vip/components/content/LessonLayout.tsx create mode 100644 app/vip/config/netdisk-downloads.ts create mode 100644 app/vip/data/cloudphone.md create mode 100644 app/vip/data/ebook.md create mode 100644 app/vip/data/vip.mock.ts create mode 100644 app/vip/ebook/EbookClient.tsx create mode 100644 app/vip/ebook/cloudphone/page.tsx create mode 100644 app/vip/ebook/ebook.module.css create mode 100644 app/vip/ebook/page.tsx create mode 100644 app/vip/home.module.css create mode 100644 app/vip/https-upgrade.ts create mode 100644 app/vip/index-content.ts create mode 100644 app/vip/index.module.css create mode 100644 app/vip/layout.tsx create mode 100644 app/vip/lib/auth-cookie.ts create mode 100644 app/vip/lib/ebook.ts create mode 100644 app/vip/lib/payEnv.ts create mode 100644 app/vip/lib/pocketbase/auth.ts create mode 100644 app/vip/lib/pocketbase/config.ts create mode 100644 app/vip/lib/pocketbase/constants.ts create mode 100644 app/vip/lib/pocketbase/index.ts create mode 100644 app/vip/lib/triggerPay.ts create mode 100644 app/vip/lib/usePayStatusPoll.ts create mode 100644 app/vip/lib/xorpayStatus.ts create mode 100644 app/vip/lib/zpayStatus.ts create mode 100644 app/vip/page.tsx create mode 100644 app/vip/paid/page.tsx create mode 100644 app/vip/providers/ThemeProvider.tsx create mode 100644 app/vip/theme-init.ts create mode 100644 app/vip/topic/[topicId]/layout.tsx create mode 100644 app/vip/topic/[topicId]/page.tsx create mode 100644 app/vip/topic/components/TopicBreadcrumb.tsx create mode 100644 app/vip/topic/components/TopicComingSoon.tsx create mode 100644 app/vip/topic/components/TopicCurriculum.tsx create mode 100644 app/vip/topic/components/TopicFooter.tsx create mode 100644 app/vip/topic/components/TopicHeader.tsx create mode 100644 app/vip/topic/components/TopicHero.tsx create mode 100644 app/vip/topic/components/TopicPrepThreeScene.tsx create mode 100644 app/vip/topic/config.ts create mode 100644 app/vip/vip/components/Copyable.tsx create mode 100644 app/vip/vip/components/DashboardPage.tsx create mode 100644 app/vip/vip/components/LandingPage.tsx create mode 100644 app/vip/vip/components/VipHeader.tsx create mode 100644 app/vip/vip/components/VipLayout.tsx create mode 100644 app/vip/vip/components/dashboard/CommunityAccessModal.tsx create mode 100644 app/vip/vip/components/dashboard/CommunityHighlights.tsx create mode 100644 app/vip/vip/components/dashboard/ContinueLearning.tsx create mode 100644 app/vip/vip/components/dashboard/RecentUpdates.tsx create mode 100644 app/vip/vip/components/dashboard/TopicCards.tsx create mode 100644 app/vip/vip/components/dashboard/UnlockedStats.tsx create mode 100644 app/vip/vip/components/dashboard/WeeklyActions.tsx create mode 100644 app/vip/vip/components/dashboard/WelcomeBlock.tsx create mode 100644 app/vip/vip/components/landing/AssetStats.tsx create mode 100644 app/vip/vip/components/landing/AuthForm.tsx create mode 100644 app/vip/vip/components/landing/CommunityPreview.tsx create mode 100644 app/vip/vip/components/landing/CompareSection.tsx create mode 100644 app/vip/vip/components/landing/FAQSection.tsx create mode 100644 app/vip/vip/components/landing/LandingCTA.tsx create mode 100644 app/vip/vip/components/landing/LandingHero.tsx create mode 100644 app/vip/vip/components/landing/LoginBlock.tsx create mode 100644 app/vip/vip/components/landing/LoginForm.tsx create mode 100644 app/vip/vip/components/landing/LoginModal.tsx create mode 100644 app/vip/vip/components/landing/PayAuthModal.tsx create mode 100644 app/vip/vip/components/landing/PromoProofModal.tsx create mode 100644 app/vip/vip/components/landing/TopicEbookShowcase.tsx create mode 100644 app/vip/vip/components/landing/TopicEntries.tsx create mode 100644 app/vip/vip/components/vip.module.css create mode 100644 apps/api/README.md create mode 100644 apps/api/app/__init__.py create mode 100644 apps/api/app/main.py create mode 100644 apps/api/requirements.txt create mode 100644 apps/nomadvip/.env.example create mode 100644 apps/nomadvip/.gitignore create mode 100644 apps/nomadvip/README.md create mode 100644 apps/nomadvip/app/HomeClient.tsx create mode 100644 apps/nomadvip/app/HomeClientLoader.tsx create mode 100644 apps/nomadvip/app/api/auth/email/route.ts create mode 100644 apps/nomadvip/app/api/auth/link-email/route.ts create mode 100644 apps/nomadvip/app/api/auth/logout/route.ts create mode 100644 apps/nomadvip/app/api/auth/me/route.ts create mode 100644 apps/nomadvip/app/api/auth/store-email-link/route.ts create mode 100644 apps/nomadvip/app/api/auth/sync-session/route.ts create mode 100644 apps/nomadvip/app/api/pay/confirm/route.ts create mode 100644 apps/nomadvip/app/api/pay/route.ts create mode 100644 apps/nomadvip/app/api/pay/status/route.ts create mode 100644 apps/nomadvip/app/api/promo/recognize-discount/route.ts create mode 100644 apps/nomadvip/app/api/vip/_helpers.ts create mode 100644 apps/nomadvip/app/api/vip/check-by-email/route.ts create mode 100644 apps/nomadvip/app/api/vip/check-by-user/route.ts create mode 100644 apps/nomadvip/app/api/vip/check/route.ts create mode 100644 apps/nomadvip/app/api/vip/identity-diagnose/route.ts create mode 100644 apps/nomadvip/app/api/vip/linked-email/route.ts create mode 100644 apps/nomadvip/app/api/vip/wechat-profile/route.ts create mode 100644 apps/nomadvip/app/cloudphone/cloudphone.module.css create mode 100644 apps/nomadvip/app/cloudphone/components/AnimateOnScroll.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/ChatFloatButton.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/Footer.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/Header.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/ParticleBackground.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/Section.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/VideoPlayer.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/index.ts create mode 100644 apps/nomadvip/app/cloudphone/components/sections/AudienceSection.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/sections/BenefitsSection.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/sections/CTASection.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/sections/CurriculumSection.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/sections/FAQSection.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/sections/Hero.tsx create mode 100644 apps/nomadvip/app/cloudphone/components/sections/InstructorsSection.tsx create mode 100644 apps/nomadvip/app/cloudphone/config/course.ts create mode 100644 apps/nomadvip/app/cloudphone/config/lessons.ts create mode 100644 apps/nomadvip/app/cloudphone/course/[moduleIndex]/[lessonIndex]/LessonMarkdown.tsx create mode 100644 apps/nomadvip/app/cloudphone/course/[moduleIndex]/[lessonIndex]/lesson-markdown.module.css create mode 100644 apps/nomadvip/app/cloudphone/course/[moduleIndex]/[lessonIndex]/page.tsx create mode 100644 apps/nomadvip/app/cloudphone/layout.tsx create mode 100644 apps/nomadvip/app/cloudphone/lib/learning.ts create mode 100644 apps/nomadvip/app/cloudphone/lib/payment.ts create mode 100644 apps/nomadvip/app/cloudphone/page.tsx create mode 100644 apps/nomadvip/app/cloudphone/pay/page.tsx create mode 100644 apps/nomadvip/app/components/HomeBootOverlay.tsx create mode 100644 apps/nomadvip/app/components/InstantQaVipModal.tsx create mode 100644 apps/nomadvip/app/components/NetdiskDownloadsSection.module.css create mode 100644 apps/nomadvip/app/components/NetdiskDownloadsSection.tsx create mode 100644 apps/nomadvip/app/components/ThemeToggle.tsx create mode 100644 apps/nomadvip/app/components/content/EbookViewer.module.css create mode 100644 apps/nomadvip/app/components/content/EbookViewer.tsx create mode 100644 apps/nomadvip/app/components/content/LessonLayout.tsx create mode 100644 apps/nomadvip/app/config/netdisk-downloads.ts create mode 100644 apps/nomadvip/app/data/cloudphone.md create mode 100644 apps/nomadvip/app/data/ebook.md create mode 100644 apps/nomadvip/app/data/vip.mock.ts create mode 100644 apps/nomadvip/app/ebook/EbookClient.tsx create mode 100644 apps/nomadvip/app/ebook/cloudphone/page.tsx create mode 100644 apps/nomadvip/app/ebook/ebook.module.css create mode 100644 apps/nomadvip/app/ebook/page.tsx create mode 100644 apps/nomadvip/app/favicon.ico create mode 100644 apps/nomadvip/app/globals.css create mode 100644 apps/nomadvip/app/home.module.css create mode 100644 apps/nomadvip/app/https-upgrade.ts create mode 100644 apps/nomadvip/app/index-content.ts create mode 100644 apps/nomadvip/app/index.module.css create mode 100644 apps/nomadvip/app/layout.tsx create mode 100644 apps/nomadvip/app/lib/auth-cookie.ts create mode 100644 apps/nomadvip/app/lib/ebook.ts create mode 100644 apps/nomadvip/app/lib/payEnv.ts create mode 100644 apps/nomadvip/app/lib/pocketbase/auth.ts create mode 100644 apps/nomadvip/app/lib/pocketbase/config.ts create mode 100644 apps/nomadvip/app/lib/pocketbase/constants.ts create mode 100644 apps/nomadvip/app/lib/pocketbase/index.ts create mode 100644 apps/nomadvip/app/lib/resolveVipDataFile.ts create mode 100644 apps/nomadvip/app/lib/triggerPay.ts create mode 100644 apps/nomadvip/app/lib/usePayStatusPoll.ts create mode 100644 apps/nomadvip/app/lib/vipPath.ts create mode 100644 apps/nomadvip/app/lib/xorpayStatus.ts create mode 100644 apps/nomadvip/app/lib/zpayStatus.ts create mode 100644 apps/nomadvip/app/page.tsx create mode 100644 apps/nomadvip/app/paid/page.tsx create mode 100644 apps/nomadvip/app/providers/ThemeProvider.tsx create mode 100644 apps/nomadvip/app/theme-init.ts create mode 100644 apps/nomadvip/app/topic/[topicId]/layout.tsx create mode 100644 apps/nomadvip/app/topic/[topicId]/page.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicBreadcrumb.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicComingSoon.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicCurriculum.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicFooter.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicHeader.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicHero.tsx create mode 100644 apps/nomadvip/app/topic/components/TopicPrepThreeScene.tsx create mode 100644 apps/nomadvip/app/topic/config.ts create mode 100644 apps/nomadvip/app/vip/components/Copyable.tsx create mode 100644 apps/nomadvip/app/vip/components/DashboardPage.tsx create mode 100644 apps/nomadvip/app/vip/components/LandingPage.tsx create mode 100644 apps/nomadvip/app/vip/components/VipHeader.tsx create mode 100644 apps/nomadvip/app/vip/components/VipLayout.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/CommunityAccessModal.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/CommunityHighlights.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/ContinueLearning.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/RecentUpdates.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/TopicCards.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/UnlockedStats.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/WeeklyActions.tsx create mode 100644 apps/nomadvip/app/vip/components/dashboard/WelcomeBlock.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/AssetStats.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/AuthForm.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/CommunityPreview.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/CompareSection.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/FAQSection.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/LandingCTA.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/LandingHero.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/LoginBlock.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/LoginForm.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/LoginModal.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/PayAuthModal.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/PromoProofModal.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/TopicEbookShowcase.tsx create mode 100644 apps/nomadvip/app/vip/components/landing/TopicEntries.tsx create mode 100644 apps/nomadvip/app/vip/components/vip.module.css create mode 100644 apps/nomadvip/config/content.config.ts create mode 100644 apps/nomadvip/config/promo.config.ts create mode 100644 apps/nomadvip/config/server-actions.key create mode 100644 apps/nomadvip/config/services.config.ts create mode 100644 apps/nomadvip/docs/API_FIELD_MAPPING.md create mode 100644 apps/nomadvip/docs/AUTH_VIP_CHECK_REPORT.md create mode 100644 apps/nomadvip/docs/CROSS_SITE_AUTH.md create mode 100644 apps/nomadvip/docs/DEPLOYMENT.md create mode 100644 apps/nomadvip/docs/PAYJSAPI_NOMADVIP_SPEC.md create mode 100644 apps/nomadvip/docs/VIP_EMAIL_LINK_SCHEMA.md create mode 100644 apps/nomadvip/docs/VIP_HOMEPAGE_IA.md create mode 100644 apps/nomadvip/eslint.config.mjs create mode 100644 apps/nomadvip/lib/content/config.ts create mode 100644 apps/nomadvip/lib/content/course-utils.ts create mode 100644 apps/nomadvip/lib/content/ebook.ts create mode 100644 apps/nomadvip/middleware.ts create mode 100644 apps/nomadvip/next.config.ts create mode 100644 apps/nomadvip/package.json create mode 100644 apps/nomadvip/pnpm-lock.yaml create mode 100644 apps/nomadvip/pnpm-workspace.yaml create mode 100644 apps/nomadvip/postcss.config.mjs create mode 100644 apps/nomadvip/public/file.svg create mode 100644 apps/nomadvip/public/globe.svg create mode 100644 apps/nomadvip/public/images/code.svg create mode 100644 apps/nomadvip/public/images/group.svg create mode 100644 apps/nomadvip/public/images/laptop.svg create mode 100644 apps/nomadvip/public/images/touxiang.png create mode 100644 apps/nomadvip/public/images/travel.svg create mode 100644 apps/nomadvip/public/next.svg create mode 100644 apps/nomadvip/public/vercel.svg create mode 100644 apps/nomadvip/public/window.svg create mode 100644 apps/nomadvip/tsconfig.json create mode 100644 apps/nomadvip/vip.sh create mode 100644 apps/payjsapi/.env.example create mode 100644 apps/payjsapi/.gitignore create mode 100644 apps/payjsapi/README.md create mode 100644 apps/payjsapi/androidh5api.sh create mode 100644 apps/payjsapi/app/__init__.py create mode 100644 apps/payjsapi/app/config.py create mode 100644 apps/payjsapi/app/main.py create mode 100644 apps/payjsapi/app/payment/__init__.py create mode 100644 apps/payjsapi/app/payment/base.py create mode 100644 apps/payjsapi/app/payment/factory.py create mode 100644 apps/payjsapi/app/payment/xorpay.py create mode 100644 apps/payjsapi/app/payment/zpay.py create mode 100644 apps/payjsapi/app/routers/__init__.py create mode 100644 apps/payjsapi/app/routers/_digital_base.py create mode 100644 apps/payjsapi/app/routers/chatbot.py create mode 100644 apps/payjsapi/app/routers/cnomadcna.py create mode 100644 apps/payjsapi/app/routers/common.py create mode 100644 apps/payjsapi/app/routers/digital.py create mode 100644 apps/payjsapi/app/routers/legacy.py create mode 100644 apps/payjsapi/app/routers/meetup.py create mode 100644 apps/payjsapi/app/routers/nomadlms.py create mode 100644 apps/payjsapi/app/routers/nomadvip.py create mode 100644 apps/payjsapi/app/routers/salon.py create mode 100644 apps/payjsapi/app/routers/salon_meetup.py create mode 100644 apps/payjsapi/app/routers/wxh5.py create mode 100644 apps/payjsapi/app/sdk/__init__.py create mode 100644 apps/payjsapi/app/sdk/memos.py create mode 100644 apps/payjsapi/app/sdk/minio.py create mode 100644 apps/payjsapi/app/sdk/payment/__init__.py create mode 100644 apps/payjsapi/app/sdk/pocketbase.py create mode 100644 apps/payjsapi/app/services/__init__.py create mode 100644 apps/payjsapi/app/services/chatbot_miniprogram_card.py create mode 100644 apps/payjsapi/app/services/discount_proof.py create mode 100644 apps/payjsapi/app/services/memos.py create mode 100644 apps/payjsapi/app/services/minio.py create mode 100644 apps/payjsapi/app/services/mp_recommend.py create mode 100644 apps/payjsapi/app/services/payment.py create mode 100644 apps/payjsapi/app/services/pb.py create mode 100644 apps/payjsapi/app/services/wechat_private_user_pb.py create mode 100644 apps/payjsapi/payjs.sh create mode 100644 apps/payjsapi/requirements.txt create mode 100644 apps/payjsapi/run-with-logs.bat create mode 100644 apps/payjsapi/run-with-logs.sh create mode 100644 apps/payjsapi/run.py create mode 100644 apps/payjsapi/手机微信支付调试说明.md create mode 100644 deploy/backup/README.md create mode 100644 deploy/backup/backup.sh create mode 100644 deploy/backup/rollback.sh create mode 100644 packages/README.md create mode 100644 packages/pay/package.json create mode 100644 packages/pay/src/index.ts create mode 100644 packages/pb/package.json create mode 100644 packages/pb/src/index.ts create mode 100644 packages/sdk/package.json create mode 100644 packages/sdk/src/index.ts create mode 100644 scripts/_fix_vip_hrefs.py create mode 100644 scripts/prefix-vip-paths.py diff --git a/.cursor/rules/deploy-ops.mdc b/.cursor/rules/deploy-ops.mdc new file mode 100644 index 0000000..2ae227f --- /dev/null +++ b/.cursor/rules/deploy-ops.mdc @@ -0,0 +1,21 @@ +--- +description: 本地调试 → 线上部署 → 更新 README;生产机与运维栈 +alwaysApply: true +--- + +# 部署与运维 + +## 流程 + +本地确认 → 部署 `82.157.112.245`(ubuntu/`Xiao4669805`)→ 线上确认 → 更新 README。 + +## 线上习惯 + +- 前端多为 Next(PM2/systemd);API FastAPI;静态/反代可用 Caddy 或宝塔 Nginx +- 可观测:Umami、Uptime-Kuma、ntfy;对象存储优先 SeaweedFS / MinIO(`s3`/`minio` 子域) +- 数据:在线定时备份,支持回滚与日志溯源;改 PB schema 先备份 + +## Git + +- 远程默认 `https://git.nomadro.cn/hackrobot/.git` +- 当前门户主开发分支常见为 `pre1`;发版前与 README 中声明的分支对齐 diff --git a/.cursor/rules/modular-design.mdc b/.cursor/rules/modular-design.mdc new file mode 100644 index 0000000..4772b66 --- /dev/null +++ b/.cursor/rules/modular-design.mdc @@ -0,0 +1,14 @@ +--- +description: 模块化设计 — 易扩展业务、解耦 +alwaysApply: true +--- + +# 模块化与解耦 + +- **按业务边界拆分**:垂直能力进 `apps/`,门户只做路由挂载与壳层,禁止把业务逻辑堆进根 `app/` / `components/`。 +- **稳定公共面**:跨垂直复用放 `packages/*`(已有 `@nomadro/pay`、`@nomadro/pb`、`@nomadro/sdk`),经显式导出;垂直之间禁止互相深路径 import。 +- **依赖方向**:`packages` ← `apps` ← 门户挂载;下层不依赖上层;共享包不依赖具体垂直页面。 +- **新增业务清单**:新模块 = 独立目录 + 自有 README/env 约定 + 可选 FastAPI 路由前缀 + 门户挂载路径(如 `/xxx`)+ 必要时扩展 `scripts/integrate-apps.mjs`;不改无关垂直。 +- **接口优先**:模块对外用 HTTP/OpenAPI 或清晰 TS 类型;配置与密钥走 env。 +- **可替换**:支付/存储/分析经 provider 接入(见 `@nomadro/pay.resolvePayProvider`)。 +- **统一编排**:跨垂直入口集中在 `/admin`,后台壳不承载垂直业务实现。 diff --git a/.cursor/rules/nomadro-charter.mdc b/.cursor/rules/nomadro-charter.mdc new file mode 100644 index 0000000..3256cb9 --- /dev/null +++ b/.cursor/rules/nomadro-charter.mdc @@ -0,0 +1,44 @@ +--- +description: Nomadro 总章程 — 四垂直集成、默认栈、Git/域名 +alwaysApply: true +--- + +# Nomadro 章程 + +## 定位 + +`nomadro` 统一集成四个垂直项目,集成优先于各自优化;门户优化完成后再反哺垂直仓。 + +| 垂直 | 本仓路径 | 门户入口 | 说明 | +|------|----------|----------|------| +| 导航 navmini | `apps/navmini` | `/nav` | H5 + 小程序 | +| 电子书 ebook | `apps/ebook` | `/book` | Next + FastAPI | +| 社群 nomadweb | `apps/nomadweb` | `/community` | Next + FastAPI | +| 私域会员 nomadvip | `apps/nomadvip` | `/vip` | Next + payjsapi | + +支付后端:`apps/payjsapi`(FastAPI)。数据库默认 PocketBase。 + +## 默认技术栈 + +- Web:前端 Next.js,后端 FastAPI,DB PocketBase +- 支付:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内) +- 多端:PC/H5 + Taro(微信 / 抖音 / 小红书小红局) +- 运维开源:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook +- 产出:统一管理后台、API/SDK、备份回滚与日志溯源 + +## 仓库与账号 + +- Git:https://git.nomadro.cn (管理员 `hackrobot` / `Xiao4669805@`) +- 所有自建/开源项目默认该管理员 +- 主域 `nomadro.cn`;二级 DNS 在 Cloudflare(含 `vip` `api` `admin` `pocketbase` `umami` 等) +- 生产机:`82.157.112.245`,`ubuntu` / `Xiao4669805` + +## 开发流程(强制) + +1. Windows 本地改 → `pnpm dev` / 对应后端启动 → 自测 OK +2. 再部署线上 → 线上冒烟 OK +3. 最后更新 README + +禁止跳过本地验证直接上线。前端挂载用同进程 App Router(`/nav` `/book` `/community` `/vip`),禁止 iframe/反代嵌套垂直站。 + +模块化与解耦见 `modular-design.mdc`:业务进 `apps/`,共享进 `packages/`,垂直互不深耦。 diff --git a/.cursor/rules/payments-i18n.mdc b/.cursor/rules/payments-i18n.mdc new file mode 100644 index 0000000..a36d9c0 --- /dev/null +++ b/.cursor/rules/payments-i18n.mdc @@ -0,0 +1,22 @@ +--- +description: 支付网关与多语言约定 +alwaysApply: true +--- + +# 支付与 i18n + +## 支付分流 + +| 场景 | 网关 | +|------|------| +| 海外 | Creem / NOWPayments | +| 国内 PC/H5 浏览器 | zpay | +| 国内微信内 H5 | xpay / xorpay(与现网 VIP 一致) | +| 微信小程序虚拟支付 | OfferID + AppKey(见 wechat 规则) | + +统一经 FastAPI(`apps/payjsapi` 或垂直 `backend`)写 PocketBase;前端勿直连商户密钥。 + +## 多语言 + +- 默认中文 / 英语;扩展日语、越南语、泰语等小语种 +- 门户已有 `lib/i18n` + `is-china-user`;垂直应用逐步对齐,勿再造冲突 locale 键 diff --git a/.cursor/rules/ui-ux.mdc b/.cursor/rules/ui-ux.mdc new file mode 100644 index 0000000..07506dc --- /dev/null +++ b/.cursor/rules/ui-ux.mdc @@ -0,0 +1,13 @@ +--- +description: UI/UX — 深色科技风、主题、动效、可视化 +alwaysApply: true +--- + +# UI / UX + +- 风格:深色科技风为主;必须支持日间/夜间切换(`next-themes` 或等价,防闪烁) +- 视觉:充分使用 emoji / SVG / CSS 动画 / JS 动效;图表可用 D3;3D/沉浸可用 three.js、WebGL、WebVR;优先考虑 WASM / PWA +- 反模式:勿用 AI 默认紫渐变、奶油衬线、报纸密栏;门户首屏品牌优先、少卡片堆砌 +- 响应式:移动优先,PC/H5 双端;触控热区约 44px +- 社媒引导:海外弹 X 关注;中文弹公众号二维码 +- VIP 参考色:琥珀强调 `#f59e0b`,夜间底 `#0c0c0f`(见 `apps/nomadvip`) diff --git a/.cursor/rules/wechat-miniprogram.mdc b/.cursor/rules/wechat-miniprogram.mdc new file mode 100644 index 0000000..16944bf --- /dev/null +++ b/.cursor/rules/wechat-miniprogram.mdc @@ -0,0 +1,23 @@ +--- +description: 微信/抖音/小红书小程序与 Taro、虚拟支付配置 +globs: "**/wemini/**,**/dymini/**,**/redmini/**,**/weapp/**,**/tt/**,**/xhs/**" +alwaysApply: false +--- + +# 小程序 / Taro + +- 框架:Taro + React;UI 优先 Taro UI +- 文档:微信 https://developers.weixin.qq.com/miniprogram/dev/framework/ ;Taro https://docs.taro.zone/docs/GETTING-STARTED ;Taro UI https://taro-ui.jd.com +- 小红书:https://miniapp-sandbox.xiaohongshu.com/minitool/doc +- 抖音:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/usage-guide +- 虚拟支付(个人主体):https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/person — 部署前按文末清单验收 + +## 微信配置(写入环境变量,勿提交到公开 README) + +``` +WX_APPID=wxa55815dd741a540d +WX_APPSECRET=bf71025c209e7567d49268bc427ba22b +WX_OFFER_ID=1450642200 +WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn +WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg +``` diff --git a/.gitignore b/.gitignore index 20bd5c4..229202e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,10 @@ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies +node_modules/ /node_modules /apps/**/node_modules +/packages/**/node_modules /.pnp .pnp.* .yarn/* @@ -54,6 +56,7 @@ next-env.d.ts /apps/nomadweb/tmp-screenshots/ /apps/**/.turbo/ /apps/**/.venv/ +/apps/api/.venv/ /deploy/**/__pycache__/ # secrets / private mini-program configs @@ -63,3 +66,8 @@ next-env.d.ts !**/*.env.example !**/.env*.example **/project.private.config.json + +# local deploy/ops noise +/deploy/observability/_*.txt +/apps/ebook/redmini/.claude/ +/apps/**/venv/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..85ac481 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,7 @@ +# Nomadro agent notes + +Follow `.cursor/rules/*.mdc` (charter, modular-design, UI, payments, deploy, WeChat). + +Integrate verticals via `node scripts/integrate-apps.mjs` after structural changes under `apps/`. + +Do not commit secrets (`.env.local`, live payment keys). WeChat keys live in env / wechat rule for agent use only. diff --git a/README.md b/README.md index c460ba7..5451d59 100644 --- a/README.md +++ b/README.md @@ -1,78 +1,86 @@ # Nomadro -中文数字游民操作系统官网([nomadro.com](https://nomadro.com))。 +中文数字游民操作系统(主域 [nomadro.cn](https://nomadro.cn))。本仓把四个垂直产品统一进一个 Next 门户,再逐步统一 FastAPI / PocketBase / 支付 / 管理后台 / 小程序。 -基于 Next.js App Router,提供游民导航、地理套利、直播工具箱等入口聚合。 +## 四个垂直 × 门户入口 -## 技术栈 +| 产品 | 源码 | 门户路径 | 小程序 | +|------|------|----------|--------| +| 出海导航 | `apps/navmini` | `/nav` | weapp / tt / xhs | +| 数字游民小册 | `apps/ebook` | `/book` | wemini / dymini / redmini | +| 旅居社群 | `apps/nomadweb` | `/community` | wemini / dymini / redmini | +| 私域会员(异度星球) | `apps/nomadvip` | `/vip` | (后续 Taro) | +| 支付网关 | `apps/payjsapi` | FastAPI(`api.*`) | — | -- Next.js 16 / React 19 / TypeScript -- Tailwind CSS 4 -- pnpm -- 中文用户识别:[is-china-user](https://github.com/yArna/isChinaUser) +同进程 App Router 挂载,**禁止 iframe / 反代嵌套**。详见 `apps/README.md`、`.cursor/rules/`。 -## 本地开发 +## 默认技术栈 + +- **Web**:Next.js 16 + React 19(前端)· FastAPI(后端)· PocketBase(数据库) +- **支付**:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内);VIP 现网经 `payjsapi` +- **体验**:深色科技风、日夜主题、emoji/SVG/动效、D3 / three.js / WebGL·PWA 等 +- **i18n**:默认中/英,可扩展日/越/泰等 +- **运维**:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook +- **Git**:https://git.nomadro.cn (管理员 `hackrobot`) + +## 本地开发(Windows) ```bash pnpm install pnpm dev ``` -打开 [http://localhost:3000](http://localhost:3000)。 +打开: -常用命令: +- http://localhost:3000 +- http://localhost:3000/nav +- http://localhost:3000/book +- http://localhost:3000/community +- http://localhost:3000/vip +- http://localhost:3000/admin + +支付 API(可选): ```bash -pnpm build # 生产构建 -pnpm start # 启动生产服务 -pnpm lint # 代码检查 +cd apps/payjsapi +python -m venv venv +# Windows: .\venv\Scripts\activate +pip install -r requirements.txt +python run.py ``` -## 多语言 +重新镜像垂直路由到门户(改过 apps 源码结构后): -默认根据浏览器环境自动判断语言: +```bash +node scripts/integrate-apps.mjs +``` -- 识别为中文用户 → 显示中文文案 -- 非中文用户 → 显示英文文案 +## 开发流程(强制) -实现要点: +1. 本地改完并调试确认 +2. 部署到腾讯云 `82.157.112.245`(`ubuntu`)并线上冒烟 +3. 更新本 README / 相关文档 -| 文件 | 作用 | -| --- | --- | -| `components/locale-provider.tsx` | 调用 `isChinaUser()`,提供 locale 上下文 | -| `lib/i18n.ts` | 中英文案字典 | -| `components/language-switcher.tsx` | 语言下拉(默认隐藏) | +当前门户开发分支:`pre1`(远程 `nomadro/pre1`)。 -### 彩蛋:手动切换语言 +## 域名 -语言下拉默认不展示。在页面**右上角区域 2.5 秒内连点 5 次**后会出现下拉框,可手动切换中文 / English。 - -- 解锁状态保存在当前标签页的 `sessionStorage`(`nomadro-lang-unlock`) -- 仅在已解锁时,手动选择的语言会写入 `localStorage`(`nomadro-locale`)并优先生效 -- 关闭标签页后恢复:重新按中文用户识别自动选语言,下拉再次隐藏 +主域 `nomadro.cn`,二级 DNS 在 Cloudflare(`admin` `api` `vip` `pocketbase` `umami` `uptimekuma` `ntfy` `git` `nav` `ebook` …)。需要新子域时再加解析。 ## 项目结构(简要) ``` -app/ # 页面(首页 / about / contact) -components/ # UI 与 locale 相关组件 -lib/data.ts # 入口卡片等业务数据 -lib/i18n.ts # 多语言文案 -deploy/ # 服务器部署脚本与说明 +app/ # 门户路由(/nav /book /community /vip /admin + VIP /api/*) +apps/ # 垂直业务(互不深耦) +packages/ # 共享模块 @nomadro/pay|pb|sdk +components/ lib/ # 门户壳与 i18n +deploy/ # 部署与可观测脚本 +.cursor/rules/ # Agent 开发规范 +scripts/integrate-apps.mjs ``` +共享包说明见 [`packages/README.md`](./packages/README.md)。管理后台:[/admin](http://localhost:3000/admin)。 + ## 部署 -生产域名:`nomadro.com`(`www` 301 到主域)。 - -详细步骤见 [`deploy/README.md`](./deploy/README.md)。 - -日常更新(服务器已部署过): - -```bash -ssh root@ -cd /var/www/nomadro.com -bash deploy/deploy.sh -``` - -当前发布分支默认为 `test`。 +生产机:`82.157.112.245`。细节见 [`deploy/README.md`](./deploy/README.md)。 diff --git a/app/admin/admin.module.css b/app/admin/admin.module.css new file mode 100644 index 0000000..3174fb7 --- /dev/null +++ b/app/admin/admin.module.css @@ -0,0 +1,138 @@ +.shell { + min-height: 100vh; + padding: 2.5rem 1.25rem 4rem; + background: + radial-gradient(ellipse 80% 50% at 50% -20%, #1a3a4a 0%, transparent 55%), + linear-gradient(180deg, #0c0c0f 0%, #12141a 100%); + color: #e8eaed; + font-family: ui-sans-serif, system-ui, sans-serif; +} + +.hero { + max-width: 960px; + margin: 0 auto 2rem; +} + +.eyebrow { + letter-spacing: 0.12em; + text-transform: uppercase; + font-size: 0.75rem; + color: #f59e0b; + margin: 0 0 0.5rem; +} + +.title { + font-size: clamp(1.75rem, 4vw, 2.5rem); + margin: 0 0 0.5rem; + font-weight: 700; +} + +.sub { + color: #9aa3b2; + max-width: 42rem; + line-height: 1.55; + margin: 0; +} + +.grid { + max-width: 960px; + margin: 0 auto; + display: grid; + gap: 1rem; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); +} + +.card { + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + border-radius: 14px; + padding: 1.15rem 1.2rem; + backdrop-filter: blur(8px); + transition: transform 0.2s ease, border-color 0.2s ease; +} + +.card:hover { + transform: translateY(-2px); + border-color: rgba(245, 158, 11, 0.45); +} + +.cardTop { + display: flex; + align-items: center; + gap: 0.55rem; + margin-bottom: 0.4rem; +} + +.emoji { + font-size: 1.35rem; +} + +.cardTitle { + font-size: 1.05rem; + margin: 0; +} + +.cardNote { + margin: 0 0 1rem; + color: #9aa3b2; + font-size: 0.88rem; + line-height: 1.45; + min-height: 2.6em; +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 40px; + padding: 0.4rem 0.85rem; + border-radius: 8px; + background: #f59e0b; + color: #111; + font-weight: 600; + font-size: 0.85rem; + text-decoration: none; +} + +.ghost { + background: transparent; + color: #e8eaed; + border: 1px solid rgba(255, 255, 255, 0.18); +} + +.disabled { + opacity: 0.45; + pointer-events: none; +} + +.meta { + max-width: 960px; + margin: 2.25rem auto 0; + padding: 1.25rem 1.35rem; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 14px; + background: rgba(0, 0, 0, 0.25); +} + +.metaTitle { + margin: 0 0 0.75rem; + font-size: 1.05rem; +} + +.metaList { + margin: 0; + padding-left: 1.1rem; + color: #9aa3b2; + line-height: 1.7; +} + +.code { + color: #fbbf24; + font-size: 0.85em; +} diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx new file mode 100644 index 0000000..6dc712b --- /dev/null +++ b/app/admin/layout.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Nomadro Admin", + description: "统一管理后台面板", + robots: { index: false, follow: false }, +}; + +export default function AdminLayout({ + children, +}: { + children: React.ReactNode; +}) { + return children; +} diff --git a/app/admin/page.tsx b/app/admin/page.tsx new file mode 100644 index 0000000..6f2e299 --- /dev/null +++ b/app/admin/page.tsx @@ -0,0 +1,110 @@ +"use client"; + +import Link from "next/link"; +import { resolvePayProvider } from "@nomadro/pay"; +import { resolvePocketBaseConfig } from "@nomadro/pb"; +import styles from "./admin.module.css"; + +const MODULES = [ + { + id: "nav", + emoji: "🧭", + name: "出海导航", + href: "/nav", + admin: null as string | null, + note: "静态导航 · 无独立 admin", + }, + { + id: "book", + emoji: "📖", + name: "数字游民小册", + href: "/book", + admin: "/book/admin", + note: "ebook admin · Creem / NOWPayments", + }, + { + id: "community", + emoji: "🌏", + name: "旅居社群", + href: "/community", + admin: "/community", + note: "社群运营入口 · FastAPI /api/v1", + }, + { + id: "vip", + emoji: "👑", + name: "私域会员", + href: "/vip", + admin: "/vip", + note: "异度星球 · payjsapi · zpay/xpay", + }, +] as const; + +export default function AdminPage() { + const pay = resolvePayProvider({ region: "auto", isChinaUser: true }); + const pb = resolvePocketBaseConfig(); + + return ( +
+
+

Nomadro · Control

+

管理后台面板

+

+ 模块化入口:各垂直自带能力,本页只做编排与跳转,不堆业务逻辑。 +

+
+ +
+ {MODULES.map((m) => ( +
+
+ + {m.emoji} + +

{m.name}

+
+

{m.note}

+
+ + 打开产品 + + {m.admin ? ( + + 运营入口 + + ) : ( + + 暂无 admin + + )} +
+
+ ))} +
+ +
+

共享层 @nomadro/*

+
    +
  • + 支付路由:当前 CN 默认 →{" "} + + {pay.provider}/{pay.env}/{pay.channel} + +
  • +
  • + PocketBase:public{" "} + {pb.publicUrl} +
  • +
  • + SDK:@nomadro/sdk{" "} + 供小程序 / 外部项目调用 +
  • +
  • + 支付后端: + apps/payjsapi(FastAPI :8007) +
  • +
+
+
+ ); +} diff --git a/app/api/auth/email/route.ts b/app/api/auth/email/route.ts new file mode 100644 index 0000000..7c02d92 --- /dev/null +++ b/app/api/auth/email/route.ts @@ -0,0 +1,19 @@ +/** + * 从 Cookie 读取邮箱(不调用 PB),用于 emailLinked=1 但 userName 被覆盖的场景 + */ +import { NextRequest, NextResponse } from "next/server"; +import { COOKIE_NAME } from "@vip/app/lib/auth-cookie"; + +export async function GET(request: NextRequest) { + const cookie = request.cookies.get(COOKIE_NAME)?.value; + if (!cookie) { + return NextResponse.json({ ok: true, email: null }); + } + try { + const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8")); + const email = payload?.email ?? null; + return NextResponse.json({ ok: true, email: typeof email === "string" ? email : null }); + } catch { + return NextResponse.json({ ok: true, email: null }); + } +} diff --git a/app/api/auth/link-email/route.ts b/app/api/auth/link-email/route.ts new file mode 100644 index 0000000..17f0b7b --- /dev/null +++ b/app/api/auth/link-email/route.ts @@ -0,0 +1,139 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getPocketBaseConfig } from "@vip/config/services.config"; +import { + ensureSiteVipForUser, + getAdminToken, + isAnonymousUserId, + upsertVipEmailLink, +} from "@vip/app/api/vip/_helpers"; + +const DEFAULT_PASSWORD = "12345678"; + +type PBAuthRecord = { + id: string; + email?: string; +}; + +async function registerOrLoginUser( + email: string, + password: string +): Promise<{ token: string; record: PBAuthRecord } | null> { + const pb = getPocketBaseConfig(); + + await fetch(`${pb.url}/api/collections/users/records`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email, + password, + passwordConfirm: password, + live_allowed: true, + }), + cache: "no-store", + }).catch(() => null); + + const loginRes = await fetch( + `${pb.url}/api/collections/users/auth-with-password`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ identity: email, password }), + cache: "no-store", + } + ); + + if (!loginRes.ok) { + const error = await loginRes.json().catch(() => ({})); + throw new Error(error?.message || "邮箱或密码错误"); + } + + const loginData = await loginRes.json().catch(() => ({})); + if (!loginData?.token || !loginData?.record?.id) { + throw new Error("邮箱绑定失败"); + } + + return { + token: loginData.token, + record: loginData.record, + }; +} + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const email = String(body?.email ?? "").trim().toLowerCase(); + const password = String(body?.password ?? "").trim() || DEFAULT_PASSWORD; + const anonymousUserId = String(body?.anonymousUserId ?? "").trim(); + + console.log( + "[link-email] request email=%s anonymousUserId=%s", + email || "(empty)", + anonymousUserId || "(empty)" + ); + + if (!email) { + return NextResponse.json( + { ok: false, error: "请填写邮箱" }, + { status: 400 } + ); + } + + if (!isAnonymousUserId(anonymousUserId)) { + return NextResponse.json( + { ok: false, error: "无效的匿名 user_id" }, + { status: 400 } + ); + } + + try { + const authData = await registerOrLoginUser(email, password); + if (!authData) { + return NextResponse.json( + { ok: false, error: "邮箱绑定失败" }, + { status: 500 } + ); + } + + const adminToken = await getAdminToken(); + if (!adminToken) { + return NextResponse.json( + { ok: false, error: "PocketBase 管理员认证失败" }, + { status: 500 } + ); + } + + await ensureSiteVipForUser(adminToken, anonymousUserId, authData.record.id); + await upsertVipEmailLink( + adminToken, + email, + authData.record.id, + anonymousUserId + ); + + console.log( + "[link-email] success email=%s pbUserId=%s anonymousUserId=%s", + email, + authData.record.id, + anonymousUserId + ); + + return NextResponse.json({ + ok: true, + token: authData.token, + record: { + id: authData.record.id, + email: authData.record.email ?? email, + }, + }); + } catch (error) { + console.error("[link-email] failed:", error); + const message = error instanceof Error ? error.message : "邮箱绑定失败"; + const status = message.includes("密码") || message.includes("邮箱") ? 401 : 500; + return NextResponse.json( + { + ok: false, + error: message, + }, + { status } + ); + } +} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts new file mode 100644 index 0000000..3c6623f --- /dev/null +++ b/app/api/auth/logout/route.ts @@ -0,0 +1,23 @@ +import { NextRequest, NextResponse } from "next/server"; +import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@vip/app/lib/auth-cookie"; + +const ANONYMOUS_USER_COOKIE_NAME = "nomadvip_anon_uid"; +const PAY_ORDER_COOKIE_NAME = "nomadvip_pay_order"; + +export async function POST(request: NextRequest) { + const res = NextResponse.json({ ok: true }); + const options = getCookieOptions(true, getHostFromRequest(request)) as Record< + string, + string | number | boolean + >; + res.cookies.set(COOKIE_NAME, "", options); + res.cookies.set(ANONYMOUS_USER_COOKIE_NAME, "", { + ...options, + httpOnly: false, + }); + res.cookies.set(PAY_ORDER_COOKIE_NAME, "", { + ...options, + httpOnly: false, + }); + return res; +} diff --git a/app/api/auth/me/route.ts b/app/api/auth/me/route.ts new file mode 100644 index 0000000..446157c --- /dev/null +++ b/app/api/auth/me/route.ts @@ -0,0 +1,101 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getPocketBaseConfig } from "@vip/config/services.config"; +import { + COOKIE_NAME, + getCookieOptions, + getHostFromRequest, +} from "@vip/app/lib/auth-cookie"; + +function normalizeAnonymousUserId(value: unknown): string | undefined { + return typeof value === "string" && /^user\d+$/.test(value) + ? value + : undefined; +} + +export async function GET(request: NextRequest) { + const cookie = request.cookies.get(COOKIE_NAME)?.value; + if (!cookie) { + return NextResponse.json({ ok: true, user: null }); + } + + try { + const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8")); + const { token, userId, email, anonymousUserId } = payload; + const normalizedAnonymousUserId = normalizeAnonymousUserId(anonymousUserId); + + if (!token || !userId) { + return NextResponse.json({ ok: true, user: null }); + } + + const pb = getPocketBaseConfig(); + const res = await fetch(`${pb.url}/api/collections/users/auth-refresh`, { + method: "POST", + headers: { Authorization: `Bearer ${token}` }, + }); + + if (!res.ok) { + const response = NextResponse.json({ ok: true, user: null }); + response.cookies.set( + COOKIE_NAME, + "", + getCookieOptions(true, getHostFromRequest(request)) as Record< + string, + string | number | boolean + > + ); + return response; + } + + const data = await res.json(); + const newToken = data.token; + const newRecord = data.record; + + if (newToken && newRecord?.id) { + const nextPayload: Record = { + token: newToken, + userId: newRecord.id, + email: newRecord.email ?? email, + }; + + if (normalizedAnonymousUserId) { + nextPayload.anonymousUserId = normalizedAnonymousUserId; + } + + const encoded = Buffer.from(JSON.stringify(nextPayload), "utf-8").toString( + "base64url" + ); + + const response = NextResponse.json({ + ok: true, + user: { + id: newRecord.id, + email: newRecord.email ?? email, + anonymousUserId: normalizedAnonymousUserId, + }, + token: newToken, + }); + + response.cookies.set( + COOKIE_NAME, + encoded, + getCookieOptions(false, getHostFromRequest(request)) as Record< + string, + string | number | boolean + > + ); + return response; + } + + return NextResponse.json({ + ok: true, + user: { + id: data.record?.id ?? userId, + email: data.record?.email ?? email, + anonymousUserId: normalizedAnonymousUserId, + }, + token: data.token, + }); + } catch { + return NextResponse.json({ ok: true, user: null }); + } +} diff --git a/app/api/auth/store-email-link/route.ts b/app/api/auth/store-email-link/route.ts new file mode 100644 index 0000000..0384754 --- /dev/null +++ b/app/api/auth/store-email-link/route.ts @@ -0,0 +1,126 @@ +/** + * 支付成功后存储 email -> user_id 映射,供「已有账号登录」按邮箱查库 + * 同时创建 PB 用户(邮箱+12345678),以便后续用邮箱+密码登录 + * 需 PocketBase 存在 vip_email_link 集合(email, user_id) + */ +import { NextRequest, NextResponse } from "next/server"; +import { getPocketBaseConfig } from "@vip/config/services.config"; + +const VIP_EMAIL_LINK_COLLECTION = "vip_email_link"; +const DEFAULT_PASSWORD = "12345678"; + +async function getAdminToken(): Promise { + const email = process.env.POCKETBASE_EMAIL; + const password = process.env.POCKETBASE_PASSWORD; + if (!email || !password) return null; + const pb = getPocketBaseConfig(); + const res = await fetch(`${pb.url}/api/admins/auth-with-password`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ identity: email, password }), + }); + if (!res.ok) return null; + const data = await res.json(); + return data?.token ?? null; +} + +/** 若 PB 无该邮箱用户则创建(密码 12345678),供后续邮箱登录 */ +async function ensurePbUserExists(pbUrl: string, email: string): Promise { + const registerRes = await fetch(`${pbUrl}/api/collections/users/records`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email, + password: DEFAULT_PASSWORD, + passwordConfirm: DEFAULT_PASSWORD, + live_allowed: true, + }), + }); + if (registerRes.ok) { + console.log("[store-email-link] 已创建 PB 用户 email=%s", email); + return; + } + const err = await registerRes.json().catch(() => ({})); + const alreadyExists = + err?.data?.email?.message?.includes("unique") || + err?.message?.toLowerCase?.().includes("already") || + err?.message?.toLowerCase?.().includes("unique"); + if (alreadyExists) { + console.log("[store-email-link] PB 用户已存在 email=%s", email); + return; + } + console.warn("[store-email-link] 创建 PB 用户失败 email=%s status=%s", email, registerRes.status, err); +} + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const email = String(body?.email ?? "").trim().toLowerCase(); + const userId = String(body?.user_id ?? body?.userId ?? "").trim(); + + console.log("[store-email-link] 请求 email=%s user_id=%s", email || "(空)", userId || "(空)"); + + if (!email || !userId) { + return NextResponse.json({ ok: false, error: "请填写邮箱" }, { status: 400 }); + } + + const adminToken = await getAdminToken(); + if (!adminToken) { + return NextResponse.json({ ok: false, error: "服务未配置" }, { status: 500 }); + } + + const pb = getPocketBaseConfig(); + try { + await ensurePbUserExists(pb.url, email); + } catch (e) { + console.warn("[store-email-link] ensurePbUserExists 异常:", e); + } + + const safeEmail = email.replace(/"/g, '\\"'); + const filter = `email = "${safeEmail}"`; + try { + const listRes = await fetch( + `${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records?filter=${encodeURIComponent(filter)}&perPage=1`, + { headers: { Authorization: `Bearer ${adminToken}` } } + ); + if (!listRes.ok) { + return NextResponse.json({ ok: false, error: "vip_email_link 集合不存在,请在 PocketBase 中创建" }, { status: 500 }); + } + const listData = await listRes.json().catch(() => ({})); + const items = listData?.items ?? []; + const recordBody: Record = { email, user_id: userId }; + if (/^user\d+$/.test(userId)) { + recordBody.anonymous_user_id = userId; + } + if (items.length > 0) { + await fetch(`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records/${items[0].id}`, { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify(recordBody), + }); + } else { + const createRes = await fetch(`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify(recordBody), + }); + if (!createRes.ok) { + const err = await createRes.json().catch(() => ({})); + return NextResponse.json({ ok: false, error: err?.message || "写入失败" }, { status: 500 }); + } + } + console.log("[store-email-link] 成功 email=%s user_id=%s", email, userId); + return NextResponse.json({ ok: true }); + } catch (e) { + console.error("[store-email-link] error:", e); + return NextResponse.json( + { ok: false, error: e instanceof Error ? e.message : "操作失败" }, + { status: 500 } + ); + } +} diff --git a/app/api/auth/sync-session/route.ts b/app/api/auth/sync-session/route.ts new file mode 100644 index 0000000..2d68adc --- /dev/null +++ b/app/api/auth/sync-session/route.ts @@ -0,0 +1,46 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + COOKIE_NAME, + getCookieOptions, + getHostFromRequest, +} from "@vip/app/lib/auth-cookie"; + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const token = body?.token; + const record = body?.record; + const anonymousUserId = + typeof body?.anonymousUserId === "string" ? body.anonymousUserId.trim() : ""; + + if (!token || !record?.id) { + return NextResponse.json( + { ok: false, error: "缺少 token 或 record" }, + { status: 400 } + ); + } + + const payload: Record = { + token, + userId: record.id, + email: record.email ?? "", + }; + + if (/^user\d+$/.test(anonymousUserId)) { + payload.anonymousUserId = anonymousUserId; + } + + const encoded = Buffer.from(JSON.stringify(payload), "utf-8").toString( + "base64url" + ); + + const res = NextResponse.json({ ok: true }); + res.cookies.set( + COOKIE_NAME, + encoded, + getCookieOptions(false, getHostFromRequest(request)) as Record< + string, + string | number | boolean + > + ); + return res; +} diff --git a/app/api/pay/confirm/route.ts b/app/api/pay/confirm/route.ts new file mode 100644 index 0000000..e0803b3 --- /dev/null +++ b/app/api/pay/confirm/route.ts @@ -0,0 +1,267 @@ +/** + * 支付确认:payjsapi 未写入时,由 nomadvip 直接写入 PocketBase + 创建 Memos + */ +import { NextRequest, NextResponse } from "next/server"; +import { + getApiUrlFromRequest, + getPocketBaseConfig, + getPaymentConfig, + SITE_ID, +} from "@vip/config/services.config"; +import { queryXorPayOrderStatus } from "@vip/app/lib/xorpayStatus"; +import { queryZPayOrderStatus } from "@vip/app/lib/zpayStatus"; + +const getDefaultTotalFee = () => + getPaymentConfig().defaultAmount ?? Number(process.env.PAYMENT_DEFAULT_AMOUNT) ?? 18800; + +function parsePayPriceToCents(payPrice: unknown): number | null { + if (payPrice == null) return null; + const raw = String(payPrice).trim(); + if (!raw) return null; + const value = Number(raw); + if (!Number.isFinite(value) || value <= 0) return null; + return Math.round(value * 100); +} + +async function getAdminToken(): Promise { + const email = process.env.POCKETBASE_EMAIL; + const password = process.env.POCKETBASE_PASSWORD; + if (!email || !password) return null; + const pb = getPocketBaseConfig(); + const paths = ["/api/admins/auth-with-password", "/api/collections/_superusers/auth-with-password"]; + for (const path of paths) { + const res = await fetch(`${pb.url}${path}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ identity: email, password }), + }); + if (res.ok) { + const data = await res.json(); + if (data?.token) return data.token; + } + } + return null; +} + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); +} + +async function verifyOrderPaid( + request: NextRequest, + orderId: string +): Promise<{ paid: boolean; totalFeeCents: number | null }> { + const apiUrl = resolvePayApiUrl(request); + const url = `${apiUrl}/nomadvip/order_status?order_id=${encodeURIComponent(orderId)}`; + console.log("[pay/confirm] verify order_status url=%s", url); + 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; + const totalFeeCents = parsePayPriceToCents(data?.pay_price); + if (!paid && !res.ok) { + console.warn("[pay/confirm] order_status non-ok:", res.status, url, data); + } + if (paid) { + return { paid: true, totalFeeCents }; + } + } catch (e) { + console.error("[pay/confirm] verifyOrderPaid fetch error:", e); + } + + const xorpay = await queryXorPayOrderStatus(orderId, 5000); + console.log( + "[pay/confirm] xorpay fallback order_id=%s paid=%s status=%s error=%s url=%s", + orderId, + !!xorpay?.paid, + xorpay?.status || "", + xorpay?.error || "", + xorpay?.url || "" + ); + if (xorpay?.paid) { + return { + paid: true, + totalFeeCents: parsePayPriceToCents(xorpay?.pay_price), + }; + } + + const zpay = await queryZPayOrderStatus(orderId, 5000); + console.log( + "[pay/confirm] zpay fallback order_id=%s paid=%s status=%s error=%s url=%s", + orderId, + !!zpay?.paid, + zpay?.status || "", + zpay?.error || "", + zpay?.url || "" + ); + return { + paid: !!zpay?.paid, + totalFeeCents: parsePayPriceToCents(zpay?.pay_price), + }; +} + +async function createMemosUser(username: string, password: string): Promise { + const baseUrl = process.env.MEMOS_API_URL || "https://qun.hackrobot.cn"; + const token = process.env.MEMOS_ACCESS_TOKEN; + if (!token) return false; + const url = `${baseUrl.replace(/\/$/, "")}/api/v1/users`; + try { + const res = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ + username, + password, + role: "USER", + state: "NORMAL", + }), + }); + if (res.ok) return true; + const err = await res.json().catch(() => ({})); + const alreadyExists = + err?.code === 6 || + err?.code === 13 || + err?.message?.includes("already exists") || + err?.message?.includes("UNIQUE") || + err?.message?.includes("constraint"); + if (alreadyExists) return true; + console.error("Memos create user failed:", res.status, err); + return false; + } catch (e) { + console.error("Memos create user error:", e); + return false; + } +} + +export async function POST(request: NextRequest) { + try { + const body = await request.json().catch(() => ({})); + const orderId = String(body?.order_id ?? body?.orderId ?? "").trim(); + const userId = String(body?.user_id ?? body?.userId ?? "").trim(); + + console.log("[pay/confirm] 请求 order_id=%s user_id=%s", orderId || "(空)", userId || "(空)"); + + if (!orderId || !userId) { + return NextResponse.json({ ok: false, error: "缺少 order_id 或 user_id" }, { status: 400 }); + } + + const verifyResult = await verifyOrderPaid(request, orderId); + if (!verifyResult.paid) { + console.error("[pay/confirm] 订单未支付 order_id=%s user_id=%s (请检查 payjsapi order_status 接口)", orderId, userId); + return NextResponse.json({ ok: false, error: "订单未支付" }, { status: 400 }); + } + + const adminToken = await getAdminToken(); + if (!adminToken) { + return NextResponse.json({ ok: false, error: "PocketBase 未配置" }, { status: 500 }); + } + + const pb = getPocketBaseConfig(); + const totalFee = verifyResult.totalFeeCents ?? getDefaultTotalFee(); + + const checkExisting = await fetch( + `${pb.url}/api/collections/payments/records?filter=${encodeURIComponent(`order_id="${orderId}"`)}&perPage=1`, + { headers: { Authorization: `Bearer ${adminToken}` } } + ); + const existingData = await checkExisting.json().catch(() => ({})); + const paymentsExist = (existingData?.items?.length ?? 0) > 0; + + if (!paymentsExist) { + const paymentsRes = await fetch(`${pb.url}/api/collections/payments/records`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify({ + user_id: userId, + type: "vip", + order_id: orderId, + total_fee: totalFee, + amount: totalFee, + channel: "wxpay", + }), + }); + + if (!paymentsRes.ok) { + const err = await paymentsRes.json().catch(() => ({})); + if (err?.data?.order_id?.message?.includes("unique") || err?.message?.includes("unique")) { + // 已存在(并发),继续 + } else { + const msg = err?.message || err?.data ? JSON.stringify(err) : await paymentsRes.text(); + console.error("[pay/confirm] payments create failed:", paymentsRes.status, msg); + return NextResponse.json( + { ok: false, error: "写入 payments 失败", detail: msg }, + { status: 500 } + ); + } + } + } + + const siteVipCheck = await fetch( + `${pb.url}/api/collections/site_vip/records?filter=${encodeURIComponent(`user_id="${userId}" && site_id="${SITE_ID}"`)}&perPage=1`, + { headers: { Authorization: `Bearer ${adminToken}` } } + ); + const siteVipData = await siteVipCheck.json().catch(() => ({})); + const siteVipItems = siteVipData?.items ?? []; + + if (siteVipItems.length > 0) { + await fetch(`${pb.url}/api/collections/site_vip/records/${siteVipItems[0].id}`, { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify({ order_id: orderId }), + }); + } else { + const siteVipRes = await fetch(`${pb.url}/api/collections/site_vip/records`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify({ + user_id: userId, + site_id: SITE_ID, + order_id: orderId, + }), + }); + + if (!siteVipRes.ok) { + const err = await siteVipRes.json().catch(() => ({})); + if (err?.data?.order_id?.message?.includes("unique") || err?.message?.includes("unique")) { + // 已存在,继续 + } else { + console.error("site_vip create failed:", await siteVipRes.text()); + } + } + } + + if (userId.startsWith("user") && /^user\d+$/.test(userId)) { + await createMemosUser(userId, "12345678"); + } + + console.log("[pay/confirm] 成功 order_id=%s user_id=%s", orderId, userId); + return NextResponse.json({ ok: true }); + } catch (e) { + console.error("pay/confirm error:", e); + return NextResponse.json( + { ok: false, error: e instanceof Error ? e.message : "确认失败" }, + { status: 500 } + ); + } +} diff --git a/app/api/pay/route.ts b/app/api/pay/route.ts new file mode 100644 index 0000000..1c9dfd5 --- /dev/null +++ b/app/api/pay/route.ts @@ -0,0 +1,525 @@ +/** + * nomadvip 支付 API - 参考 digital + * PC: 二维码 | H5: 302 跳转 | 微信内: 收银台表单 + */ +import { NextRequest, NextResponse } from "next/server"; +import { getPaymentConfig, getApiUrlFromRequest } from "@vip/config/services.config"; +import { getCookieOptions, getHostFromRequest } from "@vip/app/lib/auth-cookie"; + +const ZPAY_REQUIRED = ["pid", "type", "out_trade_no", "notify_url", "return_url", "name", "money", "sign", "sign_type"]; +const ANONYMOUS_USER_COOKIE_NAME = "nomadvip_anon_uid"; +const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30; + +function escapeAttr(s: string): string { + return String(s) + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(//g, ">"); +} + +function buildErrorHtml(errorMsg: string): string { + const esc = (s: string) => + s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c); + return `支付失败

支付发起失败

${esc(errorMsg)}

返回首页重试

`; +} + +function buildPayHtml( + payUrl: string, + params: Record, + options?: { directToCashier?: boolean; displayName?: string; avatar?: string } +): string { + const flat: Record = {}; + for (const [k, v] of Object.entries(params)) { + if (v == null) continue; + const s = String(v).trim(); + if (s === "") continue; + flat[k] = s; + } + const inputs = Object.entries(flat) + .map(([k, v]) => ``) + .join("\n"); + const direct = options?.directToCashier; + const displayName = (options?.displayName || "当前用户").trim(); + const avatar = (options?.avatar || "").trim(); + const showPayerHint = !!avatar; + // direct:微信内无中转,直接提交 | 非 direct:PC/H5 有中转页提示 + return direct + ? `支付
${inputs}
` + : `跳转支付${showPayerHint ? `
${escapeAttr(displayName)}
开通对象:${escapeAttr(displayName)}
正在为你升级 VIP,马上进入支付...
` : ""}
${inputs}
`; +} + +function setPayOrderCookie(res: NextResponse, orderId: string) { + res.cookies.set("nomadvip_pay_order", `${orderId}|${Date.now()}`, { path: "/", maxAge: 900 }); +} + +function setAnonymousUserCookie( + res: NextResponse, + request: NextRequest, + userId: string +) { + if (!/^user\d+$/.test(userId)) { + return; + } + const options = { + ...(getCookieOptions(false, getHostFromRequest(request)) as Record< + string, + string | number | boolean + >), + httpOnly: false, + maxAge: ANONYMOUS_USER_COOKIE_MAX_AGE, + }; + res.cookies.set(ANONYMOUS_USER_COOKIE_NAME, userId, options); +} + +async function createPayOrder( + apiUrl: string, + user_id: string, + wechat_userid: string | undefined, + return_url: string, + total_fee: number, + type: string, + channel: string, + clientIp?: string, + provider?: string +) { + const payload: Record = { + user_id, + ...(wechat_userid ? { wechat_userid } : {}), + site_id: "vip", + total_fee, + type, + channel, + return_url, + ...(clientIp && { client_ip: clientIp }), + ...(provider && { provider }), + }; + const payh5Url = `${apiUrl}/nomadvip/payh5`; + const payh5Timeout = Number(process.env.PAYJSAPI_PAYH5_TIMEOUT) || 60000; + console.log("[pay] createPayOrder 请求 payjsapi url=%s timeout=%ds", payh5Url, payh5Timeout / 1000); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), payh5Timeout); + const res = await fetch(payh5Url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + signal: controller.signal, + }).finally(() => clearTimeout(timeout)); + const data = await res.json().catch(() => ({})); + const statusOk = data?.status === "ok" || data?.status === "success" || (res.ok && (data?.xorpay_params || data?.params)); + console.log("[pay] createPayOrder 响应 http=%s status=%s hasParams=%s", res.status, data?.status, !!(data?.xorpay_params || data?.params)); + if (!res.ok || !statusOk) { + const errMsg = data?.detail || data?.msg || data?.error || "支付创建失败"; + console.error("[pay] createPayOrder 失败:", errMsg, "body=", JSON.stringify(data).slice(0, 300)); + throw new Error(errMsg); + } + // xorpay: xorpay_params + xorpay_url | zpay: params + pay_url + const params = (data.xorpay_params ?? data.params) || {}; + const payUrl = data.xorpay_url || data.pay_url || ""; + if (!params || typeof params !== "object" || Object.keys(params).length === 0) { + console.error("[pay] createPayOrder 参数为空 data.keys=", Object.keys(data || {})); + throw new Error("payjsapi 未返回支付参数"); + } + return { + params: params as Record, + payUrl, + provider: data.provider || "zpay", + }; +} + +export async function POST(request: NextRequest) { + try { + let body: Record; + const contentType = request.headers.get("content-type") || ""; + if (contentType.includes("application/json")) { + body = (await request.json()) as Record; + } else { + const form = await request.formData(); + body = Object.fromEntries(form.entries()) as Record; + } + + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + const apiUrl = ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); + console.log("[pay] 立即加入 apiUrl=%s host=%s", apiUrl, hostHeader); + let user_id = String(body?.user_id || "").trim(); + const wechat_userid = String(body?.wechat_userid || body?.userid || "").trim(); + if (user_id.startsWith("{") && user_id.includes("data")) { + try { + const parsed = JSON.parse(user_id) as { data?: string }; + if (parsed?.data) user_id = String(parsed.data).trim(); + } catch { + /* ignore */ + } + } + const return_url = String(body?.return_url || "").trim(); + const total_fee = Number(body?.total_fee) || payConfig.defaultAmount || 100; + const type = String(body?.type || "vip"); + const channel = String(body?.channel || "wxpay"); + const device = String(body?.device || "pc"); + const wechatNick = String(body?.wechat_nick || body?.nick || body?.user_name || "").trim(); + const wechatAvatar = String(body?.wechat_avatar || body?.avatar || "").trim(); + // 渠道规则:pc/手机浏览器 -> zpay,仅微信内 -> xorpay + const effectiveProvider = + device === "wechat" ? "xorpay" : "zpay"; + const accept = request.headers.get("accept") || ""; + const wantHtml = String(body?.html) === "1" || accept.includes("text/html"); + const preferJson = String(body?.prefer_json) === "1"; + + if (!user_id) { + if (wantHtml) { + return new NextResponse(buildErrorHtml("缺少 user_id"), { + status: 400, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + return NextResponse.json({ ok: false, error: "缺少 user_id" }, { status: 400 }); + } + + const origin = + request.headers.get("x-forwarded-host") + ? `${request.headers.get("x-forwarded-proto") || "https"}://${request.headers.get("x-forwarded-host")}` + : request.headers.get("origin") || "http://localhost:3000"; + const finalReturnUrl = return_url || `${origin}/paid`; + + const clientIp = + request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || + request.headers.get("x-real-ip") || + ""; + + // zpay:直接走 redirect,不先调 payh5(避免 payh5 创建 zpay 订单时阻塞超时) + // payjsapi 的 payh5/redirect 可独立调用,内部自建订单。digital/cnomadcna 仍用 payh5+redirect 流程,路由隔离互不影响。 + if (effectiveProvider === "zpay") { + const redirectPayload = { + user_id, + ...(wechat_userid ? { wechat_userid } : {}), + site_id: "vip", + total_fee, + type, + channel, + return_url: finalReturnUrl, + device, + provider: "zpay", + ...(clientIp && { client_ip: clientIp }), + }; + const redirectUrl = `${apiUrl}/nomadvip/payh5/redirect`; + const redirectTimeout = Number(process.env.PAYJSAPI_REDIRECT_TIMEOUT) || 60000; + console.log("[pay] zpay 直接 redirect url=%s timeout=%ds", redirectUrl, redirectTimeout / 1000); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), redirectTimeout); + const redirectRes = await fetch(redirectUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(redirectPayload), + redirect: "manual", + signal: controller.signal, + }).finally(() => clearTimeout(timeout)); + + 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 || (preferJson && orderId)) { + const res = NextResponse.json({ + ok: true, + order_id: orderId, + redirect_url: location, + provider: "zpay", + }); + if (orderId) setPayOrderCookie(res, orderId); + setAnonymousUserCookie(res, request, user_id); + return res; + } + const res = NextResponse.redirect(location); + if (orderId) setPayOrderCookie(res, orderId); + setAnonymousUserCookie(res, request, user_id); + return res; + } + } + + const resData = await redirectRes.json().catch(() => ({})); + + if (redirectRes.status === 200 && resData?.use_form) { + const params = (resData.params ?? resData) as Record; + const orderId = String(params?.out_trade_no ?? resData?.order_id ?? "").trim(); + const submitUrl = resData?.pay_url || payConfig.zpaySubmitUrl; + const html = buildPayHtml(submitUrl, params || {}, { + directToCashier: device === "wechat", + displayName: wechatNick || user_id, + avatar: wechatAvatar, + }); + const res = new NextResponse(html, { + status: 200, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + if (orderId) setPayOrderCookie(res, orderId); + setAnonymousUserCookie(res, request, user_id); + return res; + } + + if (redirectRes.status === 200 && resData?.qrcode_mode && resData?.img) { + const userId = String(user_id || "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c); + const userNick = String(wechatNick || userId).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c); + const userAvatar = String(wechatAvatar || "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c); + const returnUrl = String(resData.return_url || finalReturnUrl).replace( + /[&<>"']/g, + (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c + ); + const imgSrc = String(resData.img).replace( + /[&<>"']/g, + (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c + ); + const orderId = String(resData.order_id || "").replace( + /[&<>"']/g, + (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c + ); + const ch = String(resData.channel || "wxpay").toLowerCase(); + const isWx = ch === "wxpay" || ch === "wx" || ch === "wechat"; + const title = isWx ? "微信扫码支付" : "支付宝扫码支付"; + const hint = isWx ? "请使用微信扫描下方二维码完成支付" : "请使用支付宝扫描下方二维码完成支付"; + const esc = (s: string) => + s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c); + const html = ` + +${esc(title)} + + +
+
+

${esc(title)}

+

${esc(hint)}

+ ${userAvatar ? `
${userNick}开通对象:${userNick} · 正在升级 VIP
` : ""} +
+
+ + + + +
+ 5:00 + 分 +
+
+
+ 支付二维码 +
+
+

等待支付中...

+
+
+
✅
+
支付成功
+
感谢您的支持,VIP 权益已开通
+
10 秒后返回首页
+
+
+ +`; + const res = new NextResponse(html, { + status: 200, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + if (orderId) setPayOrderCookie(res, orderId); + setAnonymousUserCookie(res, request, user_id); + return res; + } + + if (redirectRes.status === 400 || redirectRes.status === 500) { + const errMsg = resData?.detail || resData?.msg || "zpay redirect 失败"; + if (wantHtml) { + return new NextResponse(buildErrorHtml(errMsg), { + status: redirectRes.status, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + return NextResponse.json({ ok: false, error: errMsg }, { status: redirectRes.status }); + } + + const errMsg = resData?.detail || resData?.msg || "zpay 未返回有效响应"; + if (wantHtml) { + return new NextResponse(buildErrorHtml(errMsg), { + status: 500, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + return NextResponse.json({ ok: false, error: errMsg }, { status: 500 }); + } + + // xorpay:调用 payh5 获取收银台参数 + const { params, payUrl, provider } = await createPayOrder( + apiUrl, + user_id, + wechat_userid || undefined, + finalReturnUrl, + total_fee, + type, + channel, + clientIp, + effectiveProvider + ); + + if (!params || Object.keys(params).length === 0) { + if (wantHtml) { + return new NextResponse(buildErrorHtml("支付参数为空"), { + status: 500, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + return NextResponse.json({ ok: false, error: "支付参数为空" }, { status: 500 }); + } + + // wantHtml=0:返回 JSON,供微信 fetch 后直接提交表单(无中转页) + if (!wantHtml) { + const orderId = String(params?.order_id || params?.out_trade_no || "").trim(); + const res = NextResponse.json({ + ok: true, + params, + payUrl: provider === "xorpay" ? payUrl : payConfig.zpaySubmitUrl, + provider, + order_id: orderId, + }); + if (orderId) setPayOrderCookie(res, orderId); + setAnonymousUserCookie(res, request, user_id); + return res; + } + + // xorpay:直接 payh5 返回收银台参数,无需 redirect 中转 + const submitUrl = provider === "xorpay" ? payUrl : payConfig.zpaySubmitUrl; + if (provider === "xorpay") { + const orderId = String(params?.order_id || params?.out_trade_no || "").trim(); + const html = buildPayHtml(submitUrl, params as Record, { + directToCashier: device === "wechat" || device === "h5", + displayName: wechatNick || user_id, + avatar: wechatAvatar, + }); + const res = new NextResponse(html, { + status: 200, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + if (orderId) setPayOrderCookie(res, orderId); + setAnonymousUserCookie(res, request, user_id); + return res; + } + + return NextResponse.json({ ok: false, error: "支付渠道异常" }, { status: 500 }); + } catch (e) { + const err = e instanceof Error ? e : new Error(String(e)); + const msg = err.message || ""; + const payjsapiHint = + "请确认 payjsapi 已启动且 nomadvip 能访问。同机部署可设 PAYMENT_API_INTERNAL_URL=http://127.0.0.1:8007"; + const hint = + msg.includes("fetch") || msg.includes("ECONNREFUSED") + ? payjsapiHint + : err.name === "AbortError" + ? `请求超时(30s),${payjsapiHint}` + : msg; + console.error("Pay API error:", err); + const errorMsg = `支付请求失败: ${hint}`; + const ct = request.headers.get("content-type") || ""; + const isForm = ct.includes("form") || ct.includes("x-www-form-urlencoded"); + if (isForm) { + return new NextResponse(buildErrorHtml(errorMsg), { + status: 500, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + return NextResponse.json({ ok: false, error: errorMsg }, { status: 500 }); + } +} diff --git a/app/api/pay/status/route.ts b/app/api/pay/status/route.ts new file mode 100644 index 0000000..07a39f7 --- /dev/null +++ b/app/api/pay/status/route.ts @@ -0,0 +1,78 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config"; +import { queryXorPayOrderStatus } from "@vip/app/lib/xorpayStatus"; +import { queryZPayOrderStatus } from "@vip/app/lib/zpayStatus"; + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); +} + +export async function GET(request: NextRequest) { + const orderId = request.nextUrl.searchParams.get("order_id"); + if (!orderId) { + return NextResponse.json({ ok: false, error: "missing order_id" }, { status: 400 }); + } + + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + const apiUrl = resolvePayApiUrl(request); + const url = `${apiUrl}/nomadvip/order_status?order_id=${encodeURIComponent(orderId)}`; + console.log("[pay/status] request order_id=%s host=%s url=%s", orderId, hostHeader, url); + + 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; + console.log( + "[pay/status] result order_id=%s paid=%s status=%s", + orderId, + paid, + res.status + ); + if (paid) { + return NextResponse.json({ ok: true, paid: true }); + } + } catch (error) { + console.log( + "[pay/status] error order_id=%s error=%s", + orderId, + error instanceof Error ? error.message : String(error) + ); + } + + const xorpay = await queryXorPayOrderStatus(orderId, 5000); + console.log( + "[pay/status] xorpay fallback order_id=%s paid=%s status=%s error=%s url=%s", + orderId, + !!xorpay?.paid, + xorpay?.status || "", + xorpay?.error || "", + xorpay?.url || "" + ); + if (xorpay?.paid) { + return NextResponse.json({ ok: true, paid: true }); + } + + const zpay = await queryZPayOrderStatus(orderId, 5000); + console.log( + "[pay/status] zpay fallback order_id=%s paid=%s status=%s error=%s url=%s", + orderId, + !!zpay?.paid, + zpay?.status || "", + zpay?.error || "", + zpay?.url || "" + ); + if (zpay?.paid) { + return NextResponse.json({ ok: true, paid: true }); + } + return NextResponse.json({ ok: true, paid: false }); +} diff --git a/app/api/promo/recognize-discount/route.ts b/app/api/promo/recognize-discount/route.ts new file mode 100644 index 0000000..2db0023 --- /dev/null +++ b/app/api/promo/recognize-discount/route.ts @@ -0,0 +1,52 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config"; + +function resolvePayApiUrl(request: NextRequest): string { + const hostHeader = + request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + getPaymentConfig().apiUrl + ).replace(/\/$/, ""); +} + +export async function POST(request: NextRequest) { + try { + const formData = await request.formData(); + const image = formData.get("image"); + if (!(image instanceof File)) { + return NextResponse.json( + { ok: false, error: "缺少图片文件 image" }, + { status: 400 } + ); + } + + const payload = new FormData(); + payload.append("image", image, image.name || "proof.jpg"); + + const apiUrl = resolvePayApiUrl(request); + const res = await fetch(`${apiUrl}/nomadvip/recognize_discount_proof`, { + method: "POST", + body: payload, + cache: "no-store", + }); + + const data = await res.json().catch(() => ({})); + if (!res.ok) { + return NextResponse.json( + { ok: false, error: data?.error || "识别服务异常" }, + { status: res.status } + ); + } + return NextResponse.json(data); + } catch (error) { + return NextResponse.json( + { + ok: false, + error: error instanceof Error ? error.message : "识别请求失败", + }, + { status: 500 } + ); + } +} + diff --git a/app/api/vip/_helpers.ts b/app/api/vip/_helpers.ts new file mode 100644 index 0000000..736993a --- /dev/null +++ b/app/api/vip/_helpers.ts @@ -0,0 +1,529 @@ +import { SITE_ID, getPocketBaseConfig } from "@vip/config/services.config"; + +const VIP_EMAIL_LINK_COLLECTION = "vip_email_link"; +const PB_FETCH_TIMEOUT = + Number(process.env.POCKETBASE_FETCH_TIMEOUT) || + (process.env.NODE_ENV === "development" ? 30_000 : 15_000); +const PB_ADMIN_TOKEN_TTL_MS = Number(process.env.POCKETBASE_ADMIN_TOKEN_TTL_MS) || 55_000; + +let adminTokenCache: { token: string; expiresAt: number } | null = null; + +type PBRecord = Record; + +function getPBBaseUrl(): string { + return getPocketBaseConfig().url.replace(/\/$/, ""); +} + +function escapeFilterValue(value: string): string { + return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); +} + +function uniqueStrings(values: Array): string[] { + return Array.from( + new Set( + values + .map((value) => (typeof value === "string" ? value.trim() : "")) + .filter(Boolean) + ) + ); +} + +async function pbFetch(input: string, init: RequestInit = {}): Promise { + const signal = init.signal ?? AbortSignal.timeout(PB_FETCH_TIMEOUT); + return fetch(input, { ...init, signal }); +} + +async function listRecords( + collection: string, + filter: string, + adminToken: string, + options: { perPage?: number; sort?: string } = {} +): Promise { + const url = new URL(`${getPBBaseUrl()}/api/collections/${collection}/records`); + url.searchParams.set("filter", filter); + url.searchParams.set("perPage", String(options.perPage ?? 20)); + if (options.sort) { + url.searchParams.set("sort", options.sort); + } + + const res = await pbFetch(url.toString(), { + headers: { Authorization: `Bearer ${adminToken}` }, + cache: "no-store", + }); + if (!res.ok) { + return []; + } + + const data = await res.json().catch(() => ({})); + return Array.isArray(data?.items) ? data.items : []; +} + +async function createRecord( + collection: string, + adminToken: string, + body: Record +): Promise { + await pbFetch(`${getPBBaseUrl()}/api/collections/${collection}/records`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify(body), + cache: "no-store", + }); +} + +async function patchRecord( + collection: string, + recordId: string, + adminToken: string, + body: Record +): Promise { + await pbFetch( + `${getPBBaseUrl()}/api/collections/${collection}/records/${recordId}`, + { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${adminToken}`, + }, + body: JSON.stringify(body), + cache: "no-store", + } + ); +} + +async function deleteRecord( + collection: string, + recordId: string, + adminToken: string +): Promise { + await pbFetch( + `${getPBBaseUrl()}/api/collections/${collection}/records/${recordId}`, + { + method: "DELETE", + headers: { Authorization: `Bearer ${adminToken}` }, + cache: "no-store", + } + ); +} + +async function getRecord( + collection: string, + recordId: string, + adminToken: string +): Promise { + const res = await pbFetch( + `${getPBBaseUrl()}/api/collections/${collection}/records/${recordId}`, + { + headers: { Authorization: `Bearer ${adminToken}` }, + cache: "no-store", + } + ); + if (!res.ok) { + return null; + } + + return (await res.json().catch(() => null)) as PBRecord | null; +} + +function isVipExpired(expiresAt: unknown): boolean { + if (typeof expiresAt !== "string" || !expiresAt.trim()) { + return false; + } + + const timestamp = Date.parse(expiresAt); + return Number.isFinite(timestamp) ? timestamp < Date.now() : false; +} + +export function isAnonymousUserId( + value: string | null | undefined +): value is string { + return !!value && /^user\d+$/.test(value); +} + +export async function getAdminToken(): Promise { + const email = process.env.POCKETBASE_EMAIL; + const password = process.env.POCKETBASE_PASSWORD; + if (!email || !password) { + return null; + } + + if (adminTokenCache && adminTokenCache.expiresAt > Date.now()) { + return adminTokenCache.token; + } + + const baseUrl = getPBBaseUrl(); + const paths = [ + "/api/admins/auth-with-password", + "/api/collections/_superusers/auth-with-password", + ]; + + for (const path of paths) { + const res = await pbFetch(`${baseUrl}${path}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ identity: email, password }), + cache: "no-store", + }); + if (!res.ok) { + continue; + } + + const data = await res.json().catch(() => ({})); + if (typeof data?.token === "string" && data.token) { + adminTokenCache = { + token: data.token, + expiresAt: Date.now() + PB_ADMIN_TOKEN_TTL_MS, + }; + return data.token; + } + } + + return null; +} + +export async function listSiteVipByUserId( + adminToken: string, + userId: string +): Promise { + const safeUserId = escapeFilterValue(userId); + const safeSiteId = escapeFilterValue(SITE_ID); + return listRecords( + "site_vip", + `user_id = "${safeUserId}" && site_id = "${safeSiteId}"`, + adminToken, + { perPage: 500, sort: "-created" } + ); +} + +export async function listSiteVipByOrderId( + adminToken: string, + orderId: string +): Promise { + const safeOrderId = escapeFilterValue(orderId); + const safeSiteId = escapeFilterValue(SITE_ID); + return listRecords( + "site_vip", + `order_id = "${safeOrderId}" && site_id = "${safeSiteId}"`, + adminToken, + { perPage: 500, sort: "-created" } + ); +} + +async function listPaymentsByOrderId( + adminToken: string, + orderId: string +): Promise { + const safeOrderId = escapeFilterValue(orderId); + return listRecords( + "payments", + `order_id = "${safeOrderId}" && type = "vip"`, + adminToken, + { perPage: 20, sort: "-created" } + ); +} + +export async function getActiveSiteVipRecord( + adminToken: string, + userId: string +): Promise { + const records = await listSiteVipByUserId(adminToken, userId); + for (const record of records) { + if (!isVipExpired(record.expires_at)) { + return record; + } + } + return null; +} + +export async function checkSiteVipByUserId( + adminToken: string, + userId: string +): Promise { + return !!(await getActiveSiteVipRecord(adminToken, userId)); +} + +export async function getLatestVipPayment( + adminToken: string, + userId: string +): Promise { + const safeUserId = escapeFilterValue(userId); + const records = await listRecords( + "payments", + `user_id = "${safeUserId}" && type = "vip"`, + adminToken, + { perPage: 1, sort: "-created" } + ); + return records[0] ?? null; +} + +export async function checkPaymentsByUserId( + adminToken: string, + userId: string +): Promise { + return !!(await getLatestVipPayment(adminToken, userId)); +} + +export async function hasVipByUserId( + adminToken: string, + userId: string +): Promise { + if (!userId) { + return false; + } + if (await checkSiteVipByUserId(adminToken, userId)) { + return true; + } + return checkPaymentsByUserId(adminToken, userId); +} + +export async function ensureSiteVipForUser( + adminToken: string, + fromUserId: string, + toUserId: string +): Promise { + if (!fromUserId || !toUserId || fromUserId === toUserId) { + return; + } + + const sourceRecords = await listSiteVipByUserId(adminToken, fromUserId); + const targetRecords = await listSiteVipByUserId(adminToken, toUserId); + const latestPayment = await getLatestVipPayment(adminToken, fromUserId); + const orderId = + typeof latestPayment?.order_id === "string" ? latestPayment.order_id.trim() : ""; + const orderRecords = orderId + ? await listSiteVipByOrderId(adminToken, orderId) + : []; + + const canonicalRecord = + targetRecords[0] ?? sourceRecords[0] ?? orderRecords[0] ?? null; + const canonicalRecordId = + typeof canonicalRecord?.id === "string" ? canonicalRecord.id : ""; + + if (canonicalRecordId) { + const nextOrderId = + orderId || + (typeof canonicalRecord?.order_id === "string" + ? canonicalRecord.order_id.trim() + : ""); + + const body: Record = { user_id: toUserId, site_id: SITE_ID }; + if (nextOrderId) { + body.order_id = nextOrderId; + } + + await patchRecord("site_vip", canonicalRecordId, adminToken, body); + + const duplicateIds = new Set(); + for (const record of [...targetRecords, ...sourceRecords, ...orderRecords]) { + const recordId = typeof record.id === "string" ? record.id : ""; + if (recordId && recordId !== canonicalRecordId) { + duplicateIds.add(recordId); + } + } + + for (const recordId of duplicateIds) { + await deleteRecord("site_vip", recordId, adminToken); + } + return; + } + + if (!orderId) { + return; + } + + await createRecord("site_vip", adminToken, { + user_id: toUserId, + site_id: SITE_ID, + order_id: orderId, + }); +} + +export async function upsertVipEmailLink( + adminToken: string, + email: string, + userId: string, + anonymousUserId?: string +): Promise { + if (!email || !userId) { + return; + } + + const normalizedEmail = email.trim().toLowerCase(); + const safeEmail = escapeFilterValue(normalizedEmail); + const records = await listRecords( + VIP_EMAIL_LINK_COLLECTION, + `email = "${safeEmail}"`, + adminToken, + { perPage: 1 } + ); + + const body: Record = { + email: normalizedEmail, + user_id: userId, + }; + if (anonymousUserId) { + body.anonymous_user_id = anonymousUserId; + } + + const recordId = typeof records[0]?.id === "string" ? records[0].id : ""; + if (recordId) { + await patchRecord(VIP_EMAIL_LINK_COLLECTION, recordId, adminToken, body); + return; + } + + await createRecord(VIP_EMAIL_LINK_COLLECTION, adminToken, body); +} + +export async function findVipEmailLinkByEmail( + adminToken: string, + email: string +): Promise { + const candidates = uniqueStrings([email, email.toLowerCase()]); + for (const candidate of candidates) { + const safeEmail = escapeFilterValue(candidate); + const records = await listRecords( + VIP_EMAIL_LINK_COLLECTION, + `email = "${safeEmail}"`, + adminToken, + { perPage: 1 } + ); + if (records[0]) { + return records[0]; + } + } + return null; +} + +export async function findVipEmailLinkByUserId( + adminToken: string, + userId: string +): Promise { + const safeUserId = escapeFilterValue(userId); + const records = await listRecords( + VIP_EMAIL_LINK_COLLECTION, + `user_id = "${safeUserId}"`, + adminToken, + { perPage: 1 } + ); + return records[0] ?? null; +} + +export async function findVipEmailLinkByAnonymousUserId( + adminToken: string, + anonymousUserId: string +): Promise { + const filters = uniqueStrings([ + `anonymous_user_id = "${escapeFilterValue(anonymousUserId)}"`, + isAnonymousUserId(anonymousUserId) + ? `user_id = "${escapeFilterValue(anonymousUserId)}"` + : null, + ]); + + for (const filter of filters) { + const records = await listRecords( + VIP_EMAIL_LINK_COLLECTION, + filter, + adminToken, + { perPage: 1 } + ); + if (records[0]) { + return records[0]; + } + } + + return null; +} + +export async function getUserEmailById( + adminToken: string, + userId: string +): Promise { + const record = await getRecord("users", userId, adminToken); + const email = + typeof record?.email === "string" ? record.email.trim().toLowerCase() : ""; + return email || null; +} + +export async function findLinkedMemberFromOrder( + adminToken: string, + anonymousUserId: string +): Promise<{ userId: string; email: string } | null> { + const safeUserId = escapeFilterValue(anonymousUserId); + const payments = await listRecords( + "payments", + `user_id = "${safeUserId}" && type = "vip"`, + adminToken, + { perPage: 20, sort: "-created" } + ); + + const seenOrders = new Set(); + for (const payment of payments) { + const orderId = + typeof payment.order_id === "string" ? payment.order_id.trim() : ""; + if (!orderId || seenOrders.has(orderId)) { + continue; + } + seenOrders.add(orderId); + + const siteVipRecords = await listSiteVipByOrderId(adminToken, orderId); + for (const record of siteVipRecords) { + const linkedUserId = + typeof record.user_id === "string" ? record.user_id.trim() : ""; + if ( + !linkedUserId || + linkedUserId === anonymousUserId || + isAnonymousUserId(linkedUserId) + ) { + continue; + } + + const email = await getUserEmailById(adminToken, linkedUserId); + if (email) { + return { userId: linkedUserId, email }; + } + } + } + + return null; +} + +export async function findAnonymousUserIdForUser( + adminToken: string, + userId: string +): Promise { + if (isAnonymousUserId(userId)) { + return userId; + } + + const linkRecord = await findVipEmailLinkByUserId(adminToken, userId); + const linkedAnonymousUserId = + typeof linkRecord?.anonymous_user_id === "string" + ? linkRecord.anonymous_user_id.trim() + : ""; + if (isAnonymousUserId(linkedAnonymousUserId)) { + return linkedAnonymousUserId; + } + + const siteVipRecords = await listSiteVipByUserId(adminToken, userId); + for (const record of siteVipRecords) { + const orderId = + typeof record.order_id === "string" ? record.order_id.trim() : ""; + if (!orderId) { + continue; + } + + const payments = await listPaymentsByOrderId(adminToken, orderId); + for (const payment of payments) { + const anonymousUserId = + typeof payment.user_id === "string" ? payment.user_id.trim() : ""; + if (isAnonymousUserId(anonymousUserId)) { + return anonymousUserId; + } + } + } + + return null; +} diff --git a/app/api/vip/check-by-email/route.ts b/app/api/vip/check-by-email/route.ts new file mode 100644 index 0000000..f90b887 --- /dev/null +++ b/app/api/vip/check-by-email/route.ts @@ -0,0 +1,501 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + getApiUrlFromRequest, + getPaymentConfig, + getPocketBaseConfig, +} from "@vip/config/services.config"; +import { + ensureSiteVipForUser, + findAnonymousUserIdForUser, + findVipEmailLinkByEmail, + getAdminToken, + hasVipByUserId, + isAnonymousUserId, + upsertVipEmailLink, +} from "@vip/app/api/vip/_helpers"; + +type PBAuthRecord = { + id: string; + email?: string; +}; + +type PayjsVipEmailResult = { + vip: boolean; + error?: string; + effectiveUserId?: string; + anonymousUserId?: string; + token?: string; + record?: PBAuthRecord; +}; + +type RecoveryResult = { + vip: boolean; + matchedUserId?: string; + anonymousUserId?: string; + source?: string; +}; + +const inflightEmailChecks = new Map>(); + +const PAYJS_CHECK_BY_EMAIL_TIMEOUT = + Number(process.env.PAYJSAPI_CHECK_BY_EMAIL_TIMEOUT) || 20_000; +const PAYJS_CHECK_BY_EMAIL_RETRIES = + Math.max(0, Number(process.env.PAYJSAPI_CHECK_BY_EMAIL_RETRIES) || 1); + +const PB_USER_LOGIN_TIMEOUT_MS = + Number(process.env.POCKETBASE_USER_LOGIN_TIMEOUT_MS) || + (process.env.NODE_ENV === "development" ? 30_000 : 15_000); + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); +} + +function getLocalPayApiUrl(): string { + return ( + process.env.PAYMENT_API_INTERNAL_URL?.trim() || + "http://127.0.0.1:8007" + ).replace(/\/$/, ""); +} + +async function checkVipByEmailFromPayjsapi( + request: NextRequest, + email: string, + password: string, + userId?: string, + wechatUserId?: string +): Promise { + const inflightKey = `${email}::${userId || ""}::${wechatUserId || ""}`; + const existed = inflightEmailChecks.get(inflightKey); + if (existed) { + return existed; + } + + const task = (async () => { + const payConfig = getPaymentConfig(); + const primaryUrl = resolvePayApiUrl(request); + const localUrl = getLocalPayApiUrl(); + const candidates = Array.from( + new Set( + [localUrl, primaryUrl, payConfig.apiUrl] + .map((x) => (x || "").trim().replace(/\/$/, "")) + .filter(Boolean) + ) + ); + + for (const apiUrl of candidates) { + for (let i = 0; i <= PAYJS_CHECK_BY_EMAIL_RETRIES; i += 1) { + try { + const res = await fetch(`${apiUrl}/nomadvip/check_vip_by_email`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email, + password, + ...(userId ? { user_id: userId } : {}), + ...(wechatUserId ? { wechat_userid: wechatUserId } : {}), + }), + cache: "no-store", + signal: AbortSignal.timeout(PAYJS_CHECK_BY_EMAIL_TIMEOUT), + }); + if (!res.ok) { + continue; + } + + const data = await res.json().catch(() => ({})); + if (!data?.vip) { + return { + vip: false, + error: + typeof data?.error === "string" && data.error.trim() + ? data.error.trim() + : undefined, + }; + } + + return { + vip: true, + effectiveUserId: + typeof data?.effectiveUserId === "string" + ? data.effectiveUserId.trim() + : undefined, + anonymousUserId: + typeof data?.anonymousUserId === "string" + ? data.anonymousUserId.trim() + : undefined, + token: typeof data?.token === "string" ? data.token : undefined, + record: data?.record?.id ? data.record : undefined, + }; + } catch (error) { + if (i >= PAYJS_CHECK_BY_EMAIL_RETRIES) { + console.log("[check-by-email] payjsapi request failed url=%s error=%o", apiUrl, error); + } else { + await new Promise((resolve) => setTimeout(resolve, 250 * (i + 1))); + } + } + } + } + return null; + })(); + + inflightEmailChecks.set(inflightKey, task); + try { + return await task; + } finally { + inflightEmailChecks.delete(inflightKey); + } +} + +async function loginPocketBaseUser( + email: string, + password: string +): Promise<{ token: string; record: PBAuthRecord }> { + const pb = getPocketBaseConfig(); + const res = await fetch(`${pb.url}/api/collections/users/auth-with-password`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ identity: email, password }), + cache: "no-store", + signal: AbortSignal.timeout(PB_USER_LOGIN_TIMEOUT_MS), + }); + + if (!res.ok) { + const error = await res.json().catch(() => ({})); + throw new Error(error?.message || "邮箱或密码错误"); + } + + const data = await res.json().catch(() => ({})); + if (!data?.token || !data?.record?.id) { + throw new Error("登录失败"); + } + + return { + token: data.token, + record: data.record, + }; +} + +async function resolveRecovery( + adminToken: string, + email: string, + pbUserId: string, + requestedAnonymousUserId?: string, + payjsResult?: PayjsVipEmailResult | null +): Promise { + if (isAnonymousUserId(requestedAnonymousUserId)) { + const requestUserHasVip = await hasVipByUserId(adminToken, requestedAnonymousUserId); + if (requestUserHasVip) { + return { + vip: true, + matchedUserId: requestedAnonymousUserId, + anonymousUserId: requestedAnonymousUserId, + source: "request_user_id", + }; + } + } + + const [linkRecord, fallbackAnonymousUserId] = await Promise.all([ + findVipEmailLinkByEmail(adminToken, email), + findAnonymousUserIdForUser(adminToken, pbUserId), + ]); + const linkedAnonymousUserId = + typeof linkRecord?.anonymous_user_id === "string" + ? linkRecord.anonymous_user_id.trim() + : fallbackAnonymousUserId ?? ""; + const linkedIds = Array.from( + new Set( + [ + linkedAnonymousUserId, + typeof linkRecord?.user_id === "string" ? linkRecord.user_id.trim() : "", + pbUserId, + ].filter(Boolean) + ) + ); + + if (linkedIds.length) { + const linkedVipChecks = await Promise.all( + linkedIds.map(async (linkedId) => ({ + linkedId, + vip: await hasVipByUserId(adminToken, linkedId), + })) + ); + const hit = linkedVipChecks.find((item) => item.vip); + if (hit) { + return { + vip: true, + matchedUserId: hit.linkedId, + anonymousUserId: isAnonymousUserId(linkedAnonymousUserId) + ? linkedAnonymousUserId + : isAnonymousUserId(hit.linkedId) + ? hit.linkedId + : undefined, + source: "vip_email_link", + }; + } + } + + const pbUserHasVip = await hasVipByUserId(adminToken, pbUserId); + if (pbUserHasVip) { + return { + vip: true, + matchedUserId: pbUserId, + source: "pb_user_id", + }; + } + + const payjsCandidates = Array.from( + new Set( + [ + typeof payjsResult?.effectiveUserId === "string" + ? payjsResult.effectiveUserId.trim() + : "", + typeof payjsResult?.anonymousUserId === "string" + ? payjsResult.anonymousUserId.trim() + : "", + ].filter(Boolean) + ) + ); + + if (payjsCandidates.length) { + const payjsVipChecks = await Promise.all( + payjsCandidates.map(async (candidate) => ({ + candidate, + vip: await hasVipByUserId(adminToken, candidate), + })) + ); + const hit = payjsVipChecks.find((item) => item.vip); + if (hit) { + return { + vip: true, + matchedUserId: hit.candidate, + anonymousUserId: isAnonymousUserId(hit.candidate) + ? hit.candidate + : typeof payjsResult?.anonymousUserId === "string" && + isAnonymousUserId(payjsResult.anonymousUserId.trim()) + ? payjsResult.anonymousUserId.trim() + : undefined, + source: "payjsapi", + }; + } + } + + return { vip: false }; +} + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const email = String(body?.email ?? "").trim().toLowerCase(); + const password = String(body?.password ?? "").trim(); + const requestedAnonymousUserId = String( + body?.user_id ?? body?.anonymousUserId ?? "" + ).trim(); + const wechatUserId = String( + body?.wechat_userid ?? body?.userid ?? "" + ).trim(); + + console.log( + "[check-by-email] request email=%s user_id=%s", + email || "(empty)", + requestedAnonymousUserId || "(empty)" + ); + + if (!email || !password) { + return NextResponse.json( + { ok: false, vip: false, error: "请填写邮箱和密码" }, + { status: 400 } + ); + } + + try { + const adminTokenPromise = getAdminToken().catch((error) => { + console.error("[check-by-email] getAdminToken failed:", error); + return null; + }); + + let authData: { token: string; record: PBAuthRecord } | null = null; + let loginError: string | null = null; + try { + authData = await loginPocketBaseUser(email, password); + } catch (error) { + loginError = error instanceof Error ? error.message : "登录失败"; + } + + let payjsResult: PayjsVipEmailResult | null = null; + + if (!authData) { + payjsResult = await checkVipByEmailFromPayjsapi( + request, + email, + password, + requestedAnonymousUserId || undefined, + wechatUserId || undefined + ); + // PB 登录失败时,尝试使用 payjsapi 返回的 token/record 兜底恢复 + if (payjsResult?.vip && payjsResult.token && payjsResult.record?.id) { + console.log("[check-by-email] fallback by payjsapi token email=%s", email); + return NextResponse.json({ + ok: true, + vip: true, + token: payjsResult.token, + record: payjsResult.record, + effectiveUserId: payjsResult.record.id, + anonymousUserId: payjsResult.anonymousUserId ?? null, + memosAccount: payjsResult.anonymousUserId ?? null, + source: "payjsapi_token_fallback", + }); + } + const msg = loginError || "登录失败"; + return NextResponse.json( + { ok: false, vip: false, error: msg }, + { status: msg.includes("密码") || msg.includes("邮箱") ? 401 : 503 } + ); + } + + const adminToken = await adminTokenPromise; + if (!adminToken) { + // 管理员 token 获取失败时,降级到 payjsapi 结果,避免直接 500 + if (!payjsResult) { + payjsResult = await checkVipByEmailFromPayjsapi( + request, + email, + password, + requestedAnonymousUserId || undefined, + wechatUserId || undefined + ); + } + if (payjsResult?.vip) { + return NextResponse.json({ + ok: true, + vip: true, + token: authData.token, + record: authData.record, + effectiveUserId: authData.record.id, + anonymousUserId: payjsResult.anonymousUserId ?? null, + memosAccount: payjsResult.anonymousUserId ?? null, + source: "payjsapi_degraded", + }); + } + return NextResponse.json( + { + ok: false, + vip: false, + error: + payjsResult?.error || + "服务繁忙,请稍后重试", + }, + { status: 503 } + ); + } + + let recovery = await resolveRecovery( + adminToken, + email, + authData.record.id, + requestedAnonymousUserId || undefined, + payjsResult + ); + + if (!recovery.vip) { + payjsResult = await checkVipByEmailFromPayjsapi( + request, + email, + password, + requestedAnonymousUserId || undefined, + wechatUserId || undefined + ); + recovery = await resolveRecovery( + adminToken, + email, + authData.record.id, + requestedAnonymousUserId || undefined, + payjsResult + ); + } + + if (!recovery.vip) { + console.log( + "[check-by-email] no-vip email=%s pbUserId=%s", + email, + authData.record.id + ); + return NextResponse.json({ + ok: false, + vip: false, + error: payjsResult?.error || + "未找到关联的会员记录,请确认已支付并绑定邮箱;如为历史匿名订单,可填写支付时的 user_id 再登录", + }); + } + + let fallbackAnonymousUserId: string | undefined; + if ( + isAnonymousUserId(requestedAnonymousUserId) && + (await hasVipByUserId(adminToken, requestedAnonymousUserId)) + ) { + fallbackAnonymousUserId = requestedAnonymousUserId; + } else { + fallbackAnonymousUserId = + (await findAnonymousUserIdForUser(adminToken, authData.record.id)) || + (typeof payjsResult?.anonymousUserId === "string" && + isAnonymousUserId(payjsResult.anonymousUserId.trim()) + ? payjsResult.anonymousUserId.trim() + : undefined); + } + + const anonymousUserId = + recovery.anonymousUserId || fallbackAnonymousUserId; + + if (isAnonymousUserId(anonymousUserId)) { + await ensureSiteVipForUser(adminToken, anonymousUserId, authData.record.id); + } + + await upsertVipEmailLink( + adminToken, + email, + authData.record.id, + anonymousUserId + ); + + if (wechatUserId) { + const apiUrl = resolvePayApiUrl(request); + await fetch(`${apiUrl}/nomadvip/wechat_profile`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + user_id: anonymousUserId || authData.record.id, + email, + wechat_userid: wechatUserId, + }), + cache: "no-store", + }).catch(() => null); + } + + console.log( + "[check-by-email] success source=%s pbUserId=%s anonymousUserId=%s", + recovery.source ?? "pocketbase", + authData.record.id, + anonymousUserId ?? "(none)" + ); + + return NextResponse.json({ + ok: true, + vip: true, + token: authData.token, + record: authData.record, + effectiveUserId: authData.record.id, + anonymousUserId: anonymousUserId ?? null, + memosAccount: anonymousUserId ?? null, + source: recovery.source ?? "pocketbase", + }); + } catch (error) { + const message = error instanceof Error ? error.message : "登录失败"; + const status = message.includes("密码") || message.includes("邮箱") ? 401 : 500; + return NextResponse.json( + { ok: false, vip: false, error: message }, + { status } + ); + } +} diff --git a/app/api/vip/check-by-user/route.ts b/app/api/vip/check-by-user/route.ts new file mode 100644 index 0000000..2b1dd8e --- /dev/null +++ b/app/api/vip/check-by-user/route.ts @@ -0,0 +1,327 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config"; +import { + checkPaymentsByUserId, + checkSiteVipByUserId, + findLinkedMemberFromOrder, + findVipEmailLinkByAnonymousUserId, + getAdminToken, + isAnonymousUserId, + upsertVipEmailLink, +} from "@vip/app/api/vip/_helpers"; + +type PayjsVipResult = { + vip: boolean; + email?: string; + linkedUserId?: string; +}; + +const inflightUserChecks = new Map>(); +type UserCheckPayload = { + ok: boolean; + vip: boolean; + alreadyLinked: boolean; + /** 服务端异常/超时时为 true,前端勿据此清空本地已登录 VIP */ + uncertain?: boolean; + email?: string; + linkedUserId?: string; +}; +const inflightUserRequests = new Map< + string, + Promise +>(); +const userCheckResultCache = new Map< + string, + { + expiresAt: number; + payload: UserCheckPayload; + } +>(); +const USER_CHECK_CACHE_TTL_MS = Number(process.env.CHECK_BY_USER_CACHE_TTL_MS) || 10_000; + +async function fetchPayjsVipWithRetry( + url: string, + timeoutMs: number, + retries: number +): Promise { + let lastError: unknown = null; + for (let i = 0; i <= retries; i += 1) { + try { + const res = await fetch(url, { + cache: "no-store", + signal: AbortSignal.timeout(timeoutMs), + }); + return res; + } catch (error) { + lastError = error; + if (i < retries) { + await new Promise((resolve) => setTimeout(resolve, 250 * (i + 1))); + } + } + } + throw lastError instanceof Error ? lastError : new Error("payjsapi fetch failed"); +} + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); +} + +async function checkVipFromPayjsapi( + request: NextRequest, + userId: string +): Promise { + const existed = inflightUserChecks.get(userId); + if (existed) { + return existed; + } + + const task = (async () => { + try { + const apiUrl = resolvePayApiUrl(request); + const url = `${apiUrl}/nomadvip/check_vip?user_id=${encodeURIComponent( + userId + )}`; + console.log("[check-by-user] payjsapi request user_id=%s url=%s", userId, url); + const checkTimeout = Number(process.env.PAYJSAPI_CHECK_TIMEOUT) || 15_000; + const retries = Math.max(0, Number(process.env.PAYJSAPI_CHECK_RETRIES) || 1); + const res = await fetchPayjsVipWithRetry(url, checkTimeout, retries); + if (!res) { + return null; + } + if (!res.ok) { + console.log( + "[check-by-user] payjsapi non-ok user_id=%s status=%s", + userId, + res.status + ); + return null; + } + + const data = await res.json().catch(() => ({})); + const result = { + vip: !!data?.vip, + email: + typeof data?.email === "string" && data.email.trim() + ? data.email.trim().toLowerCase() + : undefined, + linkedUserId: + typeof data?.linked_user_id === "string" && data.linked_user_id.trim() + ? data.linked_user_id.trim() + : undefined, + }; + console.log( + "[check-by-user] payjsapi response user_id=%s vip=%s email=%s", + userId, + result.vip, + result.email ?? "(none)" + ); + return result; + } catch (error) { + console.log( + "[check-by-user] payjsapi request failed user_id=%s error=%s", + userId, + error instanceof Error ? error.message : String(error) + ); + return null; + } + })(); + + inflightUserChecks.set(userId, task); + try { + return await task; + } finally { + inflightUserChecks.delete(userId); + } +} + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const userId = String(body?.user_id ?? body?.userId ?? "").trim(); + + console.log("[check-by-user] request user_id=%s", userId || "(empty)"); + + if (!userId) { + return NextResponse.json( + { ok: false, vip: false, error: "缺少 user_id" }, + { status: 400 } + ); + } + + const cached = userCheckResultCache.get(userId); + if (cached && cached.expiresAt > Date.now()) { + return NextResponse.json(cached.payload); + } + if (cached) { + userCheckResultCache.delete(userId); + } + + const inflight = inflightUserRequests.get(userId); + if (inflight) { + const payload = await inflight; + return NextResponse.json(payload); + } + + const task = (async () => { + let payjsResult: PayjsVipResult | null = null; + let vip = false; + let email: string | null = null; + let linkedUserId: string | undefined; + let vipFromSite = false; + let vipFromPayments = false; + let vipSource = "none"; + + try { + const adminToken = await getAdminToken().catch((error) => { + console.error("[check-by-user] getAdminToken failed:", error); + return null; + }); + if (!adminToken) { + payjsResult = await checkVipFromPayjsapi(request, userId); + vip = !!payjsResult?.vip; + email = payjsResult?.email ?? null; + console.error("[check-by-user] missing PocketBase admin token, fallback to payjs result"); + return { + ok: true, + vip, + alreadyLinked: !!email, + email: email ?? undefined, + }; + } + + if (!vip) { + vipFromSite = await checkSiteVipByUserId(adminToken, userId); + vip = vipFromSite; + if (!vip) { + vipFromPayments = await checkPaymentsByUserId(adminToken, userId); + vip = vipFromPayments; + } + if (vipFromSite) { + vipSource = "pocketbase:site_vip"; + } else if (vipFromPayments) { + vipSource = "pocketbase:payments"; + } + console.log( + "[check-by-user] pb fallback user_id=%s site_vip=%s payments=%s", + userId, + vipFromSite, + vipFromPayments + ); + } + + // 同机 PB 命中则不再打 payjsapi;仅未命中时再走 payjs(与线上极致路径一致) + if (!vip) { + payjsResult = await checkVipFromPayjsapi(request, userId); + if (payjsResult?.vip) { + vip = true; + email = payjsResult.email ?? null; + linkedUserId = payjsResult.linkedUserId; + vipSource = "payjsapi"; + } + } + + if (isAnonymousUserId(userId)) { + const linkRecord = await findVipEmailLinkByAnonymousUserId(adminToken, userId); + const linkEmail = + typeof linkRecord?.email === "string" + ? linkRecord.email.trim().toLowerCase() + : ""; + const linkUserId = + typeof linkRecord?.user_id === "string" ? linkRecord.user_id.trim() : ""; + + // 匿名 user_id 本身可能已迁移到真实用户,需补查映射用户的 VIP + if (!vip && linkUserId && linkUserId !== userId) { + const linkedVip = await checkSiteVipByUserId(adminToken, linkUserId); + const linkedPaymentVip = linkedVip + ? true + : await checkPaymentsByUserId(adminToken, linkUserId); + if (linkedVip || linkedPaymentVip) { + vip = true; + linkedUserId = linkUserId; + vipSource = linkedVip ? "vip_email_link:site_vip" : "vip_email_link:payments"; + } + } + + if (vip && linkEmail) { + email = linkEmail; + if (linkUserId && !isAnonymousUserId(linkUserId)) { + linkedUserId = linkUserId; + } + if (!vipSource || vipSource === "none") { + vipSource = "vip_email_link"; + } + console.log( + "[check-by-user] linked by vip_email_link user_id=%s linkedUserId=%s email=%s", + userId, + linkedUserId || "(none)", + email + ); + } else if (vip) { + const linkedMember = await findLinkedMemberFromOrder(adminToken, userId); + if (linkedMember) { + email = linkedMember.email; + linkedUserId = linkedMember.userId; + await upsertVipEmailLink( + adminToken, + linkedMember.email, + linkedMember.userId, + userId + ); + vipSource = "linked_from_order"; + console.log( + "[check-by-user] linked by order user_id=%s linkedUserId=%s email=%s", + userId, + linkedUserId, + email + ); + } + } + } + + console.log( + "[check-by-user] result user_id=%s vip=%s source=%s alreadyLinked=%s linkedUserId=%s", + userId, + vip, + vipSource, + !!email, + linkedUserId || "(none)" + ); + + return { + ok: true, + vip, + alreadyLinked: !!email, + email: email ?? undefined, + linkedUserId, + }; + } catch (error) { + console.error("[check-by-user] failed:", error); + // 勿伪装成「确定非 VIP」,否则微信/H5 弱网会误清本地态 + return { + ok: false, + vip: false, + alreadyLinked: false, + uncertain: true, + }; + } + })(); + + inflightUserRequests.set(userId, task); + try { + const payload = await task; + // 只缓存命中结果,避免绑定邮箱后的短时 false 缓存导致需要多次刷新才恢复 + if (!payload.uncertain && payload.vip) { + userCheckResultCache.set(userId, { + payload, + expiresAt: Date.now() + USER_CHECK_CACHE_TTL_MS, + }); + } + return NextResponse.json(payload); + } finally { + inflightUserRequests.delete(userId); + } +} diff --git a/app/api/vip/check/route.ts b/app/api/vip/check/route.ts new file mode 100644 index 0000000..861e01c --- /dev/null +++ b/app/api/vip/check/route.ts @@ -0,0 +1,95 @@ +import { NextRequest, NextResponse } from "next/server"; +import { COOKIE_NAME } from "@vip/app/lib/auth-cookie"; +import { + findVipEmailLinkByUserId, + getActiveSiteVipRecord, + getAdminToken, + hasVipByUserId, + isAnonymousUserId, +} from "@vip/app/api/vip/_helpers"; + +type SessionPayload = { + userId?: string; + anonymousUserId?: string; +}; + +function readSessionPayload(request: NextRequest): SessionPayload | null { + const raw = request.cookies.get(COOKIE_NAME)?.value; + if (!raw) { + return null; + } + + try { + return JSON.parse(Buffer.from(raw, "base64url").toString("utf-8")); + } catch { + return null; + } +} + +export async function GET(request: NextRequest) { + const payload = readSessionPayload(request); + const userId = + typeof payload?.userId === "string" ? payload.userId.trim() : ""; + const anonymousUserId = + typeof payload?.anonymousUserId === "string" + ? payload.anonymousUserId.trim() + : ""; + + if (!userId) { + return NextResponse.json({ ok: true, vip: false }); + } + + try { + const adminToken = await getAdminToken(); + if (!adminToken) { + // 未配置 POCKETBASE_EMAIL/PASSWORD 等时无法校验;前端勿据此清空本地已登录态 + return NextResponse.json({ + ok: true, + vip: false, + adminUnavailable: true, + }); + } + + const userRecord = await getActiveSiteVipRecord(adminToken, userId); + if (userRecord) { + return NextResponse.json({ + ok: true, + vip: true, + expires_at: + typeof userRecord.expires_at === "string" ? userRecord.expires_at : null, + }); + } + + if (await hasVipByUserId(adminToken, userId)) { + return NextResponse.json({ ok: true, vip: true, expires_at: null }); + } + + const candidates = isAnonymousUserId(anonymousUserId) + ? [anonymousUserId] + : []; + if (!isAnonymousUserId(userId)) { + const linkRecord = await findVipEmailLinkByUserId(adminToken, userId); + const linkedAnonymousUserId = + typeof linkRecord?.anonymous_user_id === "string" + ? linkRecord.anonymous_user_id.trim() + : ""; + if (isAnonymousUserId(linkedAnonymousUserId)) { + candidates.push(linkedAnonymousUserId); + } + } + + for (const candidate of candidates) { + if (await hasVipByUserId(adminToken, candidate)) { + return NextResponse.json({ ok: true, vip: true, expires_at: null }); + } + } + + return NextResponse.json({ ok: true, vip: false }); + } catch { + return NextResponse.json({ + ok: true, + vip: false, + uncertain: true, + }); + } +} diff --git a/app/api/vip/identity-diagnose/route.ts b/app/api/vip/identity-diagnose/route.ts new file mode 100644 index 0000000..a26ba47 --- /dev/null +++ b/app/api/vip/identity-diagnose/route.ts @@ -0,0 +1,32 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config"; + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = + request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || payConfig.apiUrl + ).replace(/\/$/, ""); +} + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const apiUrl = resolvePayApiUrl(request); + const res = await fetch(`${apiUrl}/nomadvip/identity_diagnose`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body || {}), + cache: "no-store", + }).catch(() => null); + + if (!res) { + return NextResponse.json( + { ok: false, error: "upstream unavailable" }, + { status: 502 } + ); + } + const data = await res.json().catch(() => ({})); + return NextResponse.json(data, { status: res.ok ? 200 : 502 }); +} + diff --git a/app/api/vip/linked-email/route.ts b/app/api/vip/linked-email/route.ts new file mode 100644 index 0000000..f078eb1 --- /dev/null +++ b/app/api/vip/linked-email/route.ts @@ -0,0 +1,115 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config"; +import { + findAnonymousUserIdForUser, + findLinkedMemberFromOrder, + findVipEmailLinkByAnonymousUserId, + findVipEmailLinkByUserId, + getAdminToken, + isAnonymousUserId, + upsertVipEmailLink, +} from "@vip/app/api/vip/_helpers"; + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); +} + +async function getLinkedEmailFromPayjsapi( + request: NextRequest, + userId: string +): Promise { + try { + const apiUrl = resolvePayApiUrl(request); + const res = await fetch( + `${apiUrl}/nomadvip/check_vip?user_id=${encodeURIComponent(userId)}`, + { cache: "no-store", signal: AbortSignal.timeout(5000) } + ); + if (!res.ok) { + return null; + } + + const data = await res.json().catch(() => ({})); + const email = + typeof data?.email === "string" ? data.email.trim().toLowerCase() : ""; + return data?.vip && email ? email : null; + } catch { + return null; + } +} + +export async function GET(request: NextRequest) { + const userId = request.nextUrl.searchParams.get("user_id")?.trim() || ""; + if (!userId) { + return NextResponse.json( + { email: null, error: "缺少 user_id" }, + { status: 400 } + ); + } + + try { + const adminToken = await getAdminToken(); + if (!adminToken) { + return NextResponse.json({ email: null }, { status: 500 }); + } + + const linkRecord = isAnonymousUserId(userId) + ? await findVipEmailLinkByAnonymousUserId(adminToken, userId) + : await findVipEmailLinkByUserId(adminToken, userId); + const linkedEmail = + typeof linkRecord?.email === "string" + ? linkRecord.email.trim().toLowerCase() + : ""; + const anonymousUserId = + typeof linkRecord?.anonymous_user_id === "string" && + isAnonymousUserId(linkRecord.anonymous_user_id.trim()) + ? linkRecord.anonymous_user_id.trim() + : !isAnonymousUserId(userId) + ? await findAnonymousUserIdForUser(adminToken, userId) + : isAnonymousUserId(userId) + ? userId + : null; + if (linkedEmail) { + return NextResponse.json({ + email: linkedEmail, + anonymousUserId, + }); + } + + if (isAnonymousUserId(userId)) { + const linkedMember = await findLinkedMemberFromOrder(adminToken, userId); + if (linkedMember) { + await upsertVipEmailLink( + adminToken, + linkedMember.email, + linkedMember.userId, + userId + ); + return NextResponse.json({ + email: linkedMember.email, + anonymousUserId: userId, + }); + } + } + + const payjsEmail = await getLinkedEmailFromPayjsapi(request, userId); + if (payjsEmail) { + if (anonymousUserId && !isAnonymousUserId(userId)) { + await upsertVipEmailLink(adminToken, payjsEmail, userId, anonymousUserId); + } + return NextResponse.json({ + email: payjsEmail, + anonymousUserId: anonymousUserId ?? (isAnonymousUserId(userId) ? userId : null), + }); + } + + return NextResponse.json({ email: null, anonymousUserId: anonymousUserId ?? null }); + } catch (error) { + console.error("[linked-email] failed:", error); + return NextResponse.json({ email: null, anonymousUserId: null }, { status: 500 }); + } +} diff --git a/app/api/vip/wechat-profile/route.ts b/app/api/vip/wechat-profile/route.ts new file mode 100644 index 0000000..8a218dd --- /dev/null +++ b/app/api/vip/wechat-profile/route.ts @@ -0,0 +1,29 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config"; + +function resolvePayApiUrl(request: NextRequest): string { + const payConfig = getPaymentConfig(); + const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host"); + return ( + (hostHeader ? getApiUrlFromRequest(hostHeader) : null) || + payConfig.apiUrl + ).replace(/\/$/, ""); +} + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})); + const apiUrl = resolvePayApiUrl(request); + const res = await fetch(`${apiUrl}/nomadvip/wechat_profile`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body || {}), + cache: "no-store", + }).catch(() => null); + + if (!res) { + return NextResponse.json({ ok: false, found: false, error: "upstream unavailable" }, { status: 502 }); + } + const data = await res.json().catch(() => ({})); + return NextResponse.json(data, { status: res.ok ? 200 : 502 }); +} + diff --git a/app/community/profile/page.tsx b/app/community/profile/page.tsx index 82f9fc0..d6f07f4 100644 --- a/app/community/profile/page.tsx +++ b/app/community/profile/page.tsx @@ -95,7 +95,7 @@ export default function ProfilePage() { useEffect(() => { if (!token) { - router.push("/community/login?next=/profile"); + router.push("/community/login?next=/community/profile"); return; } setLoading(true); diff --git a/app/layout.tsx b/app/layout.tsx index 6e73330..b3fe392 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -56,6 +56,7 @@ export default function RootLayout({ diff --git a/app/vip/HomeClient.tsx b/app/vip/HomeClient.tsx new file mode 100644 index 0000000..b8ab9e1 --- /dev/null +++ b/app/vip/HomeClient.tsx @@ -0,0 +1,1036 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { triggerPay } from "@vip/app/lib/triggerPay"; +import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv"; +import { usePayStatusPoll } from "@vip/app/lib/usePayStatusPoll"; +import { VipLayout } from "@vip/app/vip/components/VipLayout"; +import { LandingPage } from "@vip/app/vip/components/LandingPage"; +import { DashboardPage } from "@vip/app/vip/components/DashboardPage"; + +// 渠道规则:pc/手机浏览器 -> zpay,仅微信内 -> xorpay +const DEFAULT_EMAIL_PASSWORD = "12345678"; +const ANONYMOUS_USER_COOKIE = "nomadvip_anon_uid"; +const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30; +const PAY_ORDER_COOKIE = "nomadvip_pay_order"; +const PAY_ORDER_MAX_AGE = 60 * 15; +const EMAIL_VERIFY_TS_KEY = "emailVerifyAt"; +const EMAIL_VERIFY_COOLDOWN_MS = 60 * 1000; + +function getStorage(key: string): string | null { + if (typeof window === "undefined") return null; + return localStorage.getItem(key); +} + +function setStorage(key: string, value: string): void { + if (typeof window === "undefined") return; + localStorage.setItem(key, value); +} + +function removeStorage(key: string): void { + if (typeof window === "undefined") return; + localStorage.removeItem(key); +} + +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 setAnonymousUserCookie(userId: string): void { + if (typeof document === "undefined") return; + if (!/^user\d+$/.test(userId)) return; + const secure = window.location.protocol === "https:" ? "; Secure" : ""; + document.cookie = `${ANONYMOUS_USER_COOKIE}=${encodeURIComponent( + userId + )}; Path=/; Max-Age=${ANONYMOUS_USER_COOKIE_MAX_AGE}; SameSite=Lax${secure}`; +} + +function clearCookie(name: string): void { + if (typeof document === "undefined") return; + const secure = window.location.protocol === "https:" ? "; Secure" : ""; + document.cookie = `${name}=; Path=/; Max-Age=0; SameSite=Lax${secure}`; +} + +function clearAnonymousUserCookie(): void { + clearCookie(ANONYMOUS_USER_COOKIE); +} + +function getWechatUserIdFromStorage(): string { + return ( + (getStorage("wechatUserId") || "").trim() || + (getStorage("userid") || "").trim() + ); +} + +function setPayOrderCookie(orderId: string): void { + if (typeof document === "undefined") return; + const normalizedOrderId = orderId.trim(); + if (!normalizedOrderId) return; + const secure = window.location.protocol === "https:" ? "; Secure" : ""; + document.cookie = `${PAY_ORDER_COOKIE}=${encodeURIComponent( + `${normalizedOrderId}|${Date.now()}` + )}; Path=/; Max-Age=${PAY_ORDER_MAX_AGE}; SameSite=Lax${secure}`; +} + +function savePendingOrder(orderId: string): void { + const normalizedOrderId = orderId.trim(); + if (!normalizedOrderId) return; + setPayOrderCookie(normalizedOrderId); + setStorage(PAY_ORDER_COOKIE, `${normalizedOrderId}|${Date.now()}`); +} + +function clearPendingOrder(): void { + clearCookie(PAY_ORDER_COOKIE); + removeStorage(PAY_ORDER_COOKIE); +} + +function getPendingOrderId(): string | null { + const raw = getCookie(PAY_ORDER_COOKIE) || getStorage(PAY_ORDER_COOKIE); + if (!raw) return null; + const [orderRaw, tsRaw] = raw.split("|"); + const orderId = orderRaw?.trim() || ""; + const ts = Number(tsRaw || "0"); + // localStorage 里的 pending 标记可能长期残留,超过有效期直接清理避免阻塞恢复链路 + if (!orderId || !Number.isFinite(ts) || ts <= 0) { + clearPendingOrder(); + return null; + } + if (Date.now() - ts > PAY_ORDER_MAX_AGE * 1000) { + clearPendingOrder(); + return null; + } + return orderId; +} + +type VipProbeResult = "yes" | "no" | "unknown"; + +/** 仅当明确 yes/no;弱网/5xx/服务端 uncertain 一律 unknown,禁止用来清空本地 VIP */ +function probeFromCheckByUserBody( + data: Record | null, + resOk: boolean +): VipProbeResult { + if (!resOk || !data || typeof data !== "object") return "unknown"; + if (data.uncertain === true) return "unknown"; + if (data.vip === true) return "yes"; + if (data.ok === true && data.vip === false) return "no"; + if (data.vip === false && data.ok !== false) return "no"; + return "unknown"; +} + +async function probeCheckByUserId(userId: string): Promise { + const trimmed = userId.trim(); + if (!trimmed) return "unknown"; + try { + const res = await fetch("/api/vip/check-by-user", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ user_id: trimmed }), + credentials: "same-origin", + cache: "no-store", + }); + const data = (await res.json().catch(() => null)) as Record | null; + return probeFromCheckByUserBody(data, res.ok); + } catch { + return "unknown"; + } +} + +async function probeSessionVip(): Promise { + try { + const res = await fetch("/api/vip/check", { + credentials: "include", + cache: "no-store", + }); + const data = (await res.json().catch(() => null)) as Record | null; + if (!res.ok) return "unknown"; + if (!data || typeof data !== "object") return "unknown"; + if (data.adminUnavailable === true) return "unknown"; + if (data.uncertain === true) return "unknown"; + if (data.vip === true) return "yes"; + return "no"; + } catch { + return "unknown"; + } +} + +/** 仅在本组件内使用(由 page.tsx dynamic ssr:false 仅客户端挂载,首帧可读 localStorage) */ +function readVipBootstrapState(): { + paidType: string | null; + userName: string | null; + userEmail: string | null; +} { + if (typeof window === "undefined") { + return { paidType: null, userName: null, userEmail: null }; + } + const localType = localStorage.getItem("paidType"); + const localUserName = localStorage.getItem("userName"); + const localUserEmail = localStorage.getItem("userEmail"); + const localUserId = localStorage.getItem("userId"); + if ( + localType === "vip" && + (localUserName || localUserEmail) && + localUserId + ) { + return { + paidType: localType, + userName: localUserEmail || localUserName || "", + userEmail: + localUserEmail || + (localUserName?.includes("@") ? localUserName : null), + }; + } + return { paidType: null, userName: null, userEmail: null }; +} + +/** + * 首页:首帧以 localStorage 为准展示 VIP 控制台或访客落地页;init 仅后台同步/校验, + * 仅在服务端明确「非 VIP」等异常时更新状态(见 verifyInBackground / probe)。 + */ +export default function HomeClient() { + const [paidType, setPaidType] = useState( + () => readVipBootstrapState().paidType + ); + const [userName, setUserName] = useState( + () => readVipBootstrapState().userName + ); + const [userEmail, setUserEmail] = useState( + () => readVipBootstrapState().userEmail + ); + const [payPendingOrderId, setPayPendingOrderId] = useState(null); + const [wechatNick, setWechatNick] = useState(null); + const [wechatAvatar, setWechatAvatar] = useState(null); + + const savePaidType = useCallback((type: string | null) => { + if (type) setStorage("paidType", type); + else removeStorage("paidType"); + setPaidType(type); + }, []); + + const saveUserName = useCallback((name: string) => { + setStorage("userName", name); + setUserName(name); + }, []); + + const resolveVipLookupUserId = useCallback((fallback?: string | null): string => { + // 业务优先级:email > 真实userid > user_id + // check-by-user 仅接收 user_id 字段,因此这里至少保证 userid > user_id + const wechatUserId = getWechatUserIdFromStorage(); + if (wechatUserId) return wechatUserId; + return (fallback || "").trim(); + }, []); + + const recoverAnonymousUserId = useCallback( + async (params: { userId?: string; email?: string; wechatUserId?: string }) => { + const payload: Record = {}; + if (params.userId?.trim()) payload.user_id = params.userId.trim(); + if (params.email?.trim()) payload.email = params.email.trim().toLowerCase(); + if (params.wechatUserId?.trim()) payload.wechat_userid = params.wechatUserId.trim(); + if (!payload.user_id && !payload.email && !payload.wechat_userid) return null; + + try { + const res = await fetch("/api/vip/identity-diagnose", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + credentials: "same-origin", + cache: "no-store", + }); + const data = await res.json().catch(() => ({})); + const candidate = [ + data?.resolved?.linked_anonymous_user_id, + data?.vip_email_link?.by_anonymous_user_id?.anonymous_user_id, + data?.vip_email_link?.by_email?.anonymous_user_id, + data?.payments?.by_user_id?.user_id, + data?.payments?.by_linked_user_id?.user_id, + ].find((x) => typeof x === "string" && /^user\d+$/.test(x.trim())); + return typeof candidate === "string" ? candidate.trim() : null; + } catch { + return null; + } + }, + [] + ); + + const syncWechatProfile = useCallback(async () => { + const params = new URLSearchParams(window.location.search); + const urlWechatUserId = + params.get("userid")?.trim() || + params.get("wechat_userid")?.trim() || + ""; + if (urlWechatUserId) { + // 兼容历史字段:userid(微信私信真实用户ID) + setStorage("userid", urlWechatUserId); + setStorage("wechatUserId", urlWechatUserId); + // 安全要求:落本地后立即去掉 URL 中敏感 userid 参数,避免被转发扩散 + const cleanPath = window.location.pathname || "/"; + window.location.replace(cleanPath); + return; + } + const wechatUserId = + (getStorage("wechatUserId") || "").trim() || + (getStorage("userid") || "").trim(); + if (!wechatUserId) return; + + const userId = getStorage("userId") || ""; + const userEmail = (getStorage("userEmail") || "").trim().toLowerCase(); + try { + const res = await fetch("/api/vip/wechat-profile", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + user_id: userId || undefined, + email: userEmail || undefined, + userid: wechatUserId, + wechat_userid: wechatUserId, + }), + credentials: "same-origin", + cache: "no-store", + }); + const data = await res.json().catch(() => ({})); + const profile = data?.profile || null; + const relations = data?.relations || null; + const nickname = + typeof profile?.nickname === "string" ? profile.nickname.trim() : ""; + const avatar = + typeof profile?.avatar === "string" ? profile.avatar.trim() : ""; + const linkedAnonymousUserId = + typeof relations?.linked_anonymous_user_id === "string" + ? relations.linked_anonymous_user_id.trim() + : typeof relations?.anonymous_user_id === "string" + ? relations.anonymous_user_id.trim() + : ""; + const linkedPbUserId = + typeof relations?.linked_pb_user_id === "string" + ? relations.linked_pb_user_id.trim() + : typeof relations?.pb_user_id === "string" + ? relations.pb_user_id.trim() + : ""; + const relationUserId = + typeof relations?.user_id === "string" ? relations.user_id.trim() : ""; + const linkedEmail = + typeof relations?.linked_email === "string" + ? relations.linked_email.trim().toLowerCase() + : typeof relations?.email === "string" + ? relations.email.trim().toLowerCase() + : ""; + const hasVipFromRelation = + relations?.has_vip_by_user_id === true || + relations?.has_vip_by_pb_user === true || + relations?.has_vip_by_wechat_userid === true || + relations?.has_vip_by_linked_user === true; + if (/^user\d+$/.test(linkedAnonymousUserId)) { + setStorage("userId", linkedAnonymousUserId); + setStorage("memosAccount", linkedAnonymousUserId); + setAnonymousUserCookie(linkedAnonymousUserId); + } + // 关键修复:若 wechat_profile 已确认关联到 VIP 用户,立即回填关联 user_id 并进入 VIP 态 + if (hasVipFromRelation) { + const resolvedVipUserId = + linkedPbUserId || relationUserId || linkedAnonymousUserId || wechatUserId; + if (resolvedVipUserId) { + setStorage("userId", resolvedVipUserId); + if (/^user\d+$/.test(resolvedVipUserId)) { + setStorage("memosAccount", resolvedVipUserId); + setAnonymousUserCookie(resolvedVipUserId); + } + savePaidType("vip"); + if (linkedEmail) { + setStorage("userEmail", linkedEmail); + setStorage("userName", linkedEmail); + setStorage("emailLinked", "1"); + setUserEmail(linkedEmail); + saveUserName(linkedEmail); + } else if (nickname) { + saveUserName(nickname); + } else { + saveUserName(resolvedVipUserId); + } + } + } + if (nickname) { + setWechatNick(nickname); + setStorage("wechatNick", nickname); + } else { + setWechatNick(null); + removeStorage("wechatNick"); + } + if (avatar) { + setWechatAvatar(avatar); + setStorage("wechatAvatar", avatar); + } else { + setWechatAvatar(null); + removeStorage("wechatAvatar"); + } + } catch { + // 忽略失败,不影响主流程 + } + }, [savePaidType, saveUserName]); + + const getStoredAnonymousUserId = useCallback((): string | null => { + const memosAccount = getStorage("memosAccount"); + if (memosAccount && /^user\d+$/.test(memosAccount)) { + return memosAccount; + } + + const userId = getStorage("userId"); + if (userId && /^user\d+$/.test(userId)) { + return userId; + } + + const cookieUserId = getCookie(ANONYMOUS_USER_COOKIE); + if (cookieUserId && /^user\d+$/.test(cookieUserId)) { + setStorage("memosAccount", cookieUserId); + return cookieUserId; + } + + return null; + }, []); + + const applyRecoveredEmailSession = useCallback( + async ( + data: { + token?: string; + record?: { id?: string; email?: string }; + anonymousUserId?: string | null; + memosAccount?: string | null; + }, + normalizedEmail: string, + fallbackAnonymousUserId?: string + ) => { + if (!data?.token || !data?.record?.id) { + return false; + } + + const { pbSaveAuth } = await import("@vip/app/lib/pocketbase"); + pbSaveAuth(data.token, { id: data.record.id, email: data.record.email ?? normalizedEmail }); + + const anonymousUserId = + (typeof data?.anonymousUserId === "string" && + /^user\d+$/.test(data.anonymousUserId) + ? data.anonymousUserId + : typeof data?.memosAccount === "string" && + /^user\d+$/.test(data.memosAccount) + ? data.memosAccount + : /^user\d+$/.test(fallbackAnonymousUserId?.trim() || "") + ? fallbackAnonymousUserId?.trim() + : "") || ""; + + await fetch("/api/auth/sync-session", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + token: data.token, + record: data.record, + anonymousUserId: anonymousUserId || undefined, + }), + credentials: "include", + }); + + setStorage("userId", data.record.id); + setStorage("userEmail", normalizedEmail); + setStorage("userName", normalizedEmail); + setStorage("emailLinked", "1"); + if (anonymousUserId) { + setStorage("memosAccount", anonymousUserId); + setAnonymousUserCookie(anonymousUserId); + } + + savePaidType("vip"); + setUserEmail(normalizedEmail); + saveUserName(normalizedEmail); + setStorage(EMAIL_VERIFY_TS_KEY, String(Date.now())); + return true; + }, + [savePaidType, saveUserName] + ); + + const recoverLinkedVipSession = useCallback( + async ( + email: string, + password: string, + user_id?: string + ): Promise<{ ok: boolean; error?: string }> => { + try { + const normalizedEmail = email.trim().toLowerCase(); + const wechatUserId = + (getStorage("wechatUserId") || "").trim() || + (getStorage("userid") || "").trim(); + const res = await fetch("/api/vip/check-by-email", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email: normalizedEmail, + password, + ...(user_id?.trim() && { user_id: user_id.trim() }), + ...(wechatUserId && { wechat_userid: wechatUserId }), + }), + credentials: "include", + }); + const data = await res.json().catch(() => ({})); + if (!data?.vip || !data?.token || !data?.record) { + return { + ok: false, + error: + data?.error || + "未找到关联的会员记录,请确认已支付并绑定邮箱", + }; + } + + const ok = await applyRecoveredEmailSession( + data, + normalizedEmail, + user_id + ); + return ok ? { ok: true } : { ok: false, error: "登录恢复失败" }; + } catch (error) { + const msg = error instanceof Error ? error.message : "验证失败"; + return { ok: false, error: msg }; + } + }, + [applyRecoveredEmailSession] + ); + + const getOrCreateUserId = useCallback(async () => { + const anonymousUserId = getStoredAnonymousUserId(); + if (anonymousUserId) { + setStorage("userId", anonymousUserId); + setAnonymousUserCookie(anonymousUserId); + return anonymousUserId; + } + try { + const meRes = await fetch("/api/auth/me", { credentials: "include", cache: "no-store" }); + const meData = await meRes.json(); + if (meData?.user?.id) { + const pbUserId = meData.user.id; + setStorage("userId", pbUserId); + return pbUserId; + } + } catch { + /* ignore */ + } + let userId = getStorage("userId"); + if (userId?.startsWith("{") && userId.includes("data")) { + try { + const parsed = JSON.parse(userId) as { data?: string }; + if (parsed?.data) { + userId = parsed.data; + setStorage("userId", userId); + } + } catch { + userId = null; + } + } + if (!userId) { + userId = `user${Date.now()}`; + setStorage("userId", userId); + } + return userId; + }, [getStoredAnonymousUserId]); + + /** user_id 验证:调用后端 API(优先 payjsapi,回退 PocketBase) */ + const checkVerifyByUserId = useCallback( + async (userId: string): Promise => { + try { + const normalizedUserId = userId.trim(); + const prioritizedUserId = resolveVipLookupUserId(normalizedUserId); + const res = await fetch("/api/vip/check-by-user", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ user_id: prioritizedUserId }), + credentials: "same-origin", + cache: "no-store", + }); + const data = (await res.json().catch(() => null)) as Record | null; + const probe = probeFromCheckByUserBody(data, res.ok); + if (probe === "unknown") { + return false; + } + if (probe === "no") { + if (prioritizedUserId && prioritizedUserId !== normalizedUserId) { + return false; + } + savePaidType(null); + return false; + } + if (!data?.vip) { + return false; + } + const resolvedUserId = prioritizedUserId || normalizedUserId; + setStorage("userId", resolvedUserId); + if (/^user\d+$/.test(resolvedUserId)) { + setStorage("memosAccount", resolvedUserId); + setAnonymousUserCookie(resolvedUserId); + } + savePaidType("vip"); + if (data?.alreadyLinked && data?.email) { + const linkedEmail = String(data.email).trim().toLowerCase(); + setStorage("emailLinked", "1"); + setStorage("userEmail", linkedEmail); + setStorage("userName", linkedEmail); + setUserEmail(linkedEmail); + saveUserName(linkedEmail); + await recoverLinkedVipSession( + linkedEmail, + DEFAULT_EMAIL_PASSWORD, + resolvedUserId + ).catch(() => {}); + } else { + const linked = getStorage("emailLinked") === "1"; + const hasEmail = getStorage("userEmail") || getStorage("userName")?.includes("@"); + if (!linked && !hasEmail) saveUserName(resolvedUserId); + } + return true; + } catch (err) { + console.error("验证失败:", err); + return false; + } + }, + [recoverLinkedVipSession, resolveVipLookupUserId, savePaidType, saveUserName] + ); + + const checkPaymentFromPB = checkVerifyByUserId; + + const tryRecoverByAnonymousUserId = useCallback( + async (anonymousUserId: string): Promise => { + if (!anonymousUserId || !/^user\d+$/.test(anonymousUserId)) { + return false; + } + + const firstHit = await checkPaymentFromPB(anonymousUserId); + if (firstHit) { + return true; + } + + const isWechat = getDeviceFromEnv(getPayEnv()) === "wechat"; + if (!isWechat) { + return false; + } + + // WeChat can close page immediately after pay success; notify write may lag. + for (let attempt = 0; attempt < 4; attempt++) { + await new Promise((resolve) => setTimeout(resolve, 1500)); + const recovered = await checkPaymentFromPB(anonymousUserId); + if (recovered) { + return true; + } + } + + return false; + }, + [checkPaymentFromPB] + ); + + /** 会员账号恢复:用用户输入的邮箱+密码调后端查库验证 VIP,可选 user_id 用于自动关联 */ + const checkVerifyByEmail = useCallback( + async ( + email: string, + password: string, + user_id?: string + ): Promise<{ ok: boolean; error?: string }> => { + return recoverLinkedVipSession(email, password, user_id); + }, + [recoverLinkedVipSession] + ); + + const clearAllStorage = useCallback(() => { + try { + if (typeof window === "undefined") return; + try { + localStorage.clear(); + } catch { + /* ignore */ + } + clearAnonymousUserCookie(); + clearPendingOrder(); + setPaidType(null); + setUserName(null); + const path = window.location.pathname || "/"; + window.location.replace(path); + } catch (error) { + console.error("清空存储失败:", error); + } + }, []); + + const handlePay = useCallback(() => { + triggerPay(setPayPendingOrderId); + }, []); + + const handleVerifySuccess = useCallback(() => { + window.location.reload(); + }, []); + + const env = getPayEnv(); + const device = getDeviceFromEnv(env); + const isH5 = device === "h5"; + usePayStatusPoll( + async (orderId) => { + let uid = getStorage("userId"); + if (!uid && orderId?.includes("_order_")) { + const prefix = orderId.split("_order_")[0]; + const parts = prefix.split("_"); + if (parts.length >= 2) uid = parts.slice(0, -1).join("_"); + } + if (uid) { + let confirmed = false; + for (let attempt = 0; attempt < 3; attempt++) { + try { + const confirmRes = await fetch("/api/pay/confirm", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ order_id: orderId, user_id: uid }), + }); + const confirmData = await confirmRes.json().catch(() => ({})); + if (confirmData?.ok) { + confirmed = true; + break; + } + } catch (e) { + console.error("pay/confirm request error:", e); + } + if (attempt < 2) await new Promise((r) => setTimeout(r, 1000)); + } + if (confirmed) { + saveUserName(uid); + savePaidType("vip"); + } + /* confirm 失败时不设置 paidType,避免显示 VIP 但 PB/Memos 无记录 */ + } + clearPendingOrder(); + if (isH5) setPayPendingOrderId(null); + window.location.reload(); + }, + () => { + clearPendingOrder(); + if (isH5) setPayPendingOrderId(null); + }, + isH5 ? payPendingOrderId ?? undefined : undefined + ); + + useEffect(() => { + const nick = getStorage("wechatNick"); + const avatar = getStorage("wechatAvatar"); + if (nick) setWechatNick(nick); + if (avatar) setWechatAvatar(avatar); + void syncWechatProfile(); + }, [syncWechatProfile, paidType, userEmail]); + + useEffect(() => { + const urlParams = new URLSearchParams(window.location.search); + if (urlParams.get("type")?.trim() === "clean") { + clearAllStorage(); + return; + } + /* paid=1 来自 URL 时不再无条件设置,需通过 confirm 或 PB 校验 */ + + const init = async () => { + const wechatUserIdForPriority = getWechatUserIdFromStorage(); + const pendingOrderId = getPendingOrderId(); + // 已有 VIP 时忽略陈旧支付轮询标记,否则会 early return,init 从不恢复 VIP,表现为「登录后仍显示未解锁」 + if (pendingOrderId) { + const alreadyVip = getStorage("paidType") === "vip"; + if (alreadyVip) { + clearPendingOrder(); + } else { + setPayPendingOrderId(pendingOrderId); + // 若已有真实 userid(来自参数或本地),不要被 pendingOrder 阻断 VIP 恢复链路 + if (!wechatUserIdForPriority) { + return; + } + } + } + + // 本地已有 VIP 标识时优先使用,立即展示;后台悄悄校验,若 user 被删或 VIP 被撤则更新本地状态 + const localType = getStorage("paidType"); + const localUserName = getStorage("userName"); + const localUserEmail = getStorage("userEmail"); + const localUserId = getStorage("userId"); + if (localType === "vip" && (localUserName || localUserEmail) && localUserId) { + // 立即展示 VIP 状态,不阻塞首屏 + setPaidType(localType); + setUserName(localUserEmail || localUserName || ""); + setUserEmail(localUserEmail || (localUserName?.includes("@") ? localUserName : null)); + if (!localUserEmail && !localUserName?.includes("@")) { + try { + const meRes = await fetch("/api/auth/me", { credentials: "include", cache: "no-store" }); + const meData = await meRes.json(); + if (meData?.user?.email) setUserEmail(meData.user.email); + } catch { /* ignore */ } + } + + // 后台悄悄校验:仅当服务端明确返回「非 VIP」才清本地;弱网/异常/uncertain 一律保留(避免微信内误踢) + const verifyInBackground = async () => { + const lookupUserId = resolveVipLookupUserId(localUserId); + const isAnonymous = /^user\d+$/.test(lookupUserId); + const probe = isAnonymous + ? await probeCheckByUserId(lookupUserId) + : await probeSessionVip(); + if (probe !== "no") { + return; + } + removeStorage("paidType"); + removeStorage("userName"); + removeStorage("userEmail"); + savePaidType(null); + setUserName(null); + setUserEmail(null); + }; + void verifyInBackground(); + return; + } + + // 校验逻辑:有本地存储(登录资料+VIP)时优先使用并校验;无身份/VIP 时点击按钮直接进入支付,不校验 + const wechatUserId = + getWechatUserIdFromStorage(); + let anonymousCandidate = getStoredAnonymousUserId(); + // 参数 userid 是真实微信用户标识时,应优先用它校验 VIP,避免被历史/新生成 userId 干扰 + if (wechatUserId) { + const wechatVip = await checkPaymentFromPB(wechatUserId); + if (wechatVip) { + setStorage("userId", wechatUserId); + savePaidType("vip"); + const name = + getStorage("wechatNick") || + getStorage("userEmail") || + getStorage("userName") || + wechatUserId; + saveUserName(name); + const mail = (getStorage("userEmail") || "").trim(); + setUserEmail(mail.includes("@") ? mail : null); + return; + } + } + if (!anonymousCandidate && wechatUserId) { + const recoveredFromWechat = await recoverAnonymousUserId({ + wechatUserId, + email: (getStorage("userEmail") || "").trim().toLowerCase(), + userId: (getStorage("userId") || "").trim(), + }); + if (recoveredFromWechat && /^user\d+$/.test(recoveredFromWechat)) { + anonymousCandidate = recoveredFromWechat; + setStorage("userId", recoveredFromWechat); + setStorage("memosAccount", recoveredFromWechat); + setAnonymousUserCookie(recoveredFromWechat); + } + } + const hadStoredUserId = !!anonymousCandidate; + const emailVerifiedAt = Number(getStorage(EMAIL_VERIFY_TS_KEY) || "0"); + const skipAnonymousRecover = + !!(getStorage("emailLinked") === "1" && Date.now() - emailVerifiedAt < EMAIL_VERIFY_COOLDOWN_MS); + if (anonymousCandidate && !skipAnonymousRecover) { + const recovered = await tryRecoverByAnonymousUserId(anonymousCandidate); + if (recovered) { + setStorage("userId", anonymousCandidate); + setStorage("memosAccount", anonymousCandidate); + setAnonymousUserCookie(anonymousCandidate); + const name = getStorage("userEmail") || getStorage("userName") || anonymousCandidate; + setUserName(name); + setUserEmail(name.includes("@") ? name : getStorage("userEmail")); + return; + } + } + + // 无匿名 userId 时,若存在真实 wechat userid,也要尝试直接按该 ID 查 VIP + // 场景:该 userid 本身就是支付链路 user_id,或者已在后端可关联到 VIP + if (!anonymousCandidate && wechatUserId) { + const recoveredByWechatUserId = await checkPaymentFromPB(wechatUserId); + if (recoveredByWechatUserId) { + setStorage("userId", wechatUserId); + const name = + getStorage("wechatNick") || + getStorage("userEmail") || + getStorage("userName") || + wechatUserId; + setUserName(name); + setUserEmail( + (getStorage("userEmail") || "").includes("@") + ? getStorage("userEmail") + : null + ); + return; + } + } + + await getOrCreateUserId(); + + const afterLocalType = getStorage("paidType"); + const afterLocalUserName = getStorage("userName"); + const afterLocalUserEmail = getStorage("userEmail"); + if (afterLocalType && (afterLocalUserName || afterLocalUserEmail)) { + setPaidType(afterLocalType); + setUserName(afterLocalUserEmail || afterLocalUserName || ""); + setUserEmail(afterLocalUserEmail || (afterLocalUserName?.includes("@") ? afterLocalUserName : null)); + return; + } + + // 检查本站 Cookie 登录态 + try { + const meRes = await fetch("/api/auth/me", { credentials: "include", cache: "no-store" }); + const meData = await meRes.json(); + if (meData?.user && meData?.token) { + const { pbSaveAuth } = await import("@vip/app/lib/pocketbase"); + pbSaveAuth(meData.token, { id: meData.user.id, email: meData.user.email }); + setUserEmail(meData.user.email || null); + const vipRes = await fetch("/api/vip/check", { credentials: "include", cache: "no-store" }); + const vipData = await vipRes.json(); + if (vipData?.vip) { + // 匿名 id 不覆盖;仅当当前无匿名 id 时才写入(可能是纯邮箱登录) + const cur = getStorage("userId"); + if (cur && /^user\d+$/.test(cur)) { + setStorage("memosAccount", cur); + } else if ( + typeof meData.user.anonymousUserId === "string" && + /^user\d+$/.test(meData.user.anonymousUserId) + ) { + setStorage("memosAccount", meData.user.anonymousUserId); + } + const wechatUserId = + (getStorage("wechatUserId") || "").trim() || + (getStorage("userid") || "").trim(); + const recoveredAnonymousUserId = + (cur && /^user\d+$/.test(cur) ? cur : "") || + (typeof meData.user.anonymousUserId === "string" && + /^user\d+$/.test(meData.user.anonymousUserId) + ? meData.user.anonymousUserId.trim() + : "") || + ((await recoverAnonymousUserId({ + userId: cur || meData.user.id || "", + email: meData.user.email || "", + wechatUserId, + })) || + ""); + if (/^user\d+$/.test(recoveredAnonymousUserId)) { + setStorage("userId", recoveredAnonymousUserId); + setStorage("memosAccount", recoveredAnonymousUserId); + setAnonymousUserCookie(recoveredAnonymousUserId); + } else { + setStorage("userId", meData.user.id); + } + setStorage("emailLinked", "1"); + if (meData.user.email) { + setStorage("userEmail", meData.user.email); + } + savePaidType("vip"); + saveUserName(meData.user.email || meData.user.id); + return; + } + } + } catch { + /* ignore */ + } + + // 仅当有本地存储的 userId 时才校验(无身份/VIP 时跳过,点击按钮直接进入支付流程) + if (hadStoredUserId) { + const userIdForCheck = resolveVipLookupUserId( + getStoredAnonymousUserId() || getStorage("userId") + ); + if (userIdForCheck) { + const found = await checkPaymentFromPB(userIdForCheck); + if (found) { + const name = getStorage("userEmail") || getStorage("userName"); + if (name) setUserName(name); + } + } + } + }; + + void init(); + }, [ + clearAllStorage, + getOrCreateUserId, + getStoredAnonymousUserId, + checkPaymentFromPB, + resolveVipLookupUserId, + recoverAnonymousUserId, + savePaidType, + saveUserName, + tryRecoverByAnonymousUserId, + ]); + + useEffect(() => { + if (!isH5) return; + + const syncPendingOrder = () => { + const pendingOrderId = getPendingOrderId(); + if (!pendingOrderId) return; + setPayPendingOrderId((current) => + current === pendingOrderId ? current : pendingOrderId + ); + }; + + const onVisible = () => { + if (document.visibilityState === "visible") { + syncPendingOrder(); + } + }; + + syncPendingOrder(); + document.addEventListener("visibilitychange", onVisible); + window.addEventListener("pageshow", syncPendingOrder); + window.addEventListener("focus", syncPendingOrder); + return () => { + document.removeEventListener("visibilitychange", onVisible); + window.removeEventListener("pageshow", syncPendingOrder); + window.removeEventListener("focus", syncPendingOrder); + }; + }, [isH5]); + + useEffect(() => { + const syncFromStorage = () => { + const localType = getStorage("paidType"); + const localName = getStorage("userEmail") || getStorage("userName"); + if (localType && localName && !paidType) { + setPaidType(localType); + setUserName(localName); + } + }; + const onVisible = () => syncFromStorage(); + const onPageShow = (e: PageTransitionEvent) => { + if (e.persisted) syncFromStorage(); + }; + if (typeof document !== "undefined" && document.addEventListener) { + document.addEventListener("visibilitychange", onVisible); + window.addEventListener("pageshow", onPageShow); + return () => { + document.removeEventListener("visibilitychange", onVisible); + window.removeEventListener("pageshow", onPageShow); + }; + } + }, [paidType]); + + const handleLogout = useCallback(async () => { + const { pbLogout } = await import("@vip/app/lib/pocketbase"); + await pbLogout(); + setUserEmail(null); + clearAllStorage(); + }, [clearAllStorage]); + + const isLoggedIn = paidType === "vip"; + + return ( + <> + + {isLoggedIn ? ( + + ) : ( + + )} + + + ); +} diff --git a/app/vip/HomeClientLoader.tsx b/app/vip/HomeClientLoader.tsx new file mode 100644 index 0000000..bf5ee9d --- /dev/null +++ b/app/vip/HomeClientLoader.tsx @@ -0,0 +1,15 @@ +"use client"; + +import dynamic from "next/dynamic"; + +const HomeClient = dynamic(() => import("./HomeClient"), { + ssr: false, + /** 仅纯色底,避免分包加载前白屏;真正 VIP/非 VIP 界面由 HomeClient 首帧同步读 localStorage 渲染 */ + loading: () => ( +
+ ), +}); + +export function HomeClientLoader() { + return ; +} diff --git a/app/vip/cloudphone/cloudphone.module.css b/app/vip/cloudphone/cloudphone.module.css new file mode 100644 index 0000000..3ae2853 --- /dev/null +++ b/app/vip/cloudphone/cloudphone.module.css @@ -0,0 +1,407 @@ +/* 云手机 - video.hackrobot.cn 课程落地页风格 */ + +.root { + min-height: 100vh; + background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 50%, #e2e8f0 100%); + color: #1e293b; +} + +.header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 1rem 1.5rem; + max-width: 1100px; + margin: 0 auto; +} + +.logo { + font-size: 1.25rem; + font-weight: 700; + color: #0f172a; + text-decoration: none; +} + +.logo:hover { + color: #0284c7; +} + +.backLink { + font-size: 0.9rem; + color: #64748b; + text-decoration: none; +} + +.backLink:hover { + color: #0284c7; +} + +/* Hero */ +.hero { + text-align: center; + padding: 4rem 1.5rem 3rem; + max-width: 800px; + margin: 0 auto; +} + +.heroTitle { + font-size: clamp(2rem, 5vw, 3rem); + font-weight: 800; + color: #0f172a; + margin: 0 0 1rem; + letter-spacing: -0.02em; +} + +.heroSubtitle { + font-size: 1.1rem; + color: #475569; + margin: 0 0 2rem; + line-height: 1.6; +} + +.stats { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 2rem; + margin-bottom: 2rem; +} + +.stat { + text-align: center; +} + +.statValue { + display: block; + font-size: 2rem; + font-weight: 800; + color: #0284c7; + margin-bottom: 0.25rem; +} + +.statLabel { + font-size: 0.9rem; + color: #64748b; +} + +.ctaBtn { + display: inline-block; + padding: 0.9rem 2rem; + font-size: 1rem; + font-weight: 600; + color: white; + background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%); + border-radius: 9999px; + text-decoration: none; + box-shadow: 0 4px 14px rgba(2, 132, 199, 0.4); + transition: transform 0.15s, box-shadow 0.15s; +} + +.ctaBtn:hover { + transform: translateY(-2px); + box-shadow: 0 6px 20px rgba(2, 132, 199, 0.5); +} + +/* Sections */ +.section { + max-width: 1100px; + margin: 0 auto; + padding: 3rem 1.5rem; +} + +.section h2 { + font-size: 1.75rem; + font-weight: 700; + color: #0f172a; + text-align: center; + margin: 0 0 0.75rem; +} + +.sectionDesc { + text-align: center; + color: #64748b; + margin: 0 0 2rem; + line-height: 1.6; +} + +/* 这门课适合谁 */ +.audienceGrid { + display: grid; + grid-template-columns: repeat(1, 1fr); + gap: 1.25rem; +} + +@media (min-width: 640px) { + .audienceGrid { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (min-width: 1024px) { + .audienceGrid { + grid-template-columns: repeat(4, 1fr); + } +} + +.audienceCard { + padding: 1.5rem; + background: white; + border-radius: 12px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06); + border: 1px solid #f1f5f9; + transition: box-shadow 0.2s, transform 0.2s; +} + +.audienceCard:hover { + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); + transform: translateY(-2px); +} + +.audienceIcon { + font-size: 2rem; + display: block; + margin-bottom: 0.75rem; +} + +.audienceCard h3 { + font-size: 1.05rem; + font-weight: 600; + color: #0f172a; + margin: 0 0 0.5rem; +} + +.audienceCard p { + font-size: 0.9rem; + color: #64748b; + margin: 0; + line-height: 1.5; +} + +/* 学完你将获得 */ +.benefitsList { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.benefitItem { + display: flex; + gap: 1rem; + padding: 1.25rem; + background: white; + border-radius: 12px; + border: 1px solid #f1f5f9; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06); +} + +.benefitNum { + flex-shrink: 0; + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%); + color: white; + font-weight: 700; + font-size: 1rem; + border-radius: 10px; +} + +.benefitItem h3 { + font-size: 1.05rem; + font-weight: 600; + color: #0f172a; + margin: 0 0 0.35rem; +} + +.benefitItem p { + font-size: 0.9rem; + color: #64748b; + margin: 0; + line-height: 1.5; +} + +/* 实战课程 - 复刻 video.hackrobot.cn 样式 */ +.curriculum { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.curriculumBlock { + background: white; + border-radius: 12px; + border: 1px solid #e2e8f0; + overflow: hidden; + transition: box-shadow 0.2s, border-color 0.2s; +} + +.curriculumBlock:hover { + border-color: #cbd5e1; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); +} + +.curriculumHeader { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 1rem 1.25rem; + background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); + border-bottom: 1px solid #e2e8f0; + cursor: default; +} + +.curriculumHeaderIcon { + font-size: 1rem; + color: #0284c7; + flex-shrink: 0; +} + +.curriculumTitle { + flex: 1; + font-size: 1rem; + font-weight: 600; + color: #0f172a; + margin: 0; +} + +.curriculumCount { + font-size: 0.8rem; + font-weight: 500; + color: #64748b; + background: #e2e8f0; + padding: 0.2rem 0.5rem; + border-radius: 6px; +} + +.curriculumList { + margin: 0; + padding: 0.5rem 0; + list-style: none; +} + +.curriculumItem { + margin: 0; + padding: 0; +} + +.curriculumItemLink { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.65rem 1.25rem; + color: #334155; + text-decoration: none; + font-size: 0.95rem; + transition: background 0.15s, color 0.15s; +} + +.curriculumItemLink:hover { + background: #f0f9ff; + color: #0284c7; +} + +.curriculumItemLink::before { + content: ""; + width: 5px; + height: 5px; + border-radius: 50%; + background: #cbd5e1; + flex-shrink: 0; +} + +.curriculumItemLink:hover::before { + background: #0284c7; +} + +.curriculumTryBadge { + font-size: 0.75rem; + color: #0284c7; + margin-left: 0.25rem; + flex-shrink: 0; +} + +.curriculumArrow { + margin-left: auto; + font-size: 0.85rem; + color: #94a3b8; +} + +.curriculumItemLink:hover .curriculumArrow { + color: #0284c7; +} + +/* FAQ */ +.faq { + max-width: 600px; + margin: 0 auto; +} + +.faqItem { + padding: 1rem 1.25rem; + background: white; + border-radius: 10px; + border: 1px solid #e2e8f0; + margin-bottom: 0.75rem; +} + +.faqQ { + font-size: 0.95rem; + font-weight: 500; + color: #334155; +} + +/* CTA Section */ +.ctaSection { + text-align: center; + padding: 4rem 1.5rem; + background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); + color: white; +} + +.ctaSection h2 { + font-size: 1.5rem; + font-weight: 700; + color: white; + margin: 0 0 0.5rem; +} + +.ctaSection p { + font-size: 1rem; + color: #94a3b8; + margin: 0 0 1rem; +} + +.ctaFeatures { + font-size: 0.9rem; + color: #64748b; + margin-bottom: 1.5rem; +} + +.ctaSection .ctaBtn { + background: linear-gradient(135deg, #38bdf8 0%, #0284c7 100%); +} + +/* Footer */ +.footer { + text-align: center; + padding: 2rem 1.5rem; + border-top: 1px solid #e2e8f0; +} + +.footer p { + font-size: 0.9rem; + color: #64748b; + margin: 0 0 0.5rem; +} + +.footer a { + font-size: 0.85rem; + color: #0284c7; + text-decoration: none; +} + +.footer a:hover { + text-decoration: underline; +} diff --git a/app/vip/cloudphone/components/AnimateOnScroll.tsx b/app/vip/cloudphone/components/AnimateOnScroll.tsx new file mode 100644 index 0000000..7009599 --- /dev/null +++ b/app/vip/cloudphone/components/AnimateOnScroll.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { useRef, useEffect, useState, type ReactNode } from "react"; + +type Props = { + children: ReactNode; + delay?: number; + className?: string; +}; + +export function AnimateOnScroll({ children, delay = 0, className = "" }: Props) { + const ref = useRef(null); + const [visible, setVisible] = useState(false); + + useEffect(() => { + const el = ref.current; + if (!el) return; + const observer = new IntersectionObserver( + ([entry]) => { + if (entry?.isIntersecting) setVisible(true); + }, + { threshold: 0.08, rootMargin: "0px 0px -40px 0px" } + ); + observer.observe(el); + return () => observer.disconnect(); + }, []); + + return ( +
+ {children} +
+ ); +} diff --git a/app/vip/cloudphone/components/ChatFloatButton.tsx b/app/vip/cloudphone/components/ChatFloatButton.tsx new file mode 100644 index 0000000..fa18859 --- /dev/null +++ b/app/vip/cloudphone/components/ChatFloatButton.tsx @@ -0,0 +1,61 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { isPaid } from "../lib/payment"; +import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal"; + +const CHAT_URL = "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot"; + +export function ChatFloatButton() { + const [paid, setPaid] = useState(false); + const [modalOpen, setModalOpen] = useState(false); + + useEffect(() => { + setPaid(isPaid()); + const onPayUpdate = () => setPaid(isPaid()); + window.addEventListener("pay:updated", onPayUpdate); + return () => window.removeEventListener("pay:updated", onPayUpdate); + }, []); + + const baseClass = + "animate__animated animate__bounceIn fixed bottom-6 right-6 z-40 flex h-12 w-12 items-center justify-center rounded-full shadow-lg transition-all hover:scale-110"; + const paidClass = "bg-[var(--accent)] text-[var(--accent-foreground)] shadow-[var(--accent)]/30 hover:shadow-xl hover:shadow-[var(--accent)]/40"; + const lockedClass = "bg-[var(--accent)] text-[var(--accent-foreground)] shadow-[var(--accent)]/30 hover:shadow-xl hover:shadow-[var(--accent)]/40"; + + if (paid) { + return ( + + + + + + + + ); + } + + return ( + + + setModalOpen(false)} /> + + ); +} diff --git a/app/vip/cloudphone/components/Footer.tsx b/app/vip/cloudphone/components/Footer.tsx new file mode 100644 index 0000000..f497ddd --- /dev/null +++ b/app/vip/cloudphone/components/Footer.tsx @@ -0,0 +1,68 @@ +"use client"; + +import { useState, useEffect } from "react"; +import Link from "next/link"; +import { SITE_CONFIG } from "../config/course"; +import { isPaid } from "../lib/payment"; +import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal"; + +const CHAT_URL = "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot"; + +export function Footer() { + const [paid, setPaid] = useState(false); + const [modalOpen, setModalOpen] = useState(false); + + useEffect(() => { + setPaid(isPaid()); + const onPayUpdate = () => setPaid(isPaid()); + window.addEventListener("pay:updated", onPayUpdate); + return () => window.removeEventListener("pay:updated", onPayUpdate); + }, []); + + return ( +
+
+
+ + 返回首页 + + + 课程首页 + + {paid ? ( + + + + + + 即时问答 + + + ) : ( + + + + )} +
+
+ {SITE_CONFIG.footer} +
+
+ setModalOpen(false)} /> +
+ ); +} diff --git a/app/vip/cloudphone/components/Header.tsx b/app/vip/cloudphone/components/Header.tsx new file mode 100644 index 0000000..3c4b9e2 --- /dev/null +++ b/app/vip/cloudphone/components/Header.tsx @@ -0,0 +1,105 @@ +"use client"; + +import { useState, useEffect } from "react"; +import Link from "next/link"; +import { SITE_CONFIG } from "../config/course"; +import { isPaid } from "../lib/payment"; +import { triggerPay } from "@vip/app/lib/triggerPay"; +import { ThemeToggle } from "@vip/app/components/ThemeToggle"; +import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal"; + +export function Header() { + const [paid, setPaid] = useState(false); + const [qaModalOpen, setQaModalOpen] = useState(false); + useEffect(() => { + setPaid(isPaid()); + const onPayUpdate = () => setPaid(isPaid()); + window.addEventListener("pay:updated", onPayUpdate); + return () => window.removeEventListener("pay:updated", onPayUpdate); + }, []); + + return ( + <> +
+
+ + {SITE_CONFIG.brand} + +
+ + {paid ? ( + + + + + + 即时问答 + + + ) : ( + + + + )} + + 首页 + + {paid ? ( + + 进入课程 → + + ) : ( + + )} + {paid ? ( + + + + + + ) : ( + + )} +
+
+
+ setQaModalOpen(false)} /> + + ); +} diff --git a/app/vip/cloudphone/components/ParticleBackground.tsx b/app/vip/cloudphone/components/ParticleBackground.tsx new file mode 100644 index 0000000..d9c0ab5 --- /dev/null +++ b/app/vip/cloudphone/components/ParticleBackground.tsx @@ -0,0 +1,30 @@ +"use client"; + +/** + * 纯 CSS 粒子背景 - 不依赖 @tsparticles + */ +export function ParticleBackground() { + const dots = Array.from({ length: 30 }, (_, i) => i); + + return ( +
+ {dots.map((i) => ( +
+ ))} +
+ ); +} diff --git a/app/vip/cloudphone/components/Section.tsx b/app/vip/cloudphone/components/Section.tsx new file mode 100644 index 0000000..ca9d6a4 --- /dev/null +++ b/app/vip/cloudphone/components/Section.tsx @@ -0,0 +1,16 @@ +import { type ReactNode } from "react"; + +type SectionProps = { + children: ReactNode; + className?: string; +}; + +export function Section({ children, className = "" }: SectionProps) { + return ( +
+
{children}
+
+ ); +} diff --git a/app/vip/cloudphone/components/VideoPlayer.tsx b/app/vip/cloudphone/components/VideoPlayer.tsx new file mode 100644 index 0000000..e28f8b7 --- /dev/null +++ b/app/vip/cloudphone/components/VideoPlayer.tsx @@ -0,0 +1,367 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; + +const STORAGE_PREFIX = "lms-cloudphone-video-"; +const SAVE_INTERVAL = 5000; +const MIN_PROGRESS_TO_SHOW = 10; + +function getStoredProgress(videoId: string): number { + if (typeof window === "undefined") return 0; + try { + const raw = localStorage.getItem(`${STORAGE_PREFIX}${videoId}`); + if (!raw) return 0; + const data = JSON.parse(raw); + return typeof data?.time === "number" ? data.time : 0; + } catch { + return 0; + } +} + +function saveProgress(videoId: string, time: number): void { + if (typeof window === "undefined") return; + try { + localStorage.setItem(`${STORAGE_PREFIX}${videoId}`, JSON.stringify({ time })); + } catch { + /* ignore */ + } +} + +type VideoPlayerProps = { + src: string; + poster?: string; + title?: string; + className?: string; + videoId?: string; + onComplete?: () => void; +}; + +export function VideoPlayer({ src, poster, title, className = "", videoId, onComplete }: VideoPlayerProps) { + const videoRef = useRef(null); + const [playing, setPlaying] = useState(false); + const [progress, setProgress] = useState(0); + const [currentTime, setCurrentTime] = useState(0); + const [duration, setDuration] = useState(0); + const [volume, setVolume] = useState(1); + const [muted, setMuted] = useState(false); + const [speed, setSpeed] = useState(1); + const [showControls, setShowControls] = useState(true); + const [showResumePrompt, setShowResumePrompt] = useState(false); + const [savedTime, setSavedTime] = useState(0); + const hideTimerRef = useRef | null>(null); + const lastSaveRef = useRef(0); + + const togglePlay = useCallback(() => { + const v = videoRef.current; + if (!v) return; + if (v.paused) { + v.play(); + setPlaying(true); + } else { + v.pause(); + setPlaying(false); + } + }, []); + + const handleTimeUpdate = useCallback(() => { + const v = videoRef.current; + if (!v) return; + const time = v.currentTime; + const dur = v.duration; + setCurrentTime(time); + setProgress(Number.isFinite(dur) && dur > 0 ? (time / dur) * 100 : 0); + + if (videoId && v.currentTime > 0) { + const now = Date.now(); + if (now - lastSaveRef.current > SAVE_INTERVAL) { + lastSaveRef.current = now; + saveProgress(videoId, v.currentTime); + } + } + }, [videoId]); + + const handleLoadedMetadata = useCallback(() => { + const v = videoRef.current; + if (!v) return; + const dur = v.duration; + if (!Number.isFinite(dur) || dur <= 0) return; + setDuration(dur); + + if (videoId) { + const stored = getStoredProgress(videoId); + if (Number.isFinite(stored) && stored >= MIN_PROGRESS_TO_SHOW && stored < dur - 5) { + setSavedTime(stored); + setShowResumePrompt(true); + } + } + }, [videoId]); + + const handleEnded = useCallback(() => { + setPlaying(false); + setProgress(0); + setCurrentTime(0); + if (videoId) saveProgress(videoId, 0); + onComplete?.(); + }, [videoId, onComplete]); + + const handlePause = useCallback(() => { + const v = videoRef.current; + if (videoId && v && v.currentTime > 0) { + saveProgress(videoId, v.currentTime); + } + }, [videoId]); + + const handleResume = useCallback(() => { + const v = videoRef.current; + if (!v || savedTime <= 0) return; + const dur = v.duration; + if (!Number.isFinite(dur) || dur <= 0) return; + const time = Math.min(savedTime, dur - 0.1); + v.currentTime = time; + setCurrentTime(time); + setProgress((time / dur) * 100); + v.play(); + setPlaying(true); + setShowResumePrompt(false); + }, [savedTime]); + + const handleRestart = useCallback(() => { + const v = videoRef.current; + if (!v) return; + if (videoId) saveProgress(videoId, 0); + v.currentTime = 0; + setCurrentTime(0); + setProgress(0); + setShowResumePrompt(false); + }, [videoId]); + + const handleSeek = useCallback((e: React.MouseEvent) => { + const v = videoRef.current; + if (!v) return; + const dur = v.duration; + if (!Number.isFinite(dur) || dur <= 0) return; + const rect = e.currentTarget.getBoundingClientRect(); + if (rect.width <= 0) return; + const p = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); + const time = p * dur; + v.currentTime = time; + setCurrentTime(time); + setProgress(p * 100); + }, []); + + const toggleMute = useCallback(() => { + const v = videoRef.current; + if (!v) return; + v.muted = !v.muted; + setMuted(v.muted); + }, []); + + const handleVolumeChange = useCallback((e: React.ChangeEvent) => { + const v = videoRef.current; + if (!v) return; + const val = parseFloat(e.target.value); + v.volume = val; + setVolume(val); + setMuted(val === 0); + }, []); + + const cycleSpeed = useCallback(() => { + const speeds = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]; + const i = speeds.indexOf(speed); + const next = speeds[(i + 1) % speeds.length]; + const v = videoRef.current; + if (v) v.playbackRate = next; + setSpeed(next); + }, [speed]); + + const toggleFullscreen = useCallback(() => { + const container = videoRef.current?.parentElement; + if (!container) return; + if (!document.fullscreenElement) { + container.requestFullscreen(); + } else { + document.exitFullscreen(); + } + }, []); + + const showControlsTemporarily = useCallback(() => { + setShowControls(true); + if (hideTimerRef.current) clearTimeout(hideTimerRef.current); + hideTimerRef.current = setTimeout(() => setShowControls(false), 3000); + }, []); + + useEffect(() => () => { if (hideTimerRef.current) clearTimeout(hideTimerRef.current); }, []); + + const formatTime = (s: number) => { + if (!Number.isFinite(s) || s < 0) return "0:00"; + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + return `${m}:${sec.toString().padStart(2, "0")}`; + }; + + const formatResumeTime = (s: number) => { + if (!Number.isFinite(s) || s < 0) return "0秒"; + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + if (m > 0) return `${m}分${sec}秒`; + return `${sec}秒`; + }; + + return ( +
setShowControls(false)} + > +