From be7a2986045d333cd15dd5cf285a8068b950976e Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 10 Mar 2026 01:35:37 -0500 Subject: [PATCH] 'init' --- .cursor/rules/project-foundation.mdc | 38 + .gitignore | 41 + README.md | 196 +- app/api/pay/route.ts | 227 + app/api/pay/status/route.ts | 15 + app/certificate/page.tsx | 82 + app/components/AnimateOnScroll.tsx | 22 + app/components/Button.tsx | 43 + app/components/CommunityButton.tsx | 135 + app/components/Footer.tsx | 25 + app/components/Header.tsx | 45 + app/components/Hero.tsx | 111 + app/components/LessonNotes.tsx | 40 + app/components/MarkdownContent.tsx | 89 + app/components/ParticleBackground.tsx | 55 + app/components/PayButton.tsx | 59 + app/components/Section.tsx | 17 + app/components/ShareButton.tsx | 379 + app/components/ThemeToggle.tsx | 36 + app/components/VideoPlayer.tsx | 369 + .../custom/CustomAnimateOnScroll.tsx | 43 + .../custom/CustomParticleBackground.tsx | 117 + app/components/custom/index.ts | 2 + app/components/index.ts | 15 + app/components/sections/AudienceSection.tsx | 27 + app/components/sections/BenefitsSection.tsx | 31 + app/components/sections/CTASection.tsx | 46 + app/components/sections/CurriculumSection.tsx | 159 + app/components/sections/FAQSection.tsx | 43 + .../sections/InstructorsSection.tsx | 37 + app/components/sections/RatingSection.tsx | 67 + .../[lessonIndex]/LessonMarkdown.tsx | 195 + .../[lessonIndex]/lesson-markdown.module.css | 362 + .../[moduleIndex]/[lessonIndex]/page.tsx | 154 + app/favicon.ico | Bin 0 -> 25931 bytes app/globals.css | 111 + app/layout.tsx | 47 + app/lib/env.ts | 5 + app/lib/learning.ts | 141 + app/lib/payment.ts | 20 + app/page.tsx | 44 + app/pay/page.tsx | 60 + app/pay/paid/page.tsx | 37 + app/providers/ThemeProvider.tsx | 84 + app/theme-init.ts | 11 + config/course.ts | 215 + config/lessons.ts | 112 + eslint.config.mjs | 18 + lib/sdk/README.md | 101 + lib/sdk/config.ts | 85 + lib/sdk/index.ts | 39 + lib/sdk/minio/index.ts | 60 + lib/sdk/pocketbase/auth.ts | 91 + lib/sdk/pocketbase/constants.ts | 5 + lib/sdk/pocketbase/index.ts | 12 + lib/sdk/pocketbase/records.ts | 52 + lib/sdk/zpay/index.ts | 130 + next.config.ts | 7 + package.json | 43 + pnpm-lock.yaml | 6154 +++++++++++++++++ pnpm-workspace.yaml | 3 + postcss.config.mjs | 7 + public/file.svg | 1 + public/globe.svg | 1 + public/manifest.json | 18 + public/next.svg | 1 + public/vercel.svg | 1 + public/window.svg | 1 + tsconfig.json | 34 + 69 files changed, 11016 insertions(+), 57 deletions(-) create mode 100644 .cursor/rules/project-foundation.mdc create mode 100644 .gitignore create mode 100644 app/api/pay/route.ts create mode 100644 app/api/pay/status/route.ts create mode 100644 app/certificate/page.tsx create mode 100644 app/components/AnimateOnScroll.tsx create mode 100644 app/components/Button.tsx create mode 100644 app/components/CommunityButton.tsx create mode 100644 app/components/Footer.tsx create mode 100644 app/components/Header.tsx create mode 100644 app/components/Hero.tsx create mode 100644 app/components/LessonNotes.tsx create mode 100644 app/components/MarkdownContent.tsx create mode 100644 app/components/ParticleBackground.tsx create mode 100644 app/components/PayButton.tsx create mode 100644 app/components/Section.tsx create mode 100644 app/components/ShareButton.tsx create mode 100644 app/components/ThemeToggle.tsx create mode 100644 app/components/VideoPlayer.tsx create mode 100644 app/components/custom/CustomAnimateOnScroll.tsx create mode 100644 app/components/custom/CustomParticleBackground.tsx create mode 100644 app/components/custom/index.ts create mode 100644 app/components/index.ts create mode 100644 app/components/sections/AudienceSection.tsx create mode 100644 app/components/sections/BenefitsSection.tsx create mode 100644 app/components/sections/CTASection.tsx create mode 100644 app/components/sections/CurriculumSection.tsx create mode 100644 app/components/sections/FAQSection.tsx create mode 100644 app/components/sections/InstructorsSection.tsx create mode 100644 app/components/sections/RatingSection.tsx create mode 100644 app/course/[moduleIndex]/[lessonIndex]/LessonMarkdown.tsx create mode 100644 app/course/[moduleIndex]/[lessonIndex]/lesson-markdown.module.css create mode 100644 app/course/[moduleIndex]/[lessonIndex]/page.tsx create mode 100644 app/favicon.ico create mode 100644 app/globals.css create mode 100644 app/layout.tsx create mode 100644 app/lib/env.ts create mode 100644 app/lib/learning.ts create mode 100644 app/lib/payment.ts create mode 100644 app/page.tsx create mode 100644 app/pay/page.tsx create mode 100644 app/pay/paid/page.tsx create mode 100644 app/providers/ThemeProvider.tsx create mode 100644 app/theme-init.ts create mode 100644 config/course.ts create mode 100644 config/lessons.ts create mode 100644 eslint.config.mjs create mode 100644 lib/sdk/README.md create mode 100644 lib/sdk/config.ts create mode 100644 lib/sdk/index.ts create mode 100644 lib/sdk/minio/index.ts create mode 100644 lib/sdk/pocketbase/auth.ts create mode 100644 lib/sdk/pocketbase/constants.ts create mode 100644 lib/sdk/pocketbase/index.ts create mode 100644 lib/sdk/pocketbase/records.ts create mode 100644 lib/sdk/zpay/index.ts create mode 100644 next.config.ts create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 postcss.config.mjs create mode 100644 public/file.svg create mode 100644 public/globe.svg create mode 100644 public/manifest.json create mode 100644 public/next.svg create mode 100644 public/vercel.svg create mode 100644 public/window.svg create mode 100644 tsconfig.json diff --git a/.cursor/rules/project-foundation.mdc b/.cursor/rules/project-foundation.mdc new file mode 100644 index 0000000..d3cafcb --- /dev/null +++ b/.cursor/rules/project-foundation.mdc @@ -0,0 +1,38 @@ +--- +description: 项目基础规范 - 响应式、主题、组件化 +alwaysApply: true +--- + +# LMS 项目基础规范 + +以下 3 项为本项目**兜底要求**,任何改动都需遵守。 + +## 1. 响应式设计 + +必须支持 **PC / PAD / H5** 三种视口: + +| 设备 | 断点 | Tailwind 前缀 | +|------|------|---------------| +| H5 手机 | < 640px | 默认 / `sm:` | +| PAD 平板 | 640px ~ 1024px | `sm:` ~ `lg:` | +| PC 桌面 | ≥ 1024px | `lg:` ~ `xl:` | + +- 使用 `sm:`, `md:`, `lg:`, `xl:` 做断点适配 +- 布局:`grid-cols-1 sm:grid-cols-2 lg:grid-cols-4` +- 字号:`text-base sm:text-lg md:text-xl` +- 内边距:`px-4 sm:px-6`、`py-12 md:py-16 lg:py-20` + +## 2. 日间/夜间主题 + +- 使用 CSS 变量 `var(--background)`、`var(--foreground)` 等,勿硬编码颜色 +- 主题变量定义在 `app/globals.css` 的 `:root/.light` 和 `.dark` +- 主题切换通过 `ThemeProvider` + `ThemeToggle` 实现 +- 新增样式需同时适配 light/dark 两种模式 + +## 3. 功能组件化 / 模块化 / 配置化 + +- **组件化**:功能拆成独立组件,放在 `app/components/` +- **模块化**:区块组件放在 `app/components/sections/`,通用组件放 `app/components/` +- **配置化**:展示数据集中在 `config/course.ts`,组件只负责渲染 + +新增内容时:先加配置 → 再写/改组件 → 保持 page 简洁。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ef6a52 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/README.md b/README.md index 2278844..c535cb7 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,174 @@ -# nomadlms +# 🌍 LMS - 轻量级课程落地页与学习系统 +一个基于 Next.js 的课程落地页与视频学习系统,支持配置化课程、学习进度、支付对接、PWA 等。开箱即用,适合知识付费、在线课程、培训等场景。 +![Next.js](https://img.shields.io/badge/Next.js-16-black?logo=next.js) +![React](https://img.shields.io/badge/React-19-61dafb?logo=react) +![TypeScript](https://img.shields.io/badge/TypeScript-5-3178c6?logo=typescript) +![Tailwind CSS](https://img.shields.io/badge/Tailwind-4-38bdf8?logo=tailwindcss) -## Getting started +## ✨ 功能特性 -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +### 课程展示 +- **落地页**:Hero、受众、收益、课程大纲、导师、FAQ、CTA +- **课程大纲**:模块折叠、全文搜索、收藏标记、完成状态 +- **试看机制**:前 2 节免费试看,可配置 -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +### 学习体验 +- **继续学习**:记住上次观看章节,一键续播 +- **学习进度**:完成度展示、进度条 +- **视频播放**:续播提示、倍速、全屏、观看进度自动保存 +- **收藏/书签**:章节收藏,便于回看 +- **课程证书**:完成全部课程后可查看证书 -## Add your files +### 互动与分享 +- **分享海报**:生成课程海报、二维码,支持下载分享 +- **社群入口**:报名后解锁社群二维码弹窗 +- **课程评价**:星级 + 文字评价(可配置隐藏) -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +### 支付与接入 +- **支付对接**:支持第三方支付(如 ZPay 等),可扩展 +- **支付状态**:本地模拟 / 服务端校验,可配置 + +### 其他 +- **PWA**:manifest.json,支持添加到主屏 +- **深色模式**:跟随系统主题切换 +- **响应式**:适配桌面与移动端 + +--- + +## 🛠 技术栈 + +| 类别 | 技术 | +|------|------| +| 框架 | Next.js 16 (App Router)、React 19 | +| 语言 | TypeScript 5 | +| 样式 | Tailwind CSS 4、animate.css | +| 动画 | Framer Motion、tsParticles | +| 文档 | react-markdown、remark-gfm、rehype-highlight | +| 其他 | highlight.js、github-markdown-css | + +### 核心依赖 + +- **framer-motion**:滚动入场、组件动画 +- **@tsparticles/react**:粒子背景效果 +- **animate.css**:Hero 入场动画 +- **react-markdown**:课程配套文档 Markdown 渲染 + +--- + +## 📁 项目结构 ``` -cd existing_repo -git remote add origin http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadlms.git -git branch -M main -git push -uf origin main +lms/ +├── app/ +│ ├── api/ # API 路由 +│ │ ├── pay/ # 支付相关 +│ │ └── pay/status/ # 支付状态 +│ ├── certificate/ # 证书页 +│ ├── course/[module]/[lesson]/ # 课程详情页 +│ ├── pay/ # 支付页 +│ ├── components/ # 组件 +│ │ ├── custom/ # 自实现封装(无依赖可选) +│ │ └── sections/ # 区块组件 +│ ├── lib/ # 业务逻辑 +│ │ ├── learning.ts # 学习进度、收藏、笔记 +│ │ └── payment.ts # 支付状态 +│ └── providers/ # 主题等 Provider +├── config/ +│ ├── course.ts # 课程落地页配置 +│ └── lessons.ts # 章节详情 +├── public/ +│ └── manifest.json # PWA Manifest +└── ... ``` -## Integrate with your tools +--- -- [ ] [Set up project integrations](http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadlms/-/settings/integrations) +## 🚀 快速开始 -## Collaborate with your team +### 环境要求 -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +- Node.js 18+ +- pnpm / npm / yarn -## Test and Deploy +### 安装 -Use the built-in continuous integration in GitLab. +```bash +# 使用 pnpm(推荐) +pnpm install -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +# 或 npm +npm install -*** +# 或 yarn +yarn install +``` -# Editing this README +### 开发 -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. +```bash +pnpm dev +``` -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +访问 [http://localhost:3000](http://localhost:3000) -## Name -Choose a self-explaining name for your project. +### 构建与预览 -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +```bash +# 构建 +pnpm build -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +# 启动生产服务 +pnpm start +``` -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +--- -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +## ⚙️ 配置说明 -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +### 课程配置 `config/course.ts` -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +| 配置项 | 说明 | +|--------|------| +| `SITE_CONFIG` | 站点名称、Footer 等 | +| `HERO_CONFIG` | 标题、副标题、数据卡片 | +| `CURRICULUM_CONFIG` | 课程模块与章节 | +| `AUDIENCE_CONFIG` | 受众说明 | +| `BENEFITS_CONFIG` | 学完收益 | +| `INSTRUCTORS_CONFIG` | 导师信息 | +| `FAQ_CONFIG` | 常见问题 | +| `COMMUNITY_CONFIG` | 社群入口、二维码 URL | +| `DOWNLOAD_CONFIG` | 网盘下载模块 | -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +### 章节配置 `config/lessons.ts` -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +- 视频 URL、Markdown 文档 +- 按 `moduleIndex`、`lessonIndex` 映射 -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +### 支付与测试 -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +- 支付逻辑在 `app/lib/payment.ts`,通过 `localStorage` 的 `pay` 键判断是否已支付 +- 测试时可手动设置:`localStorage.setItem('pay', 'ok')` 模拟已报名 -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +--- -## License -For open source projects, say how it is licensed. +## 🎨 特色 -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +1. **配置驱动**:课程内容、落地页、FAQ、社群等均通过配置修改,无需改组件 +2. **轻量学习逻辑**:进度、收藏、笔记、证书基于 localStorage,无后端即可运行 +3. **动画体验**:使用 Framer Motion、tsParticles、animate.css 等库,提供流畅动效 +4. **自实现可选**:`app/components/custom/` 提供无依赖的粒子与滚动动画实现,可替换第三方库 +5. **PWA 支持**:可安装到主屏,支持离线访问 + +--- + +## 📄 许可证 + +MIT + +--- + +## 🤝 贡献 + +欢迎提交 Issue 和 Pull Request。 diff --git a/app/api/pay/route.ts b/app/api/pay/route.ts new file mode 100644 index 0000000..1b3a763 --- /dev/null +++ b/app/api/pay/route.ts @@ -0,0 +1,227 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getZPayConfig } from "@/lib/sdk"; +import { SITE_URL } from "@/app/lib/env"; + +const ZPAY_REQUIRED = [ + "pid", + "type", + "out_trade_no", + "notify_url", + "return_url", + "name", + "money", + "sign", + "sign_type", +]; + +function escapeAttr(s: string): string { + return String(s) + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(//g, ">"); +} + +function buildPayHtml(payUrl: string, params: Record): 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"); + + return ` + + + + + 跳转支付... + + + +

