feat: 支付闭环 + 运营助手 Tool Calling + 管理后台完善

- 支付系统:微信支付 mock 自动完成、NATIVE 扫码支付、JSAPI 集成
- 运营助手:Tool Calling 架构,19 个可执行工具,AI 驱动操作
- 角色管理:表格布局 + Dialog 表单 + 权限勾选
- 配置统一:config.ts 单一数据源
- API 审计:补齐 status toggle / comments 端点
- 暗黑模式硬件编码颜色全部替换为 CSS 变量
This commit is contained in:
yuzhiran-dev
2026-05-20 18:29:00 +08:00
parent 728edc59ef
commit 23edb74bce
76 changed files with 1589 additions and 473 deletions
+1 -1
View File
@@ -1 +1 @@
NEXT_PUBLIC_API_URL=http://localhost:4000
NEXT_PUBLIC_API_URL=http://localhost:4000/api/v1
+279 -2
View File
@@ -32,6 +32,7 @@
"next": "^14.2.35",
"next-themes": "^0.4.6",
"postcss": "^8.5.14",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"recharts": "^3.8.1",
@@ -44,6 +45,7 @@
"@playwright/test": "^1.60.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/qrcode": "^1.5.6",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
@@ -3049,6 +3051,15 @@
"undici-types": "~7.19.0"
}
},
"node_modules/@types/qrcode": {
"version": "1.5.6",
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/react": {
"version": "19.2.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
@@ -3224,9 +3235,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@@ -3428,6 +3437,14 @@
"node": ">=10.16.0"
}
},
"node_modules/camelcase": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
"engines": {
"node": ">=6"
}
},
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -3521,6 +3538,16 @@
"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
"license": "MIT"
},
"node_modules/cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.0",
"wrap-ansi": "^6.2.0"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -3530,6 +3557,22 @@
"node": ">=6"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -3710,6 +3753,14 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/decimal.js": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
@@ -3754,6 +3805,11 @@
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
"license": "Apache-2.0"
},
"node_modules/dijkstrajs": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="
},
"node_modules/dlv": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
@@ -3774,6 +3830,11 @@
"integrity": "sha512-9wHk8x6dyuimoe18EdiDPWKExNdxYqo4fn4FwOVVper6RxT3cmpBwBkWWfSOCYJjQdIco/nPhJhNLmn4Ufg1Yg==",
"license": "ISC"
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
},
"node_modules/entities": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
@@ -3891,6 +3952,18 @@
"node": ">=8"
}
},
"node_modules/find-up": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
"dependencies": {
"locate-path": "^5.0.0",
"path-exists": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/fraction.js": {
"version": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
@@ -3954,6 +4027,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/get-nonce": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",
@@ -4077,6 +4158,14 @@
"node": ">=0.10.0"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"engines": {
"node": ">=8"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
@@ -4440,6 +4529,17 @@
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"license": "MIT"
},
"node_modules/locate-path": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
"dependencies": {
"p-locate": "^4.1.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -4707,6 +4807,39 @@
],
"license": "MIT"
},
"node_modules/p-limit": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
"dependencies": {
"p-try": "^2.0.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/p-locate": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
"dependencies": {
"p-limit": "^2.2.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/p-try": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
"engines": {
"node": ">=6"
}
},
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
@@ -4720,6 +4853,14 @@
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
"engines": {
"node": ">=8"
}
},
"node_modules/path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
@@ -4813,6 +4954,14 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/pngjs": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/postcss": {
"version": "8.5.14",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.14.tgz",
@@ -4995,6 +5144,22 @@
"node": ">=6"
}
},
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
"dependencies": {
"dijkstrajs": "^1.0.1",
"pngjs": "^5.0.0",
"yargs": "^15.3.1"
},
"bin": {
"qrcode": "bin/qrcode"
},
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -5212,6 +5377,14 @@
"redux": "^5.0.0"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -5222,6 +5395,11 @@
"node": ">=0.10.0"
}
},
"node_modules/require-main-filename": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="
},
"node_modules/reselect": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
@@ -5337,6 +5515,11 @@
"loose-envify": "^1.1.0"
}
},
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
@@ -5385,6 +5568,30 @@
"node": ">=10.0.0"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-indent": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
@@ -6057,6 +6264,11 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/which-module": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -6074,6 +6286,33 @@
"node": ">=8"
}
},
"node_modules/wrap-ansi": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/wrap-ansi/node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -6090,6 +6329,44 @@
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
"dev": true,
"license": "MIT"
},
"node_modules/y18n": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="
},
"node_modules/yargs": {
"version": "15.4.1",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
"dependencies": {
"cliui": "^6.0.0",
"decamelize": "^1.2.0",
"find-up": "^4.1.0",
"get-caller-file": "^2.0.1",
"require-directory": "^2.1.1",
"require-main-filename": "^2.0.0",
"set-blocking": "^2.0.0",
"string-width": "^4.2.0",
"which-module": "^2.0.0",
"y18n": "^4.0.0",
"yargs-parser": "^18.1.2"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yargs-parser": {
"version": "18.1.3",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
"dependencies": {
"camelcase": "^5.0.0",
"decamelize": "^1.2.0"
},
"engines": {
"node": ">=6"
}
}
}
}
+2
View File
@@ -48,6 +48,7 @@
"next": "^14.2.35",
"next-themes": "^0.4.6",
"postcss": "^8.5.14",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"recharts": "^3.8.1",
@@ -60,6 +61,7 @@
"@playwright/test": "^1.60.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/qrcode": "^1.5.6",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
+4 -3
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts';
import { TrendingUp, TrendingDown, Users, ShoppingCart, DollarSign, BookOpen, MessageCircle } from 'lucide-react';
import { API_BASE } from '@/lib/config';
interface OverviewData {
users: { total: number; active: number; new: number; growth: number };
@@ -36,11 +37,11 @@ export default function AnalyticsPage() {
try {
const token = localStorage.getItem('adminToken');
const headers = { Authorization: `Bearer ${token}` };
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
const [ovRes, trRes] = await Promise.all([
fetch(`${base}/api/v1/admin/analytics/overview?range=${range}`, { headers }),
fetch(`${base}/api/v1/admin/analytics/trend?type=${trendType}&days=${range === 'today' ? 7 : range === '7d' ? 30 : 90}`, { headers }),
fetch(`${base}/admin/analytics/overview?range=${range}`, { headers }),
fetch(`${base}/admin/analytics/trend?type=${trendType}&days=${range === 'today' ? 7 : range === '7d' ? 30 : 90}`, { headers }),
]);
if (ovRes.ok) setOverview(await ovRes.json());
+2 -1
View File
@@ -2,6 +2,7 @@
import { useEffect, useState, useCallback } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface PendingComment {
id: number;
@@ -17,7 +18,7 @@ export default function AdminCommentsPage() {
const [loading, setLoading] = useState(true);
const [tab, setTab] = useState<'pending' | 'approved' | 'rejected'>('pending');
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api/v1';
const base = API_BASE;
function headers() {
const t = localStorage.getItem('adminToken');
return { 'Content-Type': 'application/json', ...(t ? { Authorization: `Bearer ${t}` } : {}) };
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
export default function EditContentPage() {
const params = useParams();
@@ -17,7 +18,7 @@ export default function EditContentPage() {
useEffect(() => { loadContent(); }, [params.id]);
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
function token() { return localStorage.getItem('adminToken'); }
function headers() {
const t = token();
@@ -26,7 +27,7 @@ export default function EditContentPage() {
async function loadContent() {
try {
const res = await fetch(`${base}/api/v1/contents/${params.id}`, { headers: headers() });
const res = await fetch(`${base}/contents/${params.id}`, { headers: headers() });
if (res.ok) {
const data = await res.json();
setForm({ title: data.title || '', summary: data.summary || '', content: data.content || '', cover: data.cover || '', contentType: data.contentType || 'article' });
@@ -40,7 +41,7 @@ export default function EditContentPage() {
if (!form.title.trim() || !form.content.trim()) return;
setSubmitting(true);
try {
const res = await fetch(`${base}/api/v1/contents/${params.id}`, {
const res = await fetch(`${base}/contents/${params.id}`, {
method: 'PUT', headers: headers(), body: JSON.stringify(form),
});
if (res.ok) router.push('/admin/contents');
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/contents`);
const res = await fetch(`${API_BASE}/contents`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+2 -1
View File
@@ -6,6 +6,7 @@ import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { API_BASE } from '@/lib/config';
export default function NewContentPage() {
const router = useRouter();
@@ -18,7 +19,7 @@ export default function NewContentPage() {
setSubmitting(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/contents`, {
const res = await fetch(`${API_BASE}/contents`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify(form),
+3 -2
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Content {
id: number;
@@ -24,7 +25,7 @@ export default function AdminContents() {
async function loadContents() {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/contents?pageSize=50`, {
const res = await fetch(`${API_BASE}/contents?pageSize=50`, {
headers: { Authorization: `Bearer ${token}` },
});
@@ -39,7 +40,7 @@ export default function AdminContents() {
async function toggleStatus(id: number, currentStatus: string) {
try {
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/contents/${id}/status`, {
await fetch(`${API_BASE}/admin/contents/${id}/status`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
export default function EditCoursePage() {
const params = useParams();
@@ -17,7 +18,7 @@ export default function EditCoursePage() {
useEffect(() => { loadCourse(); }, [params.id]);
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
function token() { return localStorage.getItem('adminToken'); }
function headers() {
const t = token();
@@ -26,7 +27,7 @@ export default function EditCoursePage() {
async function loadCourse() {
try {
const res = await fetch(`${base}/api/v1/courses/${params.id}`, { headers: headers() });
const res = await fetch(`${base}/courses/${params.id}`, { headers: headers() });
if (res.ok) {
const data = await res.json();
setForm({ title: data.title || '', description: data.description || '', cover: data.cover || '', isFree: data.isFree ?? true });
@@ -40,7 +41,7 @@ export default function EditCoursePage() {
if (!form.title.trim()) return;
setSubmitting(true);
try {
const res = await fetch(`${base}/api/v1/courses/${params.id}`, {
const res = await fetch(`${base}/courses/${params.id}`, {
method: 'PUT', headers: headers(), body: JSON.stringify(form),
});
if (res.ok) router.push('/admin/courses');
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/courses`);
const res = await fetch(`${API_BASE}/courses`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+2 -1
View File
@@ -6,6 +6,7 @@ import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { API_BASE } from '@/lib/config';
export default function NewCoursePage() {
const router = useRouter();
@@ -18,7 +19,7 @@ export default function NewCoursePage() {
setSubmitting(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/courses`, {
const res = await fetch(`${API_BASE}/courses`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify(form),
+3 -2
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Course {
id: number;
@@ -24,7 +25,7 @@ export default function AdminCourses() {
async function loadCourses() {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/courses?pageSize=50`, {
const res = await fetch(`${API_BASE}/courses?pageSize=50`, {
headers: { Authorization: `Bearer ${token}` },
});
@@ -39,7 +40,7 @@ export default function AdminCourses() {
async function toggleStatus(id: number, currentStatus: string) {
try {
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/courses/${id}/status`, {
await fetch(`${API_BASE}/admin/courses/${id}/status`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
export default function OrgDetailPage() {
const params = useParams();
@@ -27,11 +28,11 @@ export default function OrgDetailPage() {
useEffect(() => { loadOrg(); loadCourses(); }, [orgId]);
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
async function loadOrg() {
try {
const res = await fetch(`${base}/api/v1/enterprise/organizations/${orgId}`, { headers: headers() });
const res = await fetch(`${base}/enterprise/organizations/${orgId}`, { headers: headers() });
if (res.ok) setOrg(await res.json());
} catch {}
setLoading(false);
@@ -39,7 +40,7 @@ export default function OrgDetailPage() {
async function loadCourses() {
try {
const res = await fetch(`${base}/api/v1/courses`, { headers: headers() });
const res = await fetch(`${base}/courses`, { headers: headers() });
if (res.ok) {
const data = await res.json();
setCourses(data.items || []);
@@ -51,7 +52,7 @@ export default function OrgDetailPage() {
const uid = Number(memberUserId);
if (!uid) return;
try {
const res = await fetch(`${base}/api/v1/enterprise/organizations/${orgId}/members`, {
const res = await fetch(`${base}/enterprise/organizations/${orgId}/members`, {
method: 'POST', headers: headers(),
body: JSON.stringify({ userId: uid }),
});
@@ -65,7 +66,7 @@ export default function OrgDetailPage() {
async function removeMember(userId: number) {
try {
await fetch(`${base}/api/v1/enterprise/organizations/${orgId}/members/${userId}`, {
await fetch(`${base}/enterprise/organizations/${orgId}/members/${userId}`, {
method: 'DELETE', headers: headers(),
});
loadOrg();
@@ -78,7 +79,7 @@ export default function OrgDetailPage() {
try {
const body: any = { courseId: cid };
if (courseDeadline) body.deadline = courseDeadline;
const res = await fetch(`${base}/api/v1/enterprise/organizations/${orgId}/assignments`, {
const res = await fetch(`${base}/enterprise/organizations/${orgId}/assignments`, {
method: 'POST', headers: headers(),
body: JSON.stringify(body),
});
@@ -93,7 +94,7 @@ export default function OrgDetailPage() {
async function updateOrg() {
try {
const res = await fetch(`${base}/api/v1/enterprise/organizations/${orgId}`, {
const res = await fetch(`${base}/enterprise/organizations/${orgId}`, {
method: 'PUT', headers: headers(),
body: JSON.stringify(editForm),
});
@@ -106,7 +107,7 @@ export default function OrgDetailPage() {
async function removeAssignment(courseId: number) {
try {
await fetch(`${base}/api/v1/enterprise/organizations/${orgId}/assignments/${courseId}`, {
await fetch(`${base}/enterprise/organizations/${orgId}/assignments/${courseId}`, {
method: 'DELETE', headers: headers(),
});
loadOrg();
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/enterprise/organizations`);
const res = await fetch(`${API_BASE}/enterprise/organizations`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/enterprise/organizations`);
const res = await fetch(`${API_BASE}/enterprise/organizations`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
export default function OrgReportPage() {
const params = useParams();
@@ -19,11 +20,11 @@ export default function OrgReportPage() {
useEffect(() => { loadReport(); }, [orgId]);
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
async function loadReport() {
try {
const res = await fetch(`${base}/api/v1/enterprise/organizations/${orgId}/report`, { headers: headers() });
const res = await fetch(`${base}/enterprise/organizations/${orgId}/report`, { headers: headers() });
if (res.ok) setReport(await res.json());
} catch {}
setLoading(false);
+5 -4
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Organization {
id: number; name: string; description?: string;
@@ -30,8 +31,8 @@ export default function EnterprisePage() {
async function loadOrgs() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/enterprise/organizations`, { headers: headers() });
const base = API_BASE;
const res = await fetch(`${base}/enterprise/organizations`, { headers: headers() });
if (res.ok) {
const data = await res.json();
setOrgs(data.items || []);
@@ -43,8 +44,8 @@ export default function EnterprisePage() {
async function handleCreate(e: React.FormEvent) {
e.preventDefault();
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/enterprise/organizations`, {
const base = API_BASE;
const res = await fetch(`${base}/enterprise/organizations`, {
method: 'POST', headers: headers(),
body: JSON.stringify(form),
});
+1 -2
View File
@@ -6,8 +6,7 @@ import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
export default function AdminLoginPage() {
const router = useRouter();
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
import { API_BASE } from '@/lib/config';
interface Banner {
id: number;
@@ -24,7 +25,7 @@ export default function BannersPage() {
setLoading(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/banners`, {
const res = await fetch(`${API_BASE}/admin/banners`, {
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
@@ -38,7 +39,7 @@ export default function BannersPage() {
async function createBanner() {
if (!form.title || !form.image) return alert('请填写标题和图片');
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/banners`, {
await fetch(`${API_BASE}/admin/banners`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ ...form, status: 'PUBLISHED' }),
@@ -51,7 +52,7 @@ export default function BannersPage() {
async function deleteBanner(id: number) {
if (!confirm('确定删除?')) return;
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/banners/${id}`, {
await fetch(`${API_BASE}/admin/banners/${id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
});
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
import { API_BASE } from '@/lib/config';
interface Notification {
id: number;
@@ -24,7 +25,7 @@ export default function NotificationsPage() {
setLoading(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/notifications`, {
const res = await fetch(`${API_BASE}/admin/notifications`, {
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
@@ -38,7 +39,7 @@ export default function NotificationsPage() {
async function sendNotification() {
if (!form.title || !form.content) return alert('请填写标题和内容');
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/notifications`, {
await fetch(`${API_BASE}/admin/notifications`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ ...form, status: 'SENT' }),
@@ -51,7 +52,7 @@ export default function NotificationsPage() {
async function deleteNotification(id: number) {
if (!confirm('确定删除?')) return;
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/notifications/${id}`, {
await fetch(`${API_BASE}/admin/notifications/${id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
});
+3 -2
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Order {
id: number;
@@ -23,7 +24,7 @@ export default function AdminOrders() {
async function loadOrders() {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/orders`, {
const res = await fetch(`${API_BASE}/orders`, {
headers: { Authorization: `Bearer ${token}` },
});
@@ -39,7 +40,7 @@ export default function AdminOrders() {
if (!confirm('确认要退款吗?')) return;
try {
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/payment/wxpay/refund`, {
await fetch(`${API_BASE}/payment/wxpay/refund`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+2 -1
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Stats {
totalUsers: number;
@@ -40,7 +41,7 @@ export default function AdminDashboard() {
async function loadStats() {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/dashboard`, {
const res = await fetch(`${API_BASE}/admin/dashboard`, {
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
export default function EditPromptPage() {
const params = useParams();
@@ -17,7 +18,7 @@ export default function EditPromptPage() {
useEffect(() => { loadPrompt(); }, [params.id]);
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
function token() { return localStorage.getItem('adminToken'); }
function headers() {
const t = token();
@@ -26,7 +27,7 @@ export default function EditPromptPage() {
async function loadPrompt() {
try {
const res = await fetch(`${base}/api/v1/prompts/${params.id}`, { headers: headers() });
const res = await fetch(`${base}/prompts/${params.id}`, { headers: headers() });
if (res.ok) {
const data = await res.json();
setForm({ title: data.title || '', content: data.content || '', description: data.description || '', tags: data.tags || '', model: data.model || '' });
@@ -40,7 +41,7 @@ export default function EditPromptPage() {
if (!form.title.trim() || !form.content.trim()) return;
setSubmitting(true);
try {
const res = await fetch(`${base}/api/v1/prompts/${params.id}`, {
const res = await fetch(`${base}/prompts/${params.id}`, {
method: 'PUT', headers: headers(), body: JSON.stringify(form),
});
if (res.ok) router.push('/admin/prompts');
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/prompts`);
const res = await fetch(`${API_BASE}/prompts`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+2 -1
View File
@@ -6,6 +6,7 @@ import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { API_BASE } from '@/lib/config';
export default function NewPromptPage() {
const router = useRouter();
@@ -18,7 +19,7 @@ export default function NewPromptPage() {
setSubmitting(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/prompts`, {
const res = await fetch(`${API_BASE}/prompts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify(form),
+3 -2
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Prompt {
id: number;
@@ -24,7 +25,7 @@ export default function AdminPrompts() {
async function loadPrompts() {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/prompts?pageSize=50`, {
const res = await fetch(`${API_BASE}/prompts?pageSize=50`, {
headers: { Authorization: `Bearer ${token}` },
});
@@ -39,7 +40,7 @@ export default function AdminPrompts() {
async function toggleStatus(id: number, currentStatus: string) {
try {
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/prompts/${id}/status`, {
await fetch(`${API_BASE}/admin/prompts/${id}/status`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
import { API_BASE } from '@/lib/config';
interface Config {
key: string;
@@ -21,7 +22,7 @@ export default function ConfigPage() {
setLoading(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/config/${category}`, {
const res = await fetch(`${API_BASE}/admin/config/${category}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
@@ -37,7 +38,7 @@ export default function ConfigPage() {
async function saveConfig(key: string) {
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/config/${key}`, {
await fetch(`${API_BASE}/admin/config/${key}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ value: form[key] }),
+366 -175
View File
@@ -1,7 +1,12 @@
'use client';
import { useEffect, useState } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { API_BASE } from '@/lib/config';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import * as Dialog from '@/components/ui/dialog';
interface Role {
id: string;
@@ -17,6 +22,20 @@ interface Permission {
category: string;
}
interface Admin {
id: number;
username: string;
nickname: string;
roleId: string | null;
role: { id: string; name: string } | null;
status: string;
}
function getAuthHeaders() {
const token = localStorage.getItem('adminToken');
return { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
}
export default function SettingsRolesPage() {
const router = useRouter();
const [roles, setRoles] = useState<Role[]>([]);
@@ -24,213 +43,385 @@ export default function SettingsRolesPage() {
const [loading, setLoading] = useState(true);
const [tab, setTab] = useState<'roles' | 'admins'>('roles');
useEffect(() => {
loadData();
}, []);
async function loadData() {
const loadData = useCallback(async () => {
setLoading(true);
try {
const token = localStorage.getItem('adminToken');
const headers = { Authorization: `Bearer ${token}` };
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const headers = getAuthHeaders();
const [rolesRes, permsRes] = await Promise.all([
fetch(`${base}/api/v1/admin/settings/roles`, { headers }),
fetch(`${base}/api/v1/admin/settings/permissions`, { headers }),
fetch(`${API_BASE}/admin/settings/roles`, { headers }),
fetch(`${API_BASE}/admin/settings/permissions`, { headers }),
]);
if (rolesRes.ok) {
const data = await rolesRes.json();
setRoles(data.items || []);
}
if (permsRes.ok) {
const data = await permsRes.json();
setPermissions(data.items || []);
}
} catch {}
if (rolesRes.ok) setRoles((await rolesRes.json()).items || []);
if (permsRes.ok) setPermissions((await permsRes.json()).items || []);
} catch (e) { console.error(e); }
setLoading(false);
}
}, []);
async function createRole() {
const name = prompt('请输入角色名称:');
if (!name) return;
const desc = prompt('请输入角色描述:') || '';
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/settings/roles`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ name, description: desc }),
});
loadData();
}
async function deleteRole(id: string) {
if (!confirm('确定要删除这个角色吗?')) return;
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/settings/roles/${id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
});
loadData();
}
useEffect(() => { loadData(); }, [loadData]);
const categories = [...new Set(permissions.map(p => p.category))];
if (loading) {
return <div className="p-6">...</div>;
return <div className="p-6 text-center text-muted-foreground">...</div>;
}
return (
<div className="p-6">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-foreground"></h1>
<p className="text-sm text-muted-foreground"></p>
<h1 className="text-3xl font-bold text-foreground"></h1>
<p className="mt-2 text-muted-foreground"></p>
</div>
<button
onClick={createRole}
className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
>
</button>
</div>
<div className="flex gap-4 mb-6">
<button
onClick={() => setTab('roles')}
className={`px-4 py-2 rounded-lg ${tab === 'roles' ? 'bg-brand-600 text-white' : 'bg-muted text-muted-foreground'}`}
>
</button>
<button
onClick={() => setTab('admins')}
className={`px-4 py-2 rounded-lg ${tab === 'admins' ? 'bg-brand-600 text-white' : 'bg-muted text-muted-foreground'}`}
>
</button>
<Button variant={tab === 'roles' ? 'default' : 'outline'} onClick={() => setTab('roles')}></Button>
<Button variant={tab === 'admins' ? 'default' : 'outline'} onClick={() => setTab('admins')}></Button>
</div>
{tab === 'roles' ? (
<div className="space-y-4">
{roles.length === 0 ? (
<div className="text-center py-12 text-muted-foreground"></div>
) : (
roles.map(role => (
<div key={role.id} className="bg-card border border-border rounded-xl p-4">
<div className="flex items-center justify-between">
<div>
<div className="font-medium text-foreground">{role.name}</div>
<div className="text-sm text-muted-foreground">{role.description || '暂无描述'}</div>
<div className="flex flex-wrap gap-1 mt-2">
{(role.permissions || []).map((p: string) => (
<span key={p} className="text-xs px-2 py-0.5 bg-muted text-muted-foreground rounded">
{permissions.find(perm => perm.key === p)?.name || p}
</span>
))}
</div>
</div>
<button
onClick={() => deleteRole(role.id)}
className="text-red-500 hover:text-red-700 text-sm"
>
</button>
</div>
</div>
))
)}
</div>
<RolesTab roles={roles} permissions={permissions} categories={categories} onReload={loadData} />
) : (
<AdminsList />
<AdminsTab onReload={loadData} />
)}
</div>
);
}
function AdminsList() {
const [admins, setAdmins] = useState<any[]>([]);
const [roles, setRoles] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
loadData();
}, []);
async function loadData() {
setLoading(true);
try {
const token = localStorage.getItem('adminToken');
const headers = { Authorization: `Bearer ${token}` };
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const [adminsRes, rolesRes] = await Promise.all([
fetch(`${base}/api/v1/admin/settings/admins`, { headers }),
fetch(`${base}/api/v1/admin/settings/roles`, { headers }),
]);
if (adminsRes.ok) {
const data = await adminsRes.json();
setAdmins(data.items || []);
}
if (rolesRes.ok) {
const data = await rolesRes.json();
setRoles(data.items || []);
}
} catch {}
setLoading(false);
}
async function createAdmin() {
const username = prompt('请输入管理员用户名:');
if (!username) return;
const password = prompt('请输入密码:');
if (!password) return;
const nickname = prompt('请输入昵称(可选):') || '';
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/settings/admins`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ username, password, nickname }),
});
loadData();
}
if (loading) return <div>...</div>;
function RolesTab({ roles, permissions, categories, onReload }: {
roles: Role[]; permissions: Permission[]; categories: string[]; onReload: () => void;
}) {
const [editRole, setEditRole] = useState<Role | null>(null);
const [open, setOpen] = useState(false);
return (
<div>
<button
onClick={createAdmin}
className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 mb-4"
>
</button>
<div className="space-y-3">
{admins.map(admin => (
<div key={admin.id} className="bg-card border border-border rounded-xl p-4 flex items-center justify-between">
<div>
<div className="font-medium text-foreground">{admin.username}</div>
<div className="text-sm text-muted-foreground">{admin.nickname || '暂无昵称'} · {admin.role?.name || '未分配角色'}</div>
</div>
<button
onClick={async () => {
if (!confirm('确定要禁用这个管理员吗?')) return;
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/settings/admins/${admin.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ status: 'DISABLED' }),
});
loadData();
}}
className="text-red-500 hover:text-red-700 text-sm"
>
</button>
<div className="flex justify-end mb-4">
<Button onClick={() => { setEditRole(null); setOpen(true); }}></Button>
</div>
<RoleDialog
role={editRole}
permissions={permissions}
categories={categories}
open={open}
onOpenChange={setOpen}
onSaved={() => { setOpen(false); onReload(); }}
/>
{roles.length === 0 ? (
<div className="text-center py-12 text-muted-foreground"></div>
) : (
<div className="bg-card border border-border rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-muted/50">
<th className="text-left px-4 py-3 font-medium text-foreground"></th>
<th className="text-left px-4 py-3 font-medium text-foreground"></th>
<th className="text-left px-4 py-3 font-medium text-foreground"></th>
<th className="text-right px-4 py-3 font-medium text-foreground"></th>
</tr>
</thead>
<tbody>
{roles.map(role => (
<tr key={role.id} className="border-b border-border hover:bg-muted/30">
<td className="px-4 py-3 font-medium text-foreground">{role.name}</td>
<td className="px-4 py-3 text-muted-foreground">{role.description || '-'}</td>
<td className="px-4 py-3">
<div className="flex flex-wrap gap-1">
{(role.permissions || []).length === 0 ? (
<span className="text-xs text-muted-foreground"></span>
) : (
role.permissions.map(p => (
<Badge key={p} variant="secondary" className="text-xs">
{permissions.find(perm => perm.key === p)?.name || p}
</Badge>
))
)}
</div>
</td>
<td className="px-4 py-3 text-right">
<div className="flex justify-end gap-2">
<Button variant="ghost" size="sm" onClick={() => { setEditRole(role); setOpen(true); }}></Button>
<Button variant="ghost" size="sm" className="text-red-500 hover:text-red-700"
onClick={async () => {
if (!confirm('确定要删除此角色吗?')) return;
await fetch(`${API_BASE}/admin/settings/roles/${role.id}`, { method: 'DELETE', headers: getAuthHeaders() });
onReload();
}}
></Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
function RoleDialog({ role, permissions, categories, open, onOpenChange, onSaved }: {
role: Role | null; permissions: Permission[]; categories: string[]; open: boolean; onOpenChange: (v: boolean) => void; onSaved: () => void;
}) {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [selectedPerms, setSelectedPerms] = useState<string[]>([]);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (open) {
setName(role?.name || '');
setDescription(role?.description || '');
setSelectedPerms(role?.permissions || []);
}
}, [open, role]);
async function handleSave() {
if (!name.trim()) return;
setSaving(true);
try {
const headers = getAuthHeaders();
if (role) {
await fetch(`${API_BASE}/admin/settings/roles/${role.id}`, {
method: 'PUT', headers,
body: JSON.stringify({ name, description, permissions: selectedPerms }),
});
} else {
await fetch(`${API_BASE}/admin/settings/roles`, {
method: 'POST', headers,
body: JSON.stringify({ name, description, permissions: selectedPerms }),
});
}
onSaved();
} catch (e) { console.error(e); }
setSaving(false);
}
return (
<Dialog.Dialog open={open} onOpenChange={onOpenChange}>
<Dialog.DialogContent>
<Dialog.DialogHeader>
<Dialog.DialogTitle>{role ? '编辑角色' : '新建角色'}</Dialog.DialogTitle>
</Dialog.DialogHeader>
<div className="space-y-4 py-2">
<div>
<label className="block text-sm font-medium text-foreground mb-1"></label>
<Input value={name} onChange={e => setName(e.target.value)} placeholder="请输入角色名称" />
</div>
))}
<div>
<label className="block text-sm font-medium text-foreground mb-1"></label>
<textarea
className="flex w-full rounded-lg border border-border bg-transparent px-3 py-2 text-sm"
rows={2}
value={description}
onChange={e => setDescription(e.target.value)}
placeholder="请输入角色描述"
/>
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-2"></label>
{categories.map(cat => (
<div key={cat} className="mb-2">
<div className="text-xs font-medium text-muted-foreground mb-1">{cat}</div>
<div className="flex flex-wrap gap-2">
{permissions.filter(p => p.category === cat).map(perm => (
<label key={perm.key} className="flex items-center gap-1.5 cursor-pointer">
<input
type="checkbox"
checked={selectedPerms.includes(perm.key)}
onChange={e => {
setSelectedPerms(prev =>
e.target.checked
? [...prev, perm.key]
: prev.filter(k => k !== perm.key)
);
}}
className="rounded border-border"
/>
<span className="text-sm text-foreground">{perm.name}</span>
</label>
))}
</div>
</div>
))}
</div>
</div>
<Dialog.DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}></Button>
<Button onClick={handleSave} disabled={!name.trim() || saving}>
{saving ? '保存中...' : '保存'}
</Button>
</Dialog.DialogFooter>
</Dialog.DialogContent>
</Dialog.Dialog>
);
}
function AdminsTab({ onReload }: { onReload: () => void }) {
const [admins, setAdmins] = useState<Admin[]>([]);
const [roles, setRoles] = useState<Role[]>([]);
const [loading, setLoading] = useState(true);
const [open, setOpen] = useState(false);
const [editAdmin, setEditAdmin] = useState<Admin | null>(null);
const loadData = useCallback(async () => {
setLoading(true);
try {
const headers = getAuthHeaders();
const [adminsRes, rolesRes] = await Promise.all([
fetch(`${API_BASE}/admin/settings/admins`, { headers }),
fetch(`${API_BASE}/admin/settings/roles`, { headers }),
]);
if (adminsRes.ok) setAdmins((await adminsRes.json()).items || []);
if (rolesRes.ok) setRoles((await rolesRes.json()).items || []);
} catch (e) { console.error(e); }
setLoading(false);
}, []);
useEffect(() => { loadData(); }, [loadData]);
if (loading) return <div className="text-center py-8 text-muted-foreground">...</div>;
return (
<div>
<div className="flex justify-end mb-4">
<Button onClick={() => { setEditAdmin(null); setOpen(true); }}></Button>
</div>
<AdminDialog
admin={editAdmin}
roles={roles}
open={open}
onOpenChange={setOpen}
onSaved={() => { setOpen(false); loadData(); onReload(); }}
/>
<div className="bg-card border border-border rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-muted/50">
<th className="text-left px-4 py-3 font-medium text-foreground"></th>
<th className="text-left px-4 py-3 font-medium text-foreground"></th>
<th className="text-left px-4 py-3 font-medium text-foreground"></th>
<th className="text-right px-4 py-3 font-medium text-foreground"></th>
</tr>
</thead>
<tbody>
{admins.map(admin => (
<tr key={admin.id} className="border-b border-border hover:bg-muted/30">
<td className="px-4 py-3 font-medium text-foreground">{admin.username}</td>
<td className="px-4 py-3 text-muted-foreground">{admin.nickname || '-'}</td>
<td className="px-4 py-3">
<Badge variant="secondary" className="text-xs">{admin.role?.name || '未分配'}</Badge>
</td>
<td className="px-4 py-3 text-right">
<div className="flex justify-end gap-2">
<Button variant="ghost" size="sm" onClick={() => { setEditAdmin(admin); setOpen(true); }}></Button>
<Button variant="ghost" size="sm" className="text-red-500 hover:text-red-700"
onClick={async () => {
if (!confirm('确定要禁用此管理员吗?')) return;
await fetch(`${API_BASE}/admin/settings/admins/${admin.id}`, {
method: 'PUT', headers: getAuthHeaders(),
body: JSON.stringify({ status: 'DISABLED' }),
});
loadData();
}}
></Button>
</div>
</td>
</tr>
))}
{admins.length === 0 && (
<tr><td colSpan={4} className="text-center py-8 text-muted-foreground"></td></tr>
)}
</tbody>
</table>
</div>
</div>
);
}
}
function AdminDialog({ admin, roles, open, onOpenChange, onSaved }: {
admin: Admin | null; roles: Role[]; open: boolean; onOpenChange: (v: boolean) => void; onSaved: () => void;
}) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [nickname, setNickname] = useState('');
const [roleId, setRoleId] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (open) {
setUsername(admin?.username || '');
setPassword('');
setNickname(admin?.nickname || '');
setRoleId(admin?.roleId || '');
}
}, [open, admin]);
async function handleSave() {
if (!username.trim()) return;
if (!admin && !password.trim()) return;
setSaving(true);
try {
const headers = getAuthHeaders();
if (admin) {
await fetch(`${API_BASE}/admin/settings/admins/${admin.id}`, {
method: 'PUT', headers,
body: JSON.stringify({ nickname, roleId: roleId || null }),
});
} else {
await fetch(`${API_BASE}/admin/settings/admins`, {
method: 'POST', headers,
body: JSON.stringify({ username, password, nickname, roleId: roleId || undefined }),
});
}
onSaved();
} catch (e) { console.error(e); }
setSaving(false);
}
return (
<Dialog.Dialog open={open} onOpenChange={onOpenChange}>
<Dialog.DialogContent>
<Dialog.DialogHeader>
<Dialog.DialogTitle>{admin ? '编辑管理员' : '新建管理员'}</Dialog.DialogTitle>
</Dialog.DialogHeader>
<div className="space-y-4 py-2">
<div>
<label className="block text-sm font-medium text-foreground mb-1"></label>
<Input value={username} onChange={e => setUsername(e.target.value)} placeholder="登录用户名"
disabled={!!admin} />
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-1">{admin ? '新密码(留空不修改)' : '密码'}</label>
<Input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder={admin ? '留空则不修改' : '请输入密码'} />
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-1"></label>
<Input value={nickname} onChange={e => setNickname(e.target.value)} placeholder="可选" />
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-1"></label>
<select
className="flex w-full rounded-lg border border-border bg-transparent px-3 py-2 text-sm"
value={roleId}
onChange={e => setRoleId(e.target.value)}
>
<option value=""></option>
{roles.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
</select>
</div>
</div>
<Dialog.DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}></Button>
<Button onClick={handleSave} disabled={!username.trim() || (!admin && !password.trim()) || saving}>
{saving ? '保存中...' : '保存'}
</Button>
</Dialog.DialogFooter>
</Dialog.DialogContent>
</Dialog.Dialog>
);
}
+3 -2
View File
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
export default function EditToolPage() {
const params = useParams();
@@ -17,7 +18,7 @@ export default function EditToolPage() {
useEffect(() => { loadTool(); }, [params.id]);
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const base = API_BASE;
function token() { return localStorage.getItem('adminToken'); }
function headers() {
const t = token();
@@ -26,7 +27,7 @@ export default function EditToolPage() {
async function loadTool() {
try {
const res = await fetch(`${base}/api/v1/tools`, { headers: headers() });
const res = await fetch(`${base}/tools`, { headers: headers() });
if (res.ok) {
const data = await res.json();
const tool = (data.items || []).find((t: any) => t.id === Number(params.id));
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/tools`);
const res = await fetch(`${API_BASE}/tools`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+2 -1
View File
@@ -6,6 +6,7 @@ import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { API_BASE } from '@/lib/config';
export default function NewToolPage() {
const router = useRouter();
@@ -18,7 +19,7 @@ export default function NewToolPage() {
setSubmitting(true);
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/tools`, {
const res = await fetch(`${API_BASE}/tools`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify(form),
+3 -2
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Tool {
id: number;
@@ -23,7 +24,7 @@ export default function AdminTools() {
async function loadTools() {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/tools?pageSize=50`, {
const res = await fetch(`${API_BASE}/tools?pageSize=50`, {
headers: { Authorization: `Bearer ${token}` },
});
@@ -38,7 +39,7 @@ export default function AdminTools() {
async function toggleStatus(id: number, currentStatus: string) {
try {
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/tools/${id}/status`, {
await fetch(`${API_BASE}/admin/tools/${id}/status`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
+6 -5
View File
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
import { API_BASE } from '@/lib/config';
interface User {
id: number;
@@ -27,7 +28,7 @@ export default function UsersPage() {
try {
const token = localStorage.getItem('adminToken');
const params = search ? `?search=${encodeURIComponent(search)}` : '';
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/users${params}`, {
const res = await fetch(`${API_BASE}/admin/users${params}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
@@ -41,7 +42,7 @@ export default function UsersPage() {
async function createUser() {
if (!form.phone || !form.password) return alert('手机号和密码必填');
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/users`, {
await fetch(`${API_BASE}/admin/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify(form),
@@ -54,7 +55,7 @@ export default function UsersPage() {
async function updateUser() {
if (!editId) return;
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/users/${editId}`, {
await fetch(`${API_BASE}/admin/users/${editId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ nickname: form.nickname, email: form.email }),
@@ -68,7 +69,7 @@ export default function UsersPage() {
async function deleteUser(id: number) {
if (!confirm('确定删除该用户?')) return;
const token = localStorage.getItem('adminToken');
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/users/${id}`, {
await fetch(`${API_BASE}/admin/users/${id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
});
@@ -78,7 +79,7 @@ export default function UsersPage() {
async function toggleStatus(id: number, currentStatus: string) {
const token = localStorage.getItem('adminToken');
const newStatus = currentStatus === 'ACTIVE' ? 'BANNED' : 'ACTIVE';
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/admin/users/${id}`, {
await fetch(`${API_BASE}/admin/users/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ status: newStatus }),
+1 -2
View File
@@ -10,8 +10,7 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/com
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { useAuth } from '@/lib/auth-context';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
function AuthForm() {
const searchParams = useSearchParams();
+7 -6
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Post {
id: number;
@@ -36,8 +37,8 @@ export default function CircleDetail() {
if (token) headers['Authorization'] = `Bearer ${token}`;
const [circleRes, postsRes] = await Promise.all([
fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/circles/${circleId}`, { headers }),
fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/circles/${circleId}/posts`, { headers }),
fetch(`${API_BASE}/circles/${circleId}`, { headers }),
fetch(`${API_BASE}/circles/${circleId}/posts`, { headers }),
]);
if (circleRes.ok) setCircle(await circleRes.json());
@@ -47,7 +48,7 @@ export default function CircleDetail() {
}
if (token) {
const memRes = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/circles/${circleId}/membership`, {
const memRes = await fetch(`${API_BASE}/circles/${circleId}/membership`, {
headers: { Authorization: `Bearer ${token}` },
});
if (memRes.ok) {
@@ -65,8 +66,8 @@ export default function CircleDetail() {
const method = isMember ? 'POST' : 'POST';
const url = isMember
? `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/circles/${circleId}/leave`
: `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/circles/${circleId}/join`;
? `${API_BASE}/circles/${circleId}/leave`
: `${API_BASE}/circles/${circleId}/join`;
try {
const res = await fetch(url, {
@@ -85,7 +86,7 @@ export default function CircleDetail() {
if (!token || !formTitle || !formContent) return;
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/community/posts`, {
const res = await fetch(`${API_BASE}/community/posts`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ title: formTitle, content: formContent, circleId }),
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/circles`);
const res = await fetch(`${API_BASE}/circles`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+2 -1
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface Circle {
id: number;
@@ -21,7 +22,7 @@ export default function CirclesPage() {
async function loadCircles() {
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/v1/circles`);
const res = await fetch(`${API_BASE}/circles`);
if (res.ok) {
const data = await res.json();
setCircles(data || []);
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/community/posts`);
const res = await fetch(`${API_BASE}/community/posts`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+1 -2
View File
@@ -4,8 +4,7 @@ import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Content {
id: number; title: string; summary?: string; content?: string; cover?: string;
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/contents`);
const res = await fetch(`${API_BASE}/contents`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+1 -2
View File
@@ -6,8 +6,7 @@ import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { FileText, Eye } from 'lucide-react';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Content {
id: number; title: string; summary: string | null; cover: string | null;
+1 -2
View File
@@ -4,8 +4,7 @@ import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Lesson {
id: number; title: string; content?: string; sortOrder: number; status: string;
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/courses`);
const res = await fetch(`${API_BASE}/courses`);
const data = await res.json();
const items = data.items || [];
if (items.length === 0) return [{ id: '1' }];
+1 -2
View File
@@ -6,8 +6,7 @@ import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { BookOpen, Users } from 'lucide-react';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Course {
id: number; title: string; description: string; cover: string | null;
+2 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from 'next';
import './globals.css';
import { RootLayoutClient } from './layout-client';
import { SITE_URL } from '@/lib/config';
export const metadata: Metadata = {
title: {
@@ -20,7 +21,7 @@ export const metadata: Metadata = {
siteName: '宇之然 AI',
title: '宇之然 AI - AI 工具与知识社区',
description: '让每个人都能用好 AI',
url: 'https://yuzhiran.com',
url: SITE_URL,
},
};
+1 -2
View File
@@ -2,8 +2,7 @@
import { useEffect, useState } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface AiModel {
id: number;
+50 -6
View File
@@ -4,7 +4,19 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetch } from '../../../lib/auth';
import { Skeleton } from '@/components/ui/skeleton';
import PaymentModal from '@/components/ui/payment-modal';
import { useT } from '@/i18n';
import { isWeChatBrowser, getOpenidFromUrl, isMiniProgram } from '@/lib/wechat';
interface PayResult {
prepay_id?: string;
nonceStr?: string;
timeStamp?: string;
package?: string;
paySign?: string;
signType?: string;
codeUrl?: string;
}
interface Subscription {
id: number; plan: string; startDate: string; endDate: string; status: string;
@@ -29,6 +41,9 @@ export default function MemberPage() {
const [quota, setQuota] = useState<{ used: number; remaining: number; dailyLimit: number } | null>(null);
const [loading, setLoading] = useState(true);
const [payLoading, setPayLoading] = useState<string | null>(null);
const [paymentModal, setPaymentModal] = useState<{
open: boolean; orderNo: string; payResult: PayResult; tradeType: 'JSAPI' | 'NATIVE';
}>({ open: false, orderNo: '', payResult: {}, tradeType: 'NATIVE' });
useEffect(() => { loadData(); }, []);
@@ -51,22 +66,43 @@ export default function MemberPage() {
async function handleSubscribe(planType: string) {
setPayLoading(planType);
try {
const inWeChat = isWeChatBrowser();
const openid = getOpenidFromUrl();
const useJsapi = inWeChat && openid && isMiniProgram();
const tradeType = useJsapi ? 'JSAPI' : 'NATIVE';
const body: Record<string, any> = {
amount: planType === 'MONTHLY' ? 29.9 : 199,
planType, payChannel: 'wxpay', tradeType,
};
if (useJsapi && openid) body.openid = openid;
const res = await apiFetch('/orders/create', {
method: 'POST',
body: JSON.stringify({
amount: planType === 'MONTHLY' ? 29.9 : 199,
planType, payChannel: 'wxpay',
}),
body: JSON.stringify(body),
});
const data = await res.json();
if (data.order && data.payResult) {
alert('订单创建成功,请扫码支付(模拟模式)');
loadData();
// Mock mode → auto-completed by backend
if (data.payResult.codeUrl === 'mock://pay') {
loadData();
} else {
setPaymentModal({
open: true, orderNo: data.order.orderNo,
payResult: data.payResult, tradeType,
});
}
}
} catch (e) { console.error(e) }
setPayLoading(null);
}
function handlePaymentPaid() {
setPaymentModal(prev => ({ ...prev, open: false }));
loadData();
}
if (loading) return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<Skeleton className="h-8 w-48 mb-2" />
@@ -161,6 +197,14 @@ export default function MemberPage() {
</div>
)}
</div>
<PaymentModal
open={paymentModal.open}
orderNo={paymentModal.orderNo}
payResult={paymentModal.payResult}
tradeType={paymentModal.tradeType}
onPaid={handlePaymentPaid}
onClose={() => setPaymentModal(prev => ({ ...prev, open: false }))}
/>
</div>
);
}
+1 -2
View File
@@ -5,8 +5,7 @@ import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { MessageSquare, Heart } from 'lucide-react';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Prompt {
id: number; title: string; description: string; content: string;
+1 -2
View File
@@ -6,8 +6,7 @@ import { useAuth } from '@/lib/auth-context';
import { apiFetch, getToken } from '@/lib/auth';
import { AVAILABLE_MODELS, DEFAULT_MODEL } from '@/lib/models';
import { ModelSelector } from '@/components/ui/model-selector';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Message {
role: 'user' | 'assistant';
+3 -4
View File
@@ -9,8 +9,7 @@ import { DEFAULT_MODEL } from '@/lib/models';
import { ModelSelector } from '@/components/ui/model-selector';
import { useT } from '@/i18n';
import { CodeBlock } from '@/components/ui/code-block';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Message {
role: 'system' | 'user' | 'assistant';
@@ -22,7 +21,7 @@ interface SessionItem {
conversationId: string;
model: string;
title: string;
updatedAt: string;
createdAt: string;
tokens: number;
}
@@ -365,7 +364,7 @@ function SandboxPage() {
<div className="text-xs font-medium text-foreground truncate">{s.title}</div>
)}
<div className="flex items-center justify-between mt-1">
<span className="text-[10px] text-muted-foreground">{formatTime(s.updatedAt)} · {s.model}</span>
<span className="text-[10px] text-muted-foreground">{formatTime(s.createdAt)} · {s.model}</span>
<button onClick={e => { e.stopPropagation(); deleteSession(s.id); }}
className="opacity-0 group-hover:opacity-100 text-[10px] text-red-500 hover:text-red-700">
{t.common.delete}
+1 -2
View File
@@ -4,8 +4,7 @@ import { Suspense, useEffect, useState } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface SharedMessage {
role: string;
+1 -2
View File
@@ -8,8 +8,7 @@ import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { SearchIcon, FileText, BookOpen, Wrench, MessageSquare } from 'lucide-react';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface SearchResult {
id: number; _type: 'course' | 'prompt' | 'tool' | 'content';
+1 -2
View File
@@ -5,8 +5,7 @@ import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { useT } from '@/i18n';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface SkillTask { label: string; prompt: string }
interface Skill {
+1 -2
View File
@@ -4,8 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { useT } from '@/i18n';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Skill {
id: string; name: string; description: string; icon: string;
+1 -2
View File
@@ -5,8 +5,7 @@ import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Wrench, ExternalLink, Star } from 'lucide-react';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
interface Tool {
id: number; name: string; description: string; url: string;
+3 -2
View File
@@ -1,7 +1,8 @@
import { API_BASE } from '@/lib/config';
export async function generateStaticParams() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/users`, {
const res = await fetch(`${API_BASE}/users`, {
headers: { 'Content-Type': 'application/json' },
});
const data = await res.json();
+8 -11
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
interface UserProfile {
id: number; nickname: string; avatar?: string; bio?: string;
@@ -39,10 +40,9 @@ export default function UserProfilePage() {
async function loadData() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const [profileRes, postsRes] = await Promise.all([
fetch(`${base}/api/v1/community/users/${userId}/profile`),
fetch(`${base}/api/v1/community/posts?userId=${userId}`),
const [profileRes, postsRes] = await Promise.all([
fetch(`${API_BASE}/community/users/${userId}/profile`),
fetch(`${API_BASE}/community/posts?userId=${userId}`),
]);
if (profileRes.ok) setProfile(await profileRes.json());
if (postsRes.ok) {
@@ -52,7 +52,7 @@ export default function UserProfilePage() {
const token = getToken();
if (token) {
const followRes = await fetch(`${base}/api/v1/community/users/${userId}/follow`, {
const followRes = await fetch(`${API_BASE}/community/users/${userId}/follow`, {
headers: { Authorization: `Bearer ${token}` },
});
if (followRes.ok) {
@@ -67,8 +67,7 @@ export default function UserProfilePage() {
const token = getToken();
if (!token) return;
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/community/users/${userId}/follow`, {
const res = await fetch(`${API_BASE}/community/users/${userId}/follow`, {
method: isFollowing ? 'DELETE' : 'POST',
headers: apiHeaders(),
});
@@ -84,8 +83,7 @@ export default function UserProfilePage() {
async function loadFollowers() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/community/users/${userId}/followers`);
const res = await fetch(`${API_BASE}/community/users/${userId}/followers`);
if (res.ok) {
const d = await res.json();
setFollowers(d.items || []);
@@ -95,8 +93,7 @@ export default function UserProfilePage() {
async function loadFollowing() {
try {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const res = await fetch(`${base}/api/v1/community/users/${userId}/following`);
const res = await fetch(`${API_BASE}/community/users/${userId}/following`);
if (res.ok) {
const d = await res.json();
setFollowing(d.items || []);
+96 -134
View File
@@ -2,100 +2,97 @@
import { useState, useRef, useEffect, FormEvent } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { MessageCircle, X, Send, Minus, Sparkles, FileText, BookOpen, Image, Settings } from 'lucide-react';
import { useT } from '@/i18n';
import { X, Send, Minus } from 'lucide-react';
import { getAdminToken } from '@/lib/auth';
import { toast } from 'sonner';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api/v1';
import { API_BASE } from '@/lib/config';
interface Message {
role: 'user' | 'assistant';
content: string;
}
interface AdminContext {
page: string;
systemPrompt: string;
starters: string[];
}
const AVAILABLE_TOOLS_DESC = `可用工具列表(需要执行操作时,返回 JSON{"tool":"工具名","params":{...},"description":"简述"}):
const adminContexts: Record<string, AdminContext> = {
'/admin': {
page: 'dashboard',
systemPrompt: '你是宇之然AI管理后台的智能助手。帮助管理员完成日常运营工作,包括:数据分析、用户管理、内容审核、订单处理等。',
starters: ['查看今日数据', '最近有哪些新用户', '待处理订单数量', '系统运行状态'],
},
'/admin/users': {
page: 'users',
systemPrompt: '你是用户管理助手。可以帮助:查看用户列表、搜索用户、修改用户状态、查看用户详情。',
starters: ['列出最近注册的用户', '查找某个用户', '批量启用/禁用用户', '查看用户详情'],
},
'/admin/courses': {
page: 'courses',
systemPrompt: '你是课程管理助手。可以帮助:创建新课程、编辑课程信息、上下架课程、管理课程章节。',
starters: ['创建新课程', '课程列表', '下架某个课程', '添加课程章节'],
},
'/admin/contents': {
page: 'contents',
systemPrompt: '你是内容管理助手。可以帮助:创建文章、编辑内容、设置分类、发布/下架。',
starters: ['创建新文章', '内容列表', '编辑某篇文章', '设置文章分类'],
},
'/admin/prompts': {
page: 'prompts',
systemPrompt: '你是提示词管理助手。可以帮助:创建提示词、审核提示词、设置分类、推荐优质提示词。',
starters: ['创建新提示词', '待审核列表', '热门提示词', '添加提示词标签'],
},
'/admin/orders': {
page: 'orders',
systemPrompt: '你是订单管理助手。可以帮助:查看订单列表、订单详情、退款处理、收入统计。',
starters: ['今日订单', '待处理订单', '收入统计', '订单详情'],
},
'/admin/analytics': {
page: 'analytics',
systemPrompt: '你是数据分析助手。可以帮助:解读数据指标、分析趋势、生成报表建议。',
starters: ['用户增长趋势', '收入分析', '热门内容', '数据摘要'],
},
'/admin/operations': {
page: 'operations',
systemPrompt: '你是运营助手。可以帮助:创建Banner、发送推送通知、管理活动。',
starters: ['创建Banner', '发送系统通知', '查看推送记录', '运营数据'],
},
'/admin/settings': {
page: 'settings',
systemPrompt: '你是系统设置助手。可以帮助:修改系统配置、查看配置项、批量设置。',
starters: ['查看AI配置', '修改会员价格', '站点设置', '配置说明'],
},
};
- **get-dashboard**: 获取仪表盘概览数据(用户数、课程数、内容数、提示词数、订单数)
- **list-users**: 列出用户,可按关键词搜索(参数: search, page, pageSize
- **get-user**: 查看用户详情(参数: id)
- **update-user-status**: 修改用户状态(参数: id, status: ACTIVE|INACTIVE|BANNED
- **list-orders**: 查看最近订单列表
- **get-analytics-overview**: 获取数据分析概览(用户增长、收入、趋势)
- **list-comments**: 查看评论(参数: status: PENDING_REVIEW|PUBLISHED|REJECTED
- **approve-comment**: 通过评论(参数: id
- **reject-comment**: 拒绝评论(参数: id, reason?
- **list-banners**: 查看所有Banner
- **list-notifications**: 查看系统通知
- **list-config**: 查看系统配置
- **list-roles**: 查看管理角色
- **list-admins**: 查看管理员
- **get-enterprise-orgs**: 查看企业版组织
- **toggle-course-status**: 切换课程上下架(参数: id)
- **toggle-content-status**: 切换内容上下架(参数: id)
- **toggle-prompt-status**: 切换提示词上下架(参数: id)
- **navigate**: 跳转到某个管理页面(参数: path — 如 /admin/users, /admin/orders, /admin/analytics, /admin/enterprise, /admin/operations/banners, /admin/operations/notifications, /admin/settings/roles, /admin/settings/config, /admin/comments, /admin/courses, /admin/prompts, /admin/contents, /admin/tools
const ACTION_FORMAT = `\n\n【快捷指令】当需要执行操作时,可以返回 JSON 指令:\n- {"action":"navigate","path":"/admin/courses","description":"跳转到课程管理"}\n- {"action":"search","keyword":"xxx","target":"users","description":"搜索用户"}\n- {"action":"create","type":"course","data":{"title":"课程名"},"description":"创建课程"}\n只有确实需要跳转或执行操作时才返回指令`;
当用户请求执行操作时,先调用对应工具。工具执行完毕后会用自然语言总结结果`;
function getAdminContext(pathname: string): AdminContext {
const sorted = Object.keys(adminContexts).sort((a, b) => b.length - a.length);
for (const key of sorted) {
if (pathname.startsWith(key)) {
const ctx = { ...adminContexts[key] };
ctx.systemPrompt = ctx.systemPrompt + ACTION_FORMAT;
return ctx;
const SYSTEM_PROMPT = `你是宇之然AI管理后台的智能助手,帮助管理员完成日常运营工作。
你可以:
1. 回答管理员的问题
2. 调用工具执行操作(如查看数据、管理用户、审核评论等)
3. 跳转到各个管理页面
${AVAILABLE_TOOLS_DESC}
注意:每次只需要返回一个 JSON 工具调用,不要包含多余文字。执行结果会自动呈现给用户。`;
function parseToolCall(text: string): { tool: string; params: Record<string, any>; description?: string } | null {
let braceDepth = 0;
let start = -1;
for (let i = 0; i < text.length; i++) {
if (text[i] === '{') {
if (start === -1) start = i;
braceDepth++;
} else if (text[i] === '}') {
braceDepth--;
if (braceDepth === 0 && start !== -1) {
try {
const parsed = JSON.parse(text.slice(start, i + 1));
if (parsed.tool) return parsed;
} catch {}
start = -1;
}
}
}
const defaultCtx = { ...adminContexts['/admin'] };
defaultCtx.systemPrompt = defaultCtx.systemPrompt + ACTION_FORMAT;
return defaultCtx;
}
function parseActionCommand(text: string): any | null {
const jsonMatch = text.match(/\{[\s\S]*?"action"\s*:\s*?"[^"]+"[\s\S]*?\}/);
if (!jsonMatch) return null;
try {
const parsed = JSON.parse(jsonMatch[0]);
if (parsed.action) return parsed;
} catch {}
return null;
}
async function postChat(messages: { role: string; content: string }[]): Promise<string> {
const tk = getAdminToken();
if (!tk) return '请先登录管理账号';
const res = await fetch(`${API_BASE}/admin/ai-assistant/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk}` },
body: JSON.stringify({ messages }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.message || '请求失败');
return data.reply;
}
async function executeTool(tool: string, params: Record<string, any>, messages: { role: string; content: string }[]): Promise<{ reply: string }> {
const tk = getAdminToken();
const res = await fetch(`${API_BASE}/admin/ai-assistant/action`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk}` },
body: JSON.stringify({ tool, params, messages }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.message || '工具执行失败');
return data;
}
export function AdminAIAssistant() {
const t = useT();
const pathname = usePathname();
const router = useRouter();
const [open, setOpen] = useState(false);
@@ -103,18 +100,9 @@ export function AdminAIAssistant() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const [started, setStarted] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (open && !started) {
const ctx = getAdminContext(pathname);
setMessages([{ role: 'assistant', content: ctx.systemPrompt }]);
setStarted(true);
}
}, [open, pathname, started]);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
@@ -134,51 +122,25 @@ export function AdminAIAssistant() {
setSending(true);
try {
const tk = getAdminToken();
let reply = '';
if (tk) {
const ctx = getAdminContext(pathname);
const apiMessages = [
{ role: 'system', content: ctx.systemPrompt },
...messages.filter(m => m.role === 'user' || m.role === 'assistant').map(m => ({ role: m.role, content: m.content })),
{ role: 'user', content: text },
];
const apiMessages = [
{ role: 'system', content: SYSTEM_PROMPT },
...messages.map(m => ({ role: m.role, content: m.content })),
{ role: 'user', content: text },
];
const res = await fetch(`${API_BASE}/sandbox/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tk}`,
},
body: JSON.stringify({
conversationId: crypto.randomUUID(),
model: 'general',
messages: apiMessages,
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.message || '请求失败');
reply = data.reply;
} else {
await new Promise(r => setTimeout(r, 400));
reply = '请先登录管理账号';
}
let reply = await postChat(apiMessages);
const toolCall = parseToolCall(reply);
const action = parseActionCommand(reply);
const hasAction = !!action;
if (hasAction) {
const cleanReply = reply.replace(/\{[\s\S]*?"action"\s*:\s*?"[^"]+"[\s\S]*?\}/, '').trim();
const finalReply = cleanReply || '收到指令,正在处理...';
setMessages(prev => [...prev, { role: 'assistant', content: finalReply }]);
if (action.action === 'navigate' && action.path) {
router.push(action.path);
toast.success(`正在跳转:${action.description || action.path}`);
if (toolCall) {
if (toolCall.tool === 'navigate') {
const path = toolCall.params.path;
setMessages(prev => [...prev, { role: 'assistant', content: `正在跳转到 ${path}...` }]);
toast.success(toolCall.description || `跳转到 ${path}`);
router.push(path);
} else {
toast.info(action.description || '收到操作指令');
const result = await executeTool(toolCall.tool, toolCall.params, apiMessages);
reply = result.reply;
setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
}
} else {
setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
@@ -210,7 +172,7 @@ export function AdminAIAssistant() {
);
}
const ctx = getAdminContext(pathname);
const starters = ['查看仪表盘数据', '列出最近用户', '查看待审核评论', '查看企业版组织'];
return (
<div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2">
@@ -229,7 +191,7 @@ export function AdminAIAssistant() {
<button onClick={() => setMinimized(!minimized)} className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg">
<Minus className="w-4 h-4" />
</button>
<button onClick={() => { setOpen(false); setMinimized(false); }} className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg">
<button onClick={() => { setOpen(false); setMinimized(false); setMessages([]); }} className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg">
<X className="w-4 h-4" />
</button>
</div>
@@ -238,13 +200,13 @@ export function AdminAIAssistant() {
{!minimized && (
<>
<div className="overflow-y-auto p-3 space-y-3" style={{ maxHeight: '320px' }}>
{messages.length === 1 && messages[0].role === 'assistant' && (
{messages.length === 0 && (
<div className="mb-2">
<p className="text-xs text-muted-foreground mb-3">
</p>
<div className="flex flex-wrap gap-1.5">
{ctx.starters.map((q, i) => (
{starters.map((q, i) => (
<button key={i} onClick={() => handleStarter(q)}
className="text-xs px-2.5 py-1.5 bg-muted text-muted-foreground rounded-full border border-border hover:bg-accent hover:text-foreground">
{q}
@@ -305,4 +267,4 @@ export function AdminAIAssistant() {
</div>
</div>
);
}
}
+2 -3
View File
@@ -1,8 +1,7 @@
'use client';
import { useState, useRef } from 'react';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
import { API_BASE } from '@/lib/config';
interface ImageUploadProps {
onUploaded: (url: string) => void;
@@ -33,7 +32,7 @@ export function ImageUpload({ onUploaded, defaultImage, accept = 'image/*' }: Im
formData.append('file', file);
try {
const res = await fetch(`${API_BASE}/api/v1/upload`, {
const res = await fetch(`${API_BASE}/upload`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: formData,
@@ -0,0 +1,154 @@
'use client';
import { useEffect, useState, useRef } from 'react';
import QRCode from 'qrcode';
import { apiFetch } from '@/lib/auth';
import { isWeChatBrowser } from '@/lib/wechat';
interface PayResult {
prepay_id?: string;
nonceStr?: string;
timeStamp?: string;
package?: string;
paySign?: string;
signType?: string;
codeUrl?: string;
}
interface Props {
open: boolean;
orderNo: string;
payResult: PayResult;
tradeType: 'JSAPI' | 'NATIVE';
onPaid: () => void;
onClose: () => void;
}
export default function PaymentModal({ open, orderNo, payResult, tradeType, onPaid, onClose }: Props) {
const [status, setStatus] = useState<'pending' | 'paid' | 'failed'>('pending');
const [qrDataUrl, setQrDataUrl] = useState('');
const [message, setMessage] = useState('');
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
const wechatBridgeCalled = useRef(false);
useEffect(() => {
if (!open) {
setStatus('pending');
setMessage('');
wechatBridgeCalled.current = false;
if (pollingRef.current) { clearInterval(pollingRef.current); pollingRef.current = null; }
return;
}
// NATIVE: render QR code
if (tradeType === 'NATIVE' && payResult?.codeUrl) {
QRCode.toDataURL(payResult.codeUrl, { margin: 1, width: 280 }, (err, url) => {
if (!err) setQrDataUrl(url);
});
setMessage('请使用微信扫描二维码完成支付');
startPolling();
}
// JSAPI in WeChat: call WeixinJSBridge
if (tradeType === 'JSAPI' && isWeChatBrowser() && !wechatBridgeCalled.current) {
wechatBridgeCalled.current = true;
setMessage('正在调起微信支付...');
callWechatJsapi(payResult);
startPolling();
}
}, [open, tradeType, payResult?.codeUrl]);
function startPolling() {
if (pollingRef.current) clearInterval(pollingRef.current);
pollingRef.current = setInterval(async () => {
try {
const res = await apiFetch(`/payment/wxpay/query?outTradeNo=${orderNo}`);
const data = await res.json();
if (data.trade_state === 'SUCCESS' || data.localStatus === 'PAID') {
setStatus('paid');
setMessage('支付成功!');
if (pollingRef.current) clearInterval(pollingRef.current);
setTimeout(onPaid, 1500);
}
} catch {}
}, 3000);
}
function callWechatJsapi(params: PayResult) {
if (typeof WeixinJSBridge === 'undefined') {
document.addEventListener('WeixinJSBridgeReady', () => doInvoke(params), false);
} else {
doInvoke(params);
}
}
function doInvoke(params: PayResult) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
appId: '', // filled by WeChat
timeStamp: params.timeStamp || '',
nonceStr: params.nonceStr || '',
package: params.package || '',
signType: params.signType || 'RSA',
paySign: params.paySign || '',
},
(res: any) => {
if (res.err_msg === 'get_brand_wcpay_request:ok') {
setStatus('paid');
setMessage('支付成功!');
if (pollingRef.current) clearInterval(pollingRef.current);
setTimeout(onPaid, 1500);
} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
setMessage('已取消支付');
setStatus('pending');
} else {
setMessage('支付失败,请重试');
setStatus('failed');
}
}
);
}
useEffect(() => {
return () => { if (pollingRef.current) clearInterval(pollingRef.current); };
}, []);
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
<div className="bg-card rounded-2xl p-8 w-full max-w-sm mx-4 shadow-xl border border-border" onClick={e => e.stopPropagation()}>
<h3 className="text-lg font-semibold text-foreground text-center mb-4"></h3>
{tradeType === 'NATIVE' && (
<div className="flex justify-center mb-4">
{qrDataUrl ? (
<img src={qrDataUrl} alt="支付二维码" className="w-56 h-56 rounded-xl border border-border" />
) : (
<div className="w-56 h-56 bg-muted rounded-xl animate-pulse" />
)}
</div>
)}
{status === 'paid' ? (
<div className="text-center">
<div className="text-5xl mb-3"></div>
<p className="text-green-600 font-medium">{message}</p>
</div>
) : (
<>
<p className="text-sm text-muted-foreground text-center mb-4">{message}</p>
<div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
<span className="w-2 h-2 bg-brand-600 rounded-full animate-pulse" />
...
</div>
<button onClick={onClose} className="mt-4 w-full py-2 text-sm text-muted-foreground border border-border rounded-xl hover:bg-accent">
</button>
</>
)}
</div>
</div>
);
}
+1 -1
View File
@@ -1,4 +1,4 @@
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
import { API_BASE } from '@/lib/config';
export function getToken(): string | null {
if (typeof window === 'undefined') return null;
+7
View File
@@ -0,0 +1,7 @@
export const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api/v1';
export const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://yuzhiran.com';
export const SITE_NAME = process.env.NEXT_PUBLIC_SITE_NAME || '宇之然 AI';
export const WX_APPID = process.env.NEXT_PUBLIC_WX_APPID || '';
+3 -1
View File
@@ -7,7 +7,9 @@ export interface ModelOption {
export const AVAILABLE_MODELS: ModelOption[] = [
{ id: 'general', label: '通用模式', provider: 'OpenAI 兼容', desc: '日常问答,综合能力均衡' },
{ id: 'opencode-go', label: 'DeepSeek V4 Flash', provider: 'OpenCode Go', desc: '高速推理,代码生成强' },
{ id: 'deepseek-v4-flash', label: 'DeepSeek V4 Flash', provider: '商汤科技', desc: '高速推理,代码生成强' },
{ id: 'sensenova-6.7-flash-lite', label: 'SenseNova 6.7 Flash Lite', provider: '商汤科技', desc: '轻量快速,日常使用' },
{ id: 'sensenova-u1-fast', label: 'SenseNova U1 Fast', provider: '商汤科技', desc: '高性能推理,复杂任务' },
];
export const DEFAULT_MODEL = 'general';
+15
View File
@@ -0,0 +1,15 @@
export function isWeChatBrowser(): boolean {
if (typeof window === 'undefined') return false;
return /MicroMessenger/i.test(navigator.userAgent);
}
export function getOpenidFromUrl(): string | null {
if (typeof window === 'undefined') return null;
const params = new URLSearchParams(window.location.search);
return params.get('openid');
}
export function isMiniProgram(): boolean {
if (typeof window === 'undefined') return false;
return /miniProgram/i.test(navigator.userAgent) || !!getOpenidFromUrl();
}