正在跳转到支付页面...

+
+ ${inputs} +
+ + +`; +} + +function detectDevice(request: NextRequest): "pc" | "h5" | "wechat" { + const ua = request.headers.get("user-agent") || ""; + if (/MicroMessenger/i.test(ua)) return "wechat"; + if (/Mobile|Android|iPhone|iPad/i.test(ua)) return "h5"; + return "pc"; +} + +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(); + } else { + const form = await request.formData(); + body = Object.fromEntries(form.entries()) as Record; + } + + const payConfig = getZPayConfig(); + const user_id = String(body?.user_id || `user_${Date.now()}`).trim(); + const return_url = String(body?.return_url || "").trim(); + const total_fee = Number(body?.total_fee) || payConfig.defaultAmount; + const type = String(body?.type || payConfig.defaultType); + const channel = String(body?.channel || "alipay"); + const device = (body?.device as string) || detectDevice(request); + + 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") || SITE_URL; + const finalReturnUrl = return_url || `${origin}/pay/paid`; + + const payload = { + user_id, + total_fee, + type, + channel: device === "wechat" ? "wxpay" : channel, + return_url: finalReturnUrl, + device, + }; + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 15000); + + const redirectRes = await fetch(`${payConfig.apiUrl}/payh5/redirect`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + ...payload, + client_ip: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || + request.headers.get("x-real-ip") || + "", + }), + redirect: "manual", + signal: controller.signal, + }).finally(() => clearTimeout(timeout)); + + const orderId = redirectRes.headers.get("x-pay-order-id")?.trim(); + + if (redirectRes.status >= 301 && redirectRes.status <= 308) { + const location = redirectRes.headers.get("location"); + if (location) { + const res = NextResponse.redirect(location); + if (orderId) { + res.cookies.set("pay_order", `${orderId}|${Date.now()}`, { path: "/", maxAge: 900 }); + } + return res; + } + } + + const resData = await redirectRes.json().catch(() => ({})); + + if (redirectRes.status === 200 && resData?.use_form) { + const { createPayOrder } = await import("@/lib/sdk"); + const { params } = await createPayOrder({ + user_id, + return_url: finalReturnUrl, + total_fee, + type, + channel: "wxpay", + }); + const html = buildPayHtml(payConfig.zpaySubmitUrl, params); + const res = new NextResponse(html, { + status: 200, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + if (orderId) { + res.cookies.set("pay_order", `${orderId}|${Date.now()}`, { path: "/", maxAge: 900 }); + } + return res; + } + + if (redirectRes.status === 200 && resData?.qrcode_mode && resData?.img) { + const returnUrl = String(resData.return_url || finalReturnUrl).replace(/[&<>"']/g, (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c + ); + const imgSrc = String(resData.img).replace(/[&<>"']/g, (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c + ); + const ordId = String(resData.order_id || "").replace(/[&<>"']/g, (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c + ); + const ch = String(resData.channel || "alipay").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)}

+支付二维码 +

支付成功后将自动跳转...

+ +`; + return new NextResponse(html, { + status: 200, + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + + if (redirectRes.status === 400 || redirectRes.status === 500) { + return NextResponse.json( + { ok: false, error: resData?.detail || resData?.msg || "支付跳转失败" }, + { status: redirectRes.status } + ); + } + + 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 hint = + msg.includes("fetch") || msg.includes("ECONNREFUSED") + ? "请确认 payjsapi 已启动:cd C:\\project\\payjsapi && python run.py" + : (err as Error).name === "AbortError" + ? "请求超时,请检查 payjsapi 是否正常运行" + : msg; + console.error("Pay API error:", err); + return NextResponse.json( + { ok: false, error: `支付请求失败: ${hint}` }, + { status: 500 } + ); + } +} diff --git a/app/api/pay/status/route.ts b/app/api/pay/status/route.ts new file mode 100644 index 0000000..58c2133 --- /dev/null +++ b/app/api/pay/status/route.ts @@ -0,0 +1,15 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getOrderStatus } from "@/lib/sdk"; + +export async function GET(request: NextRequest) { + const orderId = request.nextUrl.searchParams.get("order_id"); + if (!orderId) { + return NextResponse.json({ ok: false, error: "缺少 order_id" }, { status: 400 }); + } + try { + const { paid } = await getOrderStatus(orderId); + return NextResponse.json({ ok: true, paid }); + } catch (e) { + return NextResponse.json({ ok: false, paid: false, error: String(e) }, { status: 500 }); + } +} diff --git a/app/certificate/page.tsx b/app/certificate/page.tsx new file mode 100644 index 0000000..346ed09 --- /dev/null +++ b/app/certificate/page.tsx @@ -0,0 +1,82 @@ +"use client"; + +import { useEffect, useState } from "react"; +import Link from "next/link"; +import { Header } from "@/app/components"; +import { getProgress } from "@/app/lib/learning"; +import { CURRICULUM_CONFIG } from "@/config/course"; +import { isPaid } from "@/app/lib/payment"; + +const TOTAL = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0); + +export default function CertificatePage() { + const [progress, setProgress] = useState({ completed: 0, percent: 0 }); + const [paid, setPaid] = useState(false); + + useEffect(() => { + setProgress(getProgress(TOTAL)); + setPaid(isPaid()); + }, []); + + const completed = progress.percent >= 100; + + return ( +
+
+
+
+ {!paid ? ( +
+

报名后可查看证书

+

+ 完成全部 {TOTAL} 节课程后可申请结业证书 +

+ + 立即报名 + +
+ ) : completed ? ( +
+
🎓
+

结业证书

+

+ 恭喜你完成《数字游民实战课》全部 {TOTAL} 节课程 +

+

+ 异度世界、大师兄、小美 +

+ + 返回课程 + +
+ ) : ( +
+

继续加油

+

+ 已完成 {progress.completed}/{TOTAL} 节,完成全部可解锁证书 +

+
+
+
+ + 继续学习 + +
+ )} +
+
+
+ ); +} diff --git a/app/components/AnimateOnScroll.tsx b/app/components/AnimateOnScroll.tsx new file mode 100644 index 0000000..a7e5818 --- /dev/null +++ b/app/components/AnimateOnScroll.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { motion, type HTMLMotionProps } from "framer-motion"; + +type Props = HTMLMotionProps<"div"> & { + delay?: number; +}; + +export function AnimateOnScroll({ children, delay = 0, className = "", ...rest }: Props) { + return ( + + {children} + + ); +} diff --git a/app/components/Button.tsx b/app/components/Button.tsx new file mode 100644 index 0000000..101c948 --- /dev/null +++ b/app/components/Button.tsx @@ -0,0 +1,43 @@ +import Link from "next/link"; + +type ButtonProps = { + href: string; + children: React.ReactNode; + variant?: "primary" | "secondary"; + size?: "sm" | "md" | "lg"; + className?: string; +}; + +const sizeClasses = { + sm: "px-4 py-2 text-sm", + md: "px-5 py-2.5 text-base", + lg: "px-8 py-4 text-lg sm:px-10", +}; + +export function Button({ + href, + children, + variant = "primary", + size = "md", + className = "", +}: ButtonProps) { + const base = + "inline-flex items-center justify-center gap-2 rounded-full font-medium transition"; + const variants = { + primary: + "bg-[var(--accent)] text-[var(--accent-foreground)] hover:opacity-90", + secondary: + "border border-[var(--border)] bg-[var(--card)] hover:bg-[var(--muted)]", + }; + + return ( + + {children} + + ); +} diff --git a/app/components/CommunityButton.tsx b/app/components/CommunityButton.tsx new file mode 100644 index 0000000..2954746 --- /dev/null +++ b/app/components/CommunityButton.tsx @@ -0,0 +1,135 @@ +"use client"; + +import { useState, useEffect } from "react"; +import Link from "next/link"; +import { COMMUNITY_CONFIG } from "@/config/course"; +import { isPaid } from "@/app/lib/payment"; + +export function CommunityButton() { + const [open, setOpen] = useState(false); + const [paid, setPaid] = useState(false); + + useEffect(() => { + setPaid(isPaid()); + const onPay = () => setPaid(isPaid()); + window.addEventListener("pay:updated", onPay); + return () => window.removeEventListener("pay:updated", onPay); + }, []); + + useEffect(() => { + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape") setOpen(false); + }; + if (open) { + window.addEventListener("keydown", onKeyDown); + document.body.style.overflow = "hidden"; + } + return () => { + window.removeEventListener("keydown", onKeyDown); + document.body.style.overflow = ""; + }; + }, [open]); + + if (!COMMUNITY_CONFIG.enabled || !COMMUNITY_CONFIG.wechat) return null; + + return ( + <> + + + {open && ( +
setOpen(false)} + > +
e.stopPropagation()} + > +
+ + + {paid ? ( +
+
+
+ 💬 +
+

加入数字游民社群

+

+ 与导师、同学一起交流,获取持续支持与灵感 +

+
+
+
+ 社群二维码 { + const target = e.target as HTMLImageElement; + target.style.display = "none"; + const fallback = target.parentElement?.querySelector(".qr-fallback"); + if (fallback) (fallback as HTMLElement).classList.remove("hidden"); + }} + /> +
+ 📱 + 请配置社群二维码 + config/course.ts → qrCodeUrl +
+
+
+

+ 长按识别二维码加入 +

+
+ ) : ( +
+
+
+ 🔒 +
+

报名后解锁社群

+

+ 完成课程报名后,即可加入专属社群,与导师、同学交流答疑 +

+
+
+ setOpen(false)} + > + 立即报名 + + +
+
+ )} +
+
+ )} + + ); +} \ No newline at end of file diff --git a/app/components/Footer.tsx b/app/components/Footer.tsx new file mode 100644 index 0000000..84998aa --- /dev/null +++ b/app/components/Footer.tsx @@ -0,0 +1,25 @@ +"use client"; + +import Link from "next/link"; +import { SITE_CONFIG } from "@/config/course"; +import { ShareButton } from "./ShareButton"; +import { CommunityButton } from "./CommunityButton"; + +export function Footer() { + return ( +
+
+
+ + 我的证书 + + + +
+
+ {SITE_CONFIG.footer} +
+
+
+ ); +} diff --git a/app/components/Header.tsx b/app/components/Header.tsx new file mode 100644 index 0000000..11a8bc5 --- /dev/null +++ b/app/components/Header.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { useState, useEffect } from "react"; +import Link from "next/link"; +import { ThemeToggle } from "./ThemeToggle"; +import { SITE_CONFIG } from "@/config/course"; +import { isPaid } from "@/app/lib/payment"; + +export function Header() { + const [paid, setPaid] = 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 ? "进入课程 →" : "立即报名 →"} + + + + + + +
+
+
+ ); +} diff --git a/app/components/Hero.tsx b/app/components/Hero.tsx new file mode 100644 index 0000000..37013bb --- /dev/null +++ b/app/components/Hero.tsx @@ -0,0 +1,111 @@ +"use client"; + +import { useState, useEffect } from "react"; +import Link from "next/link"; +import { HERO_CONFIG, CURRICULUM_CONFIG } from "@/config/course"; +import { isPaid } from "@/app/lib/payment"; +import { getLastWatched, getProgress } from "@/app/lib/learning"; +import { ParticleBackground } from "./ParticleBackground"; + +const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0); + +export function Hero() { + const [paid, setPaid] = useState(false); + const [last, setLast] = useState>(null); + const [progress, setProgress] = useState({ completed: 0, percent: 0 }); + + useEffect(() => { + setPaid(isPaid()); + setLast(getLastWatched()); + setProgress(getProgress(TOTAL_LESSONS)); + const onPay = () => setPaid(isPaid()); + const onProgress = () => { + setLast(getLastWatched()); + setProgress(getProgress(TOTAL_LESSONS)); + }; + window.addEventListener("pay:updated", onPay); + window.addEventListener("learning:progress", onProgress); + return () => { + window.removeEventListener("pay:updated", onPay); + window.removeEventListener("learning:progress", onProgress); + }; + }, []); + + return ( +
+
+ +
+

+ {HERO_CONFIG.title} +

+

+ {HERO_CONFIG.subtitle} +

+
+ {HERO_CONFIG.stats.map((s) => ( +
+
+ {s.value} +
+
+ {s.label} +
+
+ ))} +
+
+ {paid && last ? ( + + 继续学习 → + + ) : ( + + {paid ? "进入课程 →" : "立即报名 →"} + + )} +
+ {paid && progress.completed > 0 && ( +
+
+ 学习进度 + {progress.completed}/{TOTAL_LESSONS} 节 +
+
+
+
+ {progress.percent >= 100 && ( + + 查看证书 → + + )} +
+ )} +
+
+ ); +} diff --git a/app/components/LessonNotes.tsx b/app/components/LessonNotes.tsx new file mode 100644 index 0000000..0d1a5b2 --- /dev/null +++ b/app/components/LessonNotes.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { getNote, setNote } from "@/app/lib/learning"; + +type Props = { moduleIndex: number; lessonIndex: number }; + +export function LessonNotes({ moduleIndex, lessonIndex }: Props) { + const [text, setText] = useState(""); + const [saved, setSaved] = useState(false); + + useEffect(() => { + setText(getNote(moduleIndex, lessonIndex)); + }, [moduleIndex, lessonIndex]); + + const handleSave = () => { + setNote(moduleIndex, lessonIndex, text); + setSaved(true); + setTimeout(() => setSaved(false), 1500); + }; + + return ( +
+

+ 📝 学习笔记 +

+