mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: add CRM feedback system and test environment
- add feedback backend, H5/admin UI, CRM services, and deployment docs - add isolated local test compose on port 18007 with separate data paths - remove committed LLM secret and support provider-specific env overrides Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
941aaf10ce
commit
fae932d022
272 changed files with 181404 additions and 4 deletions
9
.gitignore
vendored
9
.gitignore
vendored
|
|
@ -148,7 +148,14 @@ cython_debug/
|
|||
tmp
|
||||
.history
|
||||
.DS_Store
|
||||
main/feedback-backend/data
|
||||
main/feedback-backend/.env
|
||||
main/feedback-backend/.env.*
|
||||
!main/feedback-backend/.env.example
|
||||
main/xiaozhi-server/docker-compose.test.override.yml
|
||||
main/xiaozhi-server/data
|
||||
main/xiaozhi-server/data-test
|
||||
main/xiaozhi-server/mysql-test
|
||||
main/xiaozhi-server/.claude
|
||||
|
||||
main/manager-web/node_modules
|
||||
|
|
@ -177,6 +184,8 @@ main/manager-web/.webpack_cache/
|
|||
main/xiaozhi-server/mysql
|
||||
uploadfile
|
||||
*.json
|
||||
!main/feedback-h5/resources/**/*.json
|
||||
!main/feedback-backend/admin-ui/resources/**/*.json
|
||||
.vscode
|
||||
.cursor
|
||||
|
||||
|
|
|
|||
47
CLAUDE.md
Normal file
47
CLAUDE.md
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
# CLAUDE.md
|
||||
|
||||
## 反馈后台公网部署前置信息
|
||||
|
||||
`feedback-admin.new123.vip` 不是在公网服务器本机托管静态文件;公网服务器只做 Nginx 反向代理。
|
||||
|
||||
当前目标链路:
|
||||
|
||||
```text
|
||||
浏览器
|
||||
-> https://feedback-admin.new123.vip/admin/
|
||||
-> 公网服务器 Nginx(ubuntu@100.66.236.1,配置 /etc/nginx/sites-enabled/new123.vip)
|
||||
-> Tailscale 到本地 Windows:100.116.124.21:8007
|
||||
-> 本地 Docker 容器 feedback-h5
|
||||
-> 挂载的本仓库 main/feedback-backend/admin-ui
|
||||
```
|
||||
|
||||
API 与后台 AI 数字人长连接也走同一条 Tailscale 链路:
|
||||
|
||||
```text
|
||||
https://feedback-admin.new123.vip/api/v1/* -> http://100.116.124.21:8007/api/v1/*
|
||||
wss://feedback-admin.new123.vip/api/v1/agent/chat/ws -> http://100.116.124.21:8007/api/v1/agent/chat/ws
|
||||
```
|
||||
|
||||
本地关键服务:
|
||||
|
||||
- Windows Tailscale IP:`100.116.124.21`(机器名 `kobe-wins-book`)
|
||||
- 公网服务器 Tailscale IP:`100.66.236.1`(SSH:`ubuntu@100.66.236.1`)
|
||||
- 本地入口容器:`feedback-h5`,宿主机端口 `8007`
|
||||
- Compose 文件:`main/xiaozhi-server/docker-compose_all.yml`
|
||||
- `feedback-h5` 必须挂载:`../feedback-backend/admin-ui:/feedback-backend/admin-ui`
|
||||
|
||||
注意:不要再把 admin 静态文件发布到公网服务器 `/var/www/feedback-admin/admin-ui/`。该目录已清空,避免占用服务器磁盘和干扰线上调试。修改后台页面时,改本地仓库并确保 `feedback-h5` 容器重建/已挂载即可。
|
||||
|
||||
常用检查:
|
||||
|
||||
```powershell
|
||||
docker ps --format "{{.Names}}\t{{.Ports}}"
|
||||
docker inspect feedback-h5 --format '{{json .Mounts}}'
|
||||
docker compose -f "main/xiaozhi-server/docker-compose_all.yml" up -d --force-recreate feedback-h5
|
||||
```
|
||||
|
||||
远端检查:
|
||||
|
||||
```bash
|
||||
ssh ubuntu@100.66.236.1 "sudo nginx -t && sudo nginx -T | grep -nE 'feedback-admin|100.116.124.21|/admin/|/api/v1/'"
|
||||
```
|
||||
204
docs/ai-voice-component-extraction-plan.md
Normal file
204
docs/ai-voice-component-extraction-plan.md
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
# AI 语音数字人 H5 组件抽取方案
|
||||
|
||||
## 目标
|
||||
|
||||
将当前 `feedback-h5` 中的 AI 语音对话能力抽成独立组件,后续可被多个业务复用:
|
||||
|
||||
- 客户反馈 H5
|
||||
- 后台 AI 数字人助手
|
||||
- CRM 建档助手
|
||||
- 产品/套餐咨询助手
|
||||
- 其他门店经营助手
|
||||
|
||||
组件只负责“对话体验”,不关心 CRM、反馈、员工 KPI 等业务细节。
|
||||
|
||||
## 当前耦合点
|
||||
|
||||
当前 `feedback-h5` 同时承担:
|
||||
|
||||
1. 门店服务码查询。
|
||||
2. 员工选择。
|
||||
3. 设备初始化/OTA。
|
||||
4. WebSocket 语音连接。
|
||||
5. 音频采集/Opus 编码。
|
||||
6. 音频播放/Opus 解码。
|
||||
7. Live2D 数字人展示。
|
||||
8. 反馈业务流程。
|
||||
9. 点评生成和发布跳转。
|
||||
|
||||
其中真正应该抽成通用组件的是:
|
||||
|
||||
```text
|
||||
音频采集
|
||||
音频播放
|
||||
WebSocket 对话协议
|
||||
Live2D 展示
|
||||
消息状态管理
|
||||
数字人说话/停顿/表情
|
||||
```
|
||||
|
||||
业务方只注入:
|
||||
|
||||
```text
|
||||
会话配置
|
||||
用户上下文
|
||||
系统提示词/业务指令
|
||||
onMessage 回调
|
||||
onResult 回调
|
||||
```
|
||||
|
||||
## 建议目录结构
|
||||
|
||||
```text
|
||||
main/ai-voice-widget/
|
||||
├── README.md
|
||||
├── index.html # 独立演示页
|
||||
├── src/
|
||||
│ ├── voice-widget.js # 对外主入口
|
||||
│ ├── voice-session.js # WebSocket 会话管理
|
||||
│ ├── audio-recorder.js # 录音/Opus 编码
|
||||
│ ├── audio-player.js # 播放/Opus 解码
|
||||
│ ├── live2d-avatar.js # Live2D 适配层
|
||||
│ ├── protocol.js # 消息协议封装
|
||||
│ └── styles.css # 组件样式
|
||||
├── adapters/
|
||||
│ ├── feedback-adapter.js # 客户反馈业务适配
|
||||
│ ├── admin-agent-adapter.js # 后台 AI 助手适配
|
||||
│ └── crm-profile-adapter.js # CRM 建档助手适配
|
||||
└── resources/ # 可选:Live2D 模型资源,或由业务方传入
|
||||
```
|
||||
|
||||
## 对外 API 设计
|
||||
|
||||
```js
|
||||
import { createVoiceWidget } from './src/voice-widget.js';
|
||||
|
||||
const widget = createVoiceWidget({
|
||||
container: '#voiceWidget',
|
||||
wsUrl: 'wss://example.com/ws',
|
||||
model: {
|
||||
type: 'live2d',
|
||||
name: 'hiyori_pro_zh',
|
||||
basePath: '/resources/hiyori_pro_zh/'
|
||||
},
|
||||
session: {
|
||||
storeId: 'store001',
|
||||
employeeId: 'emp001',
|
||||
memberId: 'member001',
|
||||
mode: 'crm-profile'
|
||||
},
|
||||
prompts: {
|
||||
system: '你是门店CRM建档助手',
|
||||
opening: '您好,我来帮您完善客户档案。'
|
||||
},
|
||||
onMessage(message) {
|
||||
console.log('message', message);
|
||||
},
|
||||
onFinal(result) {
|
||||
console.log('structured result', result);
|
||||
},
|
||||
onError(error) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
|
||||
await widget.start();
|
||||
```
|
||||
|
||||
## 与业务解耦后的事件
|
||||
|
||||
组件只抛事件:
|
||||
|
||||
```text
|
||||
ready
|
||||
connected
|
||||
disconnected
|
||||
user_speech_start
|
||||
user_speech_end
|
||||
assistant_speech_start
|
||||
assistant_speech_end
|
||||
message
|
||||
structured_result
|
||||
error
|
||||
```
|
||||
|
||||
业务方自己决定如何处理:
|
||||
|
||||
```text
|
||||
保存反馈
|
||||
创建客户
|
||||
更新客户档案
|
||||
创建建议
|
||||
创建问题
|
||||
消费套餐
|
||||
```
|
||||
|
||||
## 后台 AI 数字人的落地方式
|
||||
|
||||
后台当前已经有文本对话版 AI 助手。后续可以把输入层替换为:
|
||||
|
||||
```text
|
||||
VoiceWidget
|
||||
↓ structured_result / message
|
||||
/agent/chat
|
||||
↓ Agent Graph
|
||||
Skill / CLI / CRM API
|
||||
```
|
||||
|
||||
即:
|
||||
|
||||
```text
|
||||
数字人只是交互壳
|
||||
Agent Graph 负责思考和编排
|
||||
CLI/API 负责执行系统操作
|
||||
```
|
||||
|
||||
## CRM 建档助手示例
|
||||
|
||||
用户说:
|
||||
|
||||
```text
|
||||
她叫张女士,38岁,手机号尾号1234,主要是肩颈酸痛,睡眠不好,买了养生减肥10次套餐。
|
||||
```
|
||||
|
||||
语音组件产出文本,Agent Graph 解析为计划:
|
||||
|
||||
```json
|
||||
[
|
||||
{"skill": "crm.member-list", "args": {"keyword": "1234"}},
|
||||
{"skill": "crm.member-create-or-update", "args": {"name": "张女士", "age": 38, "healthIssues": ["肩颈酸痛", "睡眠不好"]}},
|
||||
{"skill": "crm.product-list", "args": {"keyword": "养生减肥"}},
|
||||
{"skill": "crm.product-purchase", "args": {"totalCount": 10}}
|
||||
]
|
||||
```
|
||||
|
||||
高风险或资产变动步骤进入确认:
|
||||
|
||||
```text
|
||||
我将为张女士关联“养生减肥10次套餐”,是否确认?
|
||||
```
|
||||
|
||||
## 当前建议的产品方向
|
||||
|
||||
门店核心不应以“到店记录/账户流水”为中心,而应以:
|
||||
|
||||
```text
|
||||
客户档案
|
||||
身体状态变化
|
||||
已购产品/套餐
|
||||
套餐剩余次数/金额
|
||||
累计消费金额
|
||||
建议/问题闭环
|
||||
```
|
||||
|
||||
到店记录和账户流水仍保留,但降级为支撑数据,不作为店长主视角。
|
||||
|
||||
## 下一步拆分计划
|
||||
|
||||
1. 从 `feedback-h5/js/audio-recorder.js` 抽出 `ai-voice-widget/src/audio-recorder.js`。
|
||||
2. 从 `feedback-h5/js/audio-player.js` 抽出 `ai-voice-widget/src/audio-player.js`。
|
||||
3. 从 `feedback-h5/js/live2d-manager.js` 抽出 `ai-voice-widget/src/live2d-avatar.js`。
|
||||
4. 新增 `voice-session.js` 管理 WebSocket 协议。
|
||||
5. 新增 `voice-widget.js` 作为统一入口。
|
||||
6. 用 adapter 方式接入反馈、CRM、后台 Agent。
|
||||
7. 后台 AI 助手可选择文本输入或语音数字人输入。
|
||||
73
docs/crm-user-story-test-plan.md
Normal file
73
docs/crm-user-story-test-plan.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# CRM 用户故事与 30 个自动化测试用例
|
||||
|
||||
## 用户故事
|
||||
|
||||
作为门店店长,我希望客户完成语音反馈后,系统能通过手机号后四位识别客户,并自动把客户反馈关联到客户档案、到店记录、建议管理、问题修复和账户流水;同时我能在统计概览中按员工查看好评、中评、差评,用作员工 KPI 管理。
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. 客户档案支持麦凯66字段,且字段数为66。
|
||||
2. 可按手机号/姓名搜索客户。
|
||||
3. 客户反馈可通过手机号后四位自动匹配客户。
|
||||
4. 客户反馈可自动创建/关联到店记录,并同步满意度、员工、项目、到店时间。
|
||||
5. 反馈建议自动进入建议管理,并支持去重、采纳、处理说明。
|
||||
6. 差评/退款/销卡/投诉类反馈自动进入问题修复。
|
||||
7. 账户消费如果没填到店记录,自动关联客户最近一次到店,并同步消费金额。
|
||||
8. 店长可在统计概览看到员工好评、中评、差评 KPI,并查看评价明细。
|
||||
9. 系统提供 CLI,方便 AI Agent 管理系统。
|
||||
|
||||
## 30 个自动化测试用例
|
||||
|
||||
1. 麦凯66字段数量等于66。
|
||||
2. 麦凯66字段 key 不重复。
|
||||
3. 创建客户并写入麦凯66字段。
|
||||
4. 按手机号搜索客户。
|
||||
5. 更新客户健康档案。
|
||||
6. 创建到店记录并自动计算耗时。
|
||||
7. 到店记录返回客户姓名。
|
||||
8. 创建到店后更新客户累计到店统计。
|
||||
9. 开卡/建账户自动生成充值流水。
|
||||
10. 账户消费后剩余次数减少。
|
||||
11. 账户消费自动生成消费流水。
|
||||
12. 消费未传到店记录时自动关联最近到店。
|
||||
13. 消费金额同步回到店记录。
|
||||
14. 创建客户建议。
|
||||
15. 重复建议自动去重并增加 frequency。
|
||||
16. 采纳建议并保存处理说明。
|
||||
17. 创建问题修复记录。
|
||||
18. 标记问题已修复并自动记录修复时间。
|
||||
19. 销卡后账户状态变为已销卡。
|
||||
20. 销卡原因不满意/退款时自动生成问题。
|
||||
21. 反馈记录可绑定客户和到店记录。
|
||||
22. 员工 KPI 正确统计好/中/差评。
|
||||
23. 员工评价明细可筛选差评。
|
||||
24. 从文本中提取手机号后四位。
|
||||
25. 反馈自动通过手机号后四位匹配客户。
|
||||
26. 反馈自动创建到店记录。
|
||||
27. 反馈自动创建建议。
|
||||
28. 差评反馈自动创建问题修复。
|
||||
29. 客户详情聚合到店、账户、流水、建议、问题。
|
||||
30. CRM 看板统计客户、到店、销卡、建议、问题数量。
|
||||
|
||||
## 执行命令
|
||||
|
||||
```bash
|
||||
cd main/feedback-backend
|
||||
PYTHONPATH=. python -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH="main/feedback-backend"
|
||||
python -m unittest discover -s "main/feedback-backend/tests" -v
|
||||
```
|
||||
|
||||
## CLI 示例
|
||||
|
||||
```bash
|
||||
python main/feedback-backend/cli.py login --username admin --password admin123
|
||||
python main/feedback-backend/cli.py --token <JWT> crm overview
|
||||
python main/feedback-backend/cli.py --token <JWT> crm member-list --keyword 1234
|
||||
python main/feedback-backend/cli.py --token <JWT> stats employee-kpi
|
||||
```
|
||||
304
docs/feedback-public-deployment-notes.md
Normal file
304
docs/feedback-public-deployment-notes.md
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
# 反馈系统公网部署记录与后续建议
|
||||
|
||||
本文记录本次 `feedback.new123.vip`、`feedback-admin.new123.vip` 公网部署/排障结论,便于后续维护。
|
||||
|
||||
## 服务器与入口
|
||||
|
||||
公网服务器:
|
||||
|
||||
```bash
|
||||
ssh ubuntu@100.66.236.1
|
||||
```
|
||||
|
||||
公网 Nginx 配置文件:
|
||||
|
||||
```text
|
||||
/etc/nginx/sites-enabled/new123.vip
|
||||
```
|
||||
|
||||
配置修改前建议备份到:
|
||||
|
||||
```text
|
||||
/etc/nginx/sites-disabled/
|
||||
```
|
||||
|
||||
常用验证命令:
|
||||
|
||||
```bash
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
sudo nginx -T
|
||||
```
|
||||
|
||||
## 当前域名规划
|
||||
|
||||
### H5 反馈入口
|
||||
|
||||
```text
|
||||
https://feedback.new123.vip/index.html#/home
|
||||
```
|
||||
|
||||
页面和静态资源仍走 `443`。
|
||||
|
||||
### H5 语音 WebSocket 与反馈 API
|
||||
|
||||
由于 `443` 上公网 WebSocket/部分 API 请求出现过 `ERR_CONNECTION_CLOSED`,已新增稳定专用入口:
|
||||
|
||||
```text
|
||||
wss://feedback.new123.vip:8443/ws/
|
||||
https://feedback.new123.vip:8443/api/v1/...
|
||||
```
|
||||
|
||||
`feedback-h5/js/api.js` 通过公网 Nginx 动态替换为:
|
||||
|
||||
```js
|
||||
const FEEDBACK_API_BASE = 'https://feedback.new123.vip:8443/api/v1';
|
||||
const WS_BASE = 'wss://feedback.new123.vip:8443/ws';
|
||||
```
|
||||
|
||||
8443 已在云安全组放行,Nginx 本机和公网测试均返回 WebSocket `101 Switching Protocols`。
|
||||
|
||||
### 反馈后台管理
|
||||
|
||||
```text
|
||||
https://feedback-admin.new123.vip/admin/
|
||||
```
|
||||
|
||||
根路径会跳转:
|
||||
|
||||
```text
|
||||
https://feedback-admin.new123.vip/ -> /admin/
|
||||
```
|
||||
|
||||
后台管理现在采用“公网 Nginx + Tailscale 回源到本地 Windows”的方式,不再在公网服务器托管 admin 静态文件:
|
||||
|
||||
```text
|
||||
浏览器
|
||||
-> feedback-admin.new123.vip 公网 Nginx
|
||||
-> Tailscale: 100.116.124.21:8007
|
||||
-> Windows 本地 Docker feedback-h5
|
||||
-> 本仓库 main/feedback-backend/admin-ui
|
||||
```
|
||||
|
||||
公网服务器上旧的后台静态目录已删除/清空,避免占用磁盘和干扰调试:
|
||||
|
||||
```text
|
||||
/var/www/feedback-admin/admin-ui/ # 不再使用
|
||||
/var/www/feedback-admin/admin-ui.bak-* # 已清理
|
||||
```
|
||||
|
||||
后台 API 和 AI 数字人长连接也通过同一 Tailscale 入口:
|
||||
|
||||
```text
|
||||
https://feedback-admin.new123.vip/api/v1/...
|
||||
wss://feedback-admin.new123.vip/api/v1/agent/chat/ws
|
||||
```
|
||||
|
||||
公网 Nginx 的核心配置应保持为:
|
||||
|
||||
```nginx
|
||||
location /admin/ {
|
||||
proxy_pass http://100.116.124.21:8007;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
}
|
||||
|
||||
location /api/v1/ {
|
||||
proxy_pass http://100.116.124.21:8007;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 180s;
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_buffering off;
|
||||
}
|
||||
```
|
||||
|
||||
本地必须保证 `feedback-h5` 容器挂载后台静态文件目录:
|
||||
|
||||
```yaml
|
||||
- ../feedback-backend/admin-ui:/feedback-backend/admin-ui
|
||||
```
|
||||
|
||||
如果公网 admin 页面没有更新,优先检查本地容器挂载并重建:
|
||||
|
||||
```powershell
|
||||
docker inspect feedback-h5 --format '{{json .Mounts}}'
|
||||
docker compose -f "main/xiaozhi-server/docker-compose_all.yml" up -d --force-recreate feedback-h5
|
||||
```
|
||||
|
||||
|
||||
## 后台账号与权限
|
||||
|
||||
### 超级管理员
|
||||
|
||||
```text
|
||||
用户名:admin
|
||||
密码:admin123
|
||||
```
|
||||
|
||||
> 建议上线后尽快修改默认密码。
|
||||
|
||||
管理员可以访问:
|
||||
|
||||
- 统计概览
|
||||
- 反馈记录
|
||||
- 门店管理
|
||||
- 员工管理
|
||||
- 智能体配置
|
||||
|
||||
### 门店店长
|
||||
|
||||
店长账号默认使用门店编码首次登录,例如:
|
||||
|
||||
```text
|
||||
用户名:558744
|
||||
密码:558744
|
||||
```
|
||||
|
||||
首次登录会自动创建店长账号,角色为:
|
||||
|
||||
```text
|
||||
store_manager
|
||||
```
|
||||
|
||||
并绑定门店:
|
||||
|
||||
```text
|
||||
store001 / 558744 / 腰妍美容养生馆
|
||||
```
|
||||
|
||||
店长登录后:
|
||||
|
||||
- 可访问:统计概览、反馈记录、员工管理
|
||||
- 不可访问:门店管理、智能体配置
|
||||
- 后端接口强制按店长门店过滤,不能通过改 URL 查看其他门店数据
|
||||
- 支持在侧边栏底部修改密码
|
||||
|
||||
## 手机端适配
|
||||
|
||||
反馈后台已做移动端适配,面向店长手机登录使用:
|
||||
|
||||
- 顶部汉堡菜单打开侧边栏
|
||||
- 登录页自适应手机屏幕
|
||||
- 统计卡片自动换行
|
||||
- 表格横向滚动
|
||||
- 弹窗在手机端呈底部抽屉样式
|
||||
- 统计图表使用 CSS 响应式条形/柱状图,不再使用被拉伸的 canvas
|
||||
|
||||
## 已修复问题
|
||||
|
||||
### 1. WebSocket `code 1006`
|
||||
|
||||
现象:
|
||||
|
||||
```text
|
||||
WebSocket connection failed
|
||||
code=1006
|
||||
```
|
||||
|
||||
处理:新增 `8443` 专用 WebSocket 入口,并将公网 H5 的 `WS_BASE` 指向:
|
||||
|
||||
```text
|
||||
wss://feedback.new123.vip:8443/ws
|
||||
```
|
||||
|
||||
### 2. API `ERR_CONNECTION_CLOSED`
|
||||
|
||||
现象:
|
||||
|
||||
```text
|
||||
POST /api/v1/public/record net::ERR_CONNECTION_CLOSED
|
||||
POST /api/v1/public/process net::ERR_CONNECTION_CLOSED
|
||||
```
|
||||
|
||||
处理:公网 H5 的反馈 API 也切到:
|
||||
|
||||
```text
|
||||
https://feedback.new123.vip:8443/api/v1
|
||||
```
|
||||
|
||||
### 3. CORS 重复响应头
|
||||
|
||||
现象:
|
||||
|
||||
```text
|
||||
Access-Control-Allow-Origin contains multiple values
|
||||
```
|
||||
|
||||
处理:调整 8443 API CORS,避免同时返回 `*` 和具体域名。
|
||||
|
||||
### 4. 后台静态资源改为 Tailscale 回源
|
||||
|
||||
历史原因:`feedback-admin` 曾错误返回 H5 首页 HTML,导致 JS 请求拿到 HTML;当时临时将反馈后台静态文件部署到公网服务器本机,并让 Nginx 的 `/admin/` 使用 `alias /var/www/feedback-admin/admin-ui/`。
|
||||
|
||||
现状:为节省公网服务器磁盘并避免本地代码与服务器静态文件不一致,`/admin/` 已改为反向代理到 Windows 本地 Tailscale 服务:
|
||||
|
||||
```nginx
|
||||
location /admin/ {
|
||||
proxy_pass http://100.116.124.21:8007;
|
||||
}
|
||||
```
|
||||
|
||||
`/var/www/feedback-admin/admin-ui/` 和历史 `admin-ui.bak-*` 备份目录已清理,不再用于发布。
|
||||
|
||||
### 5. 管理后台登录 500
|
||||
|
||||
原因:`passlib==1.7.4` 与容器内 `bcrypt==5.0.0` 不兼容。
|
||||
|
||||
处理:将 `bcrypt` 固定为兼容版本:
|
||||
|
||||
```text
|
||||
bcrypt==4.0.1
|
||||
```
|
||||
|
||||
并在容器内降级后重启 `feedback-backend`。
|
||||
|
||||
## 后续建议
|
||||
|
||||
1. **保持本地 Tailscale 回源链路稳定**
|
||||
`feedback-admin.new123.vip` 的 `/admin/`、`/api/v1/` 和后台 AI WebSocket 都通过公网 Nginx 回源到 Windows 本地 `100.116.124.21:8007`。不要再往公网服务器 `/var/www/feedback-admin/admin-ui/` 发布静态文件;该目录已清理。
|
||||
|
||||
2. **固化 Docker 镜像**
|
||||
本次有部分代码通过 `docker cp` 快速复制进容器验证。建议后续重新构建 `feedback-backend` 镜像,确保容器重建后权限逻辑和 `bcrypt==4.0.1` 不丢失。
|
||||
|
||||
3. **将公网 Nginx 配置纳入版本管理**
|
||||
当前公网 Nginx 配置在服务器 `/etc/nginx/sites-enabled/new123.vip`,建议把稳定版同步回仓库,例如维护一份 `deploy/nginx/new123.vip.conf`。
|
||||
|
||||
4. **减少 Nginx 动态 JS 替换**
|
||||
目前公网通过 Nginx 对 H5 `api.js` 做 `sub_filter` 动态替换。长期建议在前端代码中支持生产环境配置文件,例如 `/runtime-config.js` 或环境变量注入。
|
||||
|
||||
5. **后台 API 域名统一**
|
||||
当前后台页面在 `feedback-admin.new123.vip`,API 走 `feedback-admin.new123.vip:8443`。长期可考虑单独 API 子域名,例如 `feedback-api.new123.vip`,减少端口暴露。
|
||||
|
||||
6. **密码安全**
|
||||
管理员默认密码 `admin123` 和店长初始密码等于门店编码,仅适合初始化。建议上线后要求首次登录强制修改密码。
|
||||
|
||||
7. **权限继续细化**
|
||||
店长当前可以管理本门店员工。若后续需要更细权限,可继续区分只读店长、可编辑店长、区域经理等角色。
|
||||
|
||||
8. **日志与监控**
|
||||
重点关注:
|
||||
|
||||
```text
|
||||
/var/log/nginx/feedback-admin.access.log
|
||||
/var/log/nginx/feedback-admin.error.log
|
||||
/var/log/nginx/feedback-ws8443.access.log
|
||||
/var/log/nginx/feedback-ws8443.error.log
|
||||
```
|
||||
|
||||
以及本地容器:
|
||||
|
||||
```bash
|
||||
docker logs feedback-backend
|
||||
```
|
||||
BIN
feedback-appointment-558744-qr.png
Normal file
BIN
feedback-appointment-558744-qr.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 972 B |
|
|
@ -13,6 +13,7 @@
|
|||
4. [数据流与交互机制](#4-数据流与交互机制)
|
||||
5. [核心功能概要](#5-核心功能概要)
|
||||
6. [部署与配置概述](#6-部署与配置概述)
|
||||
7. [反馈系统公网 Admin 回源链路](#7-反馈系统公网-admin-回源链路)
|
||||
---
|
||||
|
||||
## 1. 引言
|
||||
|
|
@ -590,3 +591,44 @@ xiaozhi-esp32-server
|
|||
在全模块部署的情况下,推荐使用`manager-web`控制面板作为大多数配置任务的主要操作界面,因为它提供了一种用户友好的方式来管理由`manager-api`持久化并最终由`xiaozhi-server`使用的各项设置。
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 7. 反馈系统公网 Admin 回源链路
|
||||
|
||||
`feedback-admin.new123.vip` 采用公网 Nginx + Tailscale 回源到本地 Windows 的部署方式,公网服务器不再保存后台静态文件。
|
||||
|
||||
链路:
|
||||
|
||||
```text
|
||||
浏览器
|
||||
-> https://feedback-admin.new123.vip/admin/
|
||||
-> 公网服务器 Nginx(ubuntu@100.66.236.1)
|
||||
-> Tailscale:100.116.124.21:8007
|
||||
-> 本地 Windows Docker 容器 feedback-h5
|
||||
-> 本仓库 main/feedback-backend/admin-ui
|
||||
```
|
||||
|
||||
关键约定:
|
||||
|
||||
- 公网 Nginx 配置:`/etc/nginx/sites-enabled/new123.vip`
|
||||
- Windows Tailscale IP:`100.116.124.21`
|
||||
- 公网服务器 Tailscale IP:`100.66.236.1`
|
||||
- 本地入口容器:`feedback-h5`,宿主机端口 `8007`
|
||||
- Compose 文件:`main/xiaozhi-server/docker-compose_all.yml`
|
||||
- `feedback-h5` 必须挂载:`../feedback-backend/admin-ui:/feedback-backend/admin-ui`
|
||||
- 公网服务器 `/var/www/feedback-admin/admin-ui/` 不再使用,历史备份目录已清理,避免占用磁盘和干扰调试。
|
||||
|
||||
后台 API 和后台 AI 数字人长连接同样走这个入口:
|
||||
|
||||
```text
|
||||
https://feedback-admin.new123.vip/api/v1/...
|
||||
wss://feedback-admin.new123.vip/api/v1/agent/chat/ws
|
||||
```
|
||||
|
||||
修改后台页面后,优先检查本地容器是否挂载了 admin-ui;必要时重建入口容器:
|
||||
|
||||
```powershell
|
||||
docker inspect feedback-h5 --format '{{json .Mounts}}'
|
||||
docker compose -f "main/xiaozhi-server/docker-compose_all.yml" up -d --force-recreate feedback-h5
|
||||
```
|
||||
|
|
|
|||
49
main/ai-voice-widget/src/voice-session.js
Normal file
49
main/ai-voice-widget/src/voice-session.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// AI Voice Widget - WebSocket session scaffold
|
||||
// 预留给 xiaozhi/后端长连接语音通道使用。
|
||||
|
||||
export class VoiceSession {
|
||||
constructor({ url, onOpen, onClose, onText, onAudio, onError } = {}) {
|
||||
this.url = url;
|
||||
this.ws = null;
|
||||
this.onOpen = onOpen;
|
||||
this.onClose = onClose;
|
||||
this.onText = onText;
|
||||
this.onAudio = onAudio;
|
||||
this.onError = onError;
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (!this.url) throw new Error('VoiceSession url is required');
|
||||
this.ws = new WebSocket(this.url);
|
||||
this.ws.binaryType = 'arraybuffer';
|
||||
this.ws.onopen = () => this.onOpen?.();
|
||||
this.ws.onclose = (e) => this.onClose?.(e);
|
||||
this.ws.onerror = (e) => this.onError?.(e);
|
||||
this.ws.onmessage = (event) => {
|
||||
if (typeof event.data === 'string') {
|
||||
let data = event.data;
|
||||
try { data = JSON.parse(event.data); } catch (e) {}
|
||||
this.onText?.(data);
|
||||
} else {
|
||||
this.onAudio?.(event.data);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
sendJson(data) {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(data));
|
||||
}
|
||||
}
|
||||
|
||||
sendBinary(data) {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(data);
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
try { this.ws?.close(); } catch (e) {}
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
109
main/ai-voice-widget/src/voice-widget.js
Normal file
109
main/ai-voice-widget/src/voice-widget.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// AI Voice Widget - lightweight voice interaction component
|
||||
// 当前版本:浏览器 ASR + speechSynthesis TTS + 状态回调;预留 VoiceSession 长连接。
|
||||
|
||||
import { VoiceSession } from './voice-session.js';
|
||||
|
||||
export function createVoiceWidget(options = {}) {
|
||||
return new VoiceWidget(options);
|
||||
}
|
||||
|
||||
export class VoiceWidget {
|
||||
constructor({ onUserText, onStatus, onReplyStart, onReplyEnd, onError, voiceEnabled = true, sessionUrl = '' } = {}) {
|
||||
this.onUserText = onUserText;
|
||||
this.onStatus = onStatus;
|
||||
this.onReplyStart = onReplyStart;
|
||||
this.onReplyEnd = onReplyEnd;
|
||||
this.onError = onError;
|
||||
this.voiceEnabled = voiceEnabled;
|
||||
this.sessionUrl = sessionUrl;
|
||||
this.recognition = null;
|
||||
this.listening = false;
|
||||
this.session = null;
|
||||
}
|
||||
|
||||
setVoiceEnabled(enabled) {
|
||||
this.voiceEnabled = !!enabled;
|
||||
if (!this.voiceEnabled) this.stopSpeaking();
|
||||
}
|
||||
|
||||
async startListening() {
|
||||
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||||
if (!SpeechRecognition) {
|
||||
const err = new Error('当前浏览器不支持语音输入,请使用 Chrome/Edge,或先用文字输入。');
|
||||
this.onError?.(err);
|
||||
throw err;
|
||||
}
|
||||
if (this.listening && this.recognition) {
|
||||
this.recognition.stop();
|
||||
return;
|
||||
}
|
||||
this.recognition = new SpeechRecognition();
|
||||
this.recognition.lang = 'zh-CN';
|
||||
this.recognition.interimResults = true;
|
||||
this.recognition.continuous = false;
|
||||
this.recognition.maxAlternatives = 1;
|
||||
this.listening = true;
|
||||
this.onStatus?.('listening', '正在听你说话...');
|
||||
let finalText = '';
|
||||
this.recognition.onresult = (event) => {
|
||||
let interim = '';
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const transcript = event.results[i][0].transcript;
|
||||
if (event.results[i].isFinal) finalText += transcript;
|
||||
else interim += transcript;
|
||||
}
|
||||
this.onStatus?.('listening', finalText || interim || '正在听你说话...');
|
||||
};
|
||||
this.recognition.onerror = (event) => {
|
||||
this.onError?.(new Error(event.error || '语音识别失败'));
|
||||
};
|
||||
this.recognition.onend = () => {
|
||||
this.listening = false;
|
||||
this.onStatus?.('', '待命中 · 可语音或打字');
|
||||
const text = finalText.trim();
|
||||
if (text) this.onUserText?.(text);
|
||||
};
|
||||
this.recognition.start();
|
||||
}
|
||||
|
||||
speak(text) {
|
||||
if (!this.voiceEnabled || !window.speechSynthesis || !text) return;
|
||||
this.stopSpeaking();
|
||||
const utter = new SpeechSynthesisUtterance(String(text).replace(/<[^>]+>/g, '').slice(0, 220));
|
||||
utter.lang = 'zh-CN';
|
||||
utter.rate = 1.05;
|
||||
utter.pitch = 1.0;
|
||||
utter.onstart = () => {
|
||||
this.onStatus?.('speaking', '正在回复...');
|
||||
this.onReplyStart?.();
|
||||
};
|
||||
utter.onend = () => {
|
||||
this.onStatus?.('', '待命中 · 可语音或打字');
|
||||
this.onReplyEnd?.();
|
||||
};
|
||||
window.speechSynthesis.speak(utter);
|
||||
}
|
||||
|
||||
stopSpeaking() {
|
||||
try { window.speechSynthesis?.cancel(); } catch (e) {}
|
||||
}
|
||||
|
||||
connectSession() {
|
||||
if (!this.sessionUrl) return null;
|
||||
this.session = new VoiceSession({
|
||||
url: this.sessionUrl,
|
||||
onOpen: () => this.onStatus?.('connected', '语音长连接已建立'),
|
||||
onClose: () => this.onStatus?.('', '语音长连接已关闭'),
|
||||
onText: (data) => this.onUserText?.(typeof data === 'string' ? data : (data.text || '')),
|
||||
onError: (e) => this.onError?.(e),
|
||||
});
|
||||
this.session.connect();
|
||||
return this.session;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
try { this.recognition?.stop(); } catch (e) {}
|
||||
this.stopSpeaking();
|
||||
this.session?.close();
|
||||
}
|
||||
}
|
||||
17
main/feedback-backend/.dockerignore
Normal file
17
main/feedback-backend/.dockerignore
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.Python
|
||||
*.egg-info/
|
||||
.eggs/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.git/
|
||||
.gitignore
|
||||
.env
|
||||
data/.config.yaml
|
||||
*.log
|
||||
logs/
|
||||
admin-ui/__pycache__/
|
||||
13
main/feedback-backend/.env.example
Normal file
13
main/feedback-backend/.env.example
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# Feedback Backend 本机环境变量示例
|
||||
# 复制为 .env 或在 PowerShell 中设置后再启动 docker compose。
|
||||
|
||||
# 生产/测试均不要把真实密钥提交到仓库。
|
||||
FEEDBACK_LLM_PROVIDER=deepseek
|
||||
FEEDBACK_LLM_API_KEY=
|
||||
FEEDBACK_LLM_BASE_URL=https://api.deepseek.com/v1
|
||||
FEEDBACK_LLM_MODEL=deepseek-chat
|
||||
|
||||
# 可选:覆盖默认管理员与 JWT 密钥。
|
||||
FEEDBACK_AUTH_SECRET=change-me
|
||||
FEEDBACK_ADMIN_USER=admin
|
||||
FEEDBACK_ADMIN_PASSWORD=admin123
|
||||
26
main/feedback-backend/Dockerfile
Normal file
26
main/feedback-backend/Dockerfile
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
FROM python:3.10-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 安装系统依赖
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
default-libmysqlclient-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 配置 pip 镜像(国内加速)
|
||||
RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
|
||||
|
||||
# 安装 Python 依赖(利用 docker 层缓存)
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# 复制项目代码
|
||||
COPY . .
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 8009
|
||||
|
||||
# 生产模式启动(不带 reload,多 worker 提升稳定性与并发)
|
||||
# 单 worker 时 SQLite/连接池更稳;多 worker 用于高并发。这里用 2 worker 兼顾稳定与性能
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8009", "--workers", "1", "--log-level", "info"]
|
||||
198
main/feedback-backend/README.md
Normal file
198
main/feedback-backend/README.md
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
# 反馈系统后端 (Feedback Backend)
|
||||
|
||||
客户反馈系统独立后端服务,基于 **FastAPI + DDD 架构**,与 xiaozhi-server 完全解耦。
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
feedback-backend/
|
||||
├── app/
|
||||
│ ├── domain/ ← DDD 领域层
|
||||
│ │ ├── store/ (门店: Entity/VO/Repository接口)
|
||||
│ │ ├── employee/ (员工: Entity/VO/Repository接口)
|
||||
│ │ ├── feedback/ (反馈记录: Entity/VO/Repository接口)
|
||||
│ │ └── agent/ (智能体配置: Entity/VO/Repository接口)
|
||||
│ ├── application/ ← 应用层 (用例服务)
|
||||
│ │ ├── feedback_service.py (AI 反馈处理: 3步 LLM Pipeline)
|
||||
│ │ ├── stats_service.py (统计分析)
|
||||
│ │ ├── store_service.py (门店 CRUD)
|
||||
│ │ ├── employee_service.py (员工 CRUD)
|
||||
│ │ └── agent_config_service.py(智能体配置)
|
||||
│ ├── infrastructure/ ← 基础设施层
|
||||
│ │ ├── persistence/ (MySQL ORM + Repository 实现)
|
||||
│ │ ├── llm/ (LLM 调用服务)
|
||||
│ │ └── xiaozhi/ (xiaozhi-server 客户端)
|
||||
│ ├── interfaces/ ← 接口层 (MVC Controller)
|
||||
│ │ └── api/ (REST API: /api/v1/*)
|
||||
│ └── shared/ ← 共享: config/exceptions/utils
|
||||
├── prompts/ ← 提示词模板
|
||||
├── admin-ui/ ← 后台管理前端 (Phase C)
|
||||
├── migrations/ ← Alembic 数据库迁移
|
||||
├── config.yaml ← 配置文件
|
||||
├── alembic.ini ← Alembic 配置
|
||||
├── requirements.txt
|
||||
├── start.py ← 启动脚本
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 安装依赖
|
||||
|
||||
```bash
|
||||
cd main/feedback-backend
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### 2. 创建数据库
|
||||
|
||||
```sql
|
||||
CREATE DATABASE feedback_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
|
||||
```
|
||||
|
||||
### 3. 修改配置
|
||||
|
||||
编辑 `config.yaml`,修改数据库连接信息和 LLM API Key:
|
||||
|
||||
```yaml
|
||||
database:
|
||||
host: "127.0.0.1"
|
||||
port: 3306
|
||||
username: "root"
|
||||
password: "你的密码"
|
||||
database: "feedback_db"
|
||||
|
||||
llm:
|
||||
provider: "openai"
|
||||
openai:
|
||||
api_key: "你的API Key"
|
||||
```
|
||||
|
||||
### 4. 数据库迁移
|
||||
|
||||
```bash
|
||||
# 生成迁移脚本
|
||||
alembic revision --autogenerate -m "init tables"
|
||||
|
||||
# 执行迁移
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
> 开发模式下,首次启动会自动创建表,可以跳过 Alembic。
|
||||
|
||||
### 5. 启动服务
|
||||
|
||||
```bash
|
||||
python start.py
|
||||
```
|
||||
|
||||
访问:
|
||||
- API 文档: http://localhost:8009/docs
|
||||
- 后台管理: http://localhost:8009/admin
|
||||
- 健康检查: http://localhost:8009/health
|
||||
|
||||
### 默认管理员
|
||||
|
||||
- 用户名: `admin`
|
||||
- 密码: `admin123`
|
||||
|
||||
> ⚠️ 首次登录后请立即修改密码!
|
||||
|
||||
## API 接口
|
||||
|
||||
### 公开接口(无需认证)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/v1/public/store/{storeCode}` | 根据编码获取门店 |
|
||||
| GET | `/api/v1/public/employees/{storeId}` | 获取门店员工列表 |
|
||||
| POST | `/api/v1/public/process` | AI 处理反馈 |
|
||||
| POST | `/api/v1/public/record` | 保存反馈记录 |
|
||||
| POST | `/api/v1/public/device-init` | 设备初始化 |
|
||||
|
||||
### 认证接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| POST | `/api/v1/auth/login` | 管理员登录 |
|
||||
| GET | `/api/v1/auth/me` | 获取当前用户 |
|
||||
|
||||
### 管理接口(需要认证)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/v1/store/list` | 门店列表 |
|
||||
| POST | `/api/v1/store` | 创建门店 |
|
||||
| PUT | `/api/v1/store/{id}` | 更新门店 |
|
||||
| POST | `/api/v1/store/delete` | 删除门店 |
|
||||
| GET | `/api/v1/employee/list` | 员工列表 |
|
||||
| POST | `/api/v1/employee` | 创建员工 |
|
||||
| PUT | `/api/v1/employee/{id}` | 更新员工 |
|
||||
| POST | `/api/v1/employee/delete` | 删除员工 |
|
||||
| GET | `/api/v1/record/list` | 反馈记录列表 |
|
||||
| GET | `/api/v1/stats/overview` | 统计概览 |
|
||||
| GET | `/api/v1/stats/daily` | 按天统计 |
|
||||
| GET | `/api/v1/stats/by-store` | 按门店统计 |
|
||||
| GET | `/api/v1/agent-config/list` | 智能体配置列表 |
|
||||
| POST | `/api/v1/agent-config` | 创建智能体配置 |
|
||||
| PUT | `/api/v1/agent-config/{id}` | 更新智能体配置 |
|
||||
|
||||
## Docker 部署
|
||||
|
||||
在 `docker-compose_all.yml` 中添加:
|
||||
|
||||
```yaml
|
||||
feedback-backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile-feedback
|
||||
ports:
|
||||
- "8009:8009"
|
||||
environment:
|
||||
FEEDBACK_DB_HOST: xiaozhi-esp32-server-db
|
||||
FEEDBACK_DB_PASSWORD: "123456"
|
||||
FEEDBACK_LLM_API_KEY: "your-api-key"
|
||||
depends_on:
|
||||
- xiaozhi-esp32-server-db
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量名 | 说明 | 默认值 |
|
||||
|--------|------|--------|
|
||||
| FEEDBACK_DB_HOST | 数据库主机 | 127.0.0.1 |
|
||||
| FEEDBACK_DB_PORT | 数据库端口 | 3306 |
|
||||
| FEEDBACK_DB_USER | 数据库用户 | root |
|
||||
| FEEDBACK_DB_PASSWORD | 数据库密码 | 123456 |
|
||||
| FEEDBACK_DB_NAME | 数据库名 | feedback_db |
|
||||
| FEEDBACK_SERVER_HOST | 服务监听地址 | 0.0.0.0 |
|
||||
| FEEDBACK_SERVER_PORT | 服务端口 | 8009 |
|
||||
| FEEDBACK_LLM_PROVIDER | LLM 提供商 | openai |
|
||||
| FEEDBACK_LLM_API_KEY | LLM API Key | - |
|
||||
| FEEDBACK_LLM_BASE_URL | LLM API Base URL | - |
|
||||
| FEEDBACK_LLM_MODEL | LLM 模型 | gpt-4o-mini |
|
||||
| FEEDBACK_AUTH_SECRET | JWT 密钥 | (内置) |
|
||||
| FEEDBACK_ADMIN_USER | 管理员用户名 | admin |
|
||||
| FEEDBACK_ADMIN_PASSWORD | 管理员密码 | admin123 |
|
||||
| FEEDBACK_XIAOZHI_WS_URL | xiaozhi WebSocket URL | ws://127.0.0.1:18000 |
|
||||
| FEEDBACK_XIAOZHI_HTTP_URL | xiaozhi HTTP URL | http://127.0.0.1:18003 |
|
||||
|
||||
## 数据库表
|
||||
|
||||
| 表名 | 说明 |
|
||||
|------|------|
|
||||
| feedback_store | 门店信息 |
|
||||
| feedback_employee | 员工信息 |
|
||||
| feedback_record | 反馈记录(含满意度) |
|
||||
| agent_config | 智能体配置(对话轮次/提示词/LLM) |
|
||||
| admin_user | 管理员用户 |
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **Web 框架**: FastAPI 0.115
|
||||
- **ORM**: SQLAlchemy 2.0
|
||||
- **数据库**: MySQL (独立数据库 feedback_db)
|
||||
- **迁移**: Alembic
|
||||
- **LLM**: OpenAI SDK (兼容 OpenAI 协议)
|
||||
- **认证**: JWT (python-jose + passlib)
|
||||
- **日志**: loguru
|
||||
427
main/feedback-backend/admin-ui/css/admin.css
Normal file
427
main/feedback-backend/admin-ui/css/admin.css
Normal file
|
|
@ -0,0 +1,427 @@
|
|||
/* ===== CSS Variables ===== */
|
||||
:root {
|
||||
--primary: #4F46E5;
|
||||
--primary-light: #818CF8;
|
||||
--primary-dark: #3730A3;
|
||||
--success: #10B981;
|
||||
--warning: #F59E0B;
|
||||
--danger: #EF4444;
|
||||
--gray-50: #F9FAFB;
|
||||
--gray-100: #F3F4F6;
|
||||
--gray-200: #E5E7EB;
|
||||
--gray-300: #D1D5DB;
|
||||
--gray-400: #9CA3AF;
|
||||
--gray-500: #6B7280;
|
||||
--gray-600: #4B5563;
|
||||
--gray-700: #374151;
|
||||
--gray-800: #1F2937;
|
||||
--gray-900: #111827;
|
||||
--radius: 8px;
|
||||
--shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06);
|
||||
--shadow-md: 0 4px 6px rgba(0,0,0,0.07), 0 2px 4px rgba(0,0,0,0.06);
|
||||
}
|
||||
|
||||
/* ===== Reset ===== */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--gray-50); color: var(--gray-800); line-height: 1.5; }
|
||||
a { color: var(--primary); text-decoration: none; }
|
||||
button { cursor: pointer; font-family: inherit; }
|
||||
input, select, textarea { font-family: inherit; font-size: 14px; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
|
||||
/* ===== Layout ===== */
|
||||
.layout { display: flex; min-height: 100vh; }
|
||||
|
||||
/* Sidebar */
|
||||
.sidebar {
|
||||
width: 220px; background: var(--gray-900); color: #fff;
|
||||
display: flex; flex-direction: column; flex-shrink: 0;
|
||||
position: fixed; top: 0; left: 0; bottom: 0; z-index: 100;
|
||||
}
|
||||
.sidebar-brand { padding: 20px; border-bottom: 1px solid var(--gray-700); }
|
||||
.sidebar-brand h1 { font-size: 16px; font-weight: 600; }
|
||||
.sidebar-brand p { font-size: 12px; color: var(--gray-400); margin-top: 4px; }
|
||||
.sidebar-nav { flex: 1; padding: 12px 0; overflow-y: auto; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 10px 20px; color: var(--gray-300); font-size: 14px;
|
||||
transition: all 0.15s; border-left: 3px solid transparent;
|
||||
}
|
||||
.nav-item:hover { background: var(--gray-800); color: #fff; }
|
||||
.nav-item.active { background: var(--gray-800); color: var(--primary-light); border-left-color: var(--primary-light); }
|
||||
.nav-item .icon { width: 20px; text-align: center; }
|
||||
.sidebar-footer { padding: 16px 20px; border-top: 1px solid var(--gray-700); font-size: 12px; color: var(--gray-500); }
|
||||
.sidebar-footer a { color: var(--gray-400); }
|
||||
.sidebar-footer a:hover { color: var(--danger); }
|
||||
|
||||
/* Main */
|
||||
.main { flex: 1; margin-left: 220px; }
|
||||
.topbar {
|
||||
background: #fff; border-bottom: 1px solid var(--gray-200);
|
||||
padding: 0 24px; height: 56px; display: flex; align-items: center; justify-content: space-between;
|
||||
position: sticky; top: 0; z-index: 50;
|
||||
}
|
||||
.topbar-title { font-size: 18px; font-weight: 600; color: var(--gray-800); }
|
||||
.topbar-user { font-size: 13px; color: var(--gray-500); }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 12px; }
|
||||
.notify-btn { position: relative; width: 36px; height: 36px; border: none; border-radius: 10px; background: var(--gray-100); font-size: 17px; }
|
||||
.notify-badge { position: absolute; right: -4px; top: -4px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 999px; background: var(--danger); color: #fff; font-size: 11px; line-height: 18px; font-weight: 800; }
|
||||
.content { padding: 24px; }
|
||||
|
||||
/* ===== Cards ===== */
|
||||
.card {
|
||||
background: #fff; border-radius: var(--radius); box-shadow: var(--shadow);
|
||||
padding: 20px; margin-bottom: 20px;
|
||||
}
|
||||
.card-title { font-size: 15px; font-weight: 600; color: var(--gray-800); margin-bottom: 16px; }
|
||||
|
||||
/* ===== Stat Cards ===== */
|
||||
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
|
||||
.stat-card {
|
||||
background: #fff; border-radius: var(--radius); box-shadow: var(--shadow);
|
||||
padding: 20px; display: flex; align-items: center; gap: 16px;
|
||||
}
|
||||
.stat-icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 24px; }
|
||||
.stat-icon.blue { background: #EEF2FF; }
|
||||
.stat-icon.green { background: #ECFDF5; }
|
||||
.stat-icon.yellow { background: #FFFBEB; }
|
||||
.stat-icon.red { background: #FEF2F2; }
|
||||
.stat-info { flex: 1; }
|
||||
.stat-label { font-size: 12px; color: var(--gray-500); text-transform: uppercase; letter-spacing: 0.5px; }
|
||||
.stat-value { font-size: 28px; font-weight: 700; color: var(--gray-900); margin-top: 2px; }
|
||||
.stat-sub { font-size: 12px; color: var(--gray-400); margin-top: 2px; }
|
||||
|
||||
/* ===== Table ===== */
|
||||
.table-wrap { overflow-x: auto; }
|
||||
table th {
|
||||
background: var(--gray-50); padding: 10px 12px; text-align: left;
|
||||
font-size: 12px; font-weight: 600; color: var(--gray-500); text-transform: uppercase;
|
||||
letter-spacing: 0.5px; border-bottom: 1px solid var(--gray-200);
|
||||
}
|
||||
table td {
|
||||
padding: 10px 12px; font-size: 13px; color: var(--gray-700);
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
}
|
||||
table tr:hover td { background: var(--gray-50); }
|
||||
|
||||
/* ===== Buttons ===== */
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
padding: 8px 16px; border-radius: 6px; font-size: 13px; font-weight: 500;
|
||||
border: 1px solid transparent; transition: all 0.15s;
|
||||
}
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
.btn-primary:hover { background: var(--primary-dark); }
|
||||
.btn-secondary { background: #fff; color: var(--gray-700); border-color: var(--gray-300); }
|
||||
.btn-secondary:hover { background: var(--gray-50); }
|
||||
.btn-danger { background: var(--danger); color: #fff; }
|
||||
.btn-danger:hover { background: #DC2626; }
|
||||
.btn-sm { padding: 4px 10px; font-size: 12px; }
|
||||
.btn-icon { padding: 6px; width: 32px; height: 32px; justify-content: center; }
|
||||
|
||||
/* ===== Forms ===== */
|
||||
.form-group { margin-bottom: 16px; }
|
||||
.form-label { display: block; font-size: 13px; font-weight: 500; color: var(--gray-700); margin-bottom: 6px; }
|
||||
.form-input {
|
||||
width: 100%; padding: 8px 12px; border: 1px solid var(--gray-300); border-radius: 6px;
|
||||
font-size: 14px; color: var(--gray-800); transition: border-color 0.15s;
|
||||
}
|
||||
.form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79,70,229,0.1); }
|
||||
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
|
||||
|
||||
/* ===== Badges ===== */
|
||||
.badge {
|
||||
display: inline-block; padding: 2px 8px; border-radius: 12px;
|
||||
font-size: 11px; font-weight: 600;
|
||||
}
|
||||
.badge-green { background: #ECFDF5; color: #059669; }
|
||||
.badge-yellow { background: #FFFBEB; color: #D97706; }
|
||||
.badge-red { background: #FEF2F2; color: #DC2626; }
|
||||
.badge-blue { background: #EEF2FF; color: #4F46E5; }
|
||||
.badge-gray { background: var(--gray-100); color: var(--gray-600); }
|
||||
|
||||
/* ===== Pagination ===== */
|
||||
.pagination { display: flex; align-items: center; justify-content: space-between; margin-top: 16px; }
|
||||
.pagination-info { font-size: 13px; color: var(--gray-500); }
|
||||
.pagination-btns { display: flex; gap: 4px; }
|
||||
.pagination-btns button {
|
||||
padding: 6px 12px; border: 1px solid var(--gray-300); border-radius: 4px;
|
||||
background: #fff; font-size: 13px; color: var(--gray-700);
|
||||
}
|
||||
.pagination-btns button:hover { background: var(--gray-50); }
|
||||
.pagination-btns button.active { background: var(--primary); color: #fff; border-color: var(--primary); }
|
||||
.pagination-btns button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
/* ===== Filter Bar ===== */
|
||||
.filter-bar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
|
||||
.filter-bar .form-input { width: auto; min-width: 140px; }
|
||||
.filter-bar select { min-width: 120px; }
|
||||
|
||||
/* ===== Chart Container ===== */
|
||||
.dashboard-chart-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
|
||||
.chart-container { width: 100%; min-height: 260px; position: relative; }
|
||||
.sat-summary { display: flex; align-items: center; gap: 14px; padding: 14px; border-radius: 14px; background: linear-gradient(135deg, #EEF2FF, #F8FAFC); margin-bottom: 18px; }
|
||||
.sat-total { width: 58px; height: 58px; border-radius: 18px; background: #4F46E5; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 800; box-shadow: 0 10px 24px rgba(79,70,229,.22); }
|
||||
.sat-total-label { font-size: 13px; color: var(--gray-500); }
|
||||
.sat-rate { font-size: 18px; color: var(--gray-900); font-weight: 700; margin-top: 2px; }
|
||||
.sat-bars { display: grid; gap: 14px; }
|
||||
.sat-row-head { display: flex; align-items: center; gap: 8px; margin-bottom: 7px; font-size: 13px; }
|
||||
.sat-dot { width: 10px; height: 10px; border-radius: 999px; flex-shrink: 0; }
|
||||
.sat-name { color: var(--gray-700); font-weight: 600; }
|
||||
.sat-num { margin-left: auto; color: var(--gray-500); font-variant-numeric: tabular-nums; }
|
||||
.sat-track { height: 10px; border-radius: 999px; overflow: hidden; }
|
||||
.sat-fill { height: 100%; border-radius: 999px; transition: width .35s ease; }
|
||||
.trend-bars { height: 260px; display: flex; align-items: flex-end; gap: 10px; padding: 8px 2px 0; overflow-x: auto; -webkit-overflow-scrolling: touch; }
|
||||
.trend-item { min-width: 38px; flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%; }
|
||||
.trend-value { height: 20px; font-size: 12px; font-weight: 700; color: var(--primary); margin-bottom: 6px; }
|
||||
.trend-bar-wrap { height: 158px; width: 100%; display: flex; align-items: flex-end; justify-content: center; border-bottom: 1px solid var(--gray-200); }
|
||||
.trend-bar { width: min(28px, 70%); border-radius: 10px 10px 2px 2px; background: linear-gradient(180deg, #4F46E5 0%, #818CF8 100%); box-shadow: 0 8px 16px rgba(79,70,229,.16); transition: height .35s ease; }
|
||||
.trend-date { margin-top: 8px; font-size: 11px; color: var(--gray-500); white-space: nowrap; }
|
||||
|
||||
/* ===== Modal ===== */
|
||||
.modal-overlay {
|
||||
position: fixed; inset: 0; background: rgba(0,0,0,0.4);
|
||||
display: flex; align-items: center; justify-content: center; z-index: 200;
|
||||
}
|
||||
.modal-card {
|
||||
background: #fff; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.15);
|
||||
width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto;
|
||||
}
|
||||
.modal-header { padding: 20px 24px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; align-items: center; }
|
||||
.modal-header h3 { font-size: 16px; font-weight: 600; }
|
||||
.modal-body { padding: 24px; }
|
||||
.modal-footer { padding: 16px 24px; border-top: 1px solid var(--gray-200); display: flex; justify-content: flex-end; gap: 8px; }
|
||||
.modal-close { background: none; border: none; font-size: 20px; color: var(--gray-400); padding: 4px; }
|
||||
.modal-close:hover { color: var(--gray-700); }
|
||||
.notify-modal { max-width: 620px; }
|
||||
.notify-item { width: 100%; display: block; text-align: left; border: 1px solid var(--gray-200); background: #fff; border-radius: 12px; padding: 12px; margin-bottom: 10px; }
|
||||
.notify-item.unread { border-color: #C7D2FE; background: #EEF2FF; }
|
||||
.notify-item strong { display: block; color: var(--gray-900); margin-bottom: 4px; }
|
||||
.notify-item span { display: block; color: var(--gray-600); font-size: 13px; line-height: 1.5; }
|
||||
.notify-item small { display: block; margin-top: 6px; color: var(--gray-400); }
|
||||
|
||||
/* ===== Appointment Calendar ===== */
|
||||
.fullcalendar-box { background: #fff; border: 1px solid var(--gray-200); border-radius: 16px; padding: 12px; box-shadow: var(--shadow); }
|
||||
.fc { --fc-border-color: #E5E7EB; --fc-today-bg-color: #EEF2FF; --fc-page-bg-color: #fff; font-size: 13px; }
|
||||
.fc .fc-col-header-cell { background: #F8FAFC; padding: 8px 0; color: var(--gray-600); }
|
||||
.fc .fc-timegrid-slot { height: 42px; }
|
||||
.fc .fc-event { border: none; border-radius: 8px; padding: 2px 4px; box-shadow: 0 6px 16px rgba(79,70,229,.12); cursor: pointer; }
|
||||
.fc .fc-status-pending { background: #4F46E5; color: #fff; }
|
||||
.fc .fc-status-confirmed { background: #10B981; color: #fff; }
|
||||
.fc .fc-status-cancelled { background: #EF4444; color: #fff; opacity: .75; }
|
||||
.fc .fc-status-completed { background: #6B7280; color: #fff; }
|
||||
.appointment-board { min-height: 260px; }
|
||||
.appointment-range { color: var(--gray-500); font-size: 13px; margin-bottom: 12px; }
|
||||
.appointment-day-summary { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; padding: 10px; background: #F8FAFC; border: 1px solid var(--gray-200); border-radius: 12px; }
|
||||
.appointment-day-summary.empty { color: var(--gray-400); font-size: 13px; }
|
||||
.appointment-summary-chip { border: 1px solid #C7D2FE; background: #EEF2FF; color: #3730A3; border-radius: 999px; padding: 6px 10px; font-size: 12px; cursor: pointer; }
|
||||
.appointment-summary-chip:hover { background: #E0E7FF; }
|
||||
.resource-calendar { display: flex; border: 1px solid var(--gray-200); border-radius: 16px; overflow: auto; max-height: 720px; background: #fff; box-shadow: var(--shadow); }
|
||||
.resource-time-axis { width: 70px; flex: 0 0 70px; background: #F8FAFC; border-right: 1px solid var(--gray-200); }
|
||||
.resource-corner, .resource-head { height: 44px; display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--gray-700); background: #EEF2FF; border-bottom: 1px solid var(--gray-200); position: sticky; top: 0; z-index: 3; }
|
||||
.resource-time { height: var(--slot-h); padding: 6px; font-size: 12px; color: var(--gray-500); border-bottom: 1px solid var(--gray-100); }
|
||||
.resource-columns { display: flex; min-width: 720px; flex: 1; }
|
||||
.resource-column { min-width: 220px; flex: 1; border-right: 1px solid var(--gray-200); }
|
||||
.resource-slots { position: relative; min-height: calc(var(--slot-h) * 24); }
|
||||
.resource-slot { height: var(--slot-h); border-bottom: 1px solid var(--gray-100); cursor: pointer; background: linear-gradient(180deg, #fff, #fff); }
|
||||
.resource-slot:hover { background: #F8FAFC; }
|
||||
.resource-event { position: absolute; left: 8px; right: 8px; border-radius: 10px; padding: 8px; background: #4F46E5; color: #fff; font-size: 12px; overflow: hidden; box-shadow: 0 10px 24px rgba(79,70,229,.22); cursor: pointer; z-index: 2; }
|
||||
.resource-event.status-confirmed { background: #10B981; }
|
||||
.resource-event.status-cancelled { background: #EF4444; opacity: .78; }
|
||||
.resource-event.status-completed { background: #6B7280; }
|
||||
.resource-event span { opacity: .9; }
|
||||
.calendar-day-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; }
|
||||
.calendar-employee-col { border: 1px solid #E0E7FF; border-radius: 14px; background: linear-gradient(180deg, #fff, #F8FAFC); overflow: hidden; box-shadow: var(--shadow); }
|
||||
.calendar-employee-head { background: #EEF2FF; padding: 12px 14px; font-weight: 800; color: #3730A3; border-bottom: 1px solid #E0E7FF; }
|
||||
.appointment-empty { padding: 24px; color: var(--gray-400); font-size: 13px; text-align: center; }
|
||||
.appointment-event { margin: 10px; padding: 11px; border-radius: 12px; background: #EEF2FF; border-left: 4px solid var(--primary); font-size: 13px; box-shadow: 0 8px 20px rgba(79,70,229,.08); }
|
||||
.appointment-event.status-confirmed { background: #ECFDF5; border-left-color: var(--success); }
|
||||
.appointment-event.status-cancelled { background: #FEF2F2; border-left-color: var(--danger); opacity: .75; }
|
||||
.appointment-event.status-completed { background: var(--gray-100); border-left-color: var(--gray-500); }
|
||||
.appointment-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
|
||||
.calendar-week-grid { display: grid; grid-template-columns: repeat(7, minmax(140px, 1fr)); gap: 10px; overflow-x: auto; }
|
||||
.calendar-day-cell { min-height: 220px; border: 1px solid var(--gray-200); border-radius: 14px; background: #fff; padding: 10px; }
|
||||
.calendar-day-head { font-weight: 800; color: var(--gray-700); margin-bottom: 8px; }
|
||||
.calendar-no-event { color: var(--gray-300); font-size: 12px; padding-top: 20px; text-align: center; }
|
||||
.calendar-month { border: 1px solid var(--gray-200); border-radius: 16px; overflow: hidden; background: #fff; }
|
||||
.calendar-weekdays, .calendar-month-grid { display: grid; grid-template-columns: repeat(7, 1fr); }
|
||||
.calendar-weekdays > div { background: #F8FAFC; padding: 10px; font-size: 12px; font-weight: 700; color: var(--gray-500); text-align: center; border-bottom: 1px solid var(--gray-200); }
|
||||
.calendar-month-cell { min-height: 116px; padding: 8px; border-right: 1px solid var(--gray-100); border-bottom: 1px solid var(--gray-100); }
|
||||
.calendar-month-cell.muted-month { background: #FAFAFA; opacity: .55; }
|
||||
.calendar-month-date { font-weight: 800; color: var(--gray-700); margin-bottom: 6px; }
|
||||
.calendar-compact-event { border-radius: 7px; background: #EEF2FF; color: #3730A3; padding: 4px 6px; font-size: 11px; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.calendar-compact-event.status-confirmed { background: #ECFDF5; color: #047857; }
|
||||
.calendar-compact-event.status-cancelled { background: #FEF2F2; color: #B91C1C; }
|
||||
.calendar-compact-event.status-completed { background: var(--gray-100); color: var(--gray-600); }
|
||||
.calendar-compact-event span { font-weight: 700; }
|
||||
.calendar-more { font-size: 11px; color: var(--gray-500); }
|
||||
.slot-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 8px; }
|
||||
.slot-item { border-radius: 8px; padding: 8px; font-size: 12px; border: 1px solid var(--gray-200); }
|
||||
.slot-item.available { background: #ECFDF5; color: #047857; }
|
||||
.slot-item.busy { background: #FEF2F2; color: #B91C1C; }
|
||||
|
||||
/* ===== AI Assistant ===== */
|
||||
.ai-fab { position: fixed; right: 22px; bottom: 22px; width: 62px; height: 62px; border-radius: 999px; border: none; background: radial-gradient(circle at 30% 25%, #A5B4FC, #4F46E5 48%, #7C3AED); color: #fff; font-size: 18px; font-weight: 900; box-shadow: 0 14px 36px rgba(79,70,229,.35); z-index: 180; }
|
||||
.ai-fab span { display: inline-flex; align-items: center; justify-content: center; width: 38px; height: 38px; border-radius: 999px; border: 1px solid rgba(255,255,255,.42); background: rgba(255,255,255,.12); letter-spacing: .5px; }
|
||||
.ai-panel { position: fixed; right: 22px; bottom: 96px; width: 460px; max-width: calc(100vw - 24px); height: 720px; max-height: calc(100vh - 120px); background: #fff; border-radius: 22px; box-shadow: 0 24px 80px rgba(15,23,42,.28); z-index: 180; display: none; flex-direction: column; overflow: hidden; }
|
||||
.ai-panel.open { display: flex; }
|
||||
.ai-panel.expanded { right: 50%; bottom: 28px; transform: translateX(50%); width: min(980px, calc(100vw - 44px)); height: min(820px, calc(100vh - 56px)); }
|
||||
.ai-head { padding: 14px 16px; border-bottom: 1px solid rgba(255,255,255,.18); display: flex; justify-content: space-between; align-items: center; color: #fff; background: linear-gradient(135deg, #312E81, #4F46E5 55%, #7C3AED); }
|
||||
.ai-head .muted { color: rgba(255,255,255,.74); }
|
||||
.ai-head-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.ai-icon-btn { width: 32px; height: 32px; border: 1px solid rgba(255,255,255,.28); border-radius: 10px; color: #fff; background: rgba(255,255,255,.12); font-size: 15px; }
|
||||
.ai-head .modal-close { color: #fff; opacity: .9; }
|
||||
.ai-stage { position: relative; height: 330px; min-height: 330px; overflow: hidden; background: radial-gradient(circle at 50% 26%, #FFE5E5 0%, transparent 56%), linear-gradient(180deg, #FFB6C1 0%, #FFC8DD 30%, #BDE0FE 72%, #A2D2FF 100%); }
|
||||
.ai-panel.expanded .ai-stage { height: 58%; min-height: 420px; }
|
||||
.ai-stage-bg { position: absolute; inset: 0; z-index: 0; background: linear-gradient(180deg, rgba(255,255,255,.08), rgba(15,23,42,.16)); pointer-events: none; }
|
||||
.ai-live2d-canvas { position: absolute !important; inset: 0; width: 100% !important; height: 100% !important; display: block; z-index: 1; }
|
||||
.ai-face { position: absolute; left: 50%; top: 45%; transform: translate(-50%, -50%); font-size: 86px; z-index: 2; transition: transform .2s ease; text-shadow: 0 12px 28px rgba(79,70,229,.22); }
|
||||
.ai-face.hidden { display: none; }
|
||||
.ai-avatar { position: absolute; left: 18px; bottom: 18px; width: 86px; height: 54px; border-radius: 18px; background: rgba(255,255,255,.18); display: flex; align-items: center; justify-content: center; box-shadow: 0 10px 26px rgba(79,70,229,.16); overflow: hidden; z-index: 4; backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,.28); }
|
||||
.ai-avatar-ring { width: 14px; height: 14px; border-radius: 999px; background: #94A3B8; box-shadow: 0 0 0 6px rgba(148,163,184,.16); }
|
||||
.ai-avatar.live2d-ready .ai-avatar-ring { background: #10B981; box-shadow: 0 0 0 6px rgba(16,185,129,.16); }
|
||||
.ai-avatar.listening .ai-avatar-ring { background: #10B981; box-shadow: 0 0 0 6px rgba(16,185,129,.22); }
|
||||
.ai-avatar.thinking .ai-avatar-ring { background: #F59E0B; box-shadow: 0 0 0 6px rgba(245,158,11,.22); }
|
||||
.ai-avatar.speaking .ai-avatar-ring { background: #4F46E5; box-shadow: 0 0 0 6px rgba(79,70,229,.22); }
|
||||
.ai-avatar.speaking .ai-face { animation: avatarTalk .45s ease-in-out infinite alternate; }
|
||||
.ai-avatar.listening .ai-wave span, .ai-avatar.speaking .ai-wave span { animation: voiceWave .8s ease-in-out infinite; }
|
||||
.ai-wave { position: absolute; right: 14px; bottom: 14px; display: flex; gap: 3px; align-items: flex-end; }
|
||||
.ai-wave span { width: 4px; height: 8px; border-radius: 999px; background: #4F46E5; opacity: .35; }
|
||||
.ai-wave span:nth-child(2) { animation-delay: .12s; }
|
||||
.ai-wave span:nth-child(3) { animation-delay: .24s; }
|
||||
.ai-stage-status { position: absolute; left: 116px; right: 16px; bottom: 18px; z-index: 4; display: flex; align-items: center; gap: 8px; min-height: 54px; padding: 10px 13px; color: #fff; font-size: 13px; line-height: 1.45; border-radius: 18px; background: rgba(15,23,42,.32); backdrop-filter: blur(12px); text-shadow: 0 1px 2px rgba(0,0,0,.28); }
|
||||
.ai-status-dot { width: 8px; height: 8px; border-radius: 999px; background: #10B981; box-shadow: 0 0 0 5px rgba(16,185,129,.18); flex-shrink: 0; }
|
||||
.ai-body { flex: 1; min-height: 0; display: flex; flex-direction: column; background: var(--gray-50); }
|
||||
@keyframes avatarTalk { from { transform: scale(1); } to { transform: scale(1.08) translateY(-1px); } }
|
||||
@keyframes voiceWave { 0%,100% { height: 6px; opacity: .35; } 50% { height: 18px; opacity: 1; } }
|
||||
.ai-messages { flex: 1; overflow-y: auto; padding: 14px; background: linear-gradient(180deg, rgba(248,250,252,.98), #F8FAFC); }
|
||||
.ai-msg { padding: 10px 12px; border-radius: 14px; margin-bottom: 10px; font-size: 13px; line-height: 1.55; word-break: break-word; box-shadow: 0 4px 14px rgba(15,23,42,.05); }
|
||||
.ai-msg-bot { background: rgba(255,255,255,.92); color: var(--gray-800); border: 1px solid var(--gray-200); border-bottom-left-radius: 5px; }
|
||||
.ai-msg-user { background: linear-gradient(135deg, #4F46E5, #6366F1); color: #fff; margin-left: 54px; border-bottom-right-radius: 5px; }
|
||||
.ai-quick { display: flex; flex-wrap: wrap; gap: 6px; padding: 10px 12px; border-top: 1px solid var(--gray-100); background: #fff; }
|
||||
.ai-quick button { border: 1px solid var(--gray-300); background: #fff; border-radius: 999px; padding: 4px 9px; font-size: 12px; color: var(--gray-700); }
|
||||
.ai-input-row .btn.active, #aiLongChat.active { background: #10B981; border-color: #10B981; color: #fff; box-shadow: 0 0 0 3px rgba(16,185,129,.14); }
|
||||
.ai-feedback { margin-top: 8px; display: flex; gap: 6px; font-size: 12px; color: var(--gray-500); }
|
||||
.ai-feedback button { border: 1px solid var(--gray-300); background: #fff; border-radius: 999px; padding: 2px 8px; cursor: pointer; }
|
||||
.ai-feedback button:hover { background: var(--gray-50); }
|
||||
.ai-input-row { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--gray-200); background: #fff; }
|
||||
.ai-input-row .form-input { flex: 1; }
|
||||
@media (max-width: 768px) { .ai-fab { right: 14px; bottom: 14px; } .ai-panel, .ai-panel.expanded { right: 12px; bottom: 78px; transform: none; width: calc(100vw - 24px); height: 78vh; max-height: calc(100vh - 96px); } .ai-stage { height: 44%; min-height: 260px; } .ai-panel.expanded .ai-stage { height: 46%; min-height: 280px; } .ai-input-row { flex-wrap: wrap; } .ai-input-row .form-input { flex-basis: 100%; } }
|
||||
|
||||
/* ===== Login Page ===== */
|
||||
.login-page {
|
||||
min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
}
|
||||
.login-card {
|
||||
background: #fff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0,0,0,0.2);
|
||||
padding: 40px; width: 380px;
|
||||
}
|
||||
.login-card h1 { font-size: 24px; text-align: center; margin-bottom: 8px; color: var(--gray-900); }
|
||||
.login-card p { text-align: center; color: var(--gray-500); margin-bottom: 32px; font-size: 14px; }
|
||||
.login-card .form-input { padding: 12px; }
|
||||
.login-card .btn-primary { width: 100%; padding: 12px; font-size: 15px; justify-content: center; }
|
||||
.login-error { color: var(--danger); font-size: 13px; text-align: center; margin-top: 12px; min-height: 20px; }
|
||||
|
||||
/* ===== Empty State ===== */
|
||||
.empty-state { text-align: center; padding: 48px 20px; color: var(--gray-400); }
|
||||
.empty-state .icon { font-size: 48px; margin-bottom: 12px; }
|
||||
.empty-state p { font-size: 14px; }
|
||||
|
||||
/* ===== Satisfaction Stars ===== */
|
||||
.sat-4 { color: #059669; }
|
||||
.sat-3 { color: #10B981; }
|
||||
.sat-2 { color: #F59E0B; }
|
||||
.sat-1 { color: #EF4444; }
|
||||
|
||||
/* ===== Responsive ===== */
|
||||
@media (max-width: 768px) {
|
||||
body { font-size: 14px; }
|
||||
.layout { display: block; min-height: 100vh; }
|
||||
.sidebar {
|
||||
display: flex; transform: translateX(-100%); transition: transform 0.2s ease;
|
||||
width: 78vw; max-width: 300px; box-shadow: 0 20px 60px rgba(0,0,0,0.35);
|
||||
}
|
||||
.sidebar.open { transform: translateX(0); }
|
||||
.main { margin-left: 0; }
|
||||
.topbar { height: 52px; padding: 0 12px; gap: 10px; }
|
||||
.topbar-title { font-size: 16px; flex: 1; }
|
||||
.topbar-user { max-width: 38vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mobile-menu-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border: none; background: var(--gray-100); border-radius: 8px; font-size: 20px; }
|
||||
.content { padding: 12px; }
|
||||
.stat-grid { grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.dashboard-chart-grid { grid-template-columns: 1fr; gap: 12px; }
|
||||
.chart-container { min-height: auto; }
|
||||
.trend-bars { height: 230px; gap: 8px; }
|
||||
.stat-card { padding: 12px; gap: 10px; }
|
||||
.stat-icon { width: 38px; height: 38px; font-size: 20px; }
|
||||
.stat-value { font-size: 22px; }
|
||||
.card { padding: 12px; margin-bottom: 12px; }
|
||||
.form-row { grid-template-columns: 1fr; }
|
||||
.filter-bar { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.filter-bar .form-input, .filter-bar select, .filter-bar button { width: 100% !important; min-width: 0; }
|
||||
.table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
|
||||
table { min-width: 760px; }
|
||||
table th, table td { padding: 8px; font-size: 12px; }
|
||||
.modal-overlay { align-items: flex-end; }
|
||||
.modal-card { width: 100%; max-width: none; max-height: 92vh; border-radius: 16px 16px 0 0; }
|
||||
.modal-body { padding: 16px; }
|
||||
.modal-header { padding: 16px; }
|
||||
.modal-footer { padding: 12px 16px; }
|
||||
.login-card { width: calc(100vw - 32px); padding: 28px 20px; }
|
||||
}
|
||||
|
||||
@media (min-width: 769px) {
|
||||
.mobile-menu-btn { display: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.stat-grid { grid-template-columns: 1fr; }
|
||||
.filter-bar { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* ===== CRM ===== */
|
||||
.crm-tabs { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
|
||||
.crm-tab { padding: 9px 12px; border: 1px solid var(--gray-300); background: #fff; color: var(--gray-700); border-radius: 999px; font-size: 13px; }
|
||||
.crm-tab:hover { background: var(--gray-50); }
|
||||
.crm-tab.active { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.muted { color: var(--gray-500); font-size: 12px; }
|
||||
textarea.form-input { min-height: 86px; resize: vertical; }
|
||||
.crm-detail-modal { max-width: 700px; }
|
||||
.crm-detail-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }
|
||||
.member-combobox { position: relative; }
|
||||
.member-manual { margin-top: 6px; font-size: 12px; }
|
||||
.member-dropdown { display: none; position: absolute; left: 0; right: 0; top: 64px; z-index: 260; background: #fff; border: 1px solid var(--gray-200); border-radius: 10px; box-shadow: 0 14px 36px rgba(0,0,0,.14); max-height: 240px; overflow-y: auto; }
|
||||
.member-dropdown.open { display: block; }
|
||||
.member-option { padding: 9px 12px; cursor: pointer; display: flex; justify-content: space-between; gap: 10px; font-size: 13px; border-bottom: 1px solid var(--gray-100); }
|
||||
.member-option:hover { background: #EEF2FF; color: var(--primary); }
|
||||
.member-option.disabled { color: var(--gray-400); cursor: default; }
|
||||
.member-option.disabled:hover { background: #fff; color: var(--gray-400); }
|
||||
.member-option span { color: var(--gray-500); font-size: 12px; }
|
||||
.crm-profile-head { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 12px; background: var(--gray-50); padding: 16px; border-radius: 8px; margin-bottom: 16px; }
|
||||
.crm-detail-section { margin-bottom: 16px; }
|
||||
.crm-detail-title { font-size: 13px; font-weight: 600; color: var(--gray-600); margin-bottom: 6px; padding-bottom: 4px; border-bottom: 1px solid var(--gray-100); }
|
||||
.crm-detail-body { font-size: 13px; color: var(--gray-800); line-height: 1.6; }
|
||||
.crm-timeline { list-style: none; padding: 0; }
|
||||
.crm-timeline li { font-size: 13px; color: var(--gray-700); padding: 6px 0; border-bottom: 1px solid var(--gray-50); }
|
||||
.crm-timeline li:last-child { border: none; }
|
||||
.crm-pre { background: var(--gray-50); padding: 8px; border-radius: 4px; font-size: 11px; max-height: 150px; overflow-y: auto; white-space: pre-wrap; }
|
||||
.crm-trend-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; }
|
||||
.crm-trend-grid > div { background: var(--gray-50); border-radius: 8px; padding: 10px; font-size: 12px; color: var(--gray-500); }
|
||||
.crm-trend-grid strong { color: var(--gray-900); font-size: 18px; }
|
||||
.mekai66-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; max-height: 420px; overflow-y: auto; padding: 10px; background: var(--gray-50); border-radius: 8px; }
|
||||
.mekai66-group { background: #fff; border: 1px solid var(--gray-200); border-radius: 8px; padding: 10px; }
|
||||
.mekai66-title { font-size: 13px; font-weight: 700; color: var(--primary); margin-bottom: 8px; }
|
||||
.mekai66-field { display: grid; grid-template-columns: 88px 1fr; gap: 6px; align-items: center; margin-bottom: 6px; }
|
||||
.mekai66-field span { font-size: 12px; color: var(--gray-600); }
|
||||
.mekai66-field .form-input { padding: 5px 8px; font-size: 12px; }
|
||||
|
||||
/* ===== Detail panel ===== */
|
||||
.detail-row { display: flex; padding: 8px 0; border-bottom: 1px solid var(--gray-100); }
|
||||
.detail-label { width: 100px; font-size: 13px; color: var(--gray-500); flex-shrink: 0; }
|
||||
.detail-value { font-size: 13px; color: var(--gray-800); flex: 1; word-break: break-all; }
|
||||
|
||||
/* ===== Loading ===== */
|
||||
.loading { text-align: center; padding: 40px; color: var(--gray-400); }
|
||||
.spinner { display: inline-block; width: 24px; height: 24px; border: 3px solid var(--gray-200); border-top-color: var(--primary); border-radius: 50%; animation: spin 0.8s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
18
main/feedback-backend/admin-ui/index.html
Normal file
18
main/feedback-backend/admin-ui/index.html
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>反馈系统管理后台</title>
|
||||
<link rel="stylesheet" href="css/admin.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>
|
||||
<script src="libs/pixi.js"></script>
|
||||
<script src="libs/live2dcubismcore.min.js"></script>
|
||||
<script src="libs/cubism4.min.js"></script>
|
||||
<script src="js/live2d-manager.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="js/admin.js?v=20260625-records-fix"></script>
|
||||
</body>
|
||||
</html>
|
||||
308
main/feedback-backend/admin-ui/js/admin.js
Normal file
308
main/feedback-backend/admin-ui/js/admin.js
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
// Main Admin SPA Application
|
||||
import { api } from './api.js';
|
||||
import { renderDashboard } from './pages/dashboard.js';
|
||||
import { renderRecords } from './pages/records.js?v=20260625-records-fix';
|
||||
import { renderStores } from './pages/stores.js';
|
||||
import { renderEmployees } from './pages/employees.js';
|
||||
import { renderAgentConfigs } from './pages/agent-configs.js';
|
||||
import { renderCrm } from './pages/crm.js';
|
||||
import { initAiAssistant } from './ai-assistant.js?v=20260625-longchat-default';
|
||||
import './form-copilot.js';
|
||||
|
||||
// ---- Router ----
|
||||
function getRoute() {
|
||||
const hash = window.location.hash || '#/dashboard';
|
||||
const [path] = hash.substring(2).split('?');
|
||||
return path;
|
||||
}
|
||||
|
||||
function navigate(route) {
|
||||
window.location.hash = `#/${route}`;
|
||||
}
|
||||
|
||||
// ---- Auth Check ----
|
||||
function isLoggedIn() {
|
||||
return !!api.token;
|
||||
}
|
||||
|
||||
function getNavItems() {
|
||||
const items = [
|
||||
{ route: 'dashboard', icon: '📊', label: '统计概览' },
|
||||
{ route: 'crm', icon: '💎', label: 'CRM管理' },
|
||||
{ route: 'records', icon: '📋', label: '反馈记录' },
|
||||
{ route: 'employees', icon: '👥', label: '员工管理' },
|
||||
];
|
||||
if (!api.isStoreManager) {
|
||||
items.splice(2, 0, { route: 'stores', icon: '🏪', label: '门店管理' });
|
||||
items.push({ route: 'agent-configs', icon: '🤖', label: '智能体配置' });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// ---- Render App Shell ----
|
||||
function renderApp() {
|
||||
let route = getRoute();
|
||||
const app = document.getElementById('app');
|
||||
|
||||
if (!isLoggedIn()) {
|
||||
renderLogin(app);
|
||||
return;
|
||||
}
|
||||
|
||||
const username = localStorage.getItem('feedback_admin_user') || 'admin';
|
||||
const displayName = localStorage.getItem('feedback_admin_display_name') || username;
|
||||
const storeName = localStorage.getItem('feedback_admin_store_name') || '';
|
||||
const navItems = getNavItems();
|
||||
if (!navItems.some(i => i.route === route)) {
|
||||
route = 'dashboard';
|
||||
window.location.hash = '#/dashboard';
|
||||
}
|
||||
|
||||
app.innerHTML = `
|
||||
<div class="layout">
|
||||
<aside class="sidebar" id="sidebar">
|
||||
<div class="sidebar-brand">
|
||||
<h1>反馈系统</h1>
|
||||
<p>${api.isStoreManager ? (storeName || '店长后台') : '管理后台'} v1.0</p>
|
||||
</div>
|
||||
<nav class="sidebar-nav">
|
||||
${navItems.map(item => `
|
||||
<a class="nav-item ${route === item.route ? 'active' : ''}" href="#/${item.route}">
|
||||
<span class="icon">${item.icon}</span>
|
||||
<span>${item.label}</span>
|
||||
</a>
|
||||
`).join('')}
|
||||
</nav>
|
||||
<div class="sidebar-footer">
|
||||
<div>${escapeHtml(displayName)}</div>
|
||||
<div>${api.isStoreManager ? '店长账号' : '管理员'}</div>
|
||||
<a href="#" id="changePasswordLink">改密码</a> · <a href="#" id="logoutLink">退出</a>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<button class="mobile-menu-btn" id="mobileMenuBtn">☰</button>
|
||||
<div class="topbar-title" id="pageTitle">${navItems.find(i => i.route === route)?.label || ''}</div>
|
||||
<div class="topbar-actions">
|
||||
<button class="notify-btn" id="notifyBtn">🔔<span id="notifyBadge" class="notify-badge" style="display:none">0</span></button>
|
||||
<div class="topbar-user">${escapeHtml(displayName)}</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="content" id="pageContent"></div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('logoutLink').addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
api.logout();
|
||||
renderApp();
|
||||
});
|
||||
document.getElementById('changePasswordLink').addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
showChangePasswordDialog();
|
||||
});
|
||||
document.getElementById('mobileMenuBtn')?.addEventListener('click', () => {
|
||||
document.getElementById('sidebar')?.classList.toggle('open');
|
||||
});
|
||||
document.querySelectorAll('.nav-item').forEach(a => {
|
||||
a.addEventListener('click', () => document.getElementById('sidebar')?.classList.remove('open'));
|
||||
});
|
||||
|
||||
initAiAssistant();
|
||||
document.getElementById('notifyBtn')?.addEventListener('click', showNotificationsDialog);
|
||||
loadNotificationBadge();
|
||||
|
||||
const content = document.getElementById('pageContent');
|
||||
switch (route) {
|
||||
case 'dashboard': renderDashboard(content); break;
|
||||
case 'crm': renderCrm(content); break;
|
||||
case 'records': renderRecords(content); break;
|
||||
case 'stores': renderStores(content); break;
|
||||
case 'employees': renderEmployees(content); break;
|
||||
case 'agent-configs': renderAgentConfigs(content); break;
|
||||
default: renderDashboard(content);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadNotificationBadge() {
|
||||
try {
|
||||
const res = await api.getNotifications('page=1&page_size=5&status=unread');
|
||||
const unread = res.data?.unread || 0;
|
||||
const badge = document.getElementById('notifyBadge');
|
||||
if (badge) {
|
||||
badge.textContent = unread > 99 ? '99+' : String(unread);
|
||||
badge.style.display = unread > 0 ? '' : 'none';
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function showNotificationsDialog() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card notify-modal">
|
||||
<div class="modal-header"><h3>通知消息</h3><button class="modal-close" id="notifyClose">×</button></div>
|
||||
<div class="modal-body" id="notifyBody"><div class="loading"><div class="spinner"></div></div></div>
|
||||
<div class="modal-footer"><button class="btn btn-secondary" id="notifyReadAll">全部已读</button></div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('notifyClose').addEventListener('click', close);
|
||||
document.getElementById('notifyReadAll').addEventListener('click', async () => {
|
||||
await api.markAllNotificationsRead();
|
||||
await loadNotificationBadge();
|
||||
close();
|
||||
});
|
||||
try {
|
||||
const res = await api.getNotifications('page=1&page_size=30');
|
||||
const list = res.data?.list || [];
|
||||
document.getElementById('notifyBody').innerHTML = list.length ? list.map(n => `
|
||||
<button class="notify-item ${n.status === 'unread' ? 'unread' : ''}" data-id="${n.id}" data-route="${n.targetRoute || ''}">
|
||||
<strong>${escapeHtml(n.title)}</strong>
|
||||
<span>${escapeHtml(n.content || '')}</span>
|
||||
<small>${formatDate(n.createDate)}</small>
|
||||
</button>`).join('') : '<div class="empty-state">暂无通知</div>';
|
||||
document.querySelectorAll('.notify-item').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
await api.markNotificationRead(btn.dataset.id);
|
||||
await loadNotificationBadge();
|
||||
close();
|
||||
if (btn.dataset.route === 'crm:appointments') {
|
||||
window.location.hash = '#/crm?tab=appointments';
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
document.getElementById('notifyBody').innerHTML = `<div class="empty-state">加载通知失败:${escapeHtml(e.message || '')}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Login Page ----
|
||||
function renderLogin(container) {
|
||||
container.innerHTML = `
|
||||
<div class="login-page">
|
||||
<div class="login-card">
|
||||
<h1>反馈系统</h1>
|
||||
<p>管理后台登录</p>
|
||||
<div class="form-group">
|
||||
<input type="text" id="loginUser" class="form-input" placeholder="管理员账号 / 门店编码">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<input type="password" id="loginPass" class="form-input" placeholder="密码">
|
||||
</div>
|
||||
<button class="btn btn-primary" id="loginBtn">登 录</button>
|
||||
<div class="login-tip">店长首次登录:门店编码 / 门店编码</div>
|
||||
<div class="login-error" id="loginError"></div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
const doLogin = async () => {
|
||||
const u = document.getElementById('loginUser').value.trim();
|
||||
const p = document.getElementById('loginPass').value;
|
||||
const errEl = document.getElementById('loginError');
|
||||
errEl.textContent = '';
|
||||
try {
|
||||
await api.login(u, p);
|
||||
renderApp();
|
||||
} catch (e) {
|
||||
errEl.textContent = '用户名或密码错误';
|
||||
}
|
||||
};
|
||||
|
||||
document.getElementById('loginBtn').addEventListener('click', doLogin);
|
||||
document.getElementById('loginPass').addEventListener('keyup', (e) => {
|
||||
if (e.key === 'Enter') doLogin();
|
||||
});
|
||||
}
|
||||
|
||||
function showChangePasswordDialog() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<h3>修改密码</h3>
|
||||
<button class="modal-close" id="closePwd">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="form-group"><label class="form-label">原密码</label><input type="password" id="oldPwd" class="form-input"></div>
|
||||
<div class="form-group"><label class="form-label">新密码</label><input type="password" id="newPwd" class="form-input" placeholder="至少 6 位"></div>
|
||||
<div class="form-group"><label class="form-label">确认新密码</label><input type="password" id="newPwd2" class="form-input"></div>
|
||||
<div class="login-error" id="pwdError"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="cancelPwd">取消</button>
|
||||
<button class="btn btn-primary" id="savePwd">保存</button>
|
||||
</div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('closePwd').addEventListener('click', close);
|
||||
document.getElementById('cancelPwd').addEventListener('click', close);
|
||||
document.getElementById('savePwd').addEventListener('click', async () => {
|
||||
const oldPwd = document.getElementById('oldPwd').value;
|
||||
const newPwd = document.getElementById('newPwd').value;
|
||||
const newPwd2 = document.getElementById('newPwd2').value;
|
||||
const err = document.getElementById('pwdError');
|
||||
err.textContent = '';
|
||||
if (newPwd.length < 6) { err.textContent = '新密码至少 6 位'; return; }
|
||||
if (newPwd !== newPwd2) { err.textContent = '两次新密码不一致'; return; }
|
||||
try {
|
||||
await api.changePassword(oldPwd, newPwd);
|
||||
alert('密码已修改,请重新登录');
|
||||
api.logout();
|
||||
close();
|
||||
renderApp();
|
||||
} catch (e) {
|
||||
err.textContent = e.message || '修改失败';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Helpers (global) ----
|
||||
window.escapeHtml = function(s) {
|
||||
if (!s) return '';
|
||||
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||
};
|
||||
|
||||
window.formatDate = function(d) {
|
||||
if (!d) return '-';
|
||||
return d.replace('T', ' ').substring(0, 19);
|
||||
};
|
||||
|
||||
window.satisfactionBadge = function(s) {
|
||||
const map = {
|
||||
very_satisfied: { label: '非常满意', cls: 'badge-green' },
|
||||
satisfied: { label: '满意', cls: 'badge-green' },
|
||||
unsatisfied: { label: '不满意', cls: 'badge-yellow' },
|
||||
very_bad: { label: '很差', cls: 'badge-red' },
|
||||
};
|
||||
const info = map[s] || { label: s || '-', cls: 'badge-gray' };
|
||||
return `<span class="badge ${info.cls}">${info.label}</span>`;
|
||||
};
|
||||
|
||||
window.statusBadge = function(s) {
|
||||
return s === 1
|
||||
? '<span class="badge badge-green">启用</span>'
|
||||
: '<span class="badge badge-red">禁用</span>';
|
||||
};
|
||||
|
||||
window.employeeTypeBadge = function(t) {
|
||||
const map = {
|
||||
manager: { label: '店长', cls: 'badge-blue' },
|
||||
excellent: { label: '优秀员工', cls: 'badge-green' },
|
||||
intern: { label: '实习生', cls: 'badge-yellow' },
|
||||
normal: { label: '普通员工', cls: 'badge-gray' },
|
||||
};
|
||||
const info = map[t] || { label: t, cls: 'badge-gray' };
|
||||
return `<span class="badge ${info.cls}">${info.label}</span>`;
|
||||
};
|
||||
|
||||
window.truncate = function(s, len = 50) {
|
||||
if (!s) return '-';
|
||||
return s.length > len ? s.substring(0, len) + '...' : s;
|
||||
};
|
||||
|
||||
// ---- Init ----
|
||||
window.addEventListener('hashchange', renderApp);
|
||||
window.addEventListener('load', renderApp);
|
||||
441
main/feedback-backend/admin-ui/js/ai-assistant.js
Normal file
441
main/feedback-backend/admin-ui/js/ai-assistant.js
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
// AI 数字人助手 - 长连接持续对话数字人
|
||||
import { api } from './api.js';
|
||||
import { createVoiceWidget } from './voice-widget/voice-widget.js?v=20260625-longchat-default';
|
||||
|
||||
let lastUserMessage = '';
|
||||
let lastAgentResult = null;
|
||||
let voiceEnabled = true;
|
||||
let voiceWidget = null;
|
||||
let longChatEnabled = true;
|
||||
let sending = false;
|
||||
let live2dReady = false;
|
||||
let live2dInitializing = false;
|
||||
let sessionConnected = false;
|
||||
let reconnectTimer = null;
|
||||
let reconnectAttempts = 0;
|
||||
const pendingMessages = [];
|
||||
const conversationHistory = [];
|
||||
|
||||
export function initAiAssistant() {
|
||||
if (document.getElementById('aiAssistantFab')) return;
|
||||
const box = document.createElement('div');
|
||||
box.innerHTML = `
|
||||
<button id="aiAssistantFab" class="ai-fab" title="AI数字人助手"><span>AI</span></button>
|
||||
<div id="aiAssistantPanel" class="ai-panel ai-voice-panel">
|
||||
<div class="ai-head">
|
||||
<div>
|
||||
<strong>AI门店数字人</strong>
|
||||
<div class="muted" id="aiStatusText">待命中 · 可语音或打字</div>
|
||||
</div>
|
||||
<div class="ai-head-actions">
|
||||
<button id="aiAssistantExpand" class="ai-icon-btn" title="切换大屏数字人">⛶</button>
|
||||
<button id="aiAssistantClose" class="modal-close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ai-stage">
|
||||
<canvas id="live2d-stage" class="ai-live2d-canvas"></canvas>
|
||||
<div class="ai-stage-bg"></div>
|
||||
<div class="ai-face" id="aiFallbackFace">🤖</div>
|
||||
<div id="aiAvatar" class="ai-avatar live2d-avatar">
|
||||
<div class="ai-avatar-ring"></div>
|
||||
<div class="ai-wave"><span></span><span></span><span></span></div>
|
||||
</div>
|
||||
<div class="ai-stage-status">
|
||||
<span class="ai-status-dot"></span>
|
||||
<span id="aiStageStatusText">像客户反馈数字人一样,持续听你说话并帮你操作 CRM</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ai-body">
|
||||
<div id="aiMessages" class="ai-messages">
|
||||
<div class="ai-msg ai-msg-bot">你好,我是门店AI数字人。你可以直接说:<br>创建客户常玉亮手机号13020109833<br>创建产品冰蚕乌酒价格50<br>明天下午2点约李爱媛做乌蛇<br>查客户尾号9833套餐还剩几次</div>
|
||||
</div>
|
||||
<div class="ai-quick">
|
||||
<button data-q="CRM概览">CRM概览</button>
|
||||
<button data-q="员工KPI">员工KPI</button>
|
||||
<button data-q="预约日历">预约日历</button>
|
||||
<button data-q="查客户尾号9833">查客户</button>
|
||||
</div>
|
||||
<div class="ai-input-row">
|
||||
<input id="aiInput" class="form-input" placeholder="输入或语音说出你的需求">
|
||||
<button id="aiMic" class="btn btn-secondary btn-sm" title="按一下说话">🎙️</button>
|
||||
<button id="aiLongChat" class="btn btn-secondary btn-sm active" title="长聊默认开启,点击暂停">长聊中</button>
|
||||
<button id="aiVoiceToggle" class="btn btn-secondary btn-sm" title="语音播报开关">🔊</button>
|
||||
<button id="aiSend" class="btn btn-primary btn-sm">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
document.body.appendChild(box);
|
||||
|
||||
const panel = document.getElementById('aiAssistantPanel');
|
||||
const fab = document.getElementById('aiAssistantFab');
|
||||
fab.onclick = () => {
|
||||
panel.classList.toggle('open');
|
||||
if (panel.classList.contains('open')) initLive2DAvatar();
|
||||
};
|
||||
document.getElementById('aiAssistantClose').onclick = () => panel.classList.remove('open');
|
||||
document.getElementById('aiAssistantExpand').onclick = () => {
|
||||
panel.classList.toggle('expanded');
|
||||
setTimeout(() => window.aiLive2dManager?.resize?.(), 80);
|
||||
};
|
||||
document.getElementById('aiSend').onclick = sendAiMessage;
|
||||
document.getElementById('aiMic').onclick = startSpeechInput;
|
||||
document.getElementById('aiLongChat').onclick = toggleLongChat;
|
||||
document.getElementById('aiVoiceToggle').onclick = () => {
|
||||
voiceEnabled = !voiceEnabled;
|
||||
voiceWidget?.setVoiceEnabled(voiceEnabled);
|
||||
document.getElementById('aiVoiceToggle').textContent = voiceEnabled ? '🔊' : '🔇';
|
||||
};
|
||||
document.getElementById('aiInput').addEventListener('keyup', (e) => {
|
||||
if (e.key === 'Enter') sendAiMessage();
|
||||
});
|
||||
document.querySelectorAll('.ai-quick button').forEach(btn => {
|
||||
btn.onclick = () => {
|
||||
document.getElementById('aiInput').value = btn.dataset.q;
|
||||
sendAiMessage();
|
||||
};
|
||||
});
|
||||
voiceWidget = createVoiceWidget({
|
||||
voiceEnabled,
|
||||
sessionUrl: buildAgentWsUrl(),
|
||||
onUserText(text) {
|
||||
if (!text) return;
|
||||
document.getElementById('aiInput').value = text;
|
||||
sendAiMessage(text, { fromVoice: true });
|
||||
},
|
||||
onSessionOpen() {
|
||||
sessionConnected = true;
|
||||
reconnectAttempts = 0;
|
||||
},
|
||||
onSessionClose() {
|
||||
sessionConnected = false;
|
||||
scheduleSessionReconnect();
|
||||
},
|
||||
onSessionMessage(data) { handleSessionMessage(data); },
|
||||
onStatus(state, text) { setAiState(state, text); },
|
||||
onReplyStart() {
|
||||
try { window.aiLive2dManager?.startTalking?.(); window.aiLive2dManager?.motion?.('Tap'); } catch(e) {}
|
||||
},
|
||||
onReplyEnd() { try { window.aiLive2dManager?.stopTalking?.(); } catch(e) {} },
|
||||
onError(err) { showVoiceError(err); },
|
||||
});
|
||||
connectLongSession();
|
||||
initLive2DAvatar();
|
||||
startDefaultLongChat();
|
||||
}
|
||||
|
||||
function startDefaultLongChat() {
|
||||
const btn = document.getElementById('aiLongChat');
|
||||
longChatEnabled = true;
|
||||
if (btn) {
|
||||
btn.textContent = '长聊中';
|
||||
btn.classList.add('active');
|
||||
btn.title = '长聊默认开启,点击暂停';
|
||||
}
|
||||
setAiState('listening', '长聊中 · 我会持续听你说话');
|
||||
if (typeof voiceWidget?.startContinuous === 'function') {
|
||||
voiceWidget.startContinuous().catch((e) => {
|
||||
longChatEnabled = false;
|
||||
if (btn) {
|
||||
btn.textContent = '长聊';
|
||||
btn.classList.remove('active');
|
||||
btn.title = '开启长聊';
|
||||
}
|
||||
showVoiceError(e);
|
||||
});
|
||||
} else {
|
||||
longChatEnabled = false;
|
||||
const msg = '语音组件版本过旧,请强制刷新页面后重试';
|
||||
if (btn) {
|
||||
btn.textContent = '长聊';
|
||||
btn.classList.remove('active');
|
||||
btn.title = msg;
|
||||
}
|
||||
showVoiceError(new Error(msg));
|
||||
}
|
||||
}
|
||||
|
||||
function buildAgentWsUrl() {
|
||||
const token = localStorage.getItem('feedback_admin_token') || '';
|
||||
const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const host = window.location.hostname === 'feedback-admin.new123.vip'
|
||||
? 'feedback-admin.new123.vip:8443'
|
||||
: window.location.host;
|
||||
const url = new URL(`${scheme}//${host}/api/v1/agent/chat/ws`);
|
||||
if (token) url.searchParams.set('token', token);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function connectLongSession() {
|
||||
if (!voiceWidget) return;
|
||||
window.clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
try {
|
||||
voiceWidget.connectSession(buildAgentWsUrl());
|
||||
} catch (e) {
|
||||
showVoiceError(e);
|
||||
scheduleSessionReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleSessionReconnect() {
|
||||
if (reconnectTimer || !voiceWidget) return;
|
||||
const delay = Math.min(10000, 1000 * Math.max(1, ++reconnectAttempts));
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
connectLongSession();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
function handleSessionMessage(data) {
|
||||
if (!data) return;
|
||||
if (typeof data === 'string') {
|
||||
appendMessage(data, 'bot', false, true);
|
||||
voiceWidget?.speak(data);
|
||||
return;
|
||||
}
|
||||
if (data.type === 'hello') {
|
||||
setAiState('', '长连接已就绪 · 可语音或打字');
|
||||
return;
|
||||
}
|
||||
if (data.type === 'thinking') {
|
||||
removeThinking();
|
||||
appendMessage(data.text || '正在思考和查询...', 'bot', true);
|
||||
setAiState('thinking', data.text || '正在思考...');
|
||||
voiceWidget?.pauseContinuous(data.text || '正在思考...');
|
||||
return;
|
||||
}
|
||||
if (data.type === 'reply') {
|
||||
removeThinking();
|
||||
const result = data.data || {};
|
||||
lastAgentResult = result;
|
||||
const reply = data.text || result.reply || '已处理';
|
||||
conversationHistory.push({ role: 'assistant', text: reply });
|
||||
appendMessage(reply, 'bot', false, true);
|
||||
voiceWidget?.speak(reply);
|
||||
if (result.action && window.FormCopilot?.execute(result.action)) {
|
||||
const msg = '我已打开对应表单,并填入已识别的信息。请确认后保存。';
|
||||
conversationHistory.push({ role: 'assistant', text: msg });
|
||||
appendMessage(msg, 'bot');
|
||||
voiceWidget?.speak(msg);
|
||||
} else if (result.route) {
|
||||
appendRoute(result.route);
|
||||
}
|
||||
sending = false;
|
||||
if (!voiceWidget?.speaking) {
|
||||
setAiState(longChatEnabled ? 'listening' : '', longChatEnabled ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字');
|
||||
voiceWidget?.resumeContinuous();
|
||||
}
|
||||
flushPendingMessages();
|
||||
return;
|
||||
}
|
||||
if (data.type === 'error') {
|
||||
removeThinking();
|
||||
const msg = data.text || '长连接处理失败';
|
||||
appendMessage(msg, 'bot', false, true);
|
||||
voiceWidget?.speak(msg);
|
||||
sending = false;
|
||||
flushPendingMessages();
|
||||
}
|
||||
}
|
||||
|
||||
async function initLive2DAvatar() {
|
||||
if (live2dReady || live2dInitializing) return;
|
||||
if (!window.Live2DManager || !window.PIXI?.live2d) return;
|
||||
live2dInitializing = true;
|
||||
try {
|
||||
window.chatApp = window.chatApp || {};
|
||||
window.chatApp.audioPlayer = null;
|
||||
const manager = new window.Live2DManager();
|
||||
window.aiLive2dManager = manager;
|
||||
await manager.initializeLive2D();
|
||||
live2dReady = true;
|
||||
document.getElementById('aiFallbackFace')?.classList.add('hidden');
|
||||
document.getElementById('aiAvatar')?.classList.add('live2d-ready');
|
||||
setAiState('', '数字人已就绪 · 可语音或打字');
|
||||
} catch (e) {
|
||||
console.warn('[AI Live2D] 初始化失败,使用轻量头像', e);
|
||||
} finally {
|
||||
live2dInitializing = false;
|
||||
}
|
||||
}
|
||||
|
||||
function setAiState(state, text) {
|
||||
const avatar = document.getElementById('aiAvatar');
|
||||
const status = document.getElementById('aiStatusText');
|
||||
const stageStatus = document.getElementById('aiStageStatusText');
|
||||
if (!avatar) return;
|
||||
avatar.classList.remove('listening', 'thinking', 'speaking');
|
||||
if (state) avatar.classList.add(state);
|
||||
const statusText = text || (longChatEnabled ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字');
|
||||
if (status) status.textContent = statusText;
|
||||
if (stageStatus) stageStatus.textContent = statusText;
|
||||
}
|
||||
|
||||
function showVoiceError(err) {
|
||||
const msg = err?.message || String(err || '语音输入异常');
|
||||
if (['aborted', 'no-speech'].includes(msg)) return;
|
||||
appendMessage(msg, 'bot', false, true);
|
||||
}
|
||||
|
||||
async function toggleLongChat() {
|
||||
const btn = document.getElementById('aiLongChat');
|
||||
try {
|
||||
if (longChatEnabled) {
|
||||
longChatEnabled = false;
|
||||
voiceWidget?.stopListening?.(true);
|
||||
if (btn) {
|
||||
btn.textContent = '长聊';
|
||||
btn.classList.remove('active');
|
||||
btn.title = '开启长聊';
|
||||
}
|
||||
setAiState('', '长聊已暂停 · 可打字或点长聊继续');
|
||||
return;
|
||||
}
|
||||
longChatEnabled = true;
|
||||
if (btn) {
|
||||
btn.textContent = '长聊中';
|
||||
btn.classList.add('active');
|
||||
btn.title = '长聊默认开启,点击暂停';
|
||||
}
|
||||
setAiState('listening', '长聊中 · 我会持续听你说话');
|
||||
if (typeof voiceWidget?.startContinuous !== 'function') {
|
||||
throw new Error('语音组件版本过旧,请强制刷新页面后重试');
|
||||
}
|
||||
await voiceWidget.startContinuous();
|
||||
} catch (e) {
|
||||
longChatEnabled = false;
|
||||
if (btn) {
|
||||
btn.textContent = '长聊';
|
||||
btn.classList.remove('active');
|
||||
btn.title = '开启长聊';
|
||||
}
|
||||
showVoiceError(e);
|
||||
voiceWidget?.speak(e.message || '语音输入不可用');
|
||||
}
|
||||
}
|
||||
|
||||
async function startSpeechInput() {
|
||||
if (longChatEnabled) {
|
||||
toggleLongChat();
|
||||
return;
|
||||
}
|
||||
const mic = document.getElementById('aiMic');
|
||||
try {
|
||||
mic.textContent = '⏺';
|
||||
await voiceWidget?.startListening();
|
||||
} catch (e) {
|
||||
showVoiceError(e);
|
||||
voiceWidget?.speak(e.message || '语音输入不可用');
|
||||
} finally {
|
||||
setTimeout(() => { mic.textContent = '🎙️'; }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendAiMessage(forcedText = '', options = {}) {
|
||||
const input = document.getElementById('aiInput');
|
||||
const text = (forcedText || input.value || '').trim();
|
||||
if (!text) return;
|
||||
if (input.value.trim() === text) input.value = '';
|
||||
if (sending) {
|
||||
pendingMessages.push({ text, options });
|
||||
setAiState('thinking', '已收到,上一条处理完马上继续...');
|
||||
return;
|
||||
}
|
||||
sending = true;
|
||||
lastUserMessage = text;
|
||||
conversationHistory.push({ role: 'user', text });
|
||||
appendMessage(text, 'user');
|
||||
const localReply = window.FormCopilot?.handleUserMessage(text);
|
||||
if (localReply) {
|
||||
conversationHistory.push({ role: 'assistant', text: localReply });
|
||||
appendMessage(localReply, 'bot', false, true);
|
||||
voiceWidget?.speak(localReply);
|
||||
sending = false;
|
||||
flushPendingMessages();
|
||||
return;
|
||||
}
|
||||
voiceWidget?.pauseContinuous('正在思考...');
|
||||
setAiState('thinking', sessionConnected ? '正在通过长连接思考...' : '长连接重连中,先用普通接口处理...');
|
||||
|
||||
if (sessionConnected && voiceWidget?.sendText(text)) {
|
||||
appendMessage('正在思考和查询...', 'bot', true);
|
||||
return;
|
||||
}
|
||||
|
||||
appendMessage('正在思考和查询...', 'bot', true);
|
||||
try {
|
||||
const res = await api.agentChat(text, conversationHistory.slice(-12));
|
||||
removeThinking();
|
||||
const data = res.data || {};
|
||||
lastAgentResult = data;
|
||||
const reply = data.reply || '已处理';
|
||||
conversationHistory.push({ role: 'assistant', text: reply });
|
||||
appendMessage(reply, 'bot', false, true);
|
||||
voiceWidget?.speak(reply);
|
||||
if (data.action && window.FormCopilot?.execute(data.action)) {
|
||||
const msg = '我已打开对应表单,并填入已识别的信息。请确认后保存。';
|
||||
conversationHistory.push({ role: 'assistant', text: msg });
|
||||
appendMessage(msg, 'bot');
|
||||
voiceWidget?.speak(msg);
|
||||
} else if (data.route) {
|
||||
appendRoute(data.route);
|
||||
}
|
||||
} catch (e) {
|
||||
removeThinking();
|
||||
const msg = `操作失败:${e.message || e}`;
|
||||
appendMessage(msg, 'bot', false, true);
|
||||
voiceWidget?.speak(msg);
|
||||
} finally {
|
||||
sending = false;
|
||||
if (!voiceWidget?.speaking) {
|
||||
setAiState(longChatEnabled ? 'listening' : '', longChatEnabled ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字');
|
||||
voiceWidget?.resumeContinuous();
|
||||
}
|
||||
flushPendingMessages();
|
||||
}
|
||||
}
|
||||
|
||||
function flushPendingMessages() {
|
||||
if (sending || pendingMessages.length === 0) return;
|
||||
const next = pendingMessages.shift();
|
||||
setTimeout(() => sendAiMessage(next.text, next.options), 80);
|
||||
}
|
||||
|
||||
function appendMessage(text, who, thinking = false, feedback = false) {
|
||||
const el = document.getElementById('aiMessages');
|
||||
const div = document.createElement('div');
|
||||
div.className = `ai-msg ai-msg-${who}` + (thinking ? ' ai-thinking' : '');
|
||||
div.innerHTML = escapeHtml(text).replace(/\n/g, '<br>') + (feedback ? '<div class="ai-feedback"><button data-rate="like">👍</button><button data-rate="dislike">👎</button></div>' : '');
|
||||
el.appendChild(div);
|
||||
div.querySelectorAll('[data-rate]').forEach(btn => btn.onclick = () => submitAiFeedback(btn.dataset.rate, btn));
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
async function submitAiFeedback(rating, btn) {
|
||||
try {
|
||||
await api.agentFeedback({
|
||||
message: lastUserMessage,
|
||||
reply: lastAgentResult?.reply || '',
|
||||
intent: lastAgentResult?.intent || '',
|
||||
trace: lastAgentResult?.trace || [],
|
||||
rating,
|
||||
});
|
||||
btn.parentElement.innerHTML = rating === 'like' ? '已点赞,感谢反馈' : '已记录失败案例,我会用于复盘修复';
|
||||
} catch (e) {
|
||||
btn.parentElement.innerHTML = '反馈提交失败';
|
||||
}
|
||||
}
|
||||
|
||||
function removeThinking() {
|
||||
document.querySelectorAll('.ai-thinking').forEach(el => el.remove());
|
||||
}
|
||||
|
||||
function appendRoute(route) {
|
||||
const el = document.getElementById('aiMessages');
|
||||
const div = document.createElement('div');
|
||||
div.className = 'ai-msg ai-msg-bot';
|
||||
div.innerHTML = `<button class="btn btn-secondary btn-sm">打开${route}</button>`;
|
||||
div.querySelector('button').onclick = () => { window.location.hash = `#/${route}`; };
|
||||
el.appendChild(div);
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
263
main/feedback-backend/admin-ui/js/api.js
Normal file
263
main/feedback-backend/admin-ui/js/api.js
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
// Admin API Client
|
||||
const API_BASE = window.location.hostname === 'feedback-admin.new123.vip'
|
||||
? 'https://feedback-admin.new123.vip:8443/api/v1'
|
||||
: window.location.origin + '/api/v1';
|
||||
|
||||
class AdminAPI {
|
||||
constructor() {
|
||||
this.token = localStorage.getItem('feedback_admin_token');
|
||||
}
|
||||
|
||||
// ---- Auth ----
|
||||
async login(username, password) {
|
||||
const res = await fetch(`${API_BASE}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
if (!res.ok) throw new Error('Login failed');
|
||||
const data = await res.json();
|
||||
this.token = data.access_token;
|
||||
localStorage.setItem('feedback_admin_token', data.access_token);
|
||||
localStorage.setItem('feedback_admin_user', data.username);
|
||||
localStorage.setItem('feedback_admin_role', data.role || 'super_admin');
|
||||
localStorage.setItem('feedback_admin_display_name', data.display_name || data.username);
|
||||
if (data.store_id) localStorage.setItem('feedback_admin_store_id', data.store_id);
|
||||
else localStorage.removeItem('feedback_admin_store_id');
|
||||
if (data.store_code) localStorage.setItem('feedback_admin_store_code', data.store_code);
|
||||
else localStorage.removeItem('feedback_admin_store_code');
|
||||
if (data.store_name) localStorage.setItem('feedback_admin_store_name', data.store_name);
|
||||
else localStorage.removeItem('feedback_admin_store_name');
|
||||
return data;
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.token = null;
|
||||
localStorage.removeItem('feedback_admin_token');
|
||||
localStorage.removeItem('feedback_admin_user');
|
||||
localStorage.removeItem('feedback_admin_role');
|
||||
localStorage.removeItem('feedback_admin_display_name');
|
||||
localStorage.removeItem('feedback_admin_store_id');
|
||||
localStorage.removeItem('feedback_admin_store_code');
|
||||
localStorage.removeItem('feedback_admin_store_name');
|
||||
}
|
||||
|
||||
get role() {
|
||||
return localStorage.getItem('feedback_admin_role') || 'super_admin';
|
||||
}
|
||||
|
||||
get isStoreManager() {
|
||||
return this.role === 'store_manager';
|
||||
}
|
||||
|
||||
get storeId() {
|
||||
return localStorage.getItem('feedback_admin_store_id') || '';
|
||||
}
|
||||
|
||||
get headers() {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${this.token}`
|
||||
};
|
||||
}
|
||||
|
||||
async request(url, options = {}) {
|
||||
const res = await fetch(`${API_BASE}${url}`, {
|
||||
...options,
|
||||
headers: { ...this.headers, ...options.headers }
|
||||
});
|
||||
if (res.status === 401) {
|
||||
this.logout();
|
||||
window.location.reload();
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`;
|
||||
try {
|
||||
const data = await res.json();
|
||||
msg = data.detail || data.msg || msg;
|
||||
} catch (e) {}
|
||||
throw new Error(msg);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async changePassword(oldPassword, newPassword) {
|
||||
return this.request('/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Stats ----
|
||||
async getOverview(params = '') {
|
||||
return this.request(`/stats/overview${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async getDailyStats(params = '') {
|
||||
return this.request(`/stats/daily${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async getStoreStats(params = '') {
|
||||
return this.request(`/stats/by-store${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async getEmployeeKpi(params = '') {
|
||||
return this.request(`/stats/employee-kpi${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async getEmployeeRecords(params = '') {
|
||||
return this.request(`/stats/employee-records${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
// ---- Records ----
|
||||
async getRecords(params = '') {
|
||||
return this.request(`/record/list${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
// ---- CRM ----
|
||||
async getCrmOverview() { return this.request('/crm/overview'); }
|
||||
async getMekai66Fields() { return this.request('/crm/mekai66-fields'); }
|
||||
async getCrmMembers(params = '') { return this.request(`/crm/member/list${params ? '?' + params : ''}`); }
|
||||
async getCrmMember(id) { return this.request(`/crm/member/${id}`); }
|
||||
async createCrmMember(data) { return this.request('/crm/member', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async updateCrmMember(id, data) { return this.request(`/crm/member/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }); }
|
||||
async getCrmVisits(params = '') { return this.request(`/crm/visit/list${params ? '?' + params : ''}`); }
|
||||
async createCrmVisit(data) { return this.request('/crm/visit', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async updateCrmVisit(id, data) { return this.request(`/crm/visit/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }); }
|
||||
async getCrmAccounts(params = '') { return this.request(`/crm/account/list${params ? '?' + params : ''}`); }
|
||||
async getCrmAccountTransactions(params = '') { return this.request(`/crm/account/transactions${params ? '?' + params : ''}`); }
|
||||
async createCrmAccount(data) { return this.request('/crm/account', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async consumeCrmAccount(id, data) { return this.request(`/crm/account/${id}/consume`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
async closeCrmCard(data) { return this.request('/crm/card-close', { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
async getCrmCardCloses(params = '') { return this.request(`/crm/card-close/list${params ? '?' + params : ''}`); }
|
||||
// ---- Appointment ----
|
||||
async getAppointmentCalendar(params = '') { return this.request(`/appointment/calendar${params ? '?' + params : ''}`); }
|
||||
async getAppointmentAvailability(params = '') { return this.request(`/appointment/availability${params ? '?' + params : ''}`); }
|
||||
async createAppointment(data) { return this.request('/appointment', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async confirmAppointment(id, data = {}) { return this.request(`/appointment/${id}/confirm`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
async cancelAppointment(id, data = {}) { return this.request(`/appointment/${id}/cancel`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
async completeAppointment(id, data = {}) { return this.request(`/appointment/${id}/complete`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
|
||||
async getCrmBodyStatuses(params = '') { return this.request(`/crm/body-status/list${params ? '?' + params : ''}`); }
|
||||
async createCrmBodyStatus(data) { return this.request('/crm/body-status', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
|
||||
async getCrmProducts(params = '') { return this.request(`/crm/product/list${params ? '?' + params : ''}`); }
|
||||
async createCrmProduct(data) { return this.request('/crm/product', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async getCrmMemberProducts(params = '') { return this.request(`/crm/member-product/list${params ? '?' + params : ''}`); }
|
||||
async purchaseCrmProduct(data) { return this.request('/crm/member-product/purchase', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async consumeCrmProduct(id, data) { return this.request(`/crm/member-product/${id}/consume`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
async getCrmProductConsumes(params = '') { return this.request(`/crm/product-consume/list${params ? '?' + params : ''}`); }
|
||||
|
||||
async getCrmSuggestions(params = '') { return this.request(`/crm/suggestion/list${params ? '?' + params : ''}`); }
|
||||
async createCrmSuggestion(data) { return this.request('/crm/suggestion', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async updateCrmSuggestionStatus(id, data) { return this.request(`/crm/suggestion/${id}/status`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
async getCrmIssues(params = '') { return this.request(`/crm/issue/list${params ? '?' + params : ''}`); }
|
||||
async createCrmIssue(data) { return this.request('/crm/issue', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); }
|
||||
async updateCrmIssue(id, data) { return this.request(`/crm/issue/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }); }
|
||||
async bindCrmFeedback(id, data) { return this.request(`/crm/feedback/${id}/bind`, { method: 'POST', body: JSON.stringify({ data }) }); }
|
||||
|
||||
// ---- AI Agent ----
|
||||
async agentChat(message, history = []) {
|
||||
return this.request('/agent/chat', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ message, history })
|
||||
});
|
||||
}
|
||||
|
||||
async agentFeedback(data) {
|
||||
return this.request('/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Notifications ----
|
||||
async getNotifications(params = '') {
|
||||
return this.request(`/notification/list${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async markNotificationRead(id) {
|
||||
return this.request(`/notification/${id}/read`, { method: 'POST' });
|
||||
}
|
||||
|
||||
async markAllNotificationsRead() {
|
||||
return this.request('/notification/read-all', { method: 'POST' });
|
||||
}
|
||||
|
||||
withStore(data) {
|
||||
if (this.isStoreManager && this.storeId && !data.storeId && !data.store_id) return { ...data, storeId: this.storeId };
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---- Stores ----
|
||||
async getStores(params = '') {
|
||||
return this.request(`/store/list${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async createStore(data) {
|
||||
return this.request('/store', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async updateStore(id, data) {
|
||||
return this.request(`/store/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async deleteStore(id) {
|
||||
return this.request(`/store/delete?store_id=${id}`, { method: 'POST' });
|
||||
}
|
||||
|
||||
// ---- Employees ----
|
||||
async getEmployees(params = '') {
|
||||
return this.request(`/employee/list${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async createEmployee(data) {
|
||||
return this.request('/employee', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async updateEmployee(id, data) {
|
||||
return this.request(`/employee/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async deleteEmployee(id) {
|
||||
return this.request(`/employee/delete?employee_id=${id}`, { method: 'POST' });
|
||||
}
|
||||
|
||||
// ---- Agent Config ----
|
||||
async getAgentConfigs(params = '') {
|
||||
return this.request(`/agent-config/list${params ? '?' + params : ''}`);
|
||||
}
|
||||
|
||||
async createAgentConfig(data) {
|
||||
return this.request('/agent-config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async updateAgentConfig(id, data) {
|
||||
return this.request(`/agent-config/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async deleteAgentConfig(id) {
|
||||
return this.request(`/agent-config/delete?config_id=${id}`, { method: 'POST' });
|
||||
}
|
||||
}
|
||||
|
||||
export const api = new AdminAPI();
|
||||
189
main/feedback-backend/admin-ui/js/form-copilot.js
Normal file
189
main/feedback-backend/admin-ui/js/form-copilot.js
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
// AI 表单助手:根据 Agent action 自动跳转、打开表单、填字段,并支持多轮修改/保存
|
||||
|
||||
const FORM_FIELD_MAP = {
|
||||
'crm.member.create': {
|
||||
name: 'mName', 姓名: 'mName',
|
||||
phone: 'mPhone', 手机号: 'mPhone', 电话: 'mPhone',
|
||||
wechat: 'mWechat', 微信: 'mWechat', 微信号: 'mWechat',
|
||||
level: 'mLevel', 客户等级: 'mLevel', 等级: 'mLevel',
|
||||
health: 'mHealth', 身体: 'mHealth', 身体问题: 'mHealth', 症状: 'mHealth',
|
||||
allergies: 'mAllergies', 过敏: 'mAllergies', 过敏史: 'mAllergies',
|
||||
notes: 'mNotes', 备注: 'mNotes',
|
||||
},
|
||||
'crm.product.create': {
|
||||
productName: 'pName', 产品名称: 'pName', 名称: 'pName', 产品: 'pName',
|
||||
category: 'pCategory', 分类: 'pCategory', 类别: 'pCategory',
|
||||
productType: 'pType', 类型: 'pType',
|
||||
defaultCount: 'pCount', 默认次数: 'pCount', 次数: 'pCount', 数量: 'pCount',
|
||||
price: 'pPrice', 价格: 'pPrice', 单价: 'pPrice', 金额: 'pPrice',
|
||||
description: 'pDesc', 说明: 'pDesc', 备注: 'pDesc',
|
||||
},
|
||||
'crm.appointment.create': {
|
||||
employee: 'aptEmp', 员工: 'aptEmp', 技师: 'aptEmp',
|
||||
startAt: 'aptStart', 开始时间: 'aptStart', 时间: 'aptStart', 预约时间: 'aptStart',
|
||||
durationMinutes: 'aptDuration', 时长: 'aptDuration', 服务时长: 'aptDuration',
|
||||
notes: 'aptNotes', 备注: 'aptNotes',
|
||||
},
|
||||
'crm.body_status.create': {
|
||||
weight: 'bsWeight', 体重: 'bsWeight',
|
||||
waistline: 'bsWaist', 腰围: 'bsWaist',
|
||||
metricName: 'bsMetricName', 标签: 'bsMetricName', 身体标签: 'bsMetricName', 指标: 'bsMetricName',
|
||||
metricStatus: 'bsMetricStatus', 状态: 'bsMetricStatus', 效果: 'bsMetricStatus',
|
||||
metricValue: 'bsMetricValue', 数值: 'bsMetricValue', 好转数值: 'bsMetricValue',
|
||||
notes: 'bsNotes', 描述: 'bsNotes', 备注: 'bsNotes',
|
||||
},
|
||||
};
|
||||
|
||||
const REQUIRED_FIELDS = {
|
||||
'crm.member.create': [ ['mName', '客户姓名'], ['mPhone', '手机号'] ],
|
||||
'crm.product.create': [ ['pName', '产品名称'], ['pPrice', '价格/单价'] ],
|
||||
'crm.appointment.create': [ ['aptMember', '客户'], ['aptEmp', '员工'], ['aptStart', '预约时间'] ],
|
||||
'crm.body_status.create': [ ['bsMember', '客户'] ],
|
||||
};
|
||||
|
||||
export const FormCopilot = {
|
||||
current: null,
|
||||
|
||||
execute(action) {
|
||||
if (!action || action.type !== 'open_form') return false;
|
||||
const route = action.route || 'crm';
|
||||
if (window.location.hash !== `#/${route}`) window.location.hash = `#/${route}`;
|
||||
setTimeout(() => this.openForm(action.form, action.payload || {}), 250);
|
||||
return true;
|
||||
},
|
||||
|
||||
openForm(form, payload) {
|
||||
const forms = window.CrmForms || {};
|
||||
const fn = forms[form];
|
||||
if (!fn) { alert(`表单未注册:${form}`); return; }
|
||||
this.current = { form, payload: payload || {}, openedAt: Date.now() };
|
||||
fn(payload || {});
|
||||
setTimeout(() => this.showStatus(), 200);
|
||||
},
|
||||
|
||||
handleUserMessage(text) {
|
||||
if (!this.current) return null;
|
||||
const msg = (text || '').trim();
|
||||
if (!msg) return null;
|
||||
if (/^(保存|提交|确认保存|可以保存|确定保存)$/i.test(msg)) {
|
||||
const missing = this.getMissingFields();
|
||||
if (missing.length) return '还缺:' + missing.join('、') + '。请补充后再保存。';
|
||||
if (!confirm('确认保存当前表单吗?')) return '已取消保存,你可以继续修改。';
|
||||
const ok = this.submitCurrent();
|
||||
return ok ? '已帮你点击保存。' : '当前没有可提交的表单。';
|
||||
}
|
||||
if (/^(还缺什么|缺什么|表单状态|填了什么)$/i.test(msg)) return this.showStatus();
|
||||
const updates = this.extractFieldUpdates(msg, this.current.form);
|
||||
if (!Object.keys(updates).length) return null;
|
||||
this.fill(updates);
|
||||
return '已更新:' + Object.keys(updates).map(id => this.fieldLabel(id)).join('、') + '。' + this.missingHint();
|
||||
},
|
||||
|
||||
showStatus() {
|
||||
const missing = this.getMissingFields();
|
||||
const filled = this.getFilledFields();
|
||||
return `当前表单:${this.current?.form || '-'}。已填:${filled.length ? filled.join('、') : '暂无'}。${missing.length ? '还缺:' + missing.join('、') : '必填项已齐,可以说“保存”。'}`;
|
||||
},
|
||||
|
||||
getMissingFields() {
|
||||
const list = REQUIRED_FIELDS[this.current?.form] || [];
|
||||
return list.filter(([id]) => !this.getValue(id)).map(([, label]) => label);
|
||||
},
|
||||
|
||||
getFilledFields() {
|
||||
const map = FORM_FIELD_MAP[this.current?.form] || {};
|
||||
const seen = new Set();
|
||||
const labels = [];
|
||||
Object.entries(map).forEach(([label, id]) => {
|
||||
if (seen.has(id)) return;
|
||||
seen.add(id);
|
||||
if (this.getValue(id)) labels.push(this.fieldLabel(id));
|
||||
});
|
||||
return labels;
|
||||
},
|
||||
|
||||
missingHint() {
|
||||
const missing = this.getMissingFields();
|
||||
return missing.length ? `还缺:${missing.join('、')}。` : '必填项已齐,可以说“保存”。';
|
||||
},
|
||||
|
||||
fieldLabel(id) {
|
||||
const labels = {
|
||||
mName: '姓名', mPhone: '手机号', mWechat: '微信', mLevel: '客户等级', mHealth: '身体问题', mAllergies: '过敏', mNotes: '备注',
|
||||
pName: '产品名称', pCategory: '分类', pType: '类型', pCount: '次数', pPrice: '价格', pDesc: '说明',
|
||||
aptMember: '客户', aptEmp: '员工', aptStart: '预约时间', aptDuration: '时长', aptNotes: '备注',
|
||||
bsMember: '客户', bsWeight: '体重', bsWaist: '腰围', bsMetricName: '身体标签', bsMetricStatus: '状态', bsMetricValue: '数值', bsNotes: '描述',
|
||||
};
|
||||
return labels[id] || id;
|
||||
},
|
||||
|
||||
extractFieldUpdates(text, form) {
|
||||
const map = FORM_FIELD_MAP[form] || {};
|
||||
const updates = {};
|
||||
const normalized = text.replace(/改成|换成|改为|设置为|写成/g, '为');
|
||||
Object.entries(map).forEach(([key, id]) => {
|
||||
const patterns = [ new RegExp(`${key}[::为是 ]+([^,,。;;]+)`), new RegExp(`把${key}[改设写]?为([^,,。;;]+)`) ];
|
||||
for (const p of patterns) { const m = normalized.match(p); if (m) { updates[id] = m[1].trim(); break; } }
|
||||
});
|
||||
const phone = normalized.match(/1\d{10}/); if (phone && map.phone) updates[map.phone] = phone[0];
|
||||
const vip = normalized.match(/(VIP|vip|老客|新客)/); if (vip && map.level) updates[map.level] = vip[1].toUpperCase ? vip[1].toUpperCase() : vip[1];
|
||||
const price = normalized.match(/(?:价格|单价|金额)\D*(\d+(?:\.\d+)?)/); if (price && map.price) updates[map.price] = price[1];
|
||||
const count = normalized.match(/(?:次数|默认次数|数量)\D*(\d+)/); if (count && map.defaultCount) updates[map.defaultCount] = count[1];
|
||||
const duration = normalized.match(/(?:时长|服务时长)\D*(\d+)/); if (duration && map.durationMinutes) updates[map.durationMinutes] = duration[1];
|
||||
if (form === 'crm.product.create') {
|
||||
if (/套餐/.test(normalized)) updates.pType = 'package';
|
||||
if (/实物|产品/.test(normalized)) updates.pType = 'product';
|
||||
if (/服务|项目/.test(normalized)) updates.pType = 'service';
|
||||
}
|
||||
if (form === 'crm.appointment.create') {
|
||||
const dt = this.parseDateTimeHint(normalized);
|
||||
if (dt) updates.aptStart = dt;
|
||||
}
|
||||
if (form === 'crm.body_status.create') {
|
||||
const status = normalized.match(/(没啥效果|有改善|有好转|明显好转)/);
|
||||
if (status) updates.bsMetricStatus = status[1];
|
||||
}
|
||||
return updates;
|
||||
},
|
||||
|
||||
parseDateTimeHint(text) {
|
||||
if (!/(今天|明天|后天|上午|下午|晚上|点)/.test(text)) return '';
|
||||
const d = new Date();
|
||||
if (text.includes('明天')) d.setDate(d.getDate() + 1);
|
||||
if (text.includes('后天')) d.setDate(d.getDate() + 2);
|
||||
const cn = { '一':1, '二':2, '两':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '十':10 };
|
||||
const m = text.match(/(\d{1,2}|[一二两三四五六七八九十])点/);
|
||||
let hour = m ? (/^\d+$/.test(m[1]) ? Number(m[1]) : cn[m[1]] || 10) : 10;
|
||||
if (text.includes('下午') && hour < 12) hour += 12;
|
||||
const y = d.getFullYear(), mo = String(d.getMonth()+1).padStart(2,'0'), da = String(d.getDate()).padStart(2,'0');
|
||||
return `${y}-${mo}-${da}T${String(hour).padStart(2,'0')}:00`;
|
||||
},
|
||||
|
||||
submitCurrent() {
|
||||
const btn = document.getElementById('crmSave') || document.getElementById('recordCrmSave');
|
||||
if (!btn) return false;
|
||||
btn.click();
|
||||
this.current = null;
|
||||
return true;
|
||||
},
|
||||
|
||||
fill(fields) { Object.entries(fields || {}).forEach(([id, value]) => this.setValue(id, value)); },
|
||||
getValue(id) { return document.getElementById(id)?.value?.trim() || ''; },
|
||||
setValue(id, value) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el || value === undefined || value === null) return;
|
||||
if (Array.isArray(value)) value = value.join('\n');
|
||||
if (typeof value === 'object') value = JSON.stringify(value, null, 2);
|
||||
el.value = value;
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
},
|
||||
setMember(prefix, member) {
|
||||
if (!member) return;
|
||||
this.setValue(`${prefix}Member`, member.id || member.memberId || '');
|
||||
this.setValue(`${prefix}MemberManual`, member.id || member.memberId || '');
|
||||
this.setValue(`${prefix}MemberKeyword`, member.label || member.name || member.phone || '');
|
||||
},
|
||||
};
|
||||
|
||||
window.FormCopilot = FormCopilot;
|
||||
869
main/feedback-backend/admin-ui/js/live2d-manager.js
Normal file
869
main/feedback-backend/admin-ui/js/live2d-manager.js
Normal file
|
|
@ -0,0 +1,869 @@
|
|||
/**
|
||||
* Live2D 管理器
|
||||
* 负责 Live2D 模型的初始化、嘴部动画控制等功能
|
||||
*/
|
||||
class Live2DManager {
|
||||
constructor() {
|
||||
this.live2dApp = null;
|
||||
this.live2dModel = null;
|
||||
this.isTalking = false;
|
||||
this.mouthAnimationId = null;
|
||||
this.mouthParam = 'ParamMouthOpenY';
|
||||
this.audioContext = null;
|
||||
this.analyser = null;
|
||||
this.dataArray = null;
|
||||
this.lastEmotionActionTime = null;
|
||||
this.currentModelName = null;
|
||||
|
||||
// 模型特定配置
|
||||
this.modelConfig = {
|
||||
'hiyori_pro_zh': {
|
||||
mouthParam: 'ParamMouthOpenY',
|
||||
mouthAmplitude: 1.0,
|
||||
mouthThresholds: { low: 0.3, high: 0.7 },
|
||||
motionMap: {
|
||||
'FlickUp': 'FlickUp',
|
||||
'FlickDown': 'FlickDown',
|
||||
'Tap': 'Tap',
|
||||
'Tap@Body': 'Tap@Body',
|
||||
'Flick': 'Flick',
|
||||
'Flick@Body': 'Flick@Body'
|
||||
}
|
||||
},
|
||||
'natori_pro_zh': {
|
||||
mouthParam: 'ParamMouthOpenY',
|
||||
mouthAmplitude: 1.0,
|
||||
mouthThresholds: { low: 0.1, high: 0.4 },
|
||||
mouthFormParam: 'ParamMouthForm',
|
||||
mouthFormAmplitude: 1.0,
|
||||
mouthForm2Param: 'ParamMouthForm2',
|
||||
mouthForm2Amplitude: 0.8,
|
||||
motionMap: {
|
||||
'FlickUp': 'FlickUp',
|
||||
'FlickDown': 'Flick@Body',
|
||||
'Tap': 'Tap',
|
||||
'Tap@Body': 'Tap@Head',
|
||||
'Flick': 'Tap',
|
||||
'Flick@Body': 'Flick@Body'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 情绪到动作的映射
|
||||
this.emotionToActionMap = {
|
||||
'happy': 'FlickUp', // 开心-向上轻扫动作
|
||||
'laughing': 'FlickUp', // 大笑-向上轻扫动作
|
||||
'funny': 'FlickUp', // 搞笑-向上轻扫动作
|
||||
'sad': 'FlickDown', // 伤心-向下轻扫动作
|
||||
'crying': 'FlickDown', // 哭泣-向下轻扫动作
|
||||
'angry': 'Tap@Body', // 生气-身体点击动作
|
||||
'surprised': 'Tap', // 惊讶-点击动作
|
||||
'neutral': 'Flick', // 平常-轻扫动作
|
||||
'default': 'Flick@Body' // 默认-身体轻扫动作
|
||||
};
|
||||
|
||||
// 单/双击判定配置与状态
|
||||
this._lastClickTime = 0;
|
||||
this._lastClickPos = { x: 0, y: 0 };
|
||||
this._singleClickTimer = null;
|
||||
this._doubleClickMs = 280; // 双击时间阈值(ms)
|
||||
this._doubleClickDist = 16; // 双击允许的最大位移(px)
|
||||
// 滑动判定
|
||||
this._pointerDown = false;
|
||||
this._downPos = { x: 0, y: 0 };
|
||||
this._downTime = 0;
|
||||
this._downArea = 'Body';
|
||||
this._movedBeyondClick = false;
|
||||
this._swipeMinDist = 24; // 触发滑动的最小距离
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 Live2D
|
||||
*/
|
||||
async initializeLive2D() {
|
||||
try {
|
||||
const canvas = document.getElementById('live2d-stage');
|
||||
|
||||
// 清理之前的 PIXI 应用(防止 WebGL 上下文累积)
|
||||
if (this.live2dApp) {
|
||||
try {
|
||||
this.live2dApp.destroy(true, { children: true, texture: true });
|
||||
} catch (e) { /* 忽略清理异常 */ }
|
||||
this.live2dApp = null;
|
||||
this.live2dModel = null;
|
||||
}
|
||||
|
||||
// 供内部使用
|
||||
window.PIXI = PIXI;
|
||||
|
||||
// 使用 canvas 容器尺寸(适配 max-width:480 的 H5 容器)
|
||||
const canvasContainer = canvas.parentElement;
|
||||
const containerW = canvasContainer ? canvasContainer.clientWidth : window.innerWidth;
|
||||
const containerH = canvasContainer ? canvasContainer.clientHeight : window.innerHeight;
|
||||
|
||||
// 限制 resolution 最大为 2,避免高分屏 WebGL 纹理溢出
|
||||
const resolution = Math.min(window.devicePixelRatio || 1, 2);
|
||||
|
||||
this.live2dApp = new PIXI.Application({
|
||||
view: canvas,
|
||||
height: containerH,
|
||||
width: containerW,
|
||||
resolution: resolution,
|
||||
autoDensity: true,
|
||||
antialias: false,
|
||||
backgroundAlpha: 0,
|
||||
});
|
||||
|
||||
// 加载 Live2D 模型 - 动态检测当前目录,适配不同环境
|
||||
// 获取当前HTML文件所在的目录路径
|
||||
const currentPath = window.location.pathname;
|
||||
const lastSlashIndex = currentPath.lastIndexOf('/');
|
||||
const basePath = currentPath.substring(0, lastSlashIndex + 1);
|
||||
|
||||
// 从 localStorage 读取上次选择的模型,如果没有则使用默认
|
||||
const savedModelName = localStorage.getItem('live2dModel') || 'hiyori_pro_zh';
|
||||
const modelFileMap = {
|
||||
'hiyori_pro_zh': 'hiyori_pro_t11.model3.json',
|
||||
'natori_pro_zh': 'natori_pro_t06.model3.json'
|
||||
};
|
||||
const modelFileName = modelFileMap[savedModelName] || 'hiyori_pro_t11.model3.json';
|
||||
const modelPath = basePath + 'resources/' + savedModelName + '/runtime/' + modelFileName;
|
||||
|
||||
this.live2dModel = await PIXI.live2d.Live2DModel.from(modelPath);
|
||||
this.live2dApp.stage.addChild(this.live2dModel);
|
||||
|
||||
// 保存当前模型名称
|
||||
this.currentModelName = savedModelName;
|
||||
|
||||
// 更新下拉框显示
|
||||
const modelSelect = document.getElementById('live2dModelSelect');
|
||||
if (modelSelect) {
|
||||
modelSelect.value = savedModelName;
|
||||
}
|
||||
|
||||
// 设置模型特定的嘴部参数名
|
||||
if (this.modelConfig[savedModelName]) {
|
||||
this.mouthParam = this.modelConfig[savedModelName].mouthParam || 'ParamMouthOpenY';
|
||||
}
|
||||
|
||||
const fitModelToCanvas = () => {
|
||||
if (!this.live2dModel || !this.live2dApp) return;
|
||||
const w = canvasContainer ? canvasContainer.clientWidth : window.innerWidth;
|
||||
const h = canvasContainer ? canvasContainer.clientHeight : window.innerHeight;
|
||||
this.live2dApp.renderer.resize(w, h);
|
||||
const baseScale = Math.min(w / Math.max(this.live2dModel.width, 1), h / Math.max(this.live2dModel.height, 1));
|
||||
const scale = Math.max(0.38, Math.min(baseScale * 2.35, 1.25));
|
||||
this.live2dModel.scale.set(scale);
|
||||
this.live2dModel.x = (w - this.live2dModel.width) * 0.5;
|
||||
this.live2dModel.y = Math.max(-42, (h - this.live2dModel.height) * 0.16);
|
||||
};
|
||||
fitModelToCanvas();
|
||||
|
||||
// 启用交互并监听点击命中(头部/身体等)
|
||||
|
||||
this.live2dModel.interactive = true;
|
||||
|
||||
|
||||
this.live2dModel.on('doublehit', (args) => {
|
||||
const area = Array.isArray(args) ? args[0] : args;
|
||||
|
||||
// 触发双击动作
|
||||
if (area === 'Body') {
|
||||
this.motion('Flick@Body');
|
||||
} else if (area === 'Head' || area === 'Face') {
|
||||
this.motion('Flick');
|
||||
}
|
||||
|
||||
const app = window.chatApp;
|
||||
const payload = JSON.stringify({ type: 'live2d', event: 'doublehit', area });
|
||||
if (app && app.dataChannel && app.dataChannel.readyState === 'open') {
|
||||
app.dataChannel.send(payload);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
this.live2dModel.on('singlehit', (args) => {
|
||||
const area = Array.isArray(args) ? args[0] : args;
|
||||
|
||||
// 触发单击动作
|
||||
if (area === 'Body') {
|
||||
this.motion('Tap@Body');
|
||||
} else if (area === 'Head' || area === 'Face') {
|
||||
this.motion('Tap');
|
||||
}
|
||||
|
||||
const app = window.chatApp;
|
||||
const payload = JSON.stringify({ type: 'live2d', event: 'singlehit', area });
|
||||
if (app && app.dataChannel && app.dataChannel.readyState === 'open') {
|
||||
app.dataChannel.send(payload);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
this.live2dModel.on('swipe', (args) => {
|
||||
const area = Array.isArray(args) ? args[0] : args;
|
||||
const dir = Array.isArray(args) ? args[1] : undefined;
|
||||
|
||||
// 触发滑动动作
|
||||
if (area === 'Body') {
|
||||
if (dir === 'up') {
|
||||
this.motion('FlickUp');
|
||||
} else if (dir === 'down') {
|
||||
this.motion('FlickDown');
|
||||
}
|
||||
} else if (area === 'Head' || area === 'Face') {
|
||||
if (dir === 'up') {
|
||||
this.motion('FlickUp');
|
||||
} else if (dir === 'down') {
|
||||
this.motion('FlickDown');
|
||||
}
|
||||
}
|
||||
|
||||
const app = window.chatApp;
|
||||
const payload = JSON.stringify({ type: 'live2d', event: 'swipe', area, dir });
|
||||
if (app && app.dataChannel && app.dataChannel.readyState === 'open') {
|
||||
app.dataChannel.send(payload);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// 兜底:自定义"头部/身体"命中区域 + 单/双击/滑动区分
|
||||
this.live2dModel.on('pointerdown', (event) => {
|
||||
try {
|
||||
const global = event.data.global;
|
||||
const bounds = this.live2dModel.getBounds();
|
||||
// 仅在点击落在模型可见范围内时判定
|
||||
if (!bounds || !bounds.contains(global.x, global.y)) return;
|
||||
|
||||
const relX = (global.x - bounds.x) / (bounds.width || 1);
|
||||
const relY = (global.y - bounds.y) / (bounds.height || 1);
|
||||
let area = '';
|
||||
// 经验阈值:模型可见矩形的上部 20% 视为"头部"区域
|
||||
if (relX >= 0.4 && relX <= 0.6) {
|
||||
if (relY <= 0.15) {
|
||||
area = 'Head';
|
||||
} else if (relY <= 0.23) {
|
||||
area = 'Face';
|
||||
} else {
|
||||
area = 'Body';
|
||||
}
|
||||
}
|
||||
if (area === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 记录按下状态用于滑动判定
|
||||
this._pointerDown = true;
|
||||
this._downPos = { x: global.x, y: global.y };
|
||||
this._downTime = performance.now();
|
||||
this._downArea = area;
|
||||
this._movedBeyondClick = false;
|
||||
|
||||
const now = performance.now();
|
||||
const dt = now - (this._lastClickTime || 0);
|
||||
const dx = global.x - (this._lastClickPos?.x || 0);
|
||||
const dy = global.y - (this._lastClickPos?.y || 0);
|
||||
const dist = Math.hypot(dx, dy);
|
||||
|
||||
// 命中确认:仅当点击在模型上时做单/双击判断
|
||||
if (this._lastClickTime && dt <= this._doubleClickMs && dist <= this._doubleClickDist) {
|
||||
// 判定为双击:取消待触发的单击事件
|
||||
if (this._singleClickTimer) {
|
||||
clearTimeout(this._singleClickTimer);
|
||||
this._singleClickTimer = null;
|
||||
}
|
||||
if (typeof this.live2dModel.emit === 'function') {
|
||||
this.live2dModel.emit('doublehit', [area]);
|
||||
}
|
||||
this._lastClickTime = 0;
|
||||
this._pointerDown = false; // 双击完成,重置状态
|
||||
return;
|
||||
}
|
||||
|
||||
// 可能是单击:记录并延迟确认
|
||||
this._lastClickTime = now;
|
||||
this._lastClickPos = { x: global.x, y: global.y };
|
||||
if (this._singleClickTimer) {
|
||||
clearTimeout(this._singleClickTimer);
|
||||
this._singleClickTimer = null;
|
||||
}
|
||||
this._singleClickTimer = setTimeout(() => {
|
||||
// 若在等待期间发生了移动超过阈值,则不再当作单击
|
||||
if (!this._movedBeyondClick && typeof this.live2dModel.emit === 'function') {
|
||||
this.live2dModel.emit('singlehit', [area]);
|
||||
}
|
||||
this._singleClickTimer = null;
|
||||
this._lastClickTime = 0;
|
||||
}, this._doubleClickMs);
|
||||
} catch (e) {
|
||||
// 忽略自定义命中判断中的异常,避免影响主流程
|
||||
}
|
||||
});
|
||||
|
||||
// 指针移动:用于判定是否从"点击"升级为"滑动"
|
||||
this.live2dModel.on('pointermove', (event) => {
|
||||
try {
|
||||
if (!this._pointerDown) return;
|
||||
const global = event.data.global;
|
||||
const dx = global.x - this._downPos.x;
|
||||
const dy = global.y - this._downPos.y;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
|
||||
// 使用 _doubleClickDist 作为点击/滑动的判定阈值
|
||||
if (dist > this._doubleClickDist) {
|
||||
this._movedBeyondClick = true;
|
||||
// 若已超出点击阈值,取消可能的单击触发
|
||||
if (this._singleClickTimer) {
|
||||
clearTimeout(this._singleClickTimer);
|
||||
this._singleClickTimer = null;
|
||||
}
|
||||
this._lastClickTime = 0;
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略移动判定中的异常
|
||||
}
|
||||
});
|
||||
|
||||
// 指针抬起:确认是否为滑动
|
||||
const handlePointerUp = (event) => {
|
||||
try {
|
||||
if (!this._pointerDown) return;
|
||||
const global = (event && event.data && event.data.global) ? event.data.global : { x: this._downPos.x, y: this._downPos.y };
|
||||
const dx = global.x - this._downPos.x;
|
||||
const dy = global.y - this._downPos.y;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
|
||||
// 滑动:超过滑动最小距离则触发 swipe 事件(携带方向与区域)
|
||||
if (this._movedBeyondClick && dist >= this._swipeMinDist) {
|
||||
if (typeof this.live2dModel.emit === 'function') {
|
||||
const dir = Math.abs(dx) >= Math.abs(dy)
|
||||
? (dx > 0 ? 'right' : 'left')
|
||||
: (dy > 0 ? 'down' : 'up');
|
||||
this.live2dModel.emit('swipe', [this._downArea, dir]);
|
||||
}
|
||||
// 终止:不再让单击/双击触发
|
||||
if (this._singleClickTimer) {
|
||||
clearTimeout(this._singleClickTimer);
|
||||
this._singleClickTimer = null;
|
||||
}
|
||||
this._lastClickTime = 0;
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略抬起判定中的异常
|
||||
}
|
||||
finally {
|
||||
this._pointerDown = false;
|
||||
this._movedBeyondClick = false;
|
||||
}
|
||||
};
|
||||
|
||||
this.live2dModel.on('pointerup', handlePointerUp);
|
||||
this.live2dModel.on('pointerupoutside', handlePointerUp);
|
||||
|
||||
// 添加窗口大小变化监听器,保持模型在当前 Canvas 中间显示
|
||||
this.resize = fitModelToCanvas;
|
||||
window.addEventListener('resize', fitModelToCanvas);
|
||||
|
||||
} catch (err) {
|
||||
console.error('加载 Live2D 模型失败:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化音频分析器 - 使用音频播放器的分析器节点
|
||||
*/
|
||||
initializeAudioAnalyzer() {
|
||||
try {
|
||||
// 获取音频播放器实例
|
||||
const audioPlayer = window.chatApp?.audioPlayer;
|
||||
if (!audioPlayer) {
|
||||
console.debug('音频播放器未初始化,使用模拟口型动画');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取音频播放器的音频上下文
|
||||
this.audioContext = audioPlayer.getAudioContext();
|
||||
if (!this.audioContext) {
|
||||
console.warn('无法获取音频播放器的音频上下文');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 创建分析器节点
|
||||
this.analyser = this.audioContext.createAnalyser();
|
||||
this.analyser.fftSize = 256;
|
||||
this.dataArray = new Uint8Array(this.analyser.frequencyBinCount);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('初始化音频分析器失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接到音频播放器的输出节点
|
||||
*/
|
||||
connectToAudioPlayer() {
|
||||
try {
|
||||
// 获取音频播放器的流上下文
|
||||
const audioPlayer = window.chatApp?.audioPlayer;
|
||||
if (!audioPlayer || !audioPlayer.streamingContext) {
|
||||
console.warn('音频播放器或流上下文未初始化');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取音频播放器的流上下文
|
||||
const streamingContext = audioPlayer.streamingContext;
|
||||
|
||||
// 获取分析器节点
|
||||
const analyser = streamingContext.getAnalyser();
|
||||
if (!analyser) {
|
||||
console.warn('音频播放器尚未创建分析器节点,无法连接');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用音频播放器的分析器节点
|
||||
this.analyser = analyser;
|
||||
this.dataArray = new Uint8Array(this.analyser.frequencyBinCount);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('连接到音频播放器失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 嘴部动画循环
|
||||
*/
|
||||
animateMouth() {
|
||||
if (!this.isTalking) return;
|
||||
if (!this.live2dModel) return;
|
||||
const internal = this.live2dModel && this.live2dModel.internalModel;
|
||||
if (internal && internal.coreModel) {
|
||||
const coreModel = internal.coreModel;
|
||||
|
||||
let mouthOpenY = 0;
|
||||
let mouthForm = 0;
|
||||
let mouthForm2 = 0;
|
||||
let average = 0;
|
||||
|
||||
if (this.analyser && this.dataArray) {
|
||||
this.analyser.getByteFrequencyData(this.dataArray);
|
||||
average = this.dataArray.reduce((a, b) => a + b) / this.dataArray.length;
|
||||
|
||||
const normalizedVolume = average / 255;
|
||||
|
||||
// 获取模型特定的阈值
|
||||
let lowThreshold = 0.3;
|
||||
let highThreshold = 0.7;
|
||||
if (this.currentModelName && this.modelConfig[this.currentModelName]) {
|
||||
lowThreshold = this.modelConfig[this.currentModelName].mouthThresholds?.low || 0.3;
|
||||
highThreshold = this.modelConfig[this.currentModelName].mouthThresholds?.high || 0.7;
|
||||
}
|
||||
|
||||
// 使用模型特定的阈值进行映射
|
||||
let minOpenY = 0.1;
|
||||
if (this.currentModelName && this.modelConfig[this.currentModelName]) {
|
||||
minOpenY = this.modelConfig[this.currentModelName].mouthMinOpenY || 0.1;
|
||||
}
|
||||
|
||||
if (normalizedVolume < lowThreshold) {
|
||||
mouthOpenY = minOpenY + Math.pow(normalizedVolume / lowThreshold, 1.5) * (0.4 - minOpenY);
|
||||
} else if (normalizedVolume < highThreshold) {
|
||||
mouthOpenY = 0.4 + (normalizedVolume - lowThreshold) / (highThreshold - lowThreshold) * 0.4;
|
||||
} else {
|
||||
mouthOpenY = 0.8 + Math.pow((normalizedVolume - highThreshold) / (1 - highThreshold), 1.2) * 0.2;
|
||||
}
|
||||
|
||||
// 应用模型特定的嘴部开合幅度
|
||||
let amplitudeMultiplier = 1.0;
|
||||
let maxOpenY = 2.5;
|
||||
if (this.currentModelName && this.modelConfig[this.currentModelName]) {
|
||||
amplitudeMultiplier = this.modelConfig[this.currentModelName].mouthAmplitude;
|
||||
maxOpenY = this.modelConfig[this.currentModelName].maxOpenY || 2.5;
|
||||
}
|
||||
mouthOpenY = mouthOpenY * amplitudeMultiplier;
|
||||
mouthOpenY = Math.min(Math.max(mouthOpenY, 0), maxOpenY);
|
||||
|
||||
// 计算嘴型参数(仅对支持嘴型变化的模型)
|
||||
if (this.currentModelName && this.modelConfig[this.currentModelName]?.mouthFormParam) {
|
||||
const config = this.modelConfig[this.currentModelName];
|
||||
const formAmplitude = config.mouthFormAmplitude || 0.5;
|
||||
const form2Amplitude = config.mouthForm2Amplitude || 0;
|
||||
|
||||
// 嘴型随音量变化:
|
||||
// 低音量:嘴型偏"一"字(负值)
|
||||
// 高音量:嘴型偏"o"字(正值)
|
||||
// 音量=0时:嘴型=0(自然状态)
|
||||
mouthForm = (normalizedVolume - 0.5) * 2 * formAmplitude;
|
||||
mouthForm = Math.max(-formAmplitude, Math.min(formAmplitude, mouthForm));
|
||||
|
||||
// 第二嘴型参数(natori特有)
|
||||
if (config.mouthForm2Param) {
|
||||
mouthForm2 = (normalizedVolume - 0.3) * 2 * form2Amplitude;
|
||||
mouthForm2 = Math.max(-form2Amplitude, Math.min(form2Amplitude, mouthForm2));
|
||||
}
|
||||
}
|
||||
|
||||
// 调试日志:每60帧输出一次(避免控制台刷屏)
|
||||
if (!this._debugFrameCount) this._debugFrameCount = 0;
|
||||
this._debugFrameCount++;
|
||||
if (this._debugFrameCount % 60 === 1) {
|
||||
console.log(`[Live2D] 模型: ${this.currentModelName || 'unknown'}, 音量: ${average?.toFixed(0)}, OpenY: ${mouthOpenY.toFixed(3)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.analyser || !this.dataArray) {
|
||||
average = 80 + Math.sin(performance.now() / 90) * 48 + Math.sin(performance.now() / 37) * 18;
|
||||
mouthOpenY = 0.18 + (Math.max(0, Math.min(1, average / 145)) * 0.72);
|
||||
}
|
||||
|
||||
// 设置嘴部开合参数
|
||||
coreModel.setParameterValueById(this.mouthParam, mouthOpenY);
|
||||
|
||||
// 设置嘴型参数(仅对支持嘴型变化的模型)
|
||||
if (this.currentModelName && this.modelConfig[this.currentModelName]?.mouthFormParam) {
|
||||
const config = this.modelConfig[this.currentModelName];
|
||||
const formParam = config.mouthFormParam;
|
||||
coreModel.setParameterValueById(formParam, mouthForm);
|
||||
|
||||
// 设置第二嘴型参数(natori特有)
|
||||
if (config.mouthForm2Param) {
|
||||
coreModel.setParameterValueById(config.mouthForm2Param, mouthForm2);
|
||||
}
|
||||
}
|
||||
|
||||
coreModel.update();
|
||||
}
|
||||
this.mouthAnimationId = requestAnimationFrame(() => this.animateMouth());
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始说话动画
|
||||
*/
|
||||
startTalking() {
|
||||
if (this.isTalking || !this.live2dModel) return;
|
||||
|
||||
// 确保音频分析器已初始化
|
||||
if (!this.analyser) {
|
||||
if (!this.initializeAudioAnalyzer()) {
|
||||
console.debug('音频分析器初始化失败,使用模拟口型动画');
|
||||
// 即使分析器初始化失败,也启动动画(使用模拟数据)
|
||||
this.isTalking = true;
|
||||
this.animateMouth();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 连接到音频播放器输出
|
||||
if (!this.connectToAudioPlayer()) {
|
||||
console.warn('无法连接到音频播放器输出,将使用模拟动画');
|
||||
}
|
||||
|
||||
this.isTalking = true;
|
||||
this.animateMouth();
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止说话动画
|
||||
*/
|
||||
stopTalking() {
|
||||
this.isTalking = false;
|
||||
if (this.mouthAnimationId) {
|
||||
cancelAnimationFrame(this.mouthAnimationId);
|
||||
this.mouthAnimationId = null;
|
||||
}
|
||||
|
||||
// 重置嘴部参数
|
||||
if (this.live2dModel) {
|
||||
const internal = this.live2dModel.internalModel;
|
||||
if (internal && internal.coreModel) {
|
||||
const coreModel = internal.coreModel;
|
||||
coreModel.setParameterValueById(this.mouthParam, 0);
|
||||
coreModel.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于情绪触发动作
|
||||
* @param {string} emotion - 情绪名称
|
||||
*/
|
||||
triggerEmotionAction(emotion) {
|
||||
if (!this.live2dModel) return;
|
||||
|
||||
// 添加冷却时间控制,避免过于频繁触发
|
||||
const now = Date.now();
|
||||
if (this.lastEmotionActionTime && now - this.lastEmotionActionTime < 5000) { // 5秒冷却时间
|
||||
return;
|
||||
}
|
||||
|
||||
// 根据情绪获取对应的动作
|
||||
const action = this.emotionToActionMap[emotion] || this.emotionToActionMap['default'];
|
||||
|
||||
// 触发动作并记录时间
|
||||
this.motion(action);
|
||||
this.lastEmotionActionTime = now;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 触发模型动作(Motion)
|
||||
* @param {string} name - 动作分组名称,如 'TapBody'、'FlickUp'、'Idle' 等
|
||||
*/
|
||||
motion(name) {
|
||||
try {
|
||||
if (!this.live2dModel) return;
|
||||
|
||||
// 根据当前模型获取对应的动作名称
|
||||
let actualMotionName = name;
|
||||
if (this.currentModelName && this.modelConfig[this.currentModelName]) {
|
||||
const motionMap = this.modelConfig[this.currentModelName].motionMap;
|
||||
actualMotionName = motionMap[name] || name;
|
||||
}
|
||||
|
||||
this.live2dModel.motion(actualMotionName);
|
||||
} catch (error) {
|
||||
console.error('触发动作失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置模型交互事件
|
||||
*/
|
||||
setupModelInteractions() {
|
||||
if (!this.live2dModel) return;
|
||||
|
||||
this.live2dModel.interactive = true;
|
||||
|
||||
this.live2dModel.on('doublehit', (args) => {
|
||||
const area = Array.isArray(args) ? args[0] : args;
|
||||
|
||||
if (area === 'Body') {
|
||||
this.motion('Flick@Body');
|
||||
} else if (area === 'Head' || area === 'Face') {
|
||||
this.motion('Flick');
|
||||
}
|
||||
|
||||
const app = window.chatApp;
|
||||
const payload = JSON.stringify({ type: 'live2d', event: 'doublehit', area });
|
||||
if (app && app.dataChannel && app.dataChannel.readyState === 'open') {
|
||||
app.dataChannel.send(payload);
|
||||
}
|
||||
});
|
||||
|
||||
this.live2dModel.on('singlehit', (args) => {
|
||||
const area = Array.isArray(args) ? args[0] : args;
|
||||
|
||||
if (area === 'Body') {
|
||||
this.motion('Tap@Body');
|
||||
} else if (area === 'Head' || area === 'Face') {
|
||||
this.motion('Tap');
|
||||
}
|
||||
|
||||
const app = window.chatApp;
|
||||
const payload = JSON.stringify({ type: 'live2d', event: 'singlehit', area });
|
||||
if (app && app.dataChannel && app.dataChannel.readyState === 'open') {
|
||||
app.dataChannel.send(payload);
|
||||
}
|
||||
});
|
||||
|
||||
this.live2dModel.on('swipe', (args) => {
|
||||
const area = Array.isArray(args) ? args[0] : args;
|
||||
const dir = Array.isArray(args) ? args[1] : undefined;
|
||||
|
||||
if (area === 'Body') {
|
||||
if (dir === 'up') {
|
||||
this.motion('FlickUp');
|
||||
} else if (dir === 'down') {
|
||||
this.motion('FlickDown');
|
||||
}
|
||||
}
|
||||
|
||||
const app = window.chatApp;
|
||||
const payload = JSON.stringify({ type: 'live2d', event: 'swipe', area, dir });
|
||||
if (app && app.dataChannel && app.dataChannel.readyState === 'open') {
|
||||
app.dataChannel.send(payload);
|
||||
}
|
||||
});
|
||||
|
||||
this.live2dModel.on('pointerdown', (event) => {
|
||||
try {
|
||||
const global = event.data.global;
|
||||
const bounds = this.live2dModel.getBounds();
|
||||
if (!bounds || !bounds.contains(global.x, global.y)) return;
|
||||
|
||||
const relX = (global.x - bounds.x) / (bounds.width || 1);
|
||||
const relY = (global.y - bounds.y) / (bounds.height || 1);
|
||||
let area = '';
|
||||
|
||||
if (relX >= 0.4 && relX <= 0.6) {
|
||||
if (relY <= 0.15) {
|
||||
area = 'Head';
|
||||
} else if (relY >= 0.7) {
|
||||
area = 'Body';
|
||||
}
|
||||
}
|
||||
|
||||
if (!area) return;
|
||||
|
||||
const now = Date.now();
|
||||
const dt = now - (this._lastClickTime || 0);
|
||||
const dx = global.x - (this._lastClickPos?.x || 0);
|
||||
const dy = global.y - (this._lastClickPos?.y || 0);
|
||||
const dist = Math.hypot(dx, dy);
|
||||
|
||||
if (this._lastClickTime && dt <= this._doubleClickMs && dist <= this._doubleClickDist) {
|
||||
if (this._singleClickTimer) {
|
||||
clearTimeout(this._singleClickTimer);
|
||||
this._singleClickTimer = null;
|
||||
}
|
||||
|
||||
this.live2dModel.emit('doublehit', area);
|
||||
this._lastClickTime = null;
|
||||
this._lastClickPos = null;
|
||||
} else {
|
||||
this._lastClickTime = now;
|
||||
this._lastClickPos = { x: global.x, y: global.y };
|
||||
|
||||
this._singleClickTimer = setTimeout(() => {
|
||||
this._singleClickTimer = null;
|
||||
this.live2dModel.emit('singlehit', area);
|
||||
}, this._doubleClickMs);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('pointerdown 处理出错:', e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理资源
|
||||
*/
|
||||
destroy() {
|
||||
this.stopTalking();
|
||||
|
||||
// 清理音频分析器
|
||||
if (this.audioContext) {
|
||||
try { this.audioContext.close(); } catch (e) {}
|
||||
this.audioContext = null;
|
||||
}
|
||||
this.analyser = null;
|
||||
this.dataArray = null;
|
||||
|
||||
// 清理 Live2D 模型
|
||||
if (this.live2dModel) {
|
||||
try {
|
||||
this.live2dModel.interactive = false;
|
||||
this.live2dModel.removeAllListeners();
|
||||
if (this.live2dApp && this.live2dApp.stage) {
|
||||
this.live2dApp.stage.removeChild(this.live2dModel);
|
||||
}
|
||||
if (typeof this.live2dModel.destroy === 'function') {
|
||||
this.live2dModel.destroy();
|
||||
}
|
||||
} catch (e) { /* 忽略清理异常 */ }
|
||||
this.live2dModel = null;
|
||||
}
|
||||
|
||||
// 清理 PIXI 应用(释放 WebGL 上下文)
|
||||
if (this.live2dApp) {
|
||||
try {
|
||||
this.live2dApp.destroy(true, { children: true, texture: true, baseTexture: true });
|
||||
} catch (e) { /* 忽略清理异常 */ }
|
||||
this.live2dApp = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换 Live2D 模型
|
||||
* @param {string} modelName - 模型目录名称,如 'hiyori_pro_zh'、'natori_pro_zh'
|
||||
* @returns {Promise<boolean>} - 切换是否成功
|
||||
*/
|
||||
async switchModel(modelName) {
|
||||
try {
|
||||
// 获取模型文件名映射
|
||||
const modelFileMap = {
|
||||
'hiyori_pro_zh': 'hiyori_pro_t11.model3.json',
|
||||
'natori_pro_zh': 'natori_pro_t06.model3.json',
|
||||
'chitose': 'chitose.model3.json',
|
||||
'haru_greeter_pro_jp': 'haru_greeter_t05.model3.json'
|
||||
};
|
||||
|
||||
const modelFileName = modelFileMap[modelName];
|
||||
if (!modelFileName) {
|
||||
console.error('未知的模型名称:', modelName);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取基础路径
|
||||
const currentPath = window.location.pathname;
|
||||
const lastSlashIndex = currentPath.lastIndexOf('/');
|
||||
const basePath = currentPath.substring(0, lastSlashIndex + 1);
|
||||
const modelPath = basePath + 'resources/' + modelName + '/runtime/' + modelFileName;
|
||||
|
||||
// 如果已存在模型,先移除
|
||||
if (this.live2dModel) {
|
||||
this.live2dApp.stage.removeChild(this.live2dModel);
|
||||
this.live2dModel.destroy();
|
||||
this.live2dModel = null;
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
const app = window.chatApp;
|
||||
if (app) {
|
||||
app.setModelLoadingStatus(true);
|
||||
}
|
||||
|
||||
// 加载新模型
|
||||
this.live2dModel = await PIXI.live2d.Live2DModel.from(modelPath);
|
||||
this.live2dApp.stage.addChild(this.live2dModel);
|
||||
|
||||
// 设置模型属性
|
||||
this.live2dModel.scale.set(0.33);
|
||||
this.live2dModel.x = (window.innerWidth - this.live2dModel.width) * 0.5;
|
||||
this.live2dModel.y = -50;
|
||||
|
||||
// 重新绑定交互事件
|
||||
this.setupModelInteractions();
|
||||
|
||||
// 隐藏加载状态
|
||||
if (app) {
|
||||
app.setModelLoadingStatus(false);
|
||||
}
|
||||
|
||||
// 保存当前模型名称
|
||||
this.currentModelName = modelName;
|
||||
|
||||
// 设置模型特定的嘴部参数名
|
||||
if (this.modelConfig[modelName]) {
|
||||
this.mouthParam = this.modelConfig[modelName].mouthParam || 'ParamMouthOpenY';
|
||||
}
|
||||
|
||||
// 保存到 localStorage
|
||||
localStorage.setItem('live2dModel', modelName);
|
||||
|
||||
// 更新下拉框显示
|
||||
const modelSelect = document.getElementById('live2dModelSelect');
|
||||
if (modelSelect) {
|
||||
modelSelect.value = modelName;
|
||||
}
|
||||
|
||||
console.log('模型切换成功:', modelName);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('切换模型失败:', error);
|
||||
const app = window.chatApp;
|
||||
if (app) {
|
||||
app.setModelLoadingStatus(false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// 导出全局实例
|
||||
window.Live2DManager = Live2DManager;
|
||||
196
main/feedback-backend/admin-ui/js/pages/agent-configs.js
Normal file
196
main/feedback-backend/admin-ui/js/pages/agent-configs.js
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
// Agent Configs - 智能体配置管理
|
||||
import { api } from '../api.js';
|
||||
|
||||
let currentPage = 1;
|
||||
const pageSize = 20;
|
||||
|
||||
export async function renderAgentConfigs(container) {
|
||||
container.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<div style="flex:1"></div>
|
||||
<button class="btn btn-primary btn-sm" id="addConfigBtn">+ 新增配置</button>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>配置名称</th>
|
||||
<th>智能体ID</th>
|
||||
<th>对话轮次</th>
|
||||
<th>问题数</th>
|
||||
<th>状态</th>
|
||||
<th>创建时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="configsBody">
|
||||
<tr><td colspan="8" class="loading"><div class="spinner"></div></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="pagination" class="pagination"></div>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('addConfigBtn').addEventListener('click', () => showConfigForm());
|
||||
loadConfigs();
|
||||
}
|
||||
|
||||
async function loadConfigs() {
|
||||
const tbody = document.getElementById('configsBody');
|
||||
if (!tbody) return;
|
||||
|
||||
try {
|
||||
const res = await api.getAgentConfigs(`page=${currentPage}&page_size=${pageSize}`);
|
||||
const data = res.data || {};
|
||||
|
||||
if (!data.list || data.list.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="empty-state"><p>暂无智能体配置</p></td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.list.map(c => `
|
||||
<tr>
|
||||
<td style="font-size:11px;color:#9CA3AF">${escapeHtml(c.id).substring(0,8)}...</td>
|
||||
<td><strong>${escapeHtml(c.agentName)}</strong></td>
|
||||
<td style="font-size:11px">${escapeHtml(c.agentId || '-')}</td>
|
||||
<td>${c.dialogueRounds}</td>
|
||||
<td>${c.questions ? c.questions.length : 0}</td>
|
||||
<td>${statusBadge(c.status)}</td>
|
||||
<td style="white-space:nowrap">${formatDate(c.createDate)}</td>
|
||||
<td>
|
||||
<button class="btn btn-secondary btn-sm edit-cfg-btn" data-id="${c.id}">编辑</button>
|
||||
<button class="btn btn-danger btn-sm del-cfg-btn" data-id="${c.id}">删除</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
|
||||
tbody.querySelectorAll('.edit-cfg-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const cfg = data.list.find(c => c.id === btn.dataset.id);
|
||||
if (cfg) showConfigForm(cfg);
|
||||
});
|
||||
});
|
||||
|
||||
tbody.querySelectorAll('.del-cfg-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
if (!confirm('确定删除该配置?')) return;
|
||||
await api.deleteAgentConfig(btn.dataset.id);
|
||||
loadConfigs();
|
||||
});
|
||||
});
|
||||
|
||||
const total = data.total || 0;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
document.getElementById('pagination').innerHTML = `
|
||||
<div class="pagination-info">共 ${total} 条</div>
|
||||
<div class="pagination-btns">
|
||||
<button ${currentPage <= 1 ? 'disabled' : ''} id="prevPage">上一页</button>
|
||||
<button class="active">${currentPage}</button>
|
||||
<button ${currentPage >= totalPages ? 'disabled' : ''} id="nextPage">下一页</button>
|
||||
</div>`;
|
||||
document.getElementById('prevPage')?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; loadConfigs(); } });
|
||||
document.getElementById('nextPage')?.addEventListener('click', () => { if (currentPage < totalPages) { currentPage++; loadConfigs(); } });
|
||||
|
||||
} catch (e) {
|
||||
tbody.innerHTML = `<tr><td colspan="8" class="empty-state"><p>加载失败: ${e.message}</p></td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function showConfigForm(config = null) {
|
||||
const isEdit = !!config;
|
||||
const questions = config?.questions || [];
|
||||
const llmConfig = config?.llmConfig || {};
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card" style="max-width:600px">
|
||||
<div class="modal-header">
|
||||
<h3>${isEdit ? '编辑智能体配置' : '新增智能体配置'}</h3>
|
||||
<button class="modal-close" id="closeForm">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label class="form-label">配置名称</label>
|
||||
<input type="text" id="formName" class="form-input" value="${config?.agentName || ''}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">智能体 ID</label>
|
||||
<input type="text" id="formAgentId" class="form-input" value="${config?.agentId || ''}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">对话轮次 (1-20)</label>
|
||||
<input type="number" id="formRounds" class="form-input" value="${config?.dialogueRounds || 7}" min="1" max="20" style="width:100px">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">问题列表 (每行一个问题)</label>
|
||||
<textarea id="formQuestions" class="form-input" rows="6" style="resize:vertical">${questions.join('\n')}</textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">LLM 配置 (JSON)</label>
|
||||
<textarea id="formLLM" class="form-input" rows="4" style="resize:vertical;font-family:monospace;font-size:12px">${llmConfig.provider ? JSON.stringify(llmConfig, null, 2) : ''}</textarea>
|
||||
<div style="font-size:11px;color:#9CA3AF;margin-top:4px">格式: {"provider":"openai","api_key":"...","base_url":"...","model":"..."}</div>
|
||||
</div>
|
||||
<div id="formError" style="color:var(--danger);font-size:13px;min-height:20px;margin-top:8px"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="cancelBtn">取消</button>
|
||||
<button class="btn btn-primary" id="saveBtn">保存</button>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('closeForm').addEventListener('click', close);
|
||||
document.getElementById('cancelBtn').addEventListener('click', close);
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
|
||||
document.getElementById('saveBtn').addEventListener('click', async () => {
|
||||
const errEl = document.getElementById('formError');
|
||||
errEl.textContent = '';
|
||||
|
||||
const agentName = document.getElementById('formName').value.trim();
|
||||
const agentId = document.getElementById('formAgentId').value.trim() || null;
|
||||
const dialogueRounds = parseInt(document.getElementById('formRounds').value) || 7;
|
||||
const questionsText = document.getElementById('formQuestions').value.trim();
|
||||
const llmText = document.getElementById('formLLM').value.trim();
|
||||
|
||||
if (!agentName) {
|
||||
errEl.textContent = '配置名称不能为空';
|
||||
return;
|
||||
}
|
||||
|
||||
const questions = questionsText ? questionsText.split('\n').map(q => q.trim()).filter(Boolean) : null;
|
||||
|
||||
let llmConfig = null;
|
||||
if (llmText) {
|
||||
try {
|
||||
llmConfig = JSON.parse(llmText);
|
||||
} catch {
|
||||
errEl.textContent = 'LLM 配置 JSON 格式错误';
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
await api.updateAgentConfig(config.id, {
|
||||
agent_name: agentName, agent_id: agentId,
|
||||
dialogue_rounds: dialogueRounds, questions, llm_config: llmConfig
|
||||
});
|
||||
} else {
|
||||
await api.createAgentConfig({
|
||||
agent_name: agentName, agent_id: agentId,
|
||||
dialogue_rounds: dialogueRounds, questions, llm_config: llmConfig
|
||||
});
|
||||
}
|
||||
close();
|
||||
loadConfigs();
|
||||
} catch (e) {
|
||||
errEl.textContent = '保存失败: ' + e.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
883
main/feedback-backend/admin-ui/js/pages/crm.js
Normal file
883
main/feedback-backend/admin-ui/js/pages/crm.js
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
// CRM 管理
|
||||
import { api } from '../api.js';
|
||||
|
||||
let currentTab = 'overview';
|
||||
let currentPage = 1;
|
||||
let memberKeyword = '';
|
||||
let appointmentDate = dateInput(new Date());
|
||||
let appointmentView = 'day';
|
||||
const pageSize = 20;
|
||||
const MEKAI66_FIELDS = [
|
||||
['name','姓名','基础信息'],['nickname','昵称/常用称呼','基础信息'],['gender','性别','基础信息'],['birthday','生日','基础信息'],['age','年龄','基础信息'],['hometown','籍贯/老家','基础信息'],['address','居住地址/小区','基础信息'],['phone','手机号','基础信息'],['wechat','微信号','基础信息'],['education','学历','基础信息'],
|
||||
['marital_status','婚姻状态','家庭关系'],['spouse_name','配偶姓名','家庭关系'],['spouse_job','配偶职业','家庭关系'],['children','子女情况','家庭关系'],['children_school','子女学校/年级','家庭关系'],['parents','父母情况','家庭关系'],['family_anniversary','家庭纪念日','家庭关系'],['family_focus','家庭关注点','家庭关系'],['pet','宠物','家庭关系'],['emergency_contact','紧急联系人','家庭关系'],
|
||||
['company','公司/单位','工作事业'],['industry','行业','工作事业'],['position','职位','工作事业'],['job_responsibility','工作职责','工作事业'],['income_level','收入水平','工作事业'],['work_pressure','工作压力','工作事业'],['work_schedule','作息/上下班时间','工作事业'],['business_needs','事业需求/目标','工作事业'],['decision_style','决策风格','工作事业'],['social_circle','社交圈','工作事业'],
|
||||
['hobbies','兴趣爱好','生活方式'],['sports','运动习惯','生活方式'],['travel','旅游偏好','生活方式'],['diet','饮食偏好','生活方式'],['tea_drink','茶饮偏好','生活方式'],['music','音乐偏好','生活方式'],['reading','阅读/学习偏好','生活方式'],['shopping','购物偏好','生活方式'],['brands','喜欢品牌','生活方式'],['taboo_topics','忌讳话题','生活方式'],
|
||||
['consumption_power','消费能力','消费习惯'],['consumption_frequency','消费频次','消费习惯'],['budget','预算区间','消费习惯'],['preferred_projects','偏好项目','消费习惯'],['disliked_projects','不喜欢项目','消费习惯'],['price_sensitivity','价格敏感度','消费习惯'],['promotion_preference','优惠偏好','消费习惯'],['referral_willingness','转介绍意愿','消费习惯'],['decision_factor','购买决策因素','消费习惯'],['loss_risk','流失风险点','消费习惯'],
|
||||
['skin_type','皮肤类型','健康美容'],['beauty_concerns','美容关注点','健康美容'],['body_discomfort','身体不适','健康美容'],['chronic_disease','慢性病/疾病史','健康美容'],['allergy','过敏史','健康美容'],['contraindication','护理禁忌','健康美容'],['sleep','睡眠情况','健康美容'],['menstruation','经期/备孕/孕产情况','健康美容'],
|
||||
['preferred_employee','偏好技师','服务偏好'],['service_strength','服务力度偏好','服务偏好'],['chat_preference','聊天偏好','服务偏好'],['room_preference','房间/环境偏好','服务偏好'],['temperature_preference','温度偏好','服务偏好'],['appointment_preference','预约时间偏好','服务偏好'],['last_important_event','最近重要事件','关系维护'],['next_followup','下次跟进重点','关系维护'],
|
||||
].map(([key, label, category]) => ({ key, label, category }));
|
||||
|
||||
export async function renderCrm(container) {
|
||||
const query = (window.location.hash.split('?')[1] || '');
|
||||
const params = new URLSearchParams(query);
|
||||
if (params.get('tab')) currentTab = params.get('tab');
|
||||
container.innerHTML = `
|
||||
<div class="crm-tabs">
|
||||
${tabBtn('overview', '📊', 'CRM看板')}
|
||||
${tabBtn('members', '👤', '客户档案')}
|
||||
${tabBtn('appointments', '📅', '预约日历')}
|
||||
${tabBtn('visits', '🕒', '到店记录')}
|
||||
${tabBtn('products', '🧴', '产品管理')}
|
||||
${tabBtn('memberProducts', '🎁', '客户套餐')}
|
||||
${tabBtn('productConsumes', '📉', '套餐消费')}
|
||||
${tabBtn('cardCloses', '🚪', '销卡管理')}
|
||||
${tabBtn('suggestions', '💡', '建议管理')}
|
||||
</div>
|
||||
<div id="crmContent"></div>`;
|
||||
container.querySelectorAll('.crm-tab').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
currentTab = btn.dataset.tab;
|
||||
currentPage = 1;
|
||||
renderCrm(container);
|
||||
});
|
||||
});
|
||||
await loadTab();
|
||||
}
|
||||
|
||||
function tabBtn(tab, icon, label) {
|
||||
return `<button class="crm-tab ${currentTab === tab ? 'active' : ''}" data-tab="${tab}">${icon} ${label}</button>`;
|
||||
}
|
||||
|
||||
async function loadTab() {
|
||||
const el = document.getElementById('crmContent');
|
||||
if (!el) return;
|
||||
if (currentTab === 'overview') return loadOverview(el);
|
||||
if (currentTab === 'members') return loadMembers(el);
|
||||
if (currentTab === 'appointments') return loadAppointments(el);
|
||||
if (currentTab === 'bodyStatus') return loadBodyStatus(el);
|
||||
if (currentTab === 'visits') return loadVisits(el);
|
||||
if (currentTab === 'products') return loadProducts(el);
|
||||
if (currentTab === 'memberProducts') return loadMemberProducts(el);
|
||||
if (currentTab === 'productConsumes') return loadProductConsumes(el);
|
||||
if (currentTab === 'accounts') return loadAccounts(el);
|
||||
if (currentTab === 'transactions') return loadTransactions(el);
|
||||
if (currentTab === 'cardCloses') return loadCardCloses(el);
|
||||
if (currentTab === 'suggestions') return loadSuggestions(el);
|
||||
if (currentTab === 'issues') return loadIssues(el);
|
||||
}
|
||||
|
||||
async function loadOverview(el) {
|
||||
el.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
|
||||
try {
|
||||
const res = await api.getCrmOverview();
|
||||
const d = res.data || {};
|
||||
el.innerHTML = `
|
||||
<div class="stat-grid">
|
||||
${stat('👤', '客户数', d.members || 0, 'blue')}
|
||||
${stat('🕒', '到店记录', d.visits || 0, 'green')}
|
||||
${stat('💳', '有效账户', d.activeAccounts || 0, 'blue')}
|
||||
${stat('💰', '账户余额', `¥${d.accountBalance || 0}`, 'green')}
|
||||
${stat('🚪', '销卡记录', d.cardCloses || 0, 'yellow')}
|
||||
${stat('💡', '待处理建议', d.pendingSuggestions || 0, 'yellow')}
|
||||
${stat('✅', '已采纳建议', d.adoptedSuggestions || 0, 'green')}
|
||||
</div>
|
||||
<div class="card"><div class="card-title">使用说明</div>
|
||||
<p class="muted">当前主视角:客户档案、身体变化、已购产品/套餐、套餐消耗、建议闭环。到店记录和流水作为支撑数据保留。</p>
|
||||
</div>`;
|
||||
} catch (e) { el.innerHTML = error(e); }
|
||||
}
|
||||
|
||||
function stat(icon, label, value, color) {
|
||||
return `<div class="stat-card"><div class="stat-icon ${color}">${icon}</div><div class="stat-info"><div class="stat-label">${label}</div><div class="stat-value">${value}</div></div></div>`;
|
||||
}
|
||||
|
||||
async function loadMembers(el) {
|
||||
el.innerHTML = listShell('客户档案', '新增客户', 'memberAddBtn', `
|
||||
<input id="crmKeyword" class="form-input" placeholder="姓名/手机号" style="width:180px" value="${escapeHtml(memberKeyword)}">
|
||||
<button class="btn btn-primary btn-sm" id="crmSearchBtn">查询</button>
|
||||
`, ['姓名','手机号','美容/健康','到店','消费','时间','操作']);
|
||||
document.getElementById('memberAddBtn').onclick = () => showMemberDialog();
|
||||
document.getElementById('crmSearchBtn').onclick = () => {
|
||||
memberKeyword = document.getElementById('crmKeyword')?.value.trim() || '';
|
||||
currentPage = 1;
|
||||
loadMembers(el);
|
||||
};
|
||||
document.getElementById('crmKeyword').addEventListener('keyup', (e) => {
|
||||
if (e.key === 'Enter') document.getElementById('crmSearchBtn').click();
|
||||
});
|
||||
const params = new URLSearchParams({ page: currentPage, page_size: pageSize });
|
||||
if (memberKeyword) params.set('keyword', memberKeyword);
|
||||
try {
|
||||
const res = await api.getCrmMembers(params.toString());
|
||||
const data = res.data || {};
|
||||
renderRows(data, m => `
|
||||
<tr><td><strong>${escapeHtml(m.name || '-')}</strong><div class="muted">${escapeHtml(m.level || '')}</div></td>
|
||||
<td>${escapeHtml(m.phone || '-')}</td><td>${tags(m.beautyConcerns)}${tags(m.healthIssues)}</td>
|
||||
<td>${m.totalVisits || 0}</td><td>¥${m.totalSpent || 0}</td><td>${formatDate(m.updateDate)}</td>
|
||||
<td><button class="btn btn-secondary btn-sm" data-detail="${m.id}">详情</button></td></tr>`);
|
||||
bindDetailButtons(data.list || []);
|
||||
} catch (e) { tableError(e, 7); }
|
||||
}
|
||||
|
||||
async function loadBodyStatus(el) {
|
||||
el.innerHTML = listShell('身体变化状态', '新增状态', 'bodyAddBtn', '', ['客户','日期','体重','腰围','标签','状态','数值','描述']);
|
||||
document.getElementById('bodyAddBtn').onclick = () => showBodyStatusDialog();
|
||||
try {
|
||||
const res = await api.getCrmBodyStatuses(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, b => `<tr><td><strong>${escapeHtml(b.memberName || '-')}</strong><div class="muted">${escapeHtml(b.memberId)}</div></td><td>${formatDate(b.recordDate)}</td><td>${b.weight ?? '-'}</td><td>${b.waistline ?? '-'}</td><td>${escapeHtml(b.metrics?.name || '-')}</td><td>${escapeHtml(b.metrics?.status || '-')}</td><td>${escapeHtml(b.metrics?.value || '-')}</td><td>${escapeHtml(b.notes || '-')}</td></tr>`);
|
||||
} catch (e) { tableError(e, 8); }
|
||||
}
|
||||
|
||||
async function loadAppointments(el) {
|
||||
const range = appointmentRange(appointmentDate, appointmentView);
|
||||
el.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<div class="card-title" style="margin:0;flex:1">预约日历</div>
|
||||
<select id="aptView" class="form-input" style="width:100px"><option value="day">日</option><option value="week">周</option><option value="month">月</option></select>
|
||||
<input id="aptDate" type="date" class="form-input" style="width:150px" value="${appointmentDate}">
|
||||
<select id="aptEmployee" class="form-input" style="width:160px"><option value="">全部员工</option></select>
|
||||
<button class="btn btn-primary btn-sm" id="aptSearch">查询</button>
|
||||
<button class="btn btn-secondary btn-sm" id="aptAvailability">查看空档</button>
|
||||
<button class="btn btn-primary btn-sm" id="aptCreate">新增预约</button>
|
||||
</div>
|
||||
<div id="aptBoard" class="appointment-board"><div class="loading"><div class="spinner"></div></div></div>
|
||||
</div>`;
|
||||
document.getElementById('aptView').value = appointmentView;
|
||||
await loadAppointmentEmployees();
|
||||
document.getElementById('aptSearch').onclick = () => { appointmentDate = val('aptDate'); appointmentView = val('aptView'); loadAppointments(el); };
|
||||
document.getElementById('aptAvailability').onclick = () => showAvailabilityDialog();
|
||||
document.getElementById('aptCreate').onclick = () => showAppointmentDialog();
|
||||
await renderAppointmentBoard(range);
|
||||
}
|
||||
|
||||
function appointmentRange(baseDate, view) {
|
||||
const d = new Date(baseDate + 'T00:00:00');
|
||||
if (view === 'day') return { start: dateInput(d), end: dateInput(d) };
|
||||
if (view === 'week') {
|
||||
const start = new Date(d); start.setDate(d.getDate() - ((d.getDay() + 6) % 7));
|
||||
const end = new Date(start); end.setDate(start.getDate() + 6);
|
||||
return { start: dateInput(start), end: dateInput(end) };
|
||||
}
|
||||
const start = new Date(d.getFullYear(), d.getMonth(), 1);
|
||||
const end = new Date(d.getFullYear(), d.getMonth() + 1, 0);
|
||||
return { start: dateInput(start), end: dateInput(end) };
|
||||
}
|
||||
|
||||
async function loadAppointmentEmployees() {
|
||||
const sel = document.getElementById('aptEmployee'); if (!sel) return;
|
||||
try {
|
||||
const res = await api.getEmployees('page=1&page_size=100');
|
||||
const list = res.data?.list || [];
|
||||
sel.innerHTML = '<option value="">全部员工</option>' + list.map(e => `<option value="${e.id}">${escapeHtml(e.name)}${e.number ? `(${e.number}号)` : ''}</option>`).join('');
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function renderAppointmentBoard(range) {
|
||||
const board = document.getElementById('aptBoard'); if (!board) return;
|
||||
const params = new URLSearchParams({ start_date: range.start, end_date: range.end });
|
||||
const emp = document.getElementById('aptEmployee')?.value || '';
|
||||
if (emp) params.set('employee_id', emp);
|
||||
try {
|
||||
const res = await api.getAppointmentCalendar(params.toString());
|
||||
const data = res.data || { resources: [], events: [] };
|
||||
if (appointmentView === 'day') {
|
||||
board.innerHTML = `<div class="appointment-range">${range.start} · ${data.events.length || 0} 个预约</div>${renderDayEventSummary(data.events)}${renderResourceDayCalendar(data.resources, data.events)}`;
|
||||
bindAppointmentActions(board, range);
|
||||
setTimeout(() => {
|
||||
const first = board.querySelector('.resource-event');
|
||||
const cal = board.querySelector('.resource-calendar');
|
||||
if (first && cal) cal.scrollTop = Math.max(0, first.offsetTop - 80);
|
||||
}, 50);
|
||||
} else if (window.FullCalendar) {
|
||||
renderFullCalendar(board, range, data);
|
||||
} else {
|
||||
board.innerHTML = `
|
||||
<div class="appointment-range">${range.start} 至 ${range.end} · ${data.events.length || 0} 个预约</div>
|
||||
${appointmentView === 'month' ? renderMonthCalendar(range, data.events) : appointmentView === 'week' ? renderWeekCalendar(range, data.events) : renderDayCalendar(data.resources, data.events)}`;
|
||||
bindAppointmentActions(board, range);
|
||||
}
|
||||
} catch (e) {
|
||||
board.innerHTML = `<div class="empty-state">加载预约失败:${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderFullCalendar(board, range, data) {
|
||||
board.innerHTML = `<div class="appointment-range">${range.start} 至 ${range.end} · ${data.events.length || 0} 个预约</div><div id="fullCalendarBox" class="fullcalendar-box"></div>`;
|
||||
const initialView = appointmentView === 'month' ? 'dayGridMonth' : appointmentView === 'week' ? 'timeGridWeek' : 'timeGridDay';
|
||||
const calendar = new FullCalendar.Calendar(document.getElementById('fullCalendarBox'), {
|
||||
initialView,
|
||||
initialDate: appointmentDate,
|
||||
locale: 'zh-cn',
|
||||
height: 'auto',
|
||||
nowIndicator: true,
|
||||
slotMinTime: '09:00:00',
|
||||
slotMaxTime: '21:00:00',
|
||||
headerToolbar: false,
|
||||
eventTimeFormat: { hour: '2-digit', minute: '2-digit', hour12: false },
|
||||
events: data.events.map(ev => ({
|
||||
id: ev.id,
|
||||
title: ev.title || '-',
|
||||
start: (ev.start || '').replace(' ', 'T'),
|
||||
end: (ev.end || '').replace(' ', 'T'),
|
||||
className: [`fc-status-${ev.status || 'pending'}`],
|
||||
extendedProps: ev,
|
||||
})),
|
||||
eventClick(info) {
|
||||
const ev = info.event.extendedProps;
|
||||
showAppointmentActionDialog(ev, range);
|
||||
},
|
||||
dateClick(info) {
|
||||
appointmentDate = info.dateStr.slice(0, 10);
|
||||
showAppointmentDialog();
|
||||
},
|
||||
});
|
||||
calendar.render();
|
||||
}
|
||||
|
||||
function showAppointmentActionDialog(ev, range) {
|
||||
modal('预约操作', `<div class="detail-row"><div class="detail-label">预约</div><div class="detail-value">${escapeHtml(ev.title || '-')}</div></div><div class="detail-row"><div class="detail-label">时间</div><div class="detail-value">${formatDate(ev.start)} - ${String(ev.end || '').substring(11,16)}</div></div><div class="detail-row"><div class="detail-label">状态</div><div class="detail-value">${escapeHtml(ev.status || '-')}</div></div><div class="filter-bar"><button class="btn btn-secondary" id="aptDlgConfirm">确认</button><button class="btn btn-primary" id="aptDlgComplete">完成</button><button class="btn btn-danger" id="aptDlgCancel">取消</button></div>`, async () => {});
|
||||
document.getElementById('aptDlgConfirm').onclick = async () => { await api.confirmAppointment(ev.id); document.querySelector('.modal-overlay')?.remove(); await renderAppointmentBoard(range); };
|
||||
document.getElementById('aptDlgCancel').onclick = async () => { const reason = prompt('取消原因') || ''; await api.cancelAppointment(ev.id, { reason }); document.querySelector('.modal-overlay')?.remove(); await renderAppointmentBoard(range); };
|
||||
document.getElementById('aptDlgComplete').onclick = async () => { const consume = confirm('是否完成并扣减关联套餐1次?'); await api.completeAppointment(ev.id, consume ? { consume: true, consumeCount: 1 } : {}); document.querySelector('.modal-overlay')?.remove(); await renderAppointmentBoard(range); };
|
||||
}
|
||||
|
||||
function bindAppointmentActions(board, range) {
|
||||
board.querySelectorAll('[data-jump-apt]').forEach(btn => btn.onclick = () => {
|
||||
const target = board.querySelector(`[data-apt-open="${btn.dataset.jumpApt}"]`);
|
||||
const cal = board.querySelector('.resource-calendar');
|
||||
if (target && cal) cal.scrollTop = Math.max(0, target.offsetTop - 80);
|
||||
});
|
||||
board.querySelectorAll('[data-apt-open]').forEach(el => el.onclick = (event) => {
|
||||
event.stopPropagation();
|
||||
const id = el.dataset.aptOpen;
|
||||
showAppointmentActionDialog({ id, title: el.textContent, start: '', end: '', status: '' }, range);
|
||||
});
|
||||
board.querySelectorAll('.resource-slot').forEach(slot => slot.onclick = () => {
|
||||
appointmentDate = val('aptDate') || appointmentDate;
|
||||
showAppointmentDialog('', slot.dataset.emp, `${appointmentDate}T${slot.dataset.time}`);
|
||||
});
|
||||
board.querySelectorAll('[data-apt-confirm]').forEach(btn => btn.onclick = async () => { await api.confirmAppointment(btn.dataset.aptConfirm); await renderAppointmentBoard(range); });
|
||||
board.querySelectorAll('[data-apt-cancel]').forEach(btn => btn.onclick = async () => { const reason = prompt('取消原因') || ''; await api.cancelAppointment(btn.dataset.aptCancel, { reason }); await renderAppointmentBoard(range); });
|
||||
board.querySelectorAll('[data-apt-complete]').forEach(btn => btn.onclick = async () => { const consume = confirm('是否完成并扣减关联套餐1次?'); await api.completeAppointment(btn.dataset.aptComplete, consume ? { consume: true, consumeCount: 1 } : {}); await renderAppointmentBoard(range); });
|
||||
}
|
||||
|
||||
function renderDayEventSummary(events) {
|
||||
if (!events.length) return '<div class="appointment-day-summary empty">当天暂无预约</div>';
|
||||
return `<div class="appointment-day-summary">${events.map(ev => `<button type="button" data-jump-apt="${ev.id}" class="appointment-summary-chip"><strong>${String(ev.start || '').slice(11,16)}</strong> ${escapeHtml(ev.title || '-')}</button>`).join('')}</div>`;
|
||||
}
|
||||
|
||||
function renderResourceDayCalendar(resources, events) {
|
||||
const startHour = 9, endHour = 21, slotHeight = 44;
|
||||
const totalSlots = (endHour - startHour) * 2;
|
||||
const times = Array.from({ length: totalSlots + 1 }, (_, i) => {
|
||||
const minutes = startHour * 60 + i * 30;
|
||||
return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
||||
});
|
||||
const eventsByEmp = {};
|
||||
events.forEach(ev => { (eventsByEmp[ev.resourceId] ||= []).push(ev); });
|
||||
return `<div class="resource-calendar" style="--slot-h:${slotHeight}px"><div class="resource-time-axis"><div class="resource-corner">时间</div>${times.slice(0, -1).map(t => `<div class="resource-time">${t}</div>`).join('')}</div><div class="resource-columns">${resources.map(r => `<div class="resource-column"><div class="resource-head">${escapeHtml(r.title)}${r.number ? `(${r.number}号)` : ''}</div><div class="resource-slots">${times.slice(0, -1).map((t, idx) => `<div class="resource-slot" data-emp="${r.id}" data-time="${t}"></div>`).join('')}${(eventsByEmp[r.id] || []).map(ev => resourceEventBlock(ev, startHour, slotHeight)).join('')}</div></div>`).join('')}</div></div>`;
|
||||
}
|
||||
|
||||
function resourceEventBlock(ev, startHour, slotHeight) {
|
||||
const sm = timeToMinutes(ev.start), em = timeToMinutes(ev.end);
|
||||
const top = Math.max(0, (sm - startHour * 60) / 30 * slotHeight);
|
||||
const height = Math.max(slotHeight, (em - sm) / 30 * slotHeight - 4);
|
||||
return `<div class="resource-event status-${ev.status}" style="top:${top}px;height:${height}px" data-apt-open="${ev.id}"><strong>${escapeHtml(ev.title || '-')}</strong><br><span>${String(ev.start || '').slice(11,16)}-${String(ev.end || '').slice(11,16)}</span></div>`;
|
||||
}
|
||||
|
||||
function timeToMinutes(dt) {
|
||||
const t = String(dt || '').slice(11, 16).split(':');
|
||||
return (Number(t[0]) || 0) * 60 + (Number(t[1]) || 0);
|
||||
}
|
||||
|
||||
function renderDayCalendar(resources, events) {
|
||||
const eventsByEmp = {};
|
||||
events.forEach(ev => { (eventsByEmp[ev.resourceId] ||= []).push(ev); });
|
||||
return `<div class="calendar-day-grid">${resources.map(r => `<div class="calendar-employee-col"><div class="calendar-employee-head">${escapeHtml(r.title)}${r.number ? `(${r.number}号)` : ''}</div>${(eventsByEmp[r.id] || []).length ? (eventsByEmp[r.id] || []).map(eventCard).join('') : '<div class="appointment-empty">暂无预约</div>'}</div>`).join('')}</div>`;
|
||||
}
|
||||
|
||||
function renderWeekCalendar(range, events) {
|
||||
const days = dateRangeList(range.start, range.end);
|
||||
const byDay = groupEventsByDay(events);
|
||||
return `<div class="calendar-week-grid">${days.map(d => `<div class="calendar-day-cell"><div class="calendar-day-head">${formatDayLabel(d)}</div>${(byDay[d] || []).length ? byDay[d].map(compactEventCard).join('') : '<div class="calendar-no-event">空</div>'}</div>`).join('')}</div>`;
|
||||
}
|
||||
|
||||
function renderMonthCalendar(range, events) {
|
||||
const start = new Date(range.start + 'T00:00:00');
|
||||
const first = new Date(start.getFullYear(), start.getMonth(), 1);
|
||||
const gridStart = new Date(first); gridStart.setDate(first.getDate() - first.getDay());
|
||||
const byDay = groupEventsByDay(events);
|
||||
const cells = [];
|
||||
for (let i = 0; i < 42; i++) { const d = new Date(gridStart); d.setDate(gridStart.getDate() + i); cells.push(dateInput(d)); }
|
||||
return `<div class="calendar-month"><div class="calendar-weekdays">${['日','一','二','三','四','五','六'].map(w => `<div>周${w}</div>`).join('')}</div><div class="calendar-month-grid">${cells.map(d => `<div class="calendar-month-cell ${d.slice(5,7) !== range.start.slice(5,7) ? 'muted-month' : ''}"><div class="calendar-month-date">${Number(d.slice(8,10))}</div>${(byDay[d] || []).slice(0,3).map(compactEventCard).join('')}${(byDay[d] || []).length > 3 ? `<div class="calendar-more">+${(byDay[d] || []).length - 3}更多</div>` : ''}</div>`).join('')}</div></div>`;
|
||||
}
|
||||
|
||||
function groupEventsByDay(events) {
|
||||
const m = {};
|
||||
events.forEach(e => { const d = String(e.start || '').slice(0, 10); (m[d] ||= []).push(e); });
|
||||
return m;
|
||||
}
|
||||
function dateRangeList(start, end) {
|
||||
const arr = []; const s = new Date(start + 'T00:00:00'); const e = new Date(end + 'T00:00:00');
|
||||
for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) arr.push(dateInput(d));
|
||||
return arr;
|
||||
}
|
||||
function formatDayLabel(d) { const x = new Date(d + 'T00:00:00'); return `${x.getMonth()+1}/${x.getDate()} 周${'日一二三四五六'[x.getDay()]}`; }
|
||||
function compactEventCard(ev) { return `<div class="calendar-compact-event status-${ev.status}" title="${escapeHtml(ev.title || '')}"><span>${String(ev.start || '').slice(11,16)}</span> ${escapeHtml(ev.title || '-')}</div>`; }
|
||||
|
||||
function eventCard(ev) {
|
||||
return `<div class="appointment-event status-${ev.status}"><div><strong>${escapeHtml(ev.title || '-')}</strong></div><div>${formatDate(ev.start)} - ${String(ev.end || '').substring(11,16)}</div><div class="muted">${escapeHtml(ev.status || '')}</div><div class="appointment-actions"><button class="btn btn-secondary btn-sm" data-apt-confirm="${ev.id}">确认</button><button class="btn btn-primary btn-sm" data-apt-complete="${ev.id}">完成</button><button class="btn btn-danger btn-sm" data-apt-cancel="${ev.id}">取消</button></div></div>`;
|
||||
}
|
||||
|
||||
async function showAvailabilityDialog() {
|
||||
const date = val('aptDate') || appointmentDate;
|
||||
const emp = val('aptEmployee');
|
||||
const params = new URLSearchParams({ date, duration_minutes: 60 });
|
||||
if (emp) params.set('employee_id', emp);
|
||||
try {
|
||||
const res = await api.getAppointmentAvailability(params.toString());
|
||||
const slots = res.data?.slots || [];
|
||||
modal('可预约空档', `<div class="slot-grid">${slots.map(s => `<div class="slot-item ${s.available ? 'available' : 'busy'}"><strong>${escapeHtml(s.employeeName)}</strong><br>${s.start}-${s.end}<br>${s.available ? '可约' : '已占用'}</div>`).join('') || '暂无空档'}</div>`, async () => {});
|
||||
} catch (e) { alert('加载空档失败:' + e.message); }
|
||||
}
|
||||
|
||||
async function showAppointmentDialog(defaultMemberId = '', defaultEmployeeId = '', defaultStartAt = '') {
|
||||
let employees = [];
|
||||
try { employees = (await api.getEmployees('page=1&page_size=100')).data?.list || []; } catch (e) {}
|
||||
modal('新增预约', `
|
||||
${memberPicker('apt')}
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">员工</label><select id="aptEmp" class="form-input">${employees.map(e => `<option value="${e.id}" ${e.id === (defaultEmployeeId || val('aptEmployee')) ? 'selected' : ''}>${escapeHtml(e.name)}${e.number ? `(${e.number}号)` : ''}</option>`).join('')}</select></div><div class="form-group"><label class="form-label">客户已购套餐/产品</label><select id="aptMp" class="form-input"><option value="">请先选择客户</option></select></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">开始时间</label><input id="aptStart" type="datetime-local" class="form-input" value="${defaultStartAt || appointmentDate + 'T10:00'}"></div><div class="form-group"><label class="form-label">时长分钟</label><input id="aptDuration" type="number" class="form-input" value="60"></div></div>
|
||||
<div id="aptProductInfo" class="muted" style="margin-bottom:12px">选择客户后展示客户剩余套餐。</div>
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="aptNotes" class="form-input"></textarea></div>`,
|
||||
() => {
|
||||
const opt = document.getElementById('aptMp')?.selectedOptions?.[0];
|
||||
appointmentDate = (val('aptStart') || appointmentDate).slice(0, 10);
|
||||
appointmentView = 'day';
|
||||
return api.createAppointment({ memberId: pickedMember('apt'), employeeId: val('aptEmp'), memberProductId: val('aptMp'), productName: opt?.dataset?.name || '', startAt: val('aptStart'), durationMinutes: val('aptDuration'), storeNotes: val('aptNotes'), source: 'admin' });
|
||||
}
|
||||
);
|
||||
fillMemberPicker('apt');
|
||||
wireAppointmentMemberPicker();
|
||||
if (defaultMemberId) {
|
||||
document.getElementById('aptMemberManual').value = defaultMemberId;
|
||||
loadAppointmentMemberProducts(defaultMemberId);
|
||||
}
|
||||
}
|
||||
|
||||
function wireAppointmentMemberPicker() {
|
||||
const input = document.getElementById('aptMemberKeyword');
|
||||
const manual = document.getElementById('aptMemberManual');
|
||||
input?.addEventListener('member-selected', (e) => loadAppointmentMemberProducts(e.detail.id));
|
||||
manual?.addEventListener('change', () => loadAppointmentMemberProducts(manual.value));
|
||||
}
|
||||
|
||||
async function loadAppointmentMemberProducts(memberId) {
|
||||
const sel = document.getElementById('aptMp');
|
||||
const info = document.getElementById('aptProductInfo');
|
||||
if (!sel || !memberId) return;
|
||||
try {
|
||||
const res = await api.getCrmMemberProducts(new URLSearchParams({ page: 1, page_size: 100, member_id: memberId, status: 1 }).toString());
|
||||
const list = res.data?.list || [];
|
||||
sel.innerHTML = list.length ? list.map(p => `<option value="${p.id}" data-name="${escapeHtml(p.productName)}" data-duration="${p.durationMinutes || 60}">${escapeHtml(p.productName)} · 剩余${p.balanceCount || 0}/${p.totalCount || 0}次 · ¥${p.balanceAmount || 0}</option>`).join('') : '<option value="">该客户暂无可用套餐</option>';
|
||||
if (list.length) {
|
||||
document.getElementById('aptDuration').value = sel.selectedOptions[0].dataset.duration || 60;
|
||||
info.textContent = `当前选择:${sel.selectedOptions[0].textContent}`;
|
||||
} else {
|
||||
info.textContent = '该客户暂无可用套餐,也可以先去客户详情购买产品/套餐。';
|
||||
}
|
||||
sel.onchange = () => {
|
||||
document.getElementById('aptDuration').value = sel.selectedOptions[0]?.dataset.duration || 60;
|
||||
info.textContent = `当前选择:${sel.selectedOptions[0]?.textContent || '-'}`;
|
||||
};
|
||||
} catch (e) {
|
||||
info.textContent = '加载客户套餐失败:' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadVisits(el) {
|
||||
el.innerHTML = listShell('到店记录', '新增到店', 'visitAddBtn', '', ['客户ID','员工ID','到店','离店','耗时','项目','消费','满意度']);
|
||||
document.getElementById('visitAddBtn').onclick = () => showVisitDialog();
|
||||
try {
|
||||
const res = await api.getCrmVisits(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, v => `<tr><td><strong>${escapeHtml(v.memberName || '-')}</strong><div class="muted">${escapeHtml(v.memberId || '-')}</div></td><td>${escapeHtml(v.employeeId || '-')}</td><td>${formatDate(v.arriveAt)}</td><td>${formatDate(v.leaveAt)}</td><td>${v.durationMinutes || '-'} 分钟</td><td>${tags(v.serviceItems)}</td><td>¥${v.consumptionAmount || 0}</td><td>${satisfactionBadge(v.satisfaction)}</td></tr>`);
|
||||
} catch (e) { tableError(e, 8); }
|
||||
}
|
||||
|
||||
async function loadProducts(el) {
|
||||
el.innerHTML = listShell('产品管理', '新增产品', 'productAddBtn', '', ['名称','分类','类型','价格','默认次数','状态','操作']);
|
||||
document.getElementById('productAddBtn').onclick = () => showProductDialog();
|
||||
try {
|
||||
const res = await api.getCrmProducts(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, p => `<tr><td><strong>${escapeHtml(p.productName)}</strong><div class="muted">${escapeHtml(p.description || '')}</div></td><td>${escapeHtml(p.category || '-')}</td><td>${escapeHtml(p.productType || '-')}</td><td>¥${p.price || 0}</td><td>${p.defaultCount || 0}</td><td>${statusBadge(p.status)}</td><td><button class="btn btn-primary btn-sm" data-buy-product="${p.id}" data-name="${escapeHtml(p.productName)}" data-count="${p.defaultCount || 0}" data-price="${p.price || 0}">客户购买</button></td></tr>`);
|
||||
document.querySelectorAll('[data-buy-product]').forEach(btn => btn.onclick = () => showPurchaseDialog(btn.dataset.buyProduct, btn.dataset.name, btn.dataset.count, btn.dataset.price));
|
||||
} catch (e) { tableError(e, 7); }
|
||||
}
|
||||
|
||||
async function loadMemberProducts(el) {
|
||||
el.innerHTML = listShell('客户已购产品/套餐', '', '', '', ['客户','产品/套餐','剩余次数','剩余金额','有效期','状态','操作']);
|
||||
try {
|
||||
const res = await api.getCrmMemberProducts(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, p => `<tr><td><strong>${escapeHtml(p.memberName || '-')}</strong><div class="muted">${escapeHtml(p.memberId)}</div></td><td>${escapeHtml(p.productName)}</td><td>${p.balanceCount || 0}/${p.totalCount || 0}</td><td>¥${p.balanceAmount || 0}/¥${p.totalAmount || 0}</td><td>${p.validEnd || '-'}</td><td>${packageStatus(p.status)}</td><td><button class="btn btn-primary btn-sm" data-consume-product="${p.id}" data-name="${escapeHtml(p.productName)}">消费</button></td></tr>`);
|
||||
document.querySelectorAll('[data-consume-product]').forEach(btn => btn.onclick = () => showProductConsumeDialog(btn.dataset.consumeProduct, btn.dataset.name));
|
||||
} catch (e) { tableError(e, 7); }
|
||||
}
|
||||
|
||||
async function loadProductConsumes(el) {
|
||||
el.innerHTML = listShell('产品/套餐消费记录', '', '', '', ['客户','已购产品ID','到店ID','消费次数','消费金额','剩余次数','剩余金额','备注','时间']);
|
||||
try {
|
||||
const res = await api.getCrmProductConsumes(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, c => `<tr><td><strong>${escapeHtml(c.memberName || '-')}</strong><div class="muted">${escapeHtml(c.memberId)}</div></td><td>${escapeHtml(c.memberProductId)}</td><td>${escapeHtml(c.visitId || '-')}</td><td>${c.consumeCount || 0}</td><td>¥${c.consumeAmount || 0}</td><td>${c.balanceCountAfter || 0}</td><td>¥${c.balanceAmountAfter || 0}</td><td>${escapeHtml(c.notes || '-')}</td><td>${formatDate(c.createDate)}</td></tr>`);
|
||||
} catch (e) { tableError(e, 9); }
|
||||
}
|
||||
|
||||
async function loadAccounts(el) {
|
||||
el.innerHTML = listShell('账户管理', '开卡/建账户', 'accountAddBtn', '', ['客户ID','卡名称','类型','余额','次数','有效期','状态','操作']);
|
||||
document.getElementById('accountAddBtn').onclick = () => showAccountDialog();
|
||||
try {
|
||||
const res = await api.getCrmAccounts(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, a => `<tr><td><strong>${escapeHtml(a.memberName || '-')}</strong><div class="muted">${escapeHtml(a.memberId)}</div></td><td>${escapeHtml(a.cardName || '-')}</td><td>${escapeHtml(a.accountType)}</td><td>¥${a.balanceAmount || 0}</td><td>${a.balanceCount || 0}/${a.totalCount || 0}</td><td>${a.validEnd || '-'}</td><td>${accountStatus(a.status)}</td><td><button class="btn btn-primary btn-sm" data-consume-account="${a.id}" data-card="${escapeHtml(a.cardName || '')}">消费</button> <button class="btn btn-danger btn-sm" data-close-account="${a.id}">销卡</button></td></tr>`);
|
||||
document.querySelectorAll('[data-consume-account]').forEach(btn => btn.onclick = () => showConsumeDialog(btn.dataset.consumeAccount, btn.dataset.card));
|
||||
document.querySelectorAll('[data-close-account]').forEach(btn => btn.onclick = () => showCloseDialog(btn.dataset.closeAccount));
|
||||
} catch (e) { tableError(e, 8); }
|
||||
}
|
||||
|
||||
async function loadTransactions(el) {
|
||||
el.innerHTML = listShell('账户流水', '', '', '', ['客户','账户ID','类型','金额','次数','变动前','变动后','备注','时间']);
|
||||
try {
|
||||
const res = await api.getCrmAccountTransactions(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, t => `<tr><td><strong>${escapeHtml(t.memberName || '-')}</strong><div class="muted">${escapeHtml(t.memberId)}</div></td><td>${escapeHtml(t.accountId)}</td><td>${txType(t.transactionType)}</td><td>${t.amount || 0}</td><td>${t.countChange || 0}</td><td>¥${t.balanceBefore || 0}</td><td>¥${t.balanceAfter || 0}</td><td>${escapeHtml(t.notes || '-')}</td><td>${formatDate(t.createDate)}</td></tr>`);
|
||||
} catch (e) { tableError(e, 9); }
|
||||
}
|
||||
|
||||
async function loadCardCloses(el) {
|
||||
el.innerHTML = listShell('销卡管理', '', '', '', ['客户ID','账户ID','原因','退款','剩余次数','状态','反馈ID','时间']);
|
||||
try {
|
||||
const res = await api.getCrmCardCloses(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, c => `<tr><td><strong>${escapeHtml(c.memberName || '-')}</strong><div class="muted">${escapeHtml(c.memberId)}</div></td><td>${escapeHtml(c.accountId)}</td><td>${escapeHtml(c.reason || '-')}</td><td>¥${c.refundAmount || 0}</td><td>${c.remainingCount || 0}</td><td>${escapeHtml(c.status)}</td><td>${escapeHtml(c.feedbackRecordId || '-')}</td><td>${formatDate(c.createDate)}</td></tr>`);
|
||||
} catch (e) { tableError(e, 8); }
|
||||
}
|
||||
|
||||
async function loadSuggestions(el) {
|
||||
el.innerHTML = listShell('建议管理', '新增建议', 'suggestionAddBtn', '', ['内容','标签','优先级','提出人','来源','次数','状态','处理说明','时间','操作']);
|
||||
document.getElementById('suggestionAddBtn').onclick = () => showSuggestionDialog();
|
||||
try {
|
||||
const res = await api.getCrmSuggestions(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, s => `<tr><td>${escapeHtml(s.content)}<div class="muted">${escapeHtml(s.category || '-')}</div></td><td>${tags(s.tags)}</td><td>${priorityBadge(s.priority)}</td><td><strong>${escapeHtml(s.submitterName || s.memberName || '-')}</strong><div class="muted">${escapeHtml(s.memberName && s.submitterName && s.memberName !== s.submitterName ? s.memberName : s.memberId || '-')}</div></td><td>${escapeHtml(s.source || '-')}</td><td>${s.frequency || 1}</td><td>${suggestionStatusBadge(s.status)}</td><td>${escapeHtml(s.handleNotes || '-')}</td><td>${formatDate(s.createDate)}</td><td><button class="btn btn-primary btn-sm" data-sug-adopting="${s.id}">采纳中</button> <button class="btn btn-primary btn-sm" data-sug-adopt="${s.id}">已采纳</button> <button class="btn btn-secondary btn-sm" data-sug-ignore="${s.id}">忽略</button></td></tr>`);
|
||||
document.querySelectorAll('[data-sug-adopting]').forEach(btn => btn.onclick = () => showSuggestionStatusDialog(btn.dataset.sugAdopting, 'adopting'));
|
||||
document.querySelectorAll('[data-sug-adopt]').forEach(btn => btn.onclick = () => showSuggestionStatusDialog(btn.dataset.sugAdopt, 'adopted'));
|
||||
document.querySelectorAll('[data-sug-ignore]').forEach(btn => btn.onclick = () => showSuggestionStatusDialog(btn.dataset.sugIgnore, 'ignored'));
|
||||
} catch (e) { tableError(e, 10); }
|
||||
}
|
||||
|
||||
async function loadIssues(el) {
|
||||
el.innerHTML = listShell('问题修复', '新增问题', 'issueAddBtn', '', ['标题','分类','严重度','状态','负责人','修复方案','时间','操作']);
|
||||
document.getElementById('issueAddBtn').onclick = () => showIssueDialog();
|
||||
try {
|
||||
const res = await api.getCrmIssues(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString());
|
||||
renderRows(res.data || {}, i => `<tr><td>${escapeHtml(i.title)}</td><td>${escapeHtml(i.category || '-')}</td><td>${escapeHtml(i.severity)}</td><td>${escapeHtml(i.status)}</td><td>${escapeHtml(i.assignedTo || '-')}</td><td>${escapeHtml(i.fixPlan || '-')}</td><td>${formatDate(i.createDate)}</td><td><button class="btn btn-primary btn-sm" data-issue-fixed="${i.id}">标记修复</button></td></tr>`);
|
||||
document.querySelectorAll('[data-issue-fixed]').forEach(btn => btn.onclick = () => updateIssue(btn.dataset.issueFixed, { status: 'fixed' }));
|
||||
} catch (e) { tableError(e, 8); }
|
||||
}
|
||||
|
||||
function listShell(title, addText, addId, filters, headers) {
|
||||
return `<div class="card"><div class="filter-bar"><div class="card-title" style="margin:0;flex:1">${title}</div>${filters || ''}${addText ? `<button class="btn btn-primary btn-sm" id="${addId}">${addText}</button>` : ''}</div><div class="table-wrap"><table><thead><tr>${headers.map(h => `<th>${h}</th>`).join('')}</tr></thead><tbody id="crmTableBody"><tr><td colspan="${headers.length}" class="loading"><div class="spinner"></div></td></tr></tbody></table></div><div id="crmPagination" class="pagination"></div></div>`;
|
||||
}
|
||||
|
||||
function renderRows(data, rowFn) {
|
||||
const tbody = document.getElementById('crmTableBody');
|
||||
const list = data.list || [];
|
||||
if (!list.length) { tbody.innerHTML = `<tr><td colspan="20" class="empty-state">暂无数据</td></tr>`; return; }
|
||||
tbody.innerHTML = list.map(rowFn).join('');
|
||||
renderPagination(data);
|
||||
}
|
||||
function renderPagination(data) {
|
||||
const el = document.getElementById('crmPagination'); if (!el) return;
|
||||
const total = data.total || 0; const totalPages = Math.ceil(total / pageSize) || 1;
|
||||
el.innerHTML = `<div class="pagination-info">共 ${total} 条,第 ${currentPage}/${totalPages} 页</div><div class="pagination-btns"><button ${currentPage<=1?'disabled':''} id="crmPrev">上一页</button><button class="active">${currentPage}</button><button ${currentPage>=totalPages?'disabled':''} id="crmNext">下一页</button></div>`;
|
||||
document.getElementById('crmPrev')?.addEventListener('click', () => { currentPage--; loadTab(); });
|
||||
document.getElementById('crmNext')?.addEventListener('click', () => { currentPage++; loadTab(); });
|
||||
}
|
||||
function tableError(e, colspan) { document.getElementById('crmTableBody').innerHTML = `<tr><td colspan="${colspan}" class="empty-state">加载失败:${escapeHtml(e.message)}</td></tr>`; }
|
||||
function error(e) { return `<div class="empty-state">加载失败:${escapeHtml(e.message)}</div>`; }
|
||||
function tags(arr) { if (!arr) return ''; if (typeof arr === 'string') return `<span class="badge badge-gray">${escapeHtml(arr)}</span>`; return (arr || []).map(x => `<span class="badge badge-blue" style="margin-right:4px">${escapeHtml(x)}</span>`).join(''); }
|
||||
function accountStatus(s) { return s === 1 ? '<span class="badge badge-green">使用中</span>' : s === 0 ? '<span class="badge badge-red">已销卡</span>' : '<span class="badge badge-yellow">已过期</span>'; }
|
||||
function packageStatus(s) { return s === 1 ? '<span class="badge badge-green">使用中</span>' : s === 0 ? '<span class="badge badge-gray">已用完</span>' : '<span class="badge badge-yellow">已过期</span>'; }
|
||||
function priorityBadge(p) { const map = { urgent: ['紧急','badge-red'], high: ['高','badge-yellow'], medium: ['中','badge-blue'], low: ['低','badge-gray'] }; const it = map[p] || map.medium; return `<span class="badge ${it[1]}">${it[0]}</span>`; }
|
||||
function suggestionStatusBadge(s) { const map = { pending: ['待处理','badge-yellow'], adopting: ['采纳中','badge-blue'], adopted: ['已采纳','badge-green'], ignored: ['已忽略','badge-gray'], duplicate: ['重复','badge-gray'] }; const it = map[s] || [s || '-', 'badge-gray']; return `<span class="badge ${it[1]}">${it[0]}</span>`; }
|
||||
function txType(t) {
|
||||
const map = { recharge: '充值/开卡', consume: '消费', refund: '退款', close: '销卡', adjust: '调整' };
|
||||
const cls = t === 'consume' || t === 'close' ? 'badge-yellow' : 'badge-green';
|
||||
return `<span class="badge ${cls}">${map[t] || escapeHtml(t || '-')}</span>`;
|
||||
}
|
||||
|
||||
function modal(title, body, onSave) {
|
||||
const overlay = document.createElement('div'); overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `<div class="modal-card"><div class="modal-header"><h3>${title}</h3><button class="modal-close">×</button></div><div class="modal-body">${body}<div class="login-error" id="crmModalErr"></div></div><div class="modal-footer"><button class="btn btn-secondary" id="crmCancel">取消</button><button class="btn btn-primary" id="crmSave">保存</button></div></div>`;
|
||||
document.body.appendChild(overlay); const close = () => document.body.removeChild(overlay);
|
||||
overlay.querySelector('.modal-close').onclick = close; overlay.querySelector('#crmCancel').onclick = close;
|
||||
overlay.querySelector('#crmSave').onclick = async () => { try { await onSave(); close(); loadTab(); } catch(e) { document.getElementById('crmModalErr').textContent = e.message || '保存失败'; } };
|
||||
}
|
||||
function val(id) { return document.getElementById(id)?.value.trim(); }
|
||||
function dateInput(d) {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
function jsonList(s) { return s ? s.split(/[,,\n]/).map(x => x.trim()).filter(Boolean) : []; }
|
||||
function fillMemberPicker(prefix) {
|
||||
const input = document.getElementById(`${prefix}MemberKeyword`);
|
||||
const dropdown = document.getElementById(`${prefix}MemberDropdown`);
|
||||
const idEl = document.getElementById(`${prefix}Member`);
|
||||
const manualEl = document.getElementById(`${prefix}MemberManual`);
|
||||
if (!input || !dropdown || !idEl) return;
|
||||
let timer = null;
|
||||
const search = async () => {
|
||||
const kw = input.value.trim();
|
||||
idEl.value = '';
|
||||
if (!kw) { dropdown.innerHTML = ''; dropdown.classList.remove('open'); return; }
|
||||
try {
|
||||
const res = await api.getCrmMembers(new URLSearchParams({ page: 1, page_size: 10, keyword: kw }).toString());
|
||||
const list = res.data?.list || [];
|
||||
dropdown.innerHTML = list.length ? list.map(m => `<div class="member-option" data-id="${m.id}" data-label="${escapeHtml((m.name || '-') + ' · ' + (m.phone || '-'))}"><strong>${escapeHtml(m.name || '-')}</strong><span>${escapeHtml(m.phone || '-')}</span></div>`).join('') : '<div class="member-option disabled">未找到客户</div>';
|
||||
dropdown.classList.add('open');
|
||||
dropdown.querySelectorAll('.member-option[data-id]').forEach(opt => opt.onclick = () => {
|
||||
idEl.value = opt.dataset.id;
|
||||
input.value = opt.dataset.label;
|
||||
if (manualEl) manualEl.value = '';
|
||||
dropdown.classList.remove('open');
|
||||
input.dispatchEvent(new CustomEvent('member-selected', { detail: { id: opt.dataset.id } }));
|
||||
});
|
||||
} catch (e) {
|
||||
dropdown.innerHTML = `<div class="member-option disabled">搜索失败:${escapeHtml(e.message)}</div>`;
|
||||
dropdown.classList.add('open');
|
||||
}
|
||||
};
|
||||
input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(search, 250); });
|
||||
input.addEventListener('focus', () => { if (dropdown.innerHTML) dropdown.classList.add('open'); });
|
||||
document.addEventListener('click', (e) => { if (!e.target.closest(`#${prefix}MemberBox`)) dropdown.classList.remove('open'); });
|
||||
}
|
||||
function memberPicker(prefix, label = '客户') {
|
||||
return `<div class="form-group member-combobox" id="${prefix}MemberBox"><label class="form-label">${label}</label><input id="${prefix}MemberKeyword" class="form-input" autocomplete="off" placeholder="输入姓名/手机号搜索并选择"><input id="${prefix}Member" type="hidden"><div id="${prefix}MemberDropdown" class="member-dropdown"></div><input id="${prefix}MemberManual" class="form-input member-manual" placeholder="客户ID备用输入(可选)"></div>`;
|
||||
}
|
||||
function pickedMember(prefix) { return val(`${prefix}Member`) || val(`${prefix}MemberManual`); }
|
||||
function mekai66Form(prefix, values = {}) {
|
||||
const groups = {};
|
||||
MEKAI66_FIELDS.forEach(f => { (groups[f.category] ||= []).push(f); });
|
||||
return `<div class="form-group"><label class="form-label">麦凯66客户档案</label><div class="mekai66-grid">${Object.entries(groups).map(([cat, fields]) => `<div class="mekai66-group"><div class="mekai66-title">${cat}</div>${fields.map(f => `<label class="mekai66-field"><span>${f.label}</span><input id="${prefix}Mekai_${f.key}" class="form-input" value="${escapeHtml(values?.[f.key] || '')}"></label>`).join('')}</div>`).join('')}</div></div>`;
|
||||
}
|
||||
function collectMekai66(prefix) {
|
||||
const data = {};
|
||||
MEKAI66_FIELDS.forEach(f => {
|
||||
const value = val(`${prefix}Mekai_${f.key}`);
|
||||
if (value) data[f.key] = value;
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
function showMemberDialog() {
|
||||
modal('新增客户', `
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label class="form-label">姓名</label><input id="mName" class="form-input"></div>
|
||||
<div class="form-group"><label class="form-label">手机号</label><input id="mPhone" class="form-input"></div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label class="form-label">微信号</label><input id="mWechat" class="form-input"></div>
|
||||
<div class="form-group"><label class="form-label">客户等级</label><input id="mLevel" class="form-input" placeholder="VIP/老客/新客"></div>
|
||||
</div>
|
||||
<div class="form-group"><label class="form-label">美容关注点(逗号分隔)</label><input id="mBeauty" class="form-input" placeholder="皮肤干燥,肩颈"></div>
|
||||
<div class="form-group"><label class="form-label">身体不适/疾病/禁忌</label><textarea id="mHealth" class="form-input"></textarea></div>
|
||||
<div class="form-group"><label class="form-label">过敏信息</label><textarea id="mAllergies" class="form-input"></textarea></div>
|
||||
${mekai66Form('m')}
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="mNotes" class="form-input"></textarea></div>`,
|
||||
() => api.createCrmMember({
|
||||
name: val('mName'), phone: val('mPhone'), wechat: val('mWechat'), level: val('mLevel'),
|
||||
beautyConcerns: jsonList(val('mBeauty')), healthIssues: jsonList(val('mHealth')),
|
||||
allergies: val('mAllergies'), mekaiTags: collectMekai66('m'), notes: val('mNotes')
|
||||
})
|
||||
);
|
||||
}
|
||||
function showEditMemberDialog(m) {
|
||||
modal('编辑客户', `
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label class="form-label">姓名</label><input id="emName" class="form-input" value="${escapeHtml(m.name || '')}"></div>
|
||||
<div class="form-group"><label class="form-label">手机号</label><input id="emPhone" class="form-input" value="${escapeHtml(m.phone || '')}"></div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label class="form-label">微信号</label><input id="emWechat" class="form-input" value="${escapeHtml(m.wechat || '')}"></div>
|
||||
<div class="form-group"><label class="form-label">客户等级</label><input id="emLevel" class="form-input" value="${escapeHtml(m.level || '')}"></div>
|
||||
</div>
|
||||
<div class="form-group"><label class="form-label">美容关注点</label><input id="emBeauty" class="form-input" value="${escapeHtml((m.beautyConcerns || []).join ? m.beautyConcerns.join(',') : (m.beautyConcerns || ''))}"></div>
|
||||
<div class="form-group"><label class="form-label">身体不适/疾病/禁忌</label><textarea id="emHealth" class="form-input">${escapeHtml((m.healthIssues || []).join ? m.healthIssues.join('\n') : (m.healthIssues || ''))}</textarea></div>
|
||||
<div class="form-group"><label class="form-label">过敏信息</label><textarea id="emAllergies" class="form-input">${escapeHtml(m.allergies || '')}</textarea></div>
|
||||
${mekai66Form('em', m.mekaiTags || {})}
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="emNotes" class="form-input">${escapeHtml(m.notes || '')}</textarea></div>`,
|
||||
() => api.updateCrmMember(m.id, {
|
||||
name: val('emName'), phone: val('emPhone'), wechat: val('emWechat'), level: val('emLevel'),
|
||||
beautyConcerns: jsonList(val('emBeauty')), healthIssues: jsonList(val('emHealth')),
|
||||
allergies: val('emAllergies'), mekaiTags: collectMekai66('em'), notes: val('emNotes')
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function showVisitDialog(defaultMemberId = '') {
|
||||
modal('新增到店记录', `
|
||||
${memberPicker('v')}
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">员工ID</label><input id="vEmp" class="form-input"></div><div class="form-group"><label class="form-label">满意度</label><select id="vSat" class="form-input"><option value="">未填写</option><option value="very_satisfied">非常满意</option><option value="satisfied">满意</option><option value="unsatisfied">不满意</option><option value="very_bad">很差</option></select></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">到店时间</label><input id="vArrive" type="datetime-local" class="form-input"></div><div class="form-group"><label class="form-label">离店时间</label><input id="vLeave" type="datetime-local" class="form-input"></div></div>
|
||||
<div class="form-group"><label class="form-label">服务项目</label><input id="vItems" class="form-input"></div>
|
||||
<div class="form-group"><label class="form-label">消费金额</label><input id="vAmount" type="number" class="form-input"></div>`,
|
||||
() => api.createCrmVisit({ memberId: pickedMember('v'), employeeId: val('vEmp'), arriveAt: val('vArrive'), leaveAt: val('vLeave'), serviceItems: jsonList(val('vItems')), consumptionAmount: val('vAmount'), satisfaction: val('vSat') })
|
||||
);
|
||||
fillMemberPicker('v');
|
||||
if (defaultMemberId) document.getElementById('vMemberManual').value = defaultMemberId;
|
||||
}
|
||||
function showAccountDialog(defaultMemberId = '') {
|
||||
modal('开卡/建账户', `
|
||||
${memberPicker('a')}
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">卡名称</label><input id="aName" class="form-input"></div><div class="form-group"><label class="form-label">类型</label><select id="aType" class="form-input"><option value="balance">储值卡</option><option value="count">次卡</option><option value="course">疗程卡</option></select></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">金额</label><input id="aAmount" type="number" class="form-input"></div><div class="form-group"><label class="form-label">次数</label><input id="aCount" type="number" class="form-input"></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">有效期开始</label><input id="aStart" type="date" class="form-input"></div><div class="form-group"><label class="form-label">有效期结束</label><input id="aEnd" type="date" class="form-input"></div></div>`,
|
||||
() => api.createCrmAccount({ memberId: pickedMember('a'), cardName: val('aName'), accountType: val('aType'), totalAmount: val('aAmount'), totalCount: val('aCount'), validStart: val('aStart'), validEnd: val('aEnd') })
|
||||
);
|
||||
fillMemberPicker('a');
|
||||
if (defaultMemberId) document.getElementById('aMemberManual').value = defaultMemberId;
|
||||
}
|
||||
function showBodyStatusDialog(defaultMemberId = '') {
|
||||
modal('新增身体变化状态', `
|
||||
${memberPicker('bs')}
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">体重kg(默认指标)</label><input id="bsWeight" type="number" class="form-input"></div><div class="form-group"><label class="form-label">腰围cm(默认指标)</label><input id="bsWaist" type="number" class="form-input"></div></div>
|
||||
<div class="form-group"><label class="form-label">自定义身体标签</label><input id="bsMetricName" class="form-input" placeholder="如:膝盖积液 / 脚踝扭伤 / 肩颈酸痛"></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">状态</label><select id="bsMetricStatus" class="form-input"><option value="没啥效果">没啥效果</option><option value="有改善">有改善</option><option value="有好转">有好转</option><option value="明显好转">明显好转</option></select></div><div class="form-group"><label class="form-label">好转数值(可选)</label><input id="bsMetricValue" type="number" class="form-input" placeholder="如疼痛减少3分"></div></div>
|
||||
<div class="form-group"><label class="form-label">描述记录</label><textarea id="bsNotes" class="form-input" placeholder="如:膝盖最近温度变高;脚踝变好,开车不疼了"></textarea></div>`,
|
||||
() => api.createCrmBodyStatus({ memberId: pickedMember('bs'), weight: val('bsWeight'), waistline: val('bsWaist'), metrics: { name: val('bsMetricName'), status: val('bsMetricStatus'), value: val('bsMetricValue') }, notes: val('bsNotes') })
|
||||
);
|
||||
fillMemberPicker('bs');
|
||||
if (defaultMemberId) document.getElementById('bsMemberManual').value = defaultMemberId;
|
||||
}
|
||||
function showProductDialog() {
|
||||
modal('新增产品/套餐', `
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">产品名称</label><input id="pName" class="form-input" placeholder="养生减肥10次套餐"></div><div class="form-group"><label class="form-label">分类</label><input id="pCategory" class="form-input" placeholder="减肥/养生/美容"></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">类型</label><select id="pType" class="form-input"><option value="package">套餐</option><option value="service">服务项目</option><option value="product">实物产品</option></select></div><div class="form-group"><label class="form-label">默认次数</label><input id="pCount" type="number" class="form-input" value="1"></div></div>
|
||||
<div class="form-group"><label class="form-label">价格</label><input id="pPrice" type="number" class="form-input" value="0"></div>
|
||||
<div class="form-group"><label class="form-label">说明</label><textarea id="pDesc" class="form-input"></textarea></div>`,
|
||||
() => api.createCrmProduct({ productName: val('pName'), category: val('pCategory'), productType: val('pType'), defaultCount: val('pCount'), price: val('pPrice'), description: val('pDesc') })
|
||||
);
|
||||
}
|
||||
async function showMemberPurchaseDialog(memberId) {
|
||||
try {
|
||||
const res = await api.getCrmProducts('page=1&page_size=100&status=1');
|
||||
const products = res.data?.list || [];
|
||||
if (!products.length) { alert('暂无产品,请先到产品管理新增产品/套餐'); return; }
|
||||
const today = new Date();
|
||||
const nextYear = new Date(today); nextYear.setFullYear(today.getFullYear() + 1);
|
||||
modal('客户购买产品/套餐', `
|
||||
<input id="buyFixedMember" type="hidden" value="${escapeHtml(memberId)}">
|
||||
<div class="form-group"><label class="form-label">选择产品/套餐</label><select id="buyProductSelect" class="form-input">${products.map(p => `<option value="${p.id}" data-count="${p.defaultCount || 1}" data-price="${p.price || 0}">${escapeHtml(p.productName)} · ¥${p.price || 0} · ${p.defaultCount || 1}次</option>`).join('')}</select></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">单价</label><input id="buyFixedUnit" type="number" class="form-input" value="${products[0].price || 0}"></div><div class="form-group"><label class="form-label">数量/次数</label><input id="buyFixedCount" type="number" class="form-input" value="${products[0].defaultCount || 1}"></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">折扣(10=原价,8.5=八五折)</label><input id="buyFixedDiscount" type="number" step="0.1" class="form-input" value="10"></div><div class="form-group"><label class="form-label">购买金额</label><input id="buyFixedAmount" type="number" class="form-input" value="${(Number(products[0].price || 0) * Number(products[0].defaultCount || 1)).toFixed(2)}"></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">有效期开始</label><input id="buyFixedStart" type="date" class="form-input" value="${dateInput(today)}"></div><div class="form-group"><label class="form-label">有效期结束</label><input id="buyFixedEnd" type="date" class="form-input" value="${dateInput(nextYear)}"></div></div>
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="buyFixedNotes" class="form-input"></textarea></div>`,
|
||||
() => api.purchaseCrmProduct({ productId: val('buyProductSelect'), memberId, unitPrice: val('buyFixedUnit'), purchaseCount: val('buyFixedCount'), discount: Number(val('buyFixedDiscount') || 10) / 10, totalCount: val('buyFixedCount'), totalAmount: val('buyFixedAmount'), validStart: val('buyFixedStart'), validEnd: val('buyFixedEnd'), notes: val('buyFixedNotes') })
|
||||
);
|
||||
const recalc = () => { document.getElementById('buyFixedAmount').value = (Number(val('buyFixedUnit') || 0) * Number(val('buyFixedCount') || 0) * (Number(val('buyFixedDiscount') || 10) / 10)).toFixed(2); };
|
||||
document.getElementById('buyProductSelect').onchange = (e) => {
|
||||
const opt = e.target.selectedOptions[0];
|
||||
document.getElementById('buyFixedUnit').value = opt.dataset.price || 0;
|
||||
document.getElementById('buyFixedCount').value = opt.dataset.count || 1;
|
||||
recalc();
|
||||
};
|
||||
['buyFixedUnit','buyFixedCount','buyFixedDiscount'].forEach(id => document.getElementById(id).oninput = recalc);
|
||||
} catch (e) { alert('加载产品失败:' + e.message); }
|
||||
}
|
||||
function showPurchaseDialog(productId, productName, count, price) {
|
||||
modal(`客户购买 - ${escapeHtml(productName || '')}`, `
|
||||
${memberPicker('buy')}
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">总次数</label><input id="buyCount" type="number" class="form-input" value="${escapeHtml(count || '1')}"></div><div class="form-group"><label class="form-label">购买金额</label><input id="buyAmount" type="number" class="form-input" value="${escapeHtml(price || '0')}"></div></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">有效期开始</label><input id="buyStart" type="date" class="form-input"></div><div class="form-group"><label class="form-label">有效期结束</label><input id="buyEnd" type="date" class="form-input"></div></div>
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="buyNotes" class="form-input"></textarea></div>`,
|
||||
() => api.purchaseCrmProduct({ productId, memberId: pickedMember('buy'), totalCount: val('buyCount'), totalAmount: val('buyAmount'), validStart: val('buyStart'), validEnd: val('buyEnd'), notes: val('buyNotes') })
|
||||
);
|
||||
fillMemberPicker('buy');
|
||||
}
|
||||
function showProductConsumeDialog(memberProductId, productName = '') {
|
||||
modal(`套餐消费 - ${escapeHtml(productName || '')}`, `
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">消费次数</label><input id="pcCount" type="number" class="form-input" value="1"></div><div class="form-group"><label class="form-label">消费金额</label><input id="pcAmount" type="number" class="form-input" value="0"></div></div>
|
||||
<div class="form-group"><label class="form-label">关联到店记录ID(可选,不填自动关联最近到店)</label><input id="pcVisit" class="form-input"></div>
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="pcNotes" class="form-input"></textarea></div>`,
|
||||
() => api.consumeCrmProduct(memberProductId, { consumeCount: val('pcCount'), consumeAmount: val('pcAmount'), visitId: val('pcVisit'), notes: val('pcNotes') })
|
||||
);
|
||||
}
|
||||
function showConsumeDialog(accountId, cardName = '') {
|
||||
modal(`账户消费 ${cardName ? ' - ' + escapeHtml(cardName) : ''}`, `
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">扣减金额</label><input id="xAmount" type="number" class="form-input" value="0"></div><div class="form-group"><label class="form-label">扣减次数</label><input id="xCount" type="number" class="form-input" value="0"></div></div>
|
||||
<div class="form-group"><label class="form-label">关联到店记录ID(可选)</label><input id="xVisit" class="form-input"></div>
|
||||
<div class="form-group"><label class="form-label">备注</label><textarea id="xNotes" class="form-input" placeholder="例如:肩颈调理消费1次"></textarea></div>`,
|
||||
() => api.consumeCrmAccount(accountId, { amount: val('xAmount'), countChange: val('xCount'), visitId: val('xVisit'), notes: val('xNotes') })
|
||||
);
|
||||
}
|
||||
function showCloseDialog(accountId) { modal('销卡', `<div class="form-group"><label class="form-label">销卡原因</label><textarea id="cReason" class="form-input"></textarea><div class="muted">如包含“不满意/没效果/投诉/退款”等关键词,系统会自动创建待修复问题。</div></div><div class="form-group"><label class="form-label">退款金额</label><input id="cRefund" type="number" class="form-input"></div><div class="form-group"><label class="form-label">关联反馈ID(可选)</label><input id="cFeedback" class="form-input"></div><div class="form-group"><label class="form-label">负责人(可选)</label><input id="cAssigned" class="form-input"></div>`, () => api.closeCrmCard({ accountId, reason: val('cReason'), refundAmount: val('cRefund'), feedbackRecordId: val('cFeedback'), assignedTo: val('cAssigned') })); }
|
||||
function showSuggestionDialog() { modal('新增建议', `<div class="form-group"><label class="form-label">建议内容</label><textarea id="sContent" class="form-input"></textarea></div><div class="form-group"><label class="form-label">分类</label><input id="sCategory" class="form-input" placeholder="服务/环境/价格"></div>`, () => api.createCrmSuggestion({ content: val('sContent'), category: val('sCategory') })); }
|
||||
function showIssueDialog() { modal('新增问题', `<div class="form-group"><label class="form-label">标题</label><input id="iTitle" class="form-input"></div><div class="form-row"><div class="form-group"><label class="form-label">分类</label><input id="iCategory" class="form-input"></div><div class="form-group"><label class="form-label">严重度</label><select id="iSeverity" class="form-input"><option value="low">低</option><option value="medium">中</option><option value="high">高</option><option value="critical">严重</option></select></div></div><div class="form-group"><label class="form-label">描述</label><textarea id="iDesc" class="form-input"></textarea></div><div class="form-group"><label class="form-label">负责人</label><input id="iAssigned" class="form-input"></div>`, () => api.createCrmIssue({ title: val('iTitle'), category: val('iCategory'), severity: val('iSeverity'), description: val('iDesc'), assignedTo: val('iAssigned') })); }
|
||||
function showSuggestionStatusDialog(id, status) {
|
||||
const titleMap = { adopting: '标记采纳中', adopted: '标记已采纳', ignored: '忽略建议' };
|
||||
const title = titleMap[status] || '更新建议';
|
||||
const noteLabel = status === 'ignored' ? '忽略原因/处理说明' : '采纳方案/处理说明';
|
||||
modal(title, `<div class="form-group"><label class="form-label">${noteLabel}</label><textarea id="sHandleNotes" class="form-input"></textarea></div>`,
|
||||
() => api.updateCrmSuggestionStatus(id, {
|
||||
status,
|
||||
handleNotes: val('sHandleNotes'),
|
||||
rejectedReason: status === 'rejected' ? val('sHandleNotes') : ''
|
||||
})
|
||||
);
|
||||
}
|
||||
async function updateIssue(id, data) { await api.updateCrmIssue(id, data); loadTab(); }
|
||||
function bindDetailButtons(list) {
|
||||
document.querySelectorAll('[data-detail]').forEach(btn => {
|
||||
btn.onclick = async () => {
|
||||
try {
|
||||
const res = await api.getCrmMember(btn.dataset.detail);
|
||||
showMemberDetail(res.data || {});
|
||||
} catch (e) {
|
||||
alert(e.message || '加载客户详情失败');
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function showMemberDetail(m) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card crm-detail-modal">
|
||||
<div class="modal-header">
|
||||
<h3>${escapeHtml(m.name || '客户详情')} <span class="badge badge-blue">${escapeHtml(m.level || '客户')}</span></h3>
|
||||
<button class="modal-close" id="memberDetailClose">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="crm-detail-actions">
|
||||
<button class="btn btn-primary btn-sm" id="detailAddBody">记录身体变化</button>
|
||||
<button class="btn btn-primary btn-sm" id="detailBuyProduct">购买产品/套餐</button>
|
||||
<button class="btn btn-primary btn-sm" id="detailAddAppointment">预约服务</button>
|
||||
<button class="btn btn-secondary btn-sm" id="detailAddVisit">新增到店</button>
|
||||
<button class="btn btn-secondary btn-sm" id="detailAddAccount">开卡/建账户</button>
|
||||
<button class="btn btn-secondary btn-sm" id="detailEditMember">编辑客户</button>
|
||||
</div>
|
||||
<div class="crm-profile-head">
|
||||
<div><div class="muted">手机号</div><strong>${escapeHtml(m.phone || '-')}</strong></div>
|
||||
<div><div class="muted">微信</div><strong>${escapeHtml(m.wechat || '-')}</strong></div>
|
||||
<div><div class="muted">到店次数</div><strong>${m.totalVisits || 0}</strong></div>
|
||||
<div><div class="muted">累计消费</div><strong>¥${m.totalSpent || 0}</strong></div>
|
||||
</div>
|
||||
${detailSection('美容关注', tags(m.beautyConcerns) || '-')}
|
||||
${detailSection('身体不适/疾病/禁忌', tags(m.healthIssues) || '-')}
|
||||
${detailSection('过敏信息', escapeHtml(m.allergies || '-'))}
|
||||
${detailSection('麦凯66/客户信息', `<pre class="crm-pre">${escapeHtml(JSON.stringify(m.mekaiTags || {}, null, 2))}</pre>`)}
|
||||
${detailSection('备注', escapeHtml(m.notes || '-'))}
|
||||
${bodyTrendSection(m.bodyStatuses || [])}
|
||||
${timelineSection('身体变化', m.bodyStatuses, b => `${formatDate(b.recordDate)} · 体重${b.weight ?? '-'}kg · 腰围${b.waistline ?? '-'}cm · ${escapeHtml(b.metrics?.name || '身体状态')}:${escapeHtml(b.metrics?.status || '-')} ${b.metrics?.value ? `(${escapeHtml(b.metrics.value)})` : ''} · ${escapeHtml(b.notes || '')}`)}
|
||||
${timelineSection('到店记录', m.visits, v => `${formatDate(v.arriveAt)} · ${v.durationMinutes || '-'}分钟 · ${tags(v.serviceItems)} · ¥${v.consumptionAmount || 0}`)}
|
||||
${timelineSection('账户/卡', m.accounts, a => `${escapeHtml(a.cardName || a.accountType)} · 余额 ¥${a.balanceAmount || 0} · 剩余 ${a.balanceCount || 0} 次 · ${accountStatus(a.status)}`)}
|
||||
${timelineSection('账户流水', m.transactions, t => `${formatDate(t.createDate)} · ${txType(t.transactionType)} · 金额 ${t.amount || 0} · 次数 ${t.countChange || 0} · 余额 ¥${t.balanceAfter || 0} · ${escapeHtml(t.notes || '')}`)}
|
||||
${timelineSection('已购产品/套餐', m.products, p => `${escapeHtml(p.productName)} · 剩余 ${p.balanceCount || 0}/${p.totalCount || 0} 次 · ¥${p.balanceAmount || 0}/¥${p.totalAmount || 0} · ${packageStatus(p.status)}`)}
|
||||
${timelineSection('产品消费记录', m.productConsumes, c => `${formatDate(c.createDate)} · 消费${c.consumeCount || 0}次 · ¥${c.consumeAmount || 0} · 剩余${c.balanceCountAfter || 0}次 · ${escapeHtml(c.notes || '')}`)}
|
||||
${timelineSection('客户反馈', m.feedbacks, f => `${formatDate(f.createDate)} · ${satisfactionBadge(f.satisfaction)} · ${escapeHtml(truncate(f.cleanedText || f.rawAsrText || '-', 120))}`)}
|
||||
${timelineSection('建议', m.suggestions, s => `${escapeHtml(s.content)} · ${suggestionStatusBadge(s.status)} · ${priorityBadge(s.priority)} · ${tags(s.tags)} · ${s.frequency || 1}次`)}
|
||||
</div>
|
||||
<div class="modal-footer"><button class="btn btn-secondary" id="memberDetailCloseBtn">关闭</button></div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('memberDetailClose').onclick = close;
|
||||
document.getElementById('memberDetailCloseBtn').onclick = close;
|
||||
document.getElementById('detailAddBody').onclick = () => { close(); showBodyStatusDialog(m.id); };
|
||||
document.getElementById('detailBuyProduct').onclick = () => { close(); showMemberPurchaseDialog(m.id); };
|
||||
document.getElementById('detailAddAppointment').onclick = () => { close(); showAppointmentDialog(m.id); };
|
||||
document.getElementById('detailAddVisit').onclick = () => { close(); showVisitDialog(m.id); };
|
||||
document.getElementById('detailAddAccount').onclick = () => { close(); showAccountDialog(m.id); };
|
||||
document.getElementById('detailEditMember').onclick = () => { close(); showEditMemberDialog(m); };
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
}
|
||||
|
||||
function bodyTrendSection(list) {
|
||||
if (!list || list.length < 2) return '';
|
||||
const sorted = [...list].reverse();
|
||||
const first = sorted[0];
|
||||
const last = sorted[sorted.length - 1];
|
||||
const delta = (key, unit = '') => {
|
||||
if (first[key] == null || last[key] == null) return '-';
|
||||
const d = Number(last[key]) - Number(first[key]);
|
||||
return `${d > 0 ? '+' : ''}${d}${unit}`;
|
||||
};
|
||||
const latestMetrics = (list || []).slice(0, 3).map(b => `${escapeHtml(b.metrics?.name || '身体状态')}:${escapeHtml(b.metrics?.status || '-')} ${b.notes ? '· ' + escapeHtml(b.notes) : ''}`).join('<br>') || '-';
|
||||
return `<div class="crm-detail-section"><div class="crm-detail-title">身体变化趋势</div><div class="crm-trend-grid"><div>体重变化<br><strong>${delta('weight', 'kg')}</strong></div><div>腰围变化<br><strong>${delta('waistline', 'cm')}</strong></div><div style="grid-column: span 2">最近标签变化<br><strong style="font-size:13px;line-height:1.5">${latestMetrics}</strong></div></div></div>`;
|
||||
}
|
||||
|
||||
function detailSection(title, body) {
|
||||
return `<div class="crm-detail-section"><div class="crm-detail-title">${title}</div><div class="crm-detail-body">${body}</div></div>`;
|
||||
}
|
||||
|
||||
function timelineSection(title, list, render) {
|
||||
const rows = (list || []).length
|
||||
? list.map(item => `<li>${render(item)}</li>`).join('')
|
||||
: '<li class="muted">暂无</li>';
|
||||
return `<div class="crm-detail-section"><div class="crm-detail-title">${title}</div><ul class="crm-timeline">${rows}</ul></div>`;
|
||||
}
|
||||
|
||||
window.CrmForms = {
|
||||
'crm.member.create': (payload = {}) => {
|
||||
showMemberDialog();
|
||||
setTimeout(() => {
|
||||
FormCopilot.fill({
|
||||
mName: payload.name,
|
||||
mPhone: payload.phone,
|
||||
mBeauty: payload.beautyConcerns,
|
||||
mHealth: payload.healthIssues,
|
||||
mNotes: payload.notes,
|
||||
});
|
||||
if (payload.gender) document.getElementById('mMekai_gender') && (document.getElementById('mMekai_gender').value = payload.gender === 1 ? '男' : '女');
|
||||
Object.entries(payload.mekaiTags || {}).forEach(([k, v]) => FormCopilot.setValue(`mMekai_${k}`, v));
|
||||
}, 80);
|
||||
},
|
||||
'crm.product.create': (payload = {}) => {
|
||||
showProductDialog();
|
||||
setTimeout(() => FormCopilot.fill({
|
||||
pName: payload.productName,
|
||||
pCategory: payload.category,
|
||||
pType: payload.productType,
|
||||
pCount: payload.defaultCount,
|
||||
pPrice: payload.price,
|
||||
pDesc: payload.description,
|
||||
}), 80);
|
||||
},
|
||||
'crm.appointment.create': (payload = {}) => {
|
||||
showAppointmentDialog('', '', '');
|
||||
setTimeout(() => {
|
||||
FormCopilot.fill({ aptStart: normalizeStartHint(payload.startHint), aptProductName: payload.serviceKeyword });
|
||||
if (payload.employeeName) selectEmployeeByName('aptEmp', payload.employeeName);
|
||||
}, 120);
|
||||
},
|
||||
'crm.body_status.create': (payload = {}) => showBodyStatusDialog(payload.memberId || ''),
|
||||
'crm.product.purchase': (payload = {}) => showMemberPurchaseDialog(payload.memberId || ''),
|
||||
'crm.suggestion.create': (payload = {}) => showSuggestionDialog(payload.content || ''),
|
||||
};
|
||||
|
||||
function selectEmployeeByName(selectId, name) {
|
||||
const sel = document.getElementById(selectId); if (!sel || !name) return;
|
||||
const opt = Array.from(sel.options).find(o => o.textContent.includes(name));
|
||||
if (opt) sel.value = opt.value;
|
||||
}
|
||||
function normalizeStartHint(hint) {
|
||||
if (!hint) return '';
|
||||
const base = new Date();
|
||||
if (hint.includes('明天')) base.setDate(base.getDate() + 1);
|
||||
if (hint.includes('后天')) base.setDate(base.getDate() + 2);
|
||||
let hour = 10;
|
||||
const cn = { '一':1, '二':2, '两':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '十':10 };
|
||||
const m = hint.match(/(\d{1,2}|[一二两三四五六七八九十])点/);
|
||||
if (m) hour = /^\d+$/.test(m[1]) ? Number(m[1]) : cn[m[1]] || hour;
|
||||
if (hint.includes('下午') && hour < 12) hour += 12;
|
||||
return `${dateInput(base)}T${String(hour).padStart(2,'0')}:00`;
|
||||
}
|
||||
254
main/feedback-backend/admin-ui/js/pages/dashboard.js
Normal file
254
main/feedback-backend/admin-ui/js/pages/dashboard.js
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
// Dashboard - 统计概览
|
||||
import { api } from '../api.js';
|
||||
|
||||
export async function renderDashboard(container) {
|
||||
container.innerHTML = '<div class="loading"><div class="spinner"></div><p>加载中...</p></div>';
|
||||
|
||||
try {
|
||||
const [overviewRes, dailyRes, storeRes, employeeKpiRes] = await Promise.all([
|
||||
api.getOverview(),
|
||||
api.getDailyStats(),
|
||||
api.getStoreStats(),
|
||||
api.getEmployeeKpi(),
|
||||
]);
|
||||
|
||||
const overview = overviewRes.data || {};
|
||||
const daily = dailyRes.data || [];
|
||||
const storeStats = storeRes.data || [];
|
||||
const employeeKpi = employeeKpiRes.data || [];
|
||||
|
||||
container.innerHTML = `
|
||||
<!-- Stat Cards -->
|
||||
<div class="stat-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon blue">📋</div>
|
||||
<div class="stat-info">
|
||||
<div class="stat-label">总反馈数</div>
|
||||
<div class="stat-value">${overview.total_records || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon green">😊</div>
|
||||
<div class="stat-info">
|
||||
<div class="stat-label">满意率</div>
|
||||
<div class="stat-value">${overview.satisfaction_rate || 0}%</div>
|
||||
<div class="stat-sub">满意 ${overview.satisfied || 0} + 非常满意 ${overview.very_satisfied || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon yellow">😕</div>
|
||||
<div class="stat-info">
|
||||
<div class="stat-label">不满意</div>
|
||||
<div class="stat-value">${overview.unsatisfied || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon red">😡</div>
|
||||
<div class="stat-info">
|
||||
<div class="stat-label">很差</div>
|
||||
<div class="stat-value">${overview.very_bad || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-chart-grid">
|
||||
<!-- Satisfaction Distribution -->
|
||||
<div class="card">
|
||||
<div class="card-title">满意度分布</div>
|
||||
<div id="satChart" class="chart-container"></div>
|
||||
</div>
|
||||
|
||||
<!-- Daily Trend -->
|
||||
<div class="card">
|
||||
<div class="card-title">每日反馈趋势</div>
|
||||
<div id="trendChart" class="chart-container"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Store Stats Table -->
|
||||
<div class="card" style="margin-top:20px;">
|
||||
<div class="card-title">门店统计</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>门店</th>
|
||||
<th>编码</th>
|
||||
<th>反馈数</th>
|
||||
<th>满意率</th>
|
||||
<th>非常满意</th>
|
||||
<th>满意</th>
|
||||
<th>不满意</th>
|
||||
<th>很差</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${storeStats.length === 0 ? '<tr><td colspan="8" class="empty-state">暂无数据</td></tr>' :
|
||||
storeStats.map(s => {
|
||||
const storeName = s.storeName || s.store_name || '-';
|
||||
const storeCode = s.storeCode || s.store_code || '-';
|
||||
const totalRecords = s.totalRecords ?? s.total_records ?? 0;
|
||||
const satisfactionRate = s.satisfactionRate ?? s.satisfaction_rate ?? 0;
|
||||
const satisfactionDistribution = s.satisfactionDistribution || s.satisfaction_distribution || {};
|
||||
return `
|
||||
<tr>
|
||||
<td>${escapeHtml(storeName)}</td>
|
||||
<td>${storeCode}</td>
|
||||
<td><strong>${totalRecords}</strong></td>
|
||||
<td><strong style="color:${satisfactionRate >= 80 ? '#059669' : satisfactionRate >= 50 ? '#D97706' : '#DC2626'}">${satisfactionRate}%</strong></td>
|
||||
<td>${satisfactionDistribution.very_satisfied || 0}</td>
|
||||
<td>${satisfactionDistribution.satisfied || 0}</td>
|
||||
<td>${satisfactionDistribution.unsatisfied || 0}</td>
|
||||
<td>${satisfactionDistribution.very_bad || 0}</td>
|
||||
</tr>`;
|
||||
}).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top:20px;">
|
||||
<div class="card-title">员工KPI(好评 / 中评 / 差评)</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>员工</th><th>工号</th><th>总反馈</th><th>好评</th><th>中评</th><th>差评</th><th>好评率</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
${employeeKpi.length === 0 ? '<tr><td colspan="8" class="empty-state">暂无员工评价数据</td></tr>' : employeeKpi.map(e => `
|
||||
<tr>
|
||||
<td>${escapeHtml(e.employeeName || '-')}</td>
|
||||
<td>${escapeHtml(e.employeeNumber || '-')}</td>
|
||||
<td><strong>${e.total || 0}</strong></td>
|
||||
<td><span class="badge badge-green">${e.good || 0}</span></td>
|
||||
<td><span class="badge badge-yellow">${e.middle || 0}</span></td>
|
||||
<td><span class="badge badge-red">${e.bad || 0}</span></td>
|
||||
<td><strong style="color:${(e.goodRate || 0) >= 80 ? '#059669' : (e.goodRate || 0) >= 50 ? '#D97706' : '#DC2626'}">${e.goodRate || 0}%</strong></td>
|
||||
<td><button class="btn btn-secondary btn-sm employee-records-btn" data-id="${escapeHtml(e.employeeId || '')}" data-name="${escapeHtml(e.employeeName || '')}">评价明细</button></td>
|
||||
</tr>`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.querySelectorAll('.employee-records-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => showEmployeeRecords(btn.dataset.id, btn.dataset.name));
|
||||
});
|
||||
|
||||
// Render simple charts (no ECharts dependency - pure canvas)
|
||||
renderSatChart(overview);
|
||||
renderTrendChart(daily);
|
||||
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="empty-state"><div class="icon">⚠️</div><p>加载失败: ${e.message}</p></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function showEmployeeRecords(employeeId, employeeName) {
|
||||
if (!employeeId) return;
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card" style="max-width:820px">
|
||||
<div class="modal-header"><h3>${escapeHtml(employeeName || '员工')}评价明细</h3><button class="modal-close" id="empRecClose">×</button></div>
|
||||
<div class="modal-body">
|
||||
<div class="filter-bar">
|
||||
<select id="empRecGroup" class="form-input">
|
||||
<option value="">全部评价</option>
|
||||
<option value="good">好评</option>
|
||||
<option value="middle">中评</option>
|
||||
<option value="bad">差评</option>
|
||||
</select>
|
||||
<button class="btn btn-primary btn-sm" id="empRecSearch">查询</button>
|
||||
</div>
|
||||
<div id="empRecBody" class="loading"><div class="spinner"></div></div>
|
||||
</div>
|
||||
<div class="modal-footer"><button class="btn btn-secondary" id="empRecCloseBtn">关闭</button></div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('empRecClose').onclick = close;
|
||||
document.getElementById('empRecCloseBtn').onclick = close;
|
||||
document.getElementById('empRecSearch').onclick = () => loadEmployeeRecords(employeeId);
|
||||
loadEmployeeRecords(employeeId);
|
||||
}
|
||||
|
||||
async function loadEmployeeRecords(employeeId) {
|
||||
const body = document.getElementById('empRecBody');
|
||||
if (!body) return;
|
||||
body.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
|
||||
const params = new URLSearchParams({ employee_id: employeeId, page: 1, page_size: 50 });
|
||||
const group = document.getElementById('empRecGroup')?.value;
|
||||
if (group) params.set('satisfaction_group', group);
|
||||
try {
|
||||
const res = await api.getEmployeeRecords(params.toString());
|
||||
const list = res.data?.list || [];
|
||||
body.innerHTML = list.length ? `<div class="table-wrap"><table><thead><tr><th>满意度</th><th>点评/反馈</th><th>时间</th></tr></thead><tbody>${list.map(r => `<tr><td>${satisfactionBadge(r.satisfaction)}</td><td><div>${escapeHtml(r.reviewLong || r.reviewShort || truncate(r.cleanedText || r.rawAsrText || '-', 160))}</div><div class="muted">反馈ID:${escapeHtml(r.id)}</div></td><td>${formatDate(r.createDate)}</td></tr>`).join('')}</tbody></table></div>` : '<div class="empty-state">暂无评价明细</div>';
|
||||
} catch (e) {
|
||||
body.innerHTML = `<div class="empty-state">加载失败:${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderSatChart(overview) {
|
||||
const el = document.getElementById('satChart');
|
||||
if (!el) return;
|
||||
|
||||
const dist = overview.satisfactionDistribution || overview.satisfaction_distribution || {};
|
||||
const data = [
|
||||
{ label: '非常满意', value: dist.very_satisfied || 0, color: '#059669', bg: '#ECFDF5' },
|
||||
{ label: '满意', value: dist.satisfied || 0, color: '#10B981', bg: '#F0FDF4' },
|
||||
{ label: '不满意', value: dist.unsatisfied || 0, color: '#F59E0B', bg: '#FFFBEB' },
|
||||
{ label: '很差', value: dist.very_bad || 0, color: '#EF4444', bg: '#FEF2F2' },
|
||||
];
|
||||
|
||||
const total = data.reduce((s, d) => s + d.value, 0);
|
||||
if (total === 0) {
|
||||
el.innerHTML = '<div class="empty-state"><p>暂无满意度数据</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="sat-summary">
|
||||
<div class="sat-total">${total}</div>
|
||||
<div><div class="sat-total-label">总反馈</div><div class="sat-rate">满意率 ${overview.satisfaction_rate || 0}%</div></div>
|
||||
</div>
|
||||
<div class="sat-bars">
|
||||
${data.map(d => {
|
||||
const percent = total > 0 ? Math.round(d.value / total * 100) : 0;
|
||||
return `
|
||||
<div class="sat-row">
|
||||
<div class="sat-row-head">
|
||||
<span class="sat-dot" style="background:${d.color}"></span>
|
||||
<span class="sat-name">${d.label}</span>
|
||||
<span class="sat-num">${d.value} · ${percent}%</span>
|
||||
</div>
|
||||
<div class="sat-track" style="background:${d.bg}"><div class="sat-fill" style="width:${percent}%;background:${d.color}"></div></div>
|
||||
</div>`;
|
||||
}).join('')}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderTrendChart(daily) {
|
||||
const el = document.getElementById('trendChart');
|
||||
if (!el) return;
|
||||
|
||||
if (!daily || daily.length === 0) {
|
||||
el.innerHTML = '<div class="empty-state"><p>暂无趋势数据</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const recent = daily.slice(-14);
|
||||
const maxVal = Math.max(...recent.map(d => d.count || 0), 1);
|
||||
el.innerHTML = `
|
||||
<div class="trend-bars">
|
||||
${recent.map(d => {
|
||||
const value = d.count || 0;
|
||||
const height = Math.max(8, Math.round(value / maxVal * 150));
|
||||
const dateStr = d.date ? d.date.substring(5) : '';
|
||||
return `
|
||||
<div class="trend-item" title="${dateStr}: ${value}">
|
||||
<div class="trend-value">${value}</div>
|
||||
<div class="trend-bar-wrap"><div class="trend-bar" style="height:${height}px"></div></div>
|
||||
<div class="trend-date">${dateStr}</div>
|
||||
</div>`;
|
||||
}).join('')}
|
||||
</div>`;
|
||||
}
|
||||
186
main/feedback-backend/admin-ui/js/pages/employees.js
Normal file
186
main/feedback-backend/admin-ui/js/pages/employees.js
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
// Employees - 员工管理
|
||||
import { api } from '../api.js';
|
||||
|
||||
let currentPage = 1;
|
||||
const pageSize = 20;
|
||||
|
||||
export async function renderEmployees(container) {
|
||||
container.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<input type="text" id="filterStoreId" class="form-input" placeholder="门店ID" style="width:160px">
|
||||
<input type="text" id="filterName" class="form-input" placeholder="员工姓名" style="width:120px">
|
||||
<button class="btn btn-primary btn-sm" id="filterBtn">查询</button>
|
||||
<div style="flex:1"></div>
|
||||
<button class="btn btn-primary btn-sm" id="addEmpBtn">+ 新增员工</button>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>姓名</th>
|
||||
<th>工号</th>
|
||||
<th>门店ID</th>
|
||||
<th>类型</th>
|
||||
<th>状态</th>
|
||||
<th>创建时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="empsBody">
|
||||
<tr><td colspan="8" class="loading"><div class="spinner"></div></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="pagination" class="pagination"></div>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('filterBtn').addEventListener('click', () => { currentPage = 1; loadEmployees(); });
|
||||
document.getElementById('addEmpBtn').addEventListener('click', () => showEmployeeForm());
|
||||
loadEmployees();
|
||||
}
|
||||
|
||||
async function loadEmployees() {
|
||||
const tbody = document.getElementById('empsBody');
|
||||
if (!tbody) return;
|
||||
|
||||
const storeId = document.getElementById('filterStoreId')?.value.trim() || '';
|
||||
const name = document.getElementById('filterName')?.value.trim() || '';
|
||||
const params = new URLSearchParams({ page: currentPage, page_size: pageSize });
|
||||
if (storeId) params.set('store_id', storeId);
|
||||
if (name) params.set('name', name);
|
||||
|
||||
try {
|
||||
const res = await api.getEmployees(params.toString());
|
||||
const data = res.data || {};
|
||||
|
||||
if (!data.list || data.list.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="empty-state"><p>暂无员工</p></td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.list.map(e => `
|
||||
<tr>
|
||||
<td style="font-size:11px;color:#9CA3AF">${escapeHtml(e.id).substring(0,8)}...</td>
|
||||
<td><strong>${escapeHtml(e.name)}</strong></td>
|
||||
<td>${e.number}</td>
|
||||
<td style="font-size:11px">${escapeHtml(e.storeId)}</td>
|
||||
<td>${employeeTypeBadge(e.employeeType)}</td>
|
||||
<td>${statusBadge(e.status)}</td>
|
||||
<td style="white-space:nowrap">${formatDate(e.createDate)}</td>
|
||||
<td>
|
||||
<button class="btn btn-secondary btn-sm edit-emp-btn" data-id="${e.id}">编辑</button>
|
||||
<button class="btn btn-danger btn-sm del-emp-btn" data-id="${e.id}">删除</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
|
||||
tbody.querySelectorAll('.edit-emp-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const emp = data.list.find(e => e.id === btn.dataset.id);
|
||||
if (emp) showEmployeeForm(emp);
|
||||
});
|
||||
});
|
||||
|
||||
tbody.querySelectorAll('.del-emp-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
if (!confirm('确定删除该员工?')) return;
|
||||
await api.deleteEmployee(btn.dataset.id);
|
||||
loadEmployees();
|
||||
});
|
||||
});
|
||||
|
||||
const total = data.total || 0;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
document.getElementById('pagination').innerHTML = `
|
||||
<div class="pagination-info">共 ${total} 条</div>
|
||||
<div class="pagination-btns">
|
||||
<button ${currentPage <= 1 ? 'disabled' : ''} id="prevPage">上一页</button>
|
||||
<button class="active">${currentPage}</button>
|
||||
<button ${currentPage >= totalPages ? 'disabled' : ''} id="nextPage">下一页</button>
|
||||
</div>`;
|
||||
document.getElementById('prevPage')?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; loadEmployees(); } });
|
||||
document.getElementById('nextPage')?.addEventListener('click', () => { if (currentPage < totalPages) { currentPage++; loadEmployees(); } });
|
||||
|
||||
} catch (e) {
|
||||
tbody.innerHTML = `<tr><td colspan="8" class="empty-state"><p>加载失败: ${e.message}</p></td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function showEmployeeForm(emp = null) {
|
||||
const isEdit = !!emp;
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<h3>${isEdit ? '编辑员工' : '新增员工'}</h3>
|
||||
<button class="modal-close" id="closeForm">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label class="form-label">员工姓名</label>
|
||||
<input type="text" id="formName" class="form-input" value="${emp?.name || ''}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">工号</label>
|
||||
<input type="number" id="formNumber" class="form-input" value="${emp?.number || ''}" min="1">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label class="form-label">门店 ID</label>
|
||||
<input type="text" id="formStoreId" class="form-input" value="${emp?.storeId || ''}" ${isEdit ? 'readonly' : ''}>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">员工类型</label>
|
||||
<select id="formType" class="form-input">
|
||||
<option value="normal" ${emp?.employeeType === 'normal' ? 'selected' : ''}>普通员工</option>
|
||||
<option value="manager" ${emp?.employeeType === 'manager' ? 'selected' : ''}>店长</option>
|
||||
<option value="excellent" ${emp?.employeeType === 'excellent' ? 'selected' : ''}>优秀员工</option>
|
||||
<option value="intern" ${emp?.employeeType === 'intern' ? 'selected' : ''}>实习生</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div id="formError" style="color:var(--danger);font-size:13px;min-height:20px;margin-top:8px"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="cancelBtn">取消</button>
|
||||
<button class="btn btn-primary" id="saveBtn">保存</button>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('closeForm').addEventListener('click', close);
|
||||
document.getElementById('cancelBtn').addEventListener('click', close);
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
|
||||
document.getElementById('saveBtn').addEventListener('click', async () => {
|
||||
const errEl = document.getElementById('formError');
|
||||
errEl.textContent = '';
|
||||
|
||||
const name = document.getElementById('formName').value.trim();
|
||||
const number = parseInt(document.getElementById('formNumber').value);
|
||||
const storeId = document.getElementById('formStoreId').value.trim();
|
||||
const empType = document.getElementById('formType').value;
|
||||
|
||||
if (!name || !number || !storeId) {
|
||||
errEl.textContent = '姓名、工号、门店ID 不能为空';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
await api.updateEmployee(emp.id, { name, number, employee_type: empType });
|
||||
} else {
|
||||
await api.createEmployee({ name, number, store_id: storeId, employee_type: empType });
|
||||
}
|
||||
close();
|
||||
loadEmployees();
|
||||
} catch (e) {
|
||||
errEl.textContent = '保存失败: ' + e.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
334
main/feedback-backend/admin-ui/js/pages/records.js
Normal file
334
main/feedback-backend/admin-ui/js/pages/records.js
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
// Records - 反馈记录列表
|
||||
import { api } from '../api.js';
|
||||
|
||||
let currentPage = 1;
|
||||
const pageSize = 20;
|
||||
|
||||
export async function renderRecords(container) {
|
||||
container.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<select id="filterStore" class="form-input" style="width:180px"><option value="">全部门店</option></select>
|
||||
<select id="filterEmployee" class="form-input" style="width:160px"><option value="">全部员工</option></select>
|
||||
<select id="filterSatisfaction" class="form-input">
|
||||
<option value="">全部满意度</option>
|
||||
<option value="very_satisfied">非常满意</option>
|
||||
<option value="satisfied">满意</option>
|
||||
<option value="unsatisfied">不满意</option>
|
||||
<option value="very_bad">很差</option>
|
||||
</select>
|
||||
<input type="date" id="filterStart" class="form-input" style="width:150px">
|
||||
<input type="date" id="filterEnd" class="form-input" style="width:150px">
|
||||
<button class="btn btn-primary btn-sm" id="filterBtn">查询</button>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:40px">#</th>
|
||||
<th>门店</th>
|
||||
<th>客户</th>
|
||||
<th>满意度</th>
|
||||
<th>原始文本</th>
|
||||
<th>清洗文本</th>
|
||||
<th>点评</th>
|
||||
<th>时间</th>
|
||||
<th style="width:60px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="recordsBody">
|
||||
<tr><td colspan="9" class="loading"><div class="spinner"></div></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="pagination" class="pagination"></div>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('filterBtn').addEventListener('click', () => {
|
||||
currentPage = 1;
|
||||
loadRecords();
|
||||
});
|
||||
document.getElementById('filterStore').addEventListener('change', async () => {
|
||||
await loadEmployeeOptions(document.getElementById('filterStore').value);
|
||||
});
|
||||
|
||||
loadFilterOptions().then(loadRecords);
|
||||
}
|
||||
|
||||
async function loadFilterOptions() {
|
||||
const storeSelect = document.getElementById('filterStore');
|
||||
if (!storeSelect) return;
|
||||
if (api.isStoreManager) {
|
||||
const storeId = api.storeId;
|
||||
const storeName = localStorage.getItem('feedback_admin_store_name') || storeId;
|
||||
storeSelect.innerHTML = `<option value="${escapeHtml(storeId)}">${escapeHtml(storeName)}</option>`;
|
||||
storeSelect.value = storeId;
|
||||
storeSelect.disabled = true;
|
||||
await loadEmployeeOptions(storeId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await api.getStores('page=1&page_size=100');
|
||||
const stores = res.data?.list || [];
|
||||
storeSelect.innerHTML = '<option value="">全部门店</option>' + stores.map(s => `<option value="${s.id}">${escapeHtml(s.storeName || s.store_name || s.id)}</option>`).join('');
|
||||
} catch (e) {
|
||||
storeSelect.innerHTML = '<option value="">全部门店</option>';
|
||||
}
|
||||
await loadEmployeeOptions('');
|
||||
}
|
||||
|
||||
async function loadEmployeeOptions(storeId = '') {
|
||||
const empSelect = document.getElementById('filterEmployee');
|
||||
if (!empSelect) return;
|
||||
const params = new URLSearchParams({ page: 1, page_size: 100 });
|
||||
if (storeId) params.set('store_id', storeId);
|
||||
try {
|
||||
const res = await api.getEmployees(params.toString());
|
||||
const employees = res.data?.list || [];
|
||||
empSelect.innerHTML = '<option value="">全部员工</option>' + employees.map(e => `<option value="${e.id}">${escapeHtml(e.name || e.id)}${e.number ? `(${e.number}号)` : ''}</option>`).join('');
|
||||
} catch (e) {
|
||||
empSelect.innerHTML = '<option value="">全部员工</option>';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRecords() {
|
||||
const tbody = document.getElementById('recordsBody');
|
||||
if (!tbody) return;
|
||||
|
||||
const storeId = document.getElementById('filterStore')?.value || '';
|
||||
const employeeId = document.getElementById('filterEmployee')?.value || '';
|
||||
const satisfaction = document.getElementById('filterSatisfaction')?.value || '';
|
||||
const startDate = document.getElementById('filterStart')?.value || '';
|
||||
const endDate = document.getElementById('filterEnd')?.value || '';
|
||||
|
||||
const params = new URLSearchParams({
|
||||
page: currentPage,
|
||||
page_size: pageSize,
|
||||
});
|
||||
if (storeId) params.set('store_id', storeId);
|
||||
if (employeeId) params.set('employee_id', employeeId);
|
||||
if (satisfaction) params.set('satisfaction', satisfaction);
|
||||
if (startDate) params.set('start_date', startDate);
|
||||
if (endDate) params.set('end_date', endDate);
|
||||
|
||||
try {
|
||||
const res = await api.getRecords(params.toString());
|
||||
const data = res.data || {};
|
||||
|
||||
if (!data.list || data.list.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="9" class="empty-state"><div class="icon">📋</div><p>暂无反馈记录</p></td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.list.map((r, i) => `
|
||||
<tr>
|
||||
<td>${(currentPage - 1) * pageSize + i + 1}</td>
|
||||
<td><strong>${escapeHtml(r.storeName || r.storeId || '-')}</strong></td>
|
||||
<td>${renderCustomerCell(r)}</td>
|
||||
<td>${satisfactionBadge(r.satisfaction)}</td>
|
||||
<td title="${escapeHtml(r.rawAsrText)}">${truncate(r.rawAsrText, 40)}</td>
|
||||
<td title="${escapeHtml(r.cleanedText)}">${truncate(r.cleanedText, 40)}</td>
|
||||
<td title="${escapeHtml(r.reviewLong)}">${r.reviewLong ? '✅ ' + truncate(r.reviewLong, 30) : '-'}</td>
|
||||
<td style="white-space:nowrap">${formatDate(r.createDate)}</td>
|
||||
<td><button class="btn btn-secondary btn-sm view-record-btn" data-id="${r.id}">详情</button></td>
|
||||
</tr>`).join('');
|
||||
|
||||
// Detail buttons
|
||||
tbody.querySelectorAll('.view-record-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => showRecordDetail(btn.dataset.id, data.list));
|
||||
});
|
||||
|
||||
// Pagination
|
||||
renderPagination(data);
|
||||
|
||||
} catch (e) {
|
||||
tbody.innerHTML = `<tr><td colspan="9" class="empty-state"><p>加载失败: ${e.message}</p></td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderPagination(data) {
|
||||
const el = document.getElementById('pagination');
|
||||
if (!el) return;
|
||||
|
||||
const total = data.total || 0;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="pagination-info">共 ${total} 条记录,第 ${currentPage}/${totalPages || 1} 页</div>
|
||||
<div class="pagination-btns">
|
||||
<button ${currentPage <= 1 ? 'disabled' : ''} id="prevPage">上一页</button>
|
||||
<button class="active">${currentPage}</button>
|
||||
<button ${currentPage >= totalPages ? 'disabled' : ''} id="nextPage">下一页</button>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('prevPage')?.addEventListener('click', () => {
|
||||
if (currentPage > 1) { currentPage--; loadRecords(); }
|
||||
});
|
||||
document.getElementById('nextPage')?.addEventListener('click', () => {
|
||||
if (currentPage < totalPages) { currentPage++; loadRecords(); }
|
||||
});
|
||||
}
|
||||
|
||||
function renderCustomerCell(r) {
|
||||
const name = r.memberName || r.customerName || '-';
|
||||
const phone = r.memberPhone ? maskPhone(r.memberPhone) : (r.phoneTail ? `尾号${r.phoneTail}` : '');
|
||||
const status = r.memberMatchStatus === 'conflict'
|
||||
? '<div class="muted" style="color:#D97706">尾号冲突,按称呼区分</div>'
|
||||
: r.memberMatchStatus === 'not_found'
|
||||
? '<div class="muted" style="color:#DC2626">未匹配客户档案</div>'
|
||||
: '';
|
||||
return `<strong>${escapeHtml(name)}</strong>${phone ? `<div class="muted">${escapeHtml(phone)}</div>` : ''}${status}`;
|
||||
}
|
||||
|
||||
function maskPhone(phone) {
|
||||
const s = String(phone || '');
|
||||
return s.length >= 7 ? `${s.slice(0, 3)}****${s.slice(-4)}` : s;
|
||||
}
|
||||
|
||||
function renderCustomerDetail(r) {
|
||||
const candidates = r.memberMatchCandidates || [];
|
||||
const candidateText = candidates.length
|
||||
? candidates.map(c => `${c.name || '-'} ${maskPhone(c.phone || '')}${c.nickname ? `(${c.nickname})` : ''}`).join(';')
|
||||
: '-';
|
||||
const statusMap = { matched: '已匹配', conflict: '尾号冲突', not_found: '未匹配' };
|
||||
return `${escapeHtml(r.memberName || r.customerName || '-')}
|
||||
${r.memberPhone ? ` <span class="muted">${escapeHtml(maskPhone(r.memberPhone))}</span>` : r.phoneTail ? ` <span class="muted">尾号${escapeHtml(r.phoneTail)}</span>` : ''}
|
||||
<div class="muted">匹配状态:${escapeHtml(statusMap[r.memberMatchStatus] || '-')}</div>
|
||||
<div class="muted">候选客户:${escapeHtml(candidateText)}</div>`;
|
||||
}
|
||||
|
||||
function showRecordDetail(id, records) {
|
||||
const r = records.find(rec => rec.id === id);
|
||||
if (!r) return;
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<h3>反馈记录详情</h3>
|
||||
<button class="modal-close" id="closeDetail">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="detail-row"><div class="detail-label">ID</div><div class="detail-value">${escapeHtml(r.id)}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">会话ID</div><div class="detail-value">${escapeHtml(r.sessionId || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">门店</div><div class="detail-value">${escapeHtml(r.storeName || r.storeId || '-')} <span class="muted">${escapeHtml(r.storeId || '')}</span></div></div>
|
||||
<div class="detail-row"><div class="detail-label">员工</div><div class="detail-value">${escapeHtml(r.employeeName || '-')} ${r.employeeNumber ? `(${r.employeeNumber}号)` : ''} <span class="muted">${escapeHtml(r.employeeId || '')}</span></div></div>
|
||||
<div class="detail-row"><div class="detail-label">客户</div><div class="detail-value">${renderCustomerDetail(r)}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">设备MAC</div><div class="detail-value">${escapeHtml(r.deviceMac || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">满意度</div><div class="detail-value">${satisfactionBadge(r.satisfaction)}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">原始文本</div><div class="detail-value" style="white-space:pre-wrap">${escapeHtml(r.rawAsrText || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">清洗文本</div><div class="detail-value" style="white-space:pre-wrap">${escapeHtml(r.cleanedText || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">QA结果</div><div class="detail-value" style="white-space:pre-wrap;font-size:12px">${escapeHtml(r.qaJson || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">标准点评</div><div class="detail-value" style="color:#059669">${escapeHtml(r.reviewLong || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">精简短评</div><div class="detail-value" style="color:#059669">${escapeHtml(r.reviewShort || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">创建时间</div><div class="detail-value">${formatDate(r.createDate)}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">CRM绑定</div><div class="detail-value">客户:${escapeHtml(r.memberId || '-')} 到店:${escapeHtml(r.visitId || '-')} 销卡:${escapeHtml(r.cardCloseId || '-')}</div></div>
|
||||
<div class="detail-row"><div class="detail-label">CRM操作</div><div class="detail-value">
|
||||
<button class="btn btn-secondary btn-sm" id="bindMemberBtn">绑定客户/到店</button>
|
||||
<button class="btn btn-primary btn-sm" id="createSuggestionBtn">创建建议</button>
|
||||
<button class="btn btn-danger btn-sm" id="createIssueBtn">创建问题</button>
|
||||
</div></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="closeDetailBtn">关闭</button>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('closeDetail').addEventListener('click', close);
|
||||
document.getElementById('closeDetailBtn').addEventListener('click', close);
|
||||
document.getElementById('bindMemberBtn').addEventListener('click', () => showBindFeedbackDialog(r));
|
||||
document.getElementById('createSuggestionBtn').addEventListener('click', () => showCreateSuggestionDialog(r));
|
||||
document.getElementById('createIssueBtn').addEventListener('click', () => showCreateIssueDialog(r));
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
}
|
||||
|
||||
function showSmallModal(title, body, onSave) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card">
|
||||
<div class="modal-header"><h3>${title}</h3><button class="modal-close">×</button></div>
|
||||
<div class="modal-body">${body}<div class="login-error" id="recordCrmError"></div></div>
|
||||
<div class="modal-footer"><button class="btn btn-secondary" id="recordCrmCancel">取消</button><button class="btn btn-primary" id="recordCrmSave">保存</button></div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
overlay.querySelector('.modal-close').onclick = close;
|
||||
overlay.querySelector('#recordCrmCancel').onclick = close;
|
||||
overlay.querySelector('#recordCrmSave').onclick = async () => {
|
||||
try { await onSave(); close(); alert('操作成功'); }
|
||||
catch (e) { document.getElementById('recordCrmError').textContent = e.message || '操作失败'; }
|
||||
};
|
||||
}
|
||||
|
||||
function inputVal(id) { return document.getElementById(id)?.value.trim(); }
|
||||
function memberPicker(prefix, label = '客户') {
|
||||
return `<div class="form-group member-combobox" id="${prefix}MemberBox"><label class="form-label">${label}</label><input id="${prefix}MemberKeyword" class="form-input" autocomplete="off" placeholder="输入姓名/手机号搜索并选择"><input id="${prefix}Member" type="hidden"><div id="${prefix}MemberDropdown" class="member-dropdown"></div><input id="${prefix}MemberManual" class="form-input member-manual" placeholder="客户ID备用输入(可选)"></div>`;
|
||||
}
|
||||
function pickedMember(prefix) { return inputVal(`${prefix}Member`) || inputVal(`${prefix}MemberManual`); }
|
||||
function fillMemberPicker(prefix, defaultMemberId = '') {
|
||||
const input = document.getElementById(`${prefix}MemberKeyword`);
|
||||
const dropdown = document.getElementById(`${prefix}MemberDropdown`);
|
||||
const idEl = document.getElementById(`${prefix}Member`);
|
||||
const manualEl = document.getElementById(`${prefix}MemberManual`);
|
||||
if (defaultMemberId && manualEl) manualEl.value = defaultMemberId;
|
||||
if (!input || !dropdown || !idEl) return;
|
||||
let timer = null;
|
||||
const search = async () => {
|
||||
const kw = input.value.trim();
|
||||
idEl.value = '';
|
||||
if (!kw) { dropdown.innerHTML = ''; dropdown.classList.remove('open'); return; }
|
||||
try {
|
||||
const res = await api.getCrmMembers(new URLSearchParams({ page: 1, page_size: 10, keyword: kw }).toString());
|
||||
const list = res.data?.list || [];
|
||||
dropdown.innerHTML = list.length ? list.map(m => `<div class="member-option" data-id="${m.id}" data-label="${escapeHtml((m.name || '-') + ' · ' + (m.phone || '-'))}"><strong>${escapeHtml(m.name || '-')}</strong><span>${escapeHtml(m.phone || '-')}</span></div>`).join('') : '<div class="member-option disabled">未找到客户</div>';
|
||||
dropdown.classList.add('open');
|
||||
dropdown.querySelectorAll('.member-option[data-id]').forEach(opt => opt.onclick = () => {
|
||||
idEl.value = opt.dataset.id;
|
||||
input.value = opt.dataset.label;
|
||||
if (manualEl) manualEl.value = '';
|
||||
dropdown.classList.remove('open');
|
||||
input.dispatchEvent(new CustomEvent('member-selected', { detail: { id: opt.dataset.id } }));
|
||||
});
|
||||
} catch (e) { dropdown.innerHTML = `<div class="member-option disabled">搜索失败:${escapeHtml(e.message)}</div>`; dropdown.classList.add('open'); }
|
||||
};
|
||||
input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(search, 250); });
|
||||
input.addEventListener('focus', () => { if (dropdown.innerHTML) dropdown.classList.add('open'); });
|
||||
document.addEventListener('click', (e) => { if (!e.target.closest(`#${prefix}MemberBox`)) dropdown.classList.remove('open'); });
|
||||
}
|
||||
|
||||
function showBindFeedbackDialog(r) {
|
||||
showSmallModal('绑定反馈到CRM', `
|
||||
${memberPicker('bind', '选择客户')}
|
||||
<div class="form-group"><label class="form-label">到店记录ID</label><input id="bindVisitId" class="form-input" value="${escapeHtml(r.visitId || '')}"></div>
|
||||
<div class="form-group"><label class="form-label">销卡记录ID</label><input id="bindCardCloseId" class="form-input" value="${escapeHtml(r.cardCloseId || '')}"></div>`,
|
||||
() => api.bindCrmFeedback(r.id, { memberId: pickedMember('bind'), visitId: inputVal('bindVisitId'), cardCloseId: inputVal('bindCardCloseId') })
|
||||
);
|
||||
fillMemberPicker('bind', r.memberId || '');
|
||||
}
|
||||
|
||||
function showCreateSuggestionDialog(r) {
|
||||
const content = r.cleanedText || r.rawAsrText || '';
|
||||
showSmallModal('从反馈创建建议', `
|
||||
<div class="form-group"><label class="form-label">建议内容</label><textarea id="recordSuggestionContent" class="form-input">${escapeHtml(content)}</textarea></div>
|
||||
<div class="form-group"><label class="form-label">分类</label><input id="recordSuggestionCategory" class="form-input" placeholder="服务/环境/价格/项目"></div>
|
||||
${memberPicker('recordSuggestion', '提出客户(可选)')}`,
|
||||
() => api.createCrmSuggestion({ content: inputVal('recordSuggestionContent'), category: inputVal('recordSuggestionCategory'), memberId: pickedMember('recordSuggestion'), feedbackRecordId: r.id, storeId: r.storeId })
|
||||
);
|
||||
fillMemberPicker('recordSuggestion', r.memberId || '');
|
||||
}
|
||||
|
||||
function showCreateIssueDialog(r) {
|
||||
const content = r.cleanedText || r.rawAsrText || '';
|
||||
showSmallModal('从反馈创建问题', `
|
||||
<div class="form-group"><label class="form-label">问题标题</label><input id="recordIssueTitle" class="form-input" value="客户反馈待修复问题"></div>
|
||||
<div class="form-row"><div class="form-group"><label class="form-label">分类</label><input id="recordIssueCategory" class="form-input" value="feedback"></div><div class="form-group"><label class="form-label">严重度</label><select id="recordIssueSeverity" class="form-input"><option value="medium">中</option><option value="high">高</option><option value="critical">严重</option><option value="low">低</option></select></div></div>
|
||||
<div class="form-group"><label class="form-label">问题描述</label><textarea id="recordIssueDesc" class="form-input">${escapeHtml(content)}</textarea></div>
|
||||
${memberPicker('recordIssue', '关联客户(可选)')}`,
|
||||
() => api.createCrmIssue({ title: inputVal('recordIssueTitle'), category: inputVal('recordIssueCategory'), severity: inputVal('recordIssueSeverity'), description: inputVal('recordIssueDesc'), memberId: pickedMember('recordIssue'), feedbackRecordId: r.id, storeId: r.storeId })
|
||||
);
|
||||
fillMemberPicker('recordIssue', r.memberId || '');
|
||||
}
|
||||
184
main/feedback-backend/admin-ui/js/pages/stores.js
Normal file
184
main/feedback-backend/admin-ui/js/pages/stores.js
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// Stores - 门店管理
|
||||
import { api } from '../api.js';
|
||||
|
||||
let currentPage = 1;
|
||||
const pageSize = 20;
|
||||
|
||||
export async function renderStores(container) {
|
||||
container.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<input type="text" id="filterStoreName" class="form-input" placeholder="门店名称" style="width:160px">
|
||||
<button class="btn btn-primary btn-sm" id="filterBtn">查询</button>
|
||||
<div style="flex:1"></div>
|
||||
<button class="btn btn-primary btn-sm" id="addStoreBtn">+ 新增门店</button>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>编码</th>
|
||||
<th>门店名称</th>
|
||||
<th>店长</th>
|
||||
<th>智能体ID</th>
|
||||
<th>状态</th>
|
||||
<th>创建时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="storesBody">
|
||||
<tr><td colspan="8" class="loading"><div class="spinner"></div></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="pagination" class="pagination"></div>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('filterBtn').addEventListener('click', () => { currentPage = 1; loadStores(); });
|
||||
document.getElementById('addStoreBtn').addEventListener('click', () => showStoreForm());
|
||||
loadStores();
|
||||
}
|
||||
|
||||
async function loadStores() {
|
||||
const tbody = document.getElementById('storesBody');
|
||||
if (!tbody) return;
|
||||
|
||||
const storeName = document.getElementById('filterStoreName')?.value.trim() || '';
|
||||
const params = new URLSearchParams({ page: currentPage, page_size: pageSize });
|
||||
if (storeName) params.set('store_name', storeName);
|
||||
|
||||
try {
|
||||
const res = await api.getStores(params.toString());
|
||||
const data = res.data || {};
|
||||
|
||||
if (!data.list || data.list.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="empty-state"><p>暂无门店</p></td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.list.map(s => `
|
||||
<tr>
|
||||
<td style="font-size:11px;color:#9CA3AF">${escapeHtml(s.id).substring(0,8)}...</td>
|
||||
<td><strong>${escapeHtml(s.storeCode)}</strong></td>
|
||||
<td>${escapeHtml(s.storeName)}</td>
|
||||
<td>${escapeHtml(s.manager || '-')}</td>
|
||||
<td style="font-size:11px">${escapeHtml(s.agentId || '-')}</td>
|
||||
<td>${statusBadge(s.status)}</td>
|
||||
<td style="white-space:nowrap">${formatDate(s.createDate)}</td>
|
||||
<td>
|
||||
<button class="btn btn-secondary btn-sm edit-store-btn" data-id="${s.id}">编辑</button>
|
||||
<button class="btn btn-danger btn-sm del-store-btn" data-id="${s.id}">删除</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
|
||||
tbody.querySelectorAll('.edit-store-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const store = data.list.find(s => s.id === btn.dataset.id);
|
||||
if (store) showStoreForm(store);
|
||||
});
|
||||
});
|
||||
|
||||
tbody.querySelectorAll('.del-store-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
if (!confirm('确定删除该门店?')) return;
|
||||
await api.deleteStore(btn.dataset.id);
|
||||
loadStores();
|
||||
});
|
||||
});
|
||||
|
||||
const total = data.total || 0;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
document.getElementById('pagination').innerHTML = `
|
||||
<div class="pagination-info">共 ${total} 条</div>
|
||||
<div class="pagination-btns">
|
||||
<button ${currentPage <= 1 ? 'disabled' : ''} id="prevPage">上一页</button>
|
||||
<button class="active">${currentPage}</button>
|
||||
<button ${currentPage >= totalPages ? 'disabled' : ''} id="nextPage">下一页</button>
|
||||
</div>`;
|
||||
document.getElementById('prevPage')?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; loadStores(); } });
|
||||
document.getElementById('nextPage')?.addEventListener('click', () => { if (currentPage < totalPages) { currentPage++; loadStores(); } });
|
||||
|
||||
} catch (e) {
|
||||
tbody.innerHTML = `<tr><td colspan="8" class="empty-state"><p>加载失败: ${e.message}</p></td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function showStoreForm(store = null) {
|
||||
const isEdit = !!store;
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<h3>${isEdit ? '编辑门店' : '新增门店'}</h3>
|
||||
<button class="modal-close" id="closeForm">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label class="form-label">门店编码 (6位数字)</label>
|
||||
<input type="text" id="formStoreCode" class="form-input" value="${store?.storeCode || ''}" maxlength="6" ${isEdit ? 'readonly' : ''}>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">门店名称</label>
|
||||
<input type="text" id="formStoreName" class="form-input" value="${store?.storeName || ''}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label class="form-label">店长</label>
|
||||
<input type="text" id="formManager" class="form-input" value="${store?.manager || ''}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">智能体 ID</label>
|
||||
<input type="text" id="formAgentId" class="form-input" value="${store?.agentId || ''}">
|
||||
</div>
|
||||
</div>
|
||||
<div id="formError" style="color:var(--danger);font-size:13px;min-height:20px;margin-top:8px"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="cancelBtn">取消</button>
|
||||
<button class="btn btn-primary" id="saveBtn">保存</button>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => document.body.removeChild(overlay);
|
||||
document.getElementById('closeForm').addEventListener('click', close);
|
||||
document.getElementById('cancelBtn').addEventListener('click', close);
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
|
||||
document.getElementById('saveBtn').addEventListener('click', async () => {
|
||||
const errEl = document.getElementById('formError');
|
||||
errEl.textContent = '';
|
||||
|
||||
const code = document.getElementById('formStoreCode').value.trim();
|
||||
const name = document.getElementById('formStoreName').value.trim();
|
||||
const manager = document.getElementById('formManager').value.trim();
|
||||
const agentId = document.getElementById('formAgentId').value.trim();
|
||||
|
||||
if (!code || !name) {
|
||||
errEl.textContent = '门店编码和名称不能为空';
|
||||
return;
|
||||
}
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
errEl.textContent = '门店编码必须为6位数字';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
await api.updateStore(store.id, {
|
||||
store_code: code, store_name: name, manager, agent_id: agentId || null
|
||||
});
|
||||
} else {
|
||||
await api.createStore({ store_code: code, store_name: name, manager, agent_id: agentId || null });
|
||||
}
|
||||
close();
|
||||
loadStores();
|
||||
} catch (e) {
|
||||
errEl.textContent = '保存失败: ' + e.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
// AI Voice Widget - WebSocket session scaffold
|
||||
// 后台数字人长连接通道:文本持续会话 + 心跳 + 自动重连由上层控制。
|
||||
|
||||
export class VoiceSession {
|
||||
constructor({ url, onOpen, onClose, onText, onAudio, onError } = {}) {
|
||||
this.url = url;
|
||||
this.ws = null;
|
||||
this.onOpen = onOpen;
|
||||
this.onClose = onClose;
|
||||
this.onText = onText;
|
||||
this.onAudio = onAudio;
|
||||
this.onError = onError;
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.ws?.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (!this.url) throw new Error('VoiceSession url is required');
|
||||
if (this.ws && [WebSocket.CONNECTING, WebSocket.OPEN].includes(this.ws.readyState)) return;
|
||||
this.ws = new WebSocket(this.url);
|
||||
this.ws.binaryType = 'arraybuffer';
|
||||
this.ws.onopen = () => {
|
||||
this._startHeartbeat();
|
||||
this.onOpen?.();
|
||||
};
|
||||
this.ws.onclose = (e) => {
|
||||
this._stopHeartbeat();
|
||||
this.onClose?.(e);
|
||||
};
|
||||
this.ws.onerror = (e) => this.onError?.(e);
|
||||
this.ws.onmessage = (event) => {
|
||||
if (typeof event.data === 'string') {
|
||||
let data = event.data;
|
||||
try { data = JSON.parse(event.data); } catch (e) {}
|
||||
this.onText?.(data);
|
||||
} else {
|
||||
this.onAudio?.(event.data);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
sendJson(data) {
|
||||
if (this.isOpen) {
|
||||
this.ws.send(JSON.stringify(data));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
sendText(text) {
|
||||
return this.sendJson({ type: 'message', text });
|
||||
}
|
||||
|
||||
sendBinary(data) {
|
||||
if (this.isOpen) {
|
||||
this.ws.send(data);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
close(code = 1000, reason = 'client close') {
|
||||
this._stopHeartbeat();
|
||||
try { this.ws?.close(code, reason); } catch (e) {}
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
_startHeartbeat() {
|
||||
this._stopHeartbeat();
|
||||
this.heartbeatTimer = window.setInterval(() => {
|
||||
this.sendJson({ type: 'ping' });
|
||||
}, 25000);
|
||||
}
|
||||
|
||||
_stopHeartbeat() {
|
||||
if (this.heartbeatTimer) {
|
||||
window.clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
242
main/feedback-backend/admin-ui/js/voice-widget/voice-widget.js
Normal file
242
main/feedback-backend/admin-ui/js/voice-widget/voice-widget.js
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
// AI Voice Widget - lightweight continuous voice interaction component
|
||||
// 当前版本:浏览器 ASR + speechSynthesis TTS + 状态回调;可配合后台 WebSocket 长连接使用。
|
||||
|
||||
import { VoiceSession } from './voice-session.js';
|
||||
|
||||
export function createVoiceWidget(options = {}) {
|
||||
return new VoiceWidget(options);
|
||||
}
|
||||
|
||||
export class VoiceWidget {
|
||||
constructor({ onUserText, onSessionMessage, onSessionOpen, onSessionClose, onStatus, onReplyStart, onReplyEnd, onError, voiceEnabled = true, sessionUrl = '' } = {}) {
|
||||
this.onUserText = onUserText;
|
||||
this.onSessionMessage = onSessionMessage;
|
||||
this.onSessionOpen = onSessionOpen;
|
||||
this.onSessionClose = onSessionClose;
|
||||
this.onStatus = onStatus;
|
||||
this.onReplyStart = onReplyStart;
|
||||
this.onReplyEnd = onReplyEnd;
|
||||
this.onError = onError;
|
||||
this.voiceEnabled = voiceEnabled;
|
||||
this.sessionUrl = sessionUrl;
|
||||
this.recognition = null;
|
||||
this.listening = false;
|
||||
this.session = null;
|
||||
this.continuousMode = false;
|
||||
this.manualStop = false;
|
||||
this.paused = false;
|
||||
this.speaking = false;
|
||||
this.restartTimer = null;
|
||||
this.restartDelay = 450;
|
||||
}
|
||||
|
||||
setVoiceEnabled(enabled) {
|
||||
this.voiceEnabled = !!enabled;
|
||||
if (!this.voiceEnabled) this.stopSpeaking();
|
||||
}
|
||||
|
||||
isContinuous() {
|
||||
return this.continuousMode && !this.manualStop;
|
||||
}
|
||||
|
||||
async startListening(options = {}) {
|
||||
const continuous = !!options.continuous;
|
||||
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||||
if (!SpeechRecognition) {
|
||||
const err = new Error('当前浏览器不支持语音输入,请使用 Chrome/Edge,或先用文字输入。');
|
||||
this.onError?.(err);
|
||||
throw err;
|
||||
}
|
||||
if (this.listening && this.recognition) {
|
||||
if (continuous && this.continuousMode) return true;
|
||||
this.stopListening(false);
|
||||
}
|
||||
this._clearRestartTimer();
|
||||
this.manualStop = false;
|
||||
this.paused = false;
|
||||
|
||||
const recognition = new SpeechRecognition();
|
||||
this.recognition = recognition;
|
||||
recognition.lang = 'zh-CN';
|
||||
recognition.interimResults = true;
|
||||
recognition.continuous = continuous;
|
||||
recognition.maxAlternatives = 1;
|
||||
this.listening = true;
|
||||
this.onStatus?.('listening', continuous ? '长聊中 · 我会持续听你说话' : '正在听你说话...');
|
||||
let finalText = '';
|
||||
|
||||
recognition.onresult = (event) => {
|
||||
let interim = '';
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const transcript = event.results[i][0].transcript;
|
||||
if (event.results[i].isFinal) {
|
||||
if (continuous) {
|
||||
const text = transcript.trim();
|
||||
if (text) this.onUserText?.(text);
|
||||
} else {
|
||||
finalText += transcript;
|
||||
}
|
||||
} else {
|
||||
interim += transcript;
|
||||
}
|
||||
}
|
||||
this.onStatus?.('listening', finalText || interim || (continuous ? '长聊中 · 我会持续听你说话' : '正在听你说话...'));
|
||||
};
|
||||
recognition.onstart = () => {
|
||||
this.listening = true;
|
||||
this.onStatus?.('listening', continuous ? '长聊中 · 我会持续听你说话' : '正在听你说话...');
|
||||
};
|
||||
recognition.onerror = (event) => {
|
||||
const error = event.error || '语音识别失败';
|
||||
// Chrome 在 stop()/切换页面/播放 TTS 时经常抛 aborted/no-speech,属于可恢复状态,不展示成聊天消息。
|
||||
if (['aborted', 'no-speech'].includes(error)) {
|
||||
this.onStatus?.('listening', this.continuousMode ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字');
|
||||
if (!this.manualStop && this.continuousMode && !this.paused && !this.speaking) {
|
||||
this._scheduleRestart();
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.onError?.(new Error(error));
|
||||
};
|
||||
recognition.onend = () => {
|
||||
this.listening = false;
|
||||
this.recognition = null;
|
||||
if (!continuous) {
|
||||
const text = finalText.trim();
|
||||
if (text) this.onUserText?.(text);
|
||||
}
|
||||
if (this.continuousMode && !this.manualStop && !this.paused && !this.speaking) {
|
||||
this._scheduleRestart();
|
||||
} else if (!this.speaking && !this.paused) {
|
||||
this.onStatus?.('', this.continuousMode ? '长聊已暂停' : '待命中 · 可语音或打字');
|
||||
}
|
||||
};
|
||||
try {
|
||||
recognition.start();
|
||||
} catch (err) {
|
||||
this.listening = false;
|
||||
this.recognition = null;
|
||||
if (continuous && !this.manualStop) this._scheduleRestart();
|
||||
else this.onError?.(err);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async startContinuous() {
|
||||
this.continuousMode = true;
|
||||
this.manualStop = false;
|
||||
this.paused = false;
|
||||
return this.startListening({ continuous: true });
|
||||
}
|
||||
|
||||
stopListening(manual = true) {
|
||||
this.manualStop = manual;
|
||||
if (manual) this.continuousMode = false;
|
||||
this._clearRestartTimer();
|
||||
try { this.recognition?.stop(); } catch (e) {}
|
||||
this.recognition = null;
|
||||
this.listening = false;
|
||||
if (manual) this.onStatus?.('', '待命中 · 可语音或打字');
|
||||
}
|
||||
|
||||
pauseContinuous(text = '正在思考...') {
|
||||
if (!this.continuousMode) return;
|
||||
this.paused = true;
|
||||
this._clearRestartTimer();
|
||||
try { this.recognition?.stop(); } catch (e) {}
|
||||
this.onStatus?.('thinking', text);
|
||||
}
|
||||
|
||||
resumeContinuous() {
|
||||
if (!this.continuousMode || this.manualStop || this.speaking) return;
|
||||
this.paused = false;
|
||||
this._scheduleRestart();
|
||||
}
|
||||
|
||||
speak(text) {
|
||||
if (!this.voiceEnabled || !window.speechSynthesis || !text) {
|
||||
this.resumeContinuous();
|
||||
return;
|
||||
}
|
||||
this.stopSpeaking();
|
||||
this.speaking = true;
|
||||
this.pauseContinuous('AI正在回复...');
|
||||
const utter = new SpeechSynthesisUtterance(String(text).replace(/<[^>]+>/g, '').slice(0, 260));
|
||||
utter.lang = 'zh-CN';
|
||||
utter.rate = 1.05;
|
||||
utter.pitch = 1.0;
|
||||
utter.onstart = () => {
|
||||
this.onStatus?.('speaking', 'AI正在回复...');
|
||||
this.onReplyStart?.();
|
||||
};
|
||||
utter.onend = () => {
|
||||
this.speaking = false;
|
||||
this.paused = false;
|
||||
this.onStatus?.(this.continuousMode ? 'listening' : '', this.continuousMode ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字');
|
||||
this.onReplyEnd?.();
|
||||
this.resumeContinuous();
|
||||
};
|
||||
utter.onerror = () => {
|
||||
this.speaking = false;
|
||||
this.paused = false;
|
||||
this.onReplyEnd?.();
|
||||
this.resumeContinuous();
|
||||
};
|
||||
window.speechSynthesis.speak(utter);
|
||||
}
|
||||
|
||||
stopSpeaking() {
|
||||
try { window.speechSynthesis?.cancel(); } catch (e) {}
|
||||
this.speaking = false;
|
||||
}
|
||||
|
||||
connectSession(url = '') {
|
||||
if (url) this.sessionUrl = url;
|
||||
if (!this.sessionUrl) return null;
|
||||
if (this.session?.isOpen) return this.session;
|
||||
this.session = new VoiceSession({
|
||||
url: this.sessionUrl,
|
||||
onOpen: () => {
|
||||
this.onStatus?.('connected', '长连接已建立 · 可持续对话');
|
||||
this.onSessionOpen?.();
|
||||
},
|
||||
onClose: (event) => {
|
||||
this.onStatus?.('', this.continuousMode ? '长连接已断开 · 语音长聊仍可使用' : '长连接已关闭');
|
||||
this.onSessionClose?.(event);
|
||||
},
|
||||
onText: (data) => this.onSessionMessage?.(data),
|
||||
onError: (e) => this.onError?.(e),
|
||||
});
|
||||
this.session.connect();
|
||||
return this.session;
|
||||
}
|
||||
|
||||
sendText(text) {
|
||||
return this.session?.sendText(text) || false;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.stopListening(true);
|
||||
this.stopSpeaking();
|
||||
this.session?.close();
|
||||
}
|
||||
|
||||
_scheduleRestart() {
|
||||
if (!this.continuousMode || this.manualStop || this.paused || this.speaking || this.listening) return;
|
||||
this._clearRestartTimer();
|
||||
this.restartTimer = window.setTimeout(() => {
|
||||
this.restartTimer = null;
|
||||
if (this.continuousMode && !this.manualStop && !this.paused && !this.speaking && !this.listening) {
|
||||
this.startListening({ continuous: true }).catch(err => this.onError?.(err));
|
||||
}
|
||||
}, this.restartDelay);
|
||||
}
|
||||
|
||||
_clearRestartTimer() {
|
||||
if (this.restartTimer) {
|
||||
window.clearTimeout(this.restartTimer);
|
||||
this.restartTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
1
main/feedback-backend/admin-ui/libs/cubism4.min.js
vendored
Normal file
1
main/feedback-backend/admin-ui/libs/cubism4.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
266
main/feedback-backend/admin-ui/libs/libopus.js
Normal file
266
main/feedback-backend/admin-ui/libs/libopus.js
Normal file
File diff suppressed because one or more lines are too long
9
main/feedback-backend/admin-ui/libs/live2dcubismcore.min.js
vendored
Normal file
9
main/feedback-backend/admin-ui/libs/live2dcubismcore.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
182
main/feedback-backend/admin-ui/libs/opus-codec.js
Normal file
182
main/feedback-backend/admin-ui/libs/opus-codec.js
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { log } from '../../utils/logger.js?v=0205';
|
||||
|
||||
|
||||
// 检查Opus库是否已加载
|
||||
export function checkOpusLoaded() {
|
||||
try {
|
||||
// 检查Module是否存在(本地库导出的全局变量)
|
||||
if (typeof Module === 'undefined') {
|
||||
throw new Error('Opus库未加载,Module对象不存在');
|
||||
}
|
||||
|
||||
// 尝试先使用Module.instance(libopus.js最后一行导出方式)
|
||||
if (typeof Module.instance !== 'undefined' && typeof Module.instance._opus_decoder_get_size === 'function') {
|
||||
// 使用Module.instance对象替换全局Module对象
|
||||
window.ModuleInstance = Module.instance;
|
||||
log('Opus库加载成功(使用Module.instance)', 'success');
|
||||
|
||||
// 3秒后隐藏状态
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) statusElement.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果没有Module.instance,检查全局Module函数
|
||||
if (typeof Module._opus_decoder_get_size === 'function') {
|
||||
window.ModuleInstance = Module;
|
||||
log('Opus库加载成功(使用全局Module)', 'success');
|
||||
|
||||
// 3秒后隐藏状态
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) statusElement.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('Opus解码函数未找到,可能Module结构不正确');
|
||||
} catch (err) {
|
||||
log(`Opus库加载失败,请检查libopus.js文件是否存在且正确: ${err.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 创建一个Opus编码器
|
||||
let opusEncoder = null;
|
||||
export function initOpusEncoder() {
|
||||
try {
|
||||
if (opusEncoder) {
|
||||
return opusEncoder; // 已经初始化过
|
||||
}
|
||||
|
||||
if (!window.ModuleInstance) {
|
||||
log('无法创建Opus编码器:ModuleInstance不可用', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// 初始化一个Opus编码器
|
||||
const mod = window.ModuleInstance;
|
||||
const sampleRate = 16000; // 16kHz采样率
|
||||
const channels = 1; // 单声道
|
||||
const application = 2048; // OPUS_APPLICATION_VOIP = 2048
|
||||
|
||||
// 创建编码器
|
||||
opusEncoder = {
|
||||
channels: channels,
|
||||
sampleRate: sampleRate,
|
||||
frameSize: 960, // 60ms @ 16kHz = 60 * 16 = 960 samples
|
||||
maxPacketSize: 4000, // 最大包大小
|
||||
module: mod,
|
||||
|
||||
// 初始化编码器
|
||||
init: function () {
|
||||
try {
|
||||
// 获取编码器大小
|
||||
const encoderSize = mod._opus_encoder_get_size(this.channels);
|
||||
log(`Opus编码器大小: ${encoderSize}字节`, 'info');
|
||||
|
||||
// 分配内存
|
||||
this.encoderPtr = mod._malloc(encoderSize);
|
||||
if (!this.encoderPtr) {
|
||||
throw new Error("无法分配编码器内存");
|
||||
}
|
||||
|
||||
// 初始化编码器
|
||||
const err = mod._opus_encoder_init(
|
||||
this.encoderPtr,
|
||||
this.sampleRate,
|
||||
this.channels,
|
||||
application
|
||||
);
|
||||
|
||||
if (err < 0) {
|
||||
throw new Error(`Opus编码器初始化失败: ${err}`);
|
||||
}
|
||||
|
||||
// 设置位率 (16kbps)
|
||||
mod._opus_encoder_ctl(this.encoderPtr, 4002, 16000); // OPUS_SET_BITRATE
|
||||
|
||||
// 设置复杂度 (0-10, 越高质量越好但CPU使用越多)
|
||||
mod._opus_encoder_ctl(this.encoderPtr, 4010, 5); // OPUS_SET_COMPLEXITY
|
||||
|
||||
// 设置使用DTX (不传输静音帧)
|
||||
mod._opus_encoder_ctl(this.encoderPtr, 4016, 1); // OPUS_SET_DTX
|
||||
|
||||
log("Opus编码器初始化成功", 'success');
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (this.encoderPtr) {
|
||||
mod._free(this.encoderPtr);
|
||||
this.encoderPtr = null;
|
||||
}
|
||||
log(`Opus编码器初始化失败: ${error.message}`, 'error');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
// 编码PCM数据为Opus
|
||||
encode: function (pcmData) {
|
||||
if (!this.encoderPtr) {
|
||||
if (!this.init()) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = this.module;
|
||||
|
||||
// 为PCM数据分配内存
|
||||
const pcmPtr = mod._malloc(pcmData.length * 2); // 2字节/int16
|
||||
|
||||
// 将PCM数据复制到HEAP
|
||||
for (let i = 0; i < pcmData.length; i++) {
|
||||
mod.HEAP16[(pcmPtr >> 1) + i] = pcmData[i];
|
||||
}
|
||||
|
||||
// 为输出分配内存
|
||||
const outPtr = mod._malloc(this.maxPacketSize);
|
||||
|
||||
// 进行编码
|
||||
const encodedLen = mod._opus_encode(
|
||||
this.encoderPtr,
|
||||
pcmPtr,
|
||||
this.frameSize,
|
||||
outPtr,
|
||||
this.maxPacketSize
|
||||
);
|
||||
|
||||
if (encodedLen < 0) {
|
||||
throw new Error(`Opus编码失败: ${encodedLen}`);
|
||||
}
|
||||
|
||||
// 复制编码后的数据
|
||||
const opusData = new Uint8Array(encodedLen);
|
||||
for (let i = 0; i < encodedLen; i++) {
|
||||
opusData[i] = mod.HEAPU8[outPtr + i];
|
||||
}
|
||||
|
||||
// 释放内存
|
||||
mod._free(pcmPtr);
|
||||
mod._free(outPtr);
|
||||
|
||||
return opusData;
|
||||
} catch (error) {
|
||||
log(`Opus编码出错: ${error.message}`, 'error');
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
// 销毁编码器
|
||||
destroy: function () {
|
||||
if (this.encoderPtr) {
|
||||
this.module._free(this.encoderPtr);
|
||||
this.encoderPtr = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
opusEncoder.init();
|
||||
return opusEncoder;
|
||||
} catch (error) {
|
||||
log(`创建Opus编码器失败: ${error.message}`, 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
43379
main/feedback-backend/admin-ui/libs/pixi.js
Normal file
43379
main/feedback-backend/admin-ui/libs/pixi.js
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,72 @@
|
|||
|
||||
============================================================
|
||||
|
||||
示例模型
|
||||
桃濑日和 - PRO
|
||||
|
||||
============================================================
|
||||
|
||||
该示例时基于Cubism3.0制作的标准模型素材。
|
||||
|
||||
可用于学习变形器的构造以及参数的使用方法。
|
||||
模型的肩部应用了新功能【胶水】。
|
||||
|
||||
|
||||
------------------------------
|
||||
素材使用许可
|
||||
------------------------------
|
||||
|
||||
普通用户以及小规模企业在同意授权协议的情况下可用于商业用途。
|
||||
中/大规模的企业只能用于非公开的内部试用。
|
||||
在使用该素材时,请确认以下的【无偿提供素材使用授权协议】中的“授权类型”、“Live2D原创角色”等的相关内容,
|
||||
并必须接受【Live2D Cubism 示例模型的使用授权要求】中的利用条件。
|
||||
|
||||
有关许可证的更多信息,请参阅以下页面。
|
||||
https://www.live2d.com/zh-CHS/download/sample-data/
|
||||
|
||||
|
||||
------------------------------
|
||||
创作者
|
||||
------------------------------
|
||||
|
||||
插画:Kani Biimu
|
||||
模型:Live2D
|
||||
|
||||
|
||||
------------------------------
|
||||
素材内容
|
||||
------------------------------
|
||||
|
||||
模型文件(cmo3) ※包含物理模拟的设定
|
||||
动画文件(can3)
|
||||
嵌入文件列表(runtime文件夹)
|
||||
・模型数据(moc3)
|
||||
・动作数据(motion3.json)
|
||||
・模型设定文件(model3.json)
|
||||
・物理模拟设定文件(physics3.json)
|
||||
・姿势设定文件(pose3.json)
|
||||
・辅助显示的文件(cdi3.json)
|
||||
|
||||
|
||||
------------------------------
|
||||
更新记录
|
||||
------------------------------
|
||||
|
||||
【cmo3】
|
||||
|
||||
hiyori_pro_t11
|
||||
2023年03月08日 修改了部分模型关键点
|
||||
|
||||
hiyori_pro_t10
|
||||
2021年06月10日 公开
|
||||
|
||||
|
||||
【can3】
|
||||
|
||||
hiyori_pro_t04
|
||||
2023年03月08日 修改了部分动画关键帧
|
||||
|
||||
hiyori_pro_t03
|
||||
2021年06月10日 公开
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
|
|
@ -0,0 +1,533 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamAngleX",
|
||||
"GroupId": "ParamGroupFace",
|
||||
"Name": "角度 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAngleY",
|
||||
"GroupId": "ParamGroupFace",
|
||||
"Name": "角度 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAngleZ",
|
||||
"GroupId": "ParamGroupFace",
|
||||
"Name": "角度 Z"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"GroupId": "ParamGroupFace",
|
||||
"Name": "脸颊泛红"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"GroupId": "ParamGroupEyes",
|
||||
"Name": "左眼 开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"GroupId": "ParamGroupEyes",
|
||||
"Name": "左眼 微笑"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"GroupId": "ParamGroupEyes",
|
||||
"Name": "右眼 开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"GroupId": "ParamGroupEyes",
|
||||
"Name": "右眼 微笑"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallX",
|
||||
"GroupId": "ParamGroupEyeballs",
|
||||
"Name": "眼珠 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallY",
|
||||
"GroupId": "ParamGroupEyeballs",
|
||||
"Name": "眼珠 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "左眉 上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "右眉 上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "左眉 左右"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "右眉 左右"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "左眉 角度"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "右眉 角度"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "左眉 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"GroupId": "ParamGroupBrows",
|
||||
"Name": "右眉 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamMouthForm",
|
||||
"GroupId": "ParamGroupMouth",
|
||||
"Name": "嘴 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamMouthOpenY",
|
||||
"GroupId": "ParamGroupMouth",
|
||||
"Name": "嘴 开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyAngleX",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的旋转 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyAngleY",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的旋转 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyAngleZ",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的旋转 Z"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBreath",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "呼吸"
|
||||
},
|
||||
{
|
||||
"Id": "ParamShoulder",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "肩"
|
||||
},
|
||||
{
|
||||
"Id": "ParamLeg",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "腿"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmLA",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "左臂 A"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmRA",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "右臂 A"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmLB",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "左臂 B"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmRB",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "右臂 B"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHandLB",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "左手B 旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHandRB",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "右手B 旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHandL",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "左手"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHandR",
|
||||
"GroupId": "ParamGroupArms",
|
||||
"Name": "右手"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBustY",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "胸部 摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairAhoge",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "头发摇动 呆毛"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairFront",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "头发摇动 前"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairBack",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "头发摇动 后"
|
||||
},
|
||||
{
|
||||
"Id": "ParamSideupRibbon",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "发饰的摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamRibbon",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "蝴蝶结的摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamSkirt",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "短裙的摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamSkirt2",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "短裙的上卷"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_1_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[0]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_2_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[1]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_3_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[2]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_4_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[3]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_5_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[4]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_6_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[5]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_7_ArtMesh62",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "[6]辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_1_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[0]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_2_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[1]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_3_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[2]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_4_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[3]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_5_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[4]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_6_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[5]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_7_ArtMesh61",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "[6]辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_1_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[0]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_2_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[1]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_3_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[2]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_4_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[3]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_5_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[4]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_6_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[5]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_7_ArtMesh55",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "[6]侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_1_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[0]侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_2_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[1]侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_3_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[2]侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_4_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[3]侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_5_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[4]侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_6_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[5]侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Param_Angle_Rotation_7_ArtMesh54",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "[6]侧发右"
|
||||
}
|
||||
],
|
||||
"ParameterGroups": [
|
||||
{
|
||||
"Id": "ParamGroupFace",
|
||||
"GroupId": "",
|
||||
"Name": "脸"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupEyes",
|
||||
"GroupId": "",
|
||||
"Name": "眼睛"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupEyeballs",
|
||||
"GroupId": "",
|
||||
"Name": "眼珠"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupBrows",
|
||||
"GroupId": "",
|
||||
"Name": "眉毛"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupMouth",
|
||||
"GroupId": "",
|
||||
"Name": "嘴"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupBody",
|
||||
"GroupId": "",
|
||||
"Name": "身体"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupArms",
|
||||
"GroupId": "",
|
||||
"Name": "手臂"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupSway",
|
||||
"GroupId": "",
|
||||
"Name": "摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup2",
|
||||
"GroupId": "",
|
||||
"Name": "摇动 辫子左"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup",
|
||||
"GroupId": "",
|
||||
"Name": "摇动 辫子右"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup4",
|
||||
"GroupId": "",
|
||||
"Name": "摇动 侧发左"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup3",
|
||||
"GroupId": "",
|
||||
"Name": "摇动 侧发右"
|
||||
}
|
||||
],
|
||||
"Parts": [
|
||||
{
|
||||
"Id": "PartCore",
|
||||
"Name": "Core"
|
||||
},
|
||||
{
|
||||
"Id": "PartCheek",
|
||||
"Name": "脸颊"
|
||||
},
|
||||
{
|
||||
"Id": "PartBrow",
|
||||
"Name": "眉毛"
|
||||
},
|
||||
{
|
||||
"Id": "PartEye",
|
||||
"Name": "眼睛"
|
||||
},
|
||||
{
|
||||
"Id": "PartNose",
|
||||
"Name": "鼻子"
|
||||
},
|
||||
{
|
||||
"Id": "PartMouth",
|
||||
"Name": "嘴"
|
||||
},
|
||||
{
|
||||
"Id": "PartFace",
|
||||
"Name": "脸"
|
||||
},
|
||||
{
|
||||
"Id": "PartEar",
|
||||
"Name": "耳朵"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairSide",
|
||||
"Name": "侧发"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairFront",
|
||||
"Name": "前发"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairBack",
|
||||
"Name": "后发"
|
||||
},
|
||||
{
|
||||
"Id": "PartNeck",
|
||||
"Name": "脖子"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmA",
|
||||
"Name": "手臂A"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmB",
|
||||
"Name": "手臂B"
|
||||
},
|
||||
{
|
||||
"Id": "PartBody",
|
||||
"Name": "身体"
|
||||
},
|
||||
{
|
||||
"Id": "PartBackground",
|
||||
"Name": "背景"
|
||||
},
|
||||
{
|
||||
"Id": "PartSketch",
|
||||
"Name": "[参考图]"
|
||||
},
|
||||
{
|
||||
"Id": "PartEyeBall",
|
||||
"Name": "眼珠"
|
||||
},
|
||||
{
|
||||
"Id": "ArtMesh55_Skinning",
|
||||
"Name": "侧发右"
|
||||
},
|
||||
{
|
||||
"Id": "Part4",
|
||||
"Name": "侧发左(旋转)"
|
||||
},
|
||||
{
|
||||
"Id": "ArtMesh54_Skinning",
|
||||
"Name": "侧发右(蒙皮)"
|
||||
},
|
||||
{
|
||||
"Id": "Part3",
|
||||
"Name": "侧发右(旋转)"
|
||||
},
|
||||
{
|
||||
"Id": "ArtMesh61_Skinning",
|
||||
"Name": "辫子右(蒙皮)"
|
||||
},
|
||||
{
|
||||
"Id": "Part",
|
||||
"Name": "辫子右(旋转)"
|
||||
},
|
||||
{
|
||||
"Id": "ArtMesh62_Skinning",
|
||||
"Name": "辫子左(蒙皮)"
|
||||
},
|
||||
{
|
||||
"Id": "Part2",
|
||||
"Name": "辫子左(旋转)"
|
||||
}
|
||||
],
|
||||
"CombinedParameters": [
|
||||
[
|
||||
"ParamAngleX",
|
||||
"ParamAngleY"
|
||||
],
|
||||
[
|
||||
"ParamMouthForm",
|
||||
"ParamMouthOpenY"
|
||||
]
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
|
@ -0,0 +1,82 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"FileReferences": {
|
||||
"Moc": "hiyori_pro_t11.moc3",
|
||||
"Textures": [
|
||||
"hiyori_pro_t11.2048/texture_00.png",
|
||||
"hiyori_pro_t11.2048/texture_01.png"
|
||||
],
|
||||
"Physics": "hiyori_pro_t11.physics3.json",
|
||||
"Pose": "hiyori_pro_t11.pose3.json",
|
||||
"DisplayInfo": "hiyori_pro_t11.cdi3.json",
|
||||
"Motions": {
|
||||
"Idle": [
|
||||
{
|
||||
"File": "motion/hiyori_m01.motion3.json"
|
||||
},
|
||||
{
|
||||
"File": "motion/hiyori_m02.motion3.json"
|
||||
},
|
||||
{
|
||||
"File": "motion/hiyori_m05.motion3.json"
|
||||
}
|
||||
],
|
||||
"Flick": [
|
||||
{
|
||||
"File": "motion/hiyori_m03.motion3.json"
|
||||
}
|
||||
],
|
||||
"FlickDown": [
|
||||
{
|
||||
"File": "motion/hiyori_m04.motion3.json"
|
||||
}
|
||||
],
|
||||
"FlickUp": [
|
||||
{
|
||||
"File": "motion/hiyori_m06.motion3.json"
|
||||
}
|
||||
],
|
||||
"Tap": [
|
||||
{
|
||||
"File": "motion/hiyori_m07.motion3.json"
|
||||
},
|
||||
{
|
||||
"File": "motion/hiyori_m08.motion3.json"
|
||||
}
|
||||
],
|
||||
"Tap@Body": [
|
||||
{
|
||||
"File": "motion/hiyori_m09.motion3.json"
|
||||
}
|
||||
],
|
||||
"Flick@Body": [
|
||||
{
|
||||
"File": "motion/hiyori_m10.motion3.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"Groups": [
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Name": "LipSync",
|
||||
"Ids": [
|
||||
"ParamMouthOpenY"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Name": "EyeBlink",
|
||||
"Ids": [
|
||||
"ParamEyeLOpen",
|
||||
"ParamEyeROpen"
|
||||
]
|
||||
}
|
||||
],
|
||||
"HitAreas": [
|
||||
{
|
||||
"Id": "HitArea",
|
||||
"Name": "Body"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"Type": "Live2D Pose",
|
||||
"Groups": [
|
||||
[
|
||||
{
|
||||
"Id": "PartArmA",
|
||||
"Link": []
|
||||
},
|
||||
{
|
||||
"Id": "PartArmB",
|
||||
"Link": []
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,860 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"Meta": {
|
||||
"Duration": 4.43,
|
||||
"Fps": 30.0,
|
||||
"Loop": true,
|
||||
"AreBeziersRestricted": false,
|
||||
"CurveCount": 29,
|
||||
"TotalSegmentCount": 106,
|
||||
"TotalPointCount": 287,
|
||||
"UserDataCount": 0,
|
||||
"TotalUserDataSize": 0
|
||||
},
|
||||
"Curves": [
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleX",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.211,
|
||||
1,
|
||||
0.422,
|
||||
0,
|
||||
0.633,
|
||||
0,
|
||||
1,
|
||||
0.911,
|
||||
0,
|
||||
1.189,
|
||||
5,
|
||||
1.467,
|
||||
5,
|
||||
1,
|
||||
1.689,
|
||||
5,
|
||||
1.911,
|
||||
-16,
|
||||
2.133,
|
||||
-16,
|
||||
1,
|
||||
2.356,
|
||||
-16,
|
||||
2.578,
|
||||
13.871,
|
||||
2.8,
|
||||
13.871,
|
||||
1,
|
||||
2.956,
|
||||
13.871,
|
||||
3.111,
|
||||
0,
|
||||
3.267,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.211,
|
||||
0,
|
||||
0.422,
|
||||
0,
|
||||
0.633,
|
||||
0,
|
||||
1,
|
||||
0.911,
|
||||
0,
|
||||
1.189,
|
||||
-25,
|
||||
1.467,
|
||||
-25,
|
||||
1,
|
||||
1.689,
|
||||
-25,
|
||||
1.911,
|
||||
-15.225,
|
||||
2.133,
|
||||
-11,
|
||||
1,
|
||||
2.356,
|
||||
-6.775,
|
||||
2.578,
|
||||
-5.127,
|
||||
2.8,
|
||||
-2.5,
|
||||
1,
|
||||
2.956,
|
||||
-0.661,
|
||||
3.111,
|
||||
0,
|
||||
3.267,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleZ",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.222,
|
||||
0,
|
||||
0.444,
|
||||
0,
|
||||
0.667,
|
||||
0,
|
||||
1,
|
||||
0.756,
|
||||
0,
|
||||
0.844,
|
||||
-4,
|
||||
0.933,
|
||||
-4,
|
||||
1,
|
||||
1.122,
|
||||
-4,
|
||||
1.311,
|
||||
18,
|
||||
1.5,
|
||||
18,
|
||||
1,
|
||||
1.722,
|
||||
18,
|
||||
1.944,
|
||||
-14,
|
||||
2.167,
|
||||
-14,
|
||||
1,
|
||||
2.567,
|
||||
-14,
|
||||
2.967,
|
||||
-14,
|
||||
3.367,
|
||||
-14,
|
||||
1,
|
||||
3.511,
|
||||
-14,
|
||||
3.656,
|
||||
-12,
|
||||
3.8,
|
||||
-12,
|
||||
0,
|
||||
4.433,
|
||||
-12
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamCheek",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
4.433,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Segments": [
|
||||
0,
|
||||
1.2,
|
||||
1,
|
||||
0.389,
|
||||
1.2,
|
||||
0.778,
|
||||
1.148,
|
||||
1.167,
|
||||
1,
|
||||
1,
|
||||
1.211,
|
||||
0.983,
|
||||
1.256,
|
||||
0,
|
||||
1.3,
|
||||
0,
|
||||
1,
|
||||
1.322,
|
||||
0,
|
||||
1.344,
|
||||
0,
|
||||
1.367,
|
||||
0,
|
||||
1,
|
||||
1.422,
|
||||
0,
|
||||
1.478,
|
||||
1,
|
||||
1.533,
|
||||
1,
|
||||
1,
|
||||
1.944,
|
||||
1,
|
||||
2.356,
|
||||
1,
|
||||
2.767,
|
||||
1,
|
||||
1,
|
||||
2.811,
|
||||
1,
|
||||
2.856,
|
||||
0,
|
||||
2.9,
|
||||
0,
|
||||
1,
|
||||
2.922,
|
||||
0,
|
||||
2.944,
|
||||
0,
|
||||
2.967,
|
||||
0,
|
||||
1,
|
||||
3.022,
|
||||
0,
|
||||
3.078,
|
||||
1,
|
||||
3.133,
|
||||
1,
|
||||
0,
|
||||
4.433,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeROpen",
|
||||
"Segments": [
|
||||
0,
|
||||
1.2,
|
||||
1,
|
||||
0.389,
|
||||
1.2,
|
||||
0.778,
|
||||
1.148,
|
||||
1.167,
|
||||
1,
|
||||
1,
|
||||
1.211,
|
||||
0.983,
|
||||
1.256,
|
||||
0,
|
||||
1.3,
|
||||
0,
|
||||
1,
|
||||
1.322,
|
||||
0,
|
||||
1.344,
|
||||
0,
|
||||
1.367,
|
||||
0,
|
||||
1,
|
||||
1.422,
|
||||
0,
|
||||
1.478,
|
||||
1,
|
||||
1.533,
|
||||
1,
|
||||
1,
|
||||
1.944,
|
||||
1,
|
||||
2.356,
|
||||
1,
|
||||
2.767,
|
||||
1,
|
||||
1,
|
||||
2.811,
|
||||
1,
|
||||
2.856,
|
||||
0,
|
||||
2.9,
|
||||
0,
|
||||
1,
|
||||
2.922,
|
||||
0,
|
||||
2.944,
|
||||
0,
|
||||
2.967,
|
||||
0,
|
||||
1,
|
||||
3.022,
|
||||
0,
|
||||
3.078,
|
||||
1,
|
||||
3.133,
|
||||
1,
|
||||
0,
|
||||
4.433,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeBallX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.211,
|
||||
0,
|
||||
0.422,
|
||||
0,
|
||||
0.633,
|
||||
0,
|
||||
1,
|
||||
0.911,
|
||||
0,
|
||||
1.189,
|
||||
-0.44,
|
||||
1.467,
|
||||
-0.44,
|
||||
1,
|
||||
1.689,
|
||||
-0.44,
|
||||
1.911,
|
||||
0.79,
|
||||
2.133,
|
||||
0.79,
|
||||
1,
|
||||
2.511,
|
||||
0.79,
|
||||
2.889,
|
||||
0,
|
||||
3.267,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeBallY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.211,
|
||||
0,
|
||||
0.422,
|
||||
0,
|
||||
0.633,
|
||||
0,
|
||||
1,
|
||||
0.911,
|
||||
0,
|
||||
1.189,
|
||||
-1,
|
||||
1.467,
|
||||
-1,
|
||||
1,
|
||||
1.689,
|
||||
-1,
|
||||
1.911,
|
||||
-1,
|
||||
2.133,
|
||||
-1,
|
||||
1,
|
||||
2.511,
|
||||
-1,
|
||||
2.889,
|
||||
0,
|
||||
3.267,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLY",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.544,
|
||||
1,
|
||||
1.089,
|
||||
1,
|
||||
1.633,
|
||||
1,
|
||||
1,
|
||||
1.856,
|
||||
1,
|
||||
2.078,
|
||||
0,
|
||||
2.3,
|
||||
0,
|
||||
1,
|
||||
2.5,
|
||||
0,
|
||||
2.7,
|
||||
1,
|
||||
2.9,
|
||||
1,
|
||||
0,
|
||||
4.433,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRY",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.544,
|
||||
1,
|
||||
1.089,
|
||||
1,
|
||||
1.633,
|
||||
1,
|
||||
1,
|
||||
1.856,
|
||||
1,
|
||||
2.078,
|
||||
0,
|
||||
2.3,
|
||||
0,
|
||||
1,
|
||||
2.5,
|
||||
0,
|
||||
2.7,
|
||||
1,
|
||||
2.9,
|
||||
1,
|
||||
0,
|
||||
4.433,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLForm",
|
||||
"Segments": [
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
4.433,
|
||||
-1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRForm",
|
||||
"Segments": [
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
4.433,
|
||||
-1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.244,
|
||||
0,
|
||||
0.489,
|
||||
0,
|
||||
0.733,
|
||||
0,
|
||||
1,
|
||||
0.933,
|
||||
0,
|
||||
1.133,
|
||||
-7,
|
||||
1.333,
|
||||
-7,
|
||||
1,
|
||||
1.644,
|
||||
-7,
|
||||
1.956,
|
||||
0,
|
||||
2.267,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.244,
|
||||
0,
|
||||
0.489,
|
||||
0,
|
||||
0.733,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ",
|
||||
"Segments": [
|
||||
0,
|
||||
2,
|
||||
1,
|
||||
0.233,
|
||||
2,
|
||||
0.467,
|
||||
0,
|
||||
0.7,
|
||||
0,
|
||||
1,
|
||||
0.733,
|
||||
0,
|
||||
0.767,
|
||||
0,
|
||||
0.8,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
1.2,
|
||||
-4,
|
||||
1.4,
|
||||
-4,
|
||||
1,
|
||||
1.711,
|
||||
-4,
|
||||
2.022,
|
||||
5,
|
||||
2.333,
|
||||
5,
|
||||
1,
|
||||
2.567,
|
||||
5,
|
||||
2.8,
|
||||
3.64,
|
||||
3.033,
|
||||
0,
|
||||
1,
|
||||
3.133,
|
||||
-1.56,
|
||||
3.233,
|
||||
-3,
|
||||
3.333,
|
||||
-3,
|
||||
1,
|
||||
3.467,
|
||||
-3,
|
||||
3.6,
|
||||
-2,
|
||||
3.733,
|
||||
-2,
|
||||
0,
|
||||
4.433,
|
||||
-2
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBreath",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.189,
|
||||
0,
|
||||
0.378,
|
||||
1,
|
||||
0.567,
|
||||
1,
|
||||
1,
|
||||
0.711,
|
||||
1,
|
||||
0.856,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
1.222,
|
||||
0,
|
||||
1.444,
|
||||
1,
|
||||
1.667,
|
||||
1,
|
||||
1,
|
||||
1.889,
|
||||
1,
|
||||
2.111,
|
||||
0,
|
||||
2.333,
|
||||
0,
|
||||
1,
|
||||
2.544,
|
||||
0,
|
||||
2.756,
|
||||
1,
|
||||
2.967,
|
||||
1,
|
||||
1,
|
||||
3.167,
|
||||
1,
|
||||
3.367,
|
||||
0,
|
||||
3.567,
|
||||
0,
|
||||
0,
|
||||
4.433,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamShoulder",
|
||||
"Segments": [
|
||||
0,
|
||||
0.1,
|
||||
1,
|
||||
0.467,
|
||||
0.1,
|
||||
0.933,
|
||||
1,
|
||||
1.4,
|
||||
1,
|
||||
1,
|
||||
1.844,
|
||||
1,
|
||||
2.289,
|
||||
1,
|
||||
2.733,
|
||||
1,
|
||||
1,
|
||||
2.967,
|
||||
1,
|
||||
3.2,
|
||||
-1,
|
||||
3.433,
|
||||
-1,
|
||||
0,
|
||||
4.433,
|
||||
-1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamLeg",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
4.433,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmLA",
|
||||
"Segments": [
|
||||
0,
|
||||
-10,
|
||||
0,
|
||||
4.433,
|
||||
-10
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmRA",
|
||||
"Segments": [
|
||||
0,
|
||||
-10,
|
||||
0,
|
||||
4.433,
|
||||
-10
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairAhoge",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.3,
|
||||
0,
|
||||
0.6,
|
||||
0,
|
||||
0.9,
|
||||
-0.012,
|
||||
1,
|
||||
1.067,
|
||||
-0.019,
|
||||
1.233,
|
||||
-6.827,
|
||||
1.4,
|
||||
-6.827,
|
||||
1,
|
||||
1.511,
|
||||
-6.827,
|
||||
1.622,
|
||||
7.958,
|
||||
1.733,
|
||||
7.958,
|
||||
1,
|
||||
1.944,
|
||||
7.958,
|
||||
2.156,
|
||||
-7.565,
|
||||
2.367,
|
||||
-7.565,
|
||||
1,
|
||||
2.5,
|
||||
-7.565,
|
||||
2.633,
|
||||
9.434,
|
||||
2.767,
|
||||
9.434,
|
||||
1,
|
||||
2.978,
|
||||
9.434,
|
||||
3.189,
|
||||
-8.871,
|
||||
3.4,
|
||||
-8.871,
|
||||
1,
|
||||
3.5,
|
||||
-8.871,
|
||||
3.6,
|
||||
7.588,
|
||||
3.7,
|
||||
7.588,
|
||||
1,
|
||||
3.789,
|
||||
7.588,
|
||||
3.878,
|
||||
-3.904,
|
||||
3.967,
|
||||
-3.904,
|
||||
1,
|
||||
4.011,
|
||||
-3.904,
|
||||
4.056,
|
||||
-0.032,
|
||||
4.1,
|
||||
-0.032,
|
||||
0,
|
||||
4.433,
|
||||
-0.032
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "PartOpacity",
|
||||
"Id": "PartArmA",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
4.43,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "PartOpacity",
|
||||
"Id": "PartArmB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.43,
|
||||
0
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,927 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"Meta": {
|
||||
"Duration": 1.9,
|
||||
"Fps": 30.0,
|
||||
"Loop": true,
|
||||
"AreBeziersRestricted": false,
|
||||
"CurveCount": 30,
|
||||
"TotalSegmentCount": 121,
|
||||
"TotalPointCount": 331,
|
||||
"UserDataCount": 0,
|
||||
"TotalUserDataSize": 0
|
||||
},
|
||||
"Curves": [
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleZ",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.444,
|
||||
0,
|
||||
0.556,
|
||||
8,
|
||||
0.667,
|
||||
8,
|
||||
0,
|
||||
1.9,
|
||||
8
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamCheek",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.111,
|
||||
1,
|
||||
0.222,
|
||||
1,
|
||||
0.333,
|
||||
1,
|
||||
1,
|
||||
0.378,
|
||||
1,
|
||||
0.422,
|
||||
0,
|
||||
0.467,
|
||||
0,
|
||||
1,
|
||||
0.522,
|
||||
0,
|
||||
0.578,
|
||||
1.2,
|
||||
0.633,
|
||||
1.2,
|
||||
1,
|
||||
0.744,
|
||||
1.2,
|
||||
0.856,
|
||||
1.2,
|
||||
0.967,
|
||||
1.2,
|
||||
1,
|
||||
0.989,
|
||||
1.2,
|
||||
1.011,
|
||||
0,
|
||||
1.033,
|
||||
0,
|
||||
1,
|
||||
1.067,
|
||||
0,
|
||||
1.1,
|
||||
1.2,
|
||||
1.133,
|
||||
1.2,
|
||||
1,
|
||||
1.167,
|
||||
1.2,
|
||||
1.2,
|
||||
1.2,
|
||||
1.233,
|
||||
1.2,
|
||||
1,
|
||||
1.267,
|
||||
1.2,
|
||||
1.3,
|
||||
0,
|
||||
1.333,
|
||||
0,
|
||||
1,
|
||||
1.356,
|
||||
0,
|
||||
1.378,
|
||||
1.2,
|
||||
1.4,
|
||||
1.2,
|
||||
0,
|
||||
1.9,
|
||||
1.2
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeROpen",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.111,
|
||||
1,
|
||||
0.222,
|
||||
1,
|
||||
0.333,
|
||||
1,
|
||||
1,
|
||||
0.378,
|
||||
1,
|
||||
0.422,
|
||||
0,
|
||||
0.467,
|
||||
0,
|
||||
1,
|
||||
0.522,
|
||||
0,
|
||||
0.578,
|
||||
1.2,
|
||||
0.633,
|
||||
1.2,
|
||||
1,
|
||||
0.744,
|
||||
1.2,
|
||||
0.856,
|
||||
1.2,
|
||||
0.967,
|
||||
1.2,
|
||||
1,
|
||||
0.989,
|
||||
1.2,
|
||||
1.011,
|
||||
0,
|
||||
1.033,
|
||||
0,
|
||||
1,
|
||||
1.067,
|
||||
0,
|
||||
1.1,
|
||||
1.2,
|
||||
1.133,
|
||||
1.2,
|
||||
1,
|
||||
1.167,
|
||||
1.2,
|
||||
1.2,
|
||||
1.2,
|
||||
1.233,
|
||||
1.2,
|
||||
1,
|
||||
1.267,
|
||||
1.2,
|
||||
1.3,
|
||||
0,
|
||||
1.333,
|
||||
0,
|
||||
1,
|
||||
1.356,
|
||||
0,
|
||||
1.378,
|
||||
1.2,
|
||||
1.4,
|
||||
1.2,
|
||||
0,
|
||||
1.9,
|
||||
1.2
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0,
|
||||
0.667,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeBallX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0,
|
||||
0.667,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeBallY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0,
|
||||
0.667,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0.26,
|
||||
0.667,
|
||||
0.26,
|
||||
0,
|
||||
1.9,
|
||||
0.26
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0.36,
|
||||
0.667,
|
||||
0.36,
|
||||
0,
|
||||
1.9,
|
||||
0.36
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0,
|
||||
0.667,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
-0.27,
|
||||
0.667,
|
||||
-0.27,
|
||||
0,
|
||||
1.9,
|
||||
-0.27
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0.26,
|
||||
0.667,
|
||||
0.26,
|
||||
0,
|
||||
1.9,
|
||||
0.26
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
-0.03,
|
||||
0.667,
|
||||
-0.03,
|
||||
0,
|
||||
1.9,
|
||||
-0.03
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLForm",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0.33,
|
||||
0.667,
|
||||
0.33,
|
||||
0,
|
||||
1.9,
|
||||
0.33
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRForm",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.356,
|
||||
0,
|
||||
0.378,
|
||||
0,
|
||||
0.4,
|
||||
0,
|
||||
1,
|
||||
0.489,
|
||||
0,
|
||||
0.578,
|
||||
0.21,
|
||||
0.667,
|
||||
0.21,
|
||||
0,
|
||||
1.9,
|
||||
0.21
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.444,
|
||||
0,
|
||||
0.556,
|
||||
-6,
|
||||
0.667,
|
||||
-6,
|
||||
0,
|
||||
1.9,
|
||||
-6
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.422,
|
||||
0,
|
||||
0.511,
|
||||
10,
|
||||
0.6,
|
||||
10,
|
||||
1,
|
||||
0.667,
|
||||
10,
|
||||
0.733,
|
||||
-6,
|
||||
0.8,
|
||||
-6,
|
||||
1,
|
||||
0.833,
|
||||
-6,
|
||||
0.867,
|
||||
5,
|
||||
0.9,
|
||||
5,
|
||||
1,
|
||||
1.011,
|
||||
5,
|
||||
1.122,
|
||||
0,
|
||||
1.233,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.444,
|
||||
0,
|
||||
0.556,
|
||||
-3,
|
||||
0.667,
|
||||
-3,
|
||||
0,
|
||||
1.9,
|
||||
-3
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBreath",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamShoulder",
|
||||
"Segments": [
|
||||
0,
|
||||
-0.062,
|
||||
1,
|
||||
0.111,
|
||||
-0.062,
|
||||
0.222,
|
||||
-0.103,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.589,
|
||||
0.238,
|
||||
0.844,
|
||||
1,
|
||||
1.1,
|
||||
1,
|
||||
0,
|
||||
1.9,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmLA",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.478,
|
||||
0,
|
||||
0.622,
|
||||
-10,
|
||||
0.767,
|
||||
-10,
|
||||
1,
|
||||
0.811,
|
||||
-10,
|
||||
0.856,
|
||||
-8.2,
|
||||
0.9,
|
||||
-8.2,
|
||||
0,
|
||||
1.9,
|
||||
-8.2
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmRA",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
1,
|
||||
0.478,
|
||||
0,
|
||||
0.622,
|
||||
-10,
|
||||
0.767,
|
||||
-10,
|
||||
1,
|
||||
0.811,
|
||||
-10,
|
||||
0.856,
|
||||
-7.2,
|
||||
0.9,
|
||||
-7.2,
|
||||
0,
|
||||
1.9,
|
||||
-7.2
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmLB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmRB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
0,
|
||||
0.333,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairAhoge",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.111,
|
||||
0,
|
||||
0.222,
|
||||
1.9,
|
||||
0.333,
|
||||
5.2,
|
||||
1,
|
||||
0.444,
|
||||
8.5,
|
||||
0.556,
|
||||
9.926,
|
||||
0.667,
|
||||
9.926,
|
||||
1,
|
||||
0.744,
|
||||
9.926,
|
||||
0.822,
|
||||
-10,
|
||||
0.9,
|
||||
-10,
|
||||
1,
|
||||
0.956,
|
||||
-10,
|
||||
1.011,
|
||||
6,
|
||||
1.067,
|
||||
6,
|
||||
1,
|
||||
1.144,
|
||||
6,
|
||||
1.222,
|
||||
-4,
|
||||
1.3,
|
||||
-4,
|
||||
1,
|
||||
1.367,
|
||||
-4,
|
||||
1.433,
|
||||
0,
|
||||
1.5,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "PartOpacity",
|
||||
"Id": "PartArmA",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
1.9,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "PartOpacity",
|
||||
"Id": "PartArmB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1.9,
|
||||
0
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,924 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"Meta": {
|
||||
"Duration": 4.17,
|
||||
"Fps": 30.0,
|
||||
"Loop": true,
|
||||
"AreBeziersRestricted": false,
|
||||
"CurveCount": 31,
|
||||
"TotalSegmentCount": 118,
|
||||
"TotalPointCount": 321,
|
||||
"UserDataCount": 0,
|
||||
"TotalUserDataSize": 0
|
||||
},
|
||||
"Curves": [
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.4,
|
||||
0,
|
||||
0.6,
|
||||
0,
|
||||
0.8,
|
||||
0,
|
||||
1,
|
||||
1.067,
|
||||
0,
|
||||
1.333,
|
||||
1.041,
|
||||
1.6,
|
||||
1.041,
|
||||
1,
|
||||
1.844,
|
||||
1.041,
|
||||
2.089,
|
||||
-8,
|
||||
2.333,
|
||||
-8,
|
||||
1,
|
||||
2.656,
|
||||
-8,
|
||||
2.978,
|
||||
6,
|
||||
3.3,
|
||||
6,
|
||||
0,
|
||||
4.167,
|
||||
6
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.344,
|
||||
0,
|
||||
0.489,
|
||||
-30,
|
||||
0.633,
|
||||
-30,
|
||||
0,
|
||||
4.167,
|
||||
-30
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleZ",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamCheek",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.067,
|
||||
1,
|
||||
0.133,
|
||||
1,
|
||||
0.2,
|
||||
1,
|
||||
1,
|
||||
0.311,
|
||||
1,
|
||||
0.422,
|
||||
0.988,
|
||||
0.533,
|
||||
0.8,
|
||||
1,
|
||||
0.589,
|
||||
0.706,
|
||||
0.644,
|
||||
0,
|
||||
0.7,
|
||||
0,
|
||||
1,
|
||||
0.722,
|
||||
0,
|
||||
0.744,
|
||||
0,
|
||||
0.767,
|
||||
0,
|
||||
1,
|
||||
0.822,
|
||||
0,
|
||||
0.878,
|
||||
0.8,
|
||||
0.933,
|
||||
0.8,
|
||||
1,
|
||||
1.422,
|
||||
0.8,
|
||||
1.911,
|
||||
0.8,
|
||||
2.4,
|
||||
0.8,
|
||||
1,
|
||||
2.456,
|
||||
0.8,
|
||||
2.511,
|
||||
0,
|
||||
2.567,
|
||||
0,
|
||||
1,
|
||||
2.589,
|
||||
0,
|
||||
2.611,
|
||||
0,
|
||||
2.633,
|
||||
0,
|
||||
1,
|
||||
2.689,
|
||||
0,
|
||||
2.744,
|
||||
0.8,
|
||||
2.8,
|
||||
0.8,
|
||||
0,
|
||||
4.167,
|
||||
0.8
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeROpen",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.067,
|
||||
1,
|
||||
0.133,
|
||||
1,
|
||||
0.2,
|
||||
1,
|
||||
1,
|
||||
0.311,
|
||||
1,
|
||||
0.422,
|
||||
0.988,
|
||||
0.533,
|
||||
0.8,
|
||||
1,
|
||||
0.589,
|
||||
0.706,
|
||||
0.644,
|
||||
0,
|
||||
0.7,
|
||||
0,
|
||||
1,
|
||||
0.722,
|
||||
0,
|
||||
0.744,
|
||||
0,
|
||||
0.767,
|
||||
0,
|
||||
1,
|
||||
0.822,
|
||||
0,
|
||||
0.878,
|
||||
0.8,
|
||||
0.933,
|
||||
0.8,
|
||||
1,
|
||||
1.422,
|
||||
0.8,
|
||||
1.911,
|
||||
0.8,
|
||||
2.4,
|
||||
0.8,
|
||||
1,
|
||||
2.456,
|
||||
0.8,
|
||||
2.511,
|
||||
0,
|
||||
2.567,
|
||||
0,
|
||||
1,
|
||||
2.589,
|
||||
0,
|
||||
2.611,
|
||||
0,
|
||||
2.633,
|
||||
0,
|
||||
1,
|
||||
2.689,
|
||||
0,
|
||||
2.744,
|
||||
0.8,
|
||||
2.8,
|
||||
0.8,
|
||||
0,
|
||||
4.167,
|
||||
0.8
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
0,
|
||||
0.433,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeBallX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
0,
|
||||
0.433,
|
||||
0,
|
||||
1,
|
||||
0.667,
|
||||
0,
|
||||
0.9,
|
||||
0.004,
|
||||
1.133,
|
||||
-0.01,
|
||||
1,
|
||||
1.4,
|
||||
-0.025,
|
||||
1.667,
|
||||
-0.43,
|
||||
1.933,
|
||||
-0.43,
|
||||
1,
|
||||
2.211,
|
||||
-0.43,
|
||||
2.489,
|
||||
0.283,
|
||||
2.767,
|
||||
0.283,
|
||||
0,
|
||||
4.167,
|
||||
0.283
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamEyeBallY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
-1,
|
||||
0.433,
|
||||
-1,
|
||||
0,
|
||||
4.167,
|
||||
-1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
0.19,
|
||||
0.433,
|
||||
0.19,
|
||||
0,
|
||||
4.167,
|
||||
0.19
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
0.11,
|
||||
0.433,
|
||||
0.11,
|
||||
0,
|
||||
4.167,
|
||||
0.11
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
-0.48,
|
||||
0.433,
|
||||
-0.48,
|
||||
0,
|
||||
4.167,
|
||||
-0.48
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
-0.29,
|
||||
0.433,
|
||||
-0.29,
|
||||
0,
|
||||
4.167,
|
||||
-0.29
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
1,
|
||||
0.433,
|
||||
1,
|
||||
0,
|
||||
4.167,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
0.85,
|
||||
0.433,
|
||||
0.85,
|
||||
0,
|
||||
4.167,
|
||||
0.85
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowLForm",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
-0.75,
|
||||
0.433,
|
||||
-0.75,
|
||||
0,
|
||||
4.167,
|
||||
-0.75
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBrowRForm",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.278,
|
||||
0,
|
||||
0.356,
|
||||
-0.87,
|
||||
0.433,
|
||||
-0.87,
|
||||
0,
|
||||
4.167,
|
||||
-0.87
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.444,
|
||||
0,
|
||||
0.689,
|
||||
0,
|
||||
0.933,
|
||||
0,
|
||||
1,
|
||||
1.211,
|
||||
0,
|
||||
1.489,
|
||||
0,
|
||||
1.767,
|
||||
0,
|
||||
1,
|
||||
2.056,
|
||||
0,
|
||||
2.344,
|
||||
-6,
|
||||
2.633,
|
||||
-6,
|
||||
1,
|
||||
3.033,
|
||||
-6,
|
||||
3.433,
|
||||
10,
|
||||
3.833,
|
||||
10,
|
||||
0,
|
||||
4.167,
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleY",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.8,
|
||||
0,
|
||||
1.4,
|
||||
-2,
|
||||
2,
|
||||
-2,
|
||||
1,
|
||||
2.456,
|
||||
-2,
|
||||
2.911,
|
||||
8.125,
|
||||
3.367,
|
||||
8.125,
|
||||
0,
|
||||
4.167,
|
||||
8.125
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBreath",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamShoulder",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamLeg",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0.667,
|
||||
1,
|
||||
1.333,
|
||||
1,
|
||||
2,
|
||||
1,
|
||||
1,
|
||||
2.267,
|
||||
1,
|
||||
2.533,
|
||||
0.948,
|
||||
2.8,
|
||||
0.948,
|
||||
0,
|
||||
4.167,
|
||||
0.948
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmLA",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.233,
|
||||
0,
|
||||
0.267,
|
||||
0,
|
||||
0.3,
|
||||
0,
|
||||
1,
|
||||
0.478,
|
||||
0,
|
||||
0.656,
|
||||
-10,
|
||||
0.833,
|
||||
-10,
|
||||
1,
|
||||
0.922,
|
||||
-10,
|
||||
1.011,
|
||||
-8.846,
|
||||
1.1,
|
||||
-8.846,
|
||||
1,
|
||||
1.467,
|
||||
-8.846,
|
||||
1.833,
|
||||
-8.835,
|
||||
2.2,
|
||||
-9.1,
|
||||
1,
|
||||
2.622,
|
||||
-9.405,
|
||||
3.044,
|
||||
-10,
|
||||
3.467,
|
||||
-10,
|
||||
0,
|
||||
4.167,
|
||||
-10
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmRA",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.233,
|
||||
0,
|
||||
0.267,
|
||||
0,
|
||||
0.3,
|
||||
0,
|
||||
1,
|
||||
0.478,
|
||||
0,
|
||||
0.656,
|
||||
-10,
|
||||
0.833,
|
||||
-10,
|
||||
1,
|
||||
0.922,
|
||||
-10,
|
||||
1.011,
|
||||
-8.972,
|
||||
1.1,
|
||||
-8.846,
|
||||
1,
|
||||
1.467,
|
||||
-8.328,
|
||||
1.833,
|
||||
-8.2,
|
||||
2.2,
|
||||
-8.2,
|
||||
1,
|
||||
2.622,
|
||||
-8.2,
|
||||
3.044,
|
||||
-10,
|
||||
3.467,
|
||||
-10,
|
||||
0,
|
||||
4.167,
|
||||
-10
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmLB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmRB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.167,
|
||||
0
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairAhoge",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0.067,
|
||||
0,
|
||||
0.133,
|
||||
0,
|
||||
0.2,
|
||||
0,
|
||||
1,
|
||||
0.233,
|
||||
0,
|
||||
0.267,
|
||||
-5,
|
||||
0.3,
|
||||
-5,
|
||||
1,
|
||||
0.378,
|
||||
-5,
|
||||
0.456,
|
||||
10,
|
||||
0.533,
|
||||
10,
|
||||
1,
|
||||
0.633,
|
||||
10,
|
||||
0.733,
|
||||
4,
|
||||
0.833,
|
||||
4,
|
||||
0,
|
||||
4.167,
|
||||
4
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "PartOpacity",
|
||||
"Id": "PartArmA",
|
||||
"Segments": [
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
4.17,
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "PartOpacity",
|
||||
"Id": "PartArmB",
|
||||
"Segments": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
4.17,
|
||||
0
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
|
||||
============================================================
|
||||
|
||||
示例模型
|
||||
名执 尽 - PRO
|
||||
|
||||
============================================================
|
||||
|
||||
该示例可用于学习商用的游戏和App中常用到的手臂切换等难度较高的制作方法。
|
||||
|
||||
该模型角色由画师先崎真琴设计。
|
||||
模型的手臂通过渐变实现不同部件间的切换,这种制作方法经常应用于商用的游戏和App中。
|
||||
通过该模型,可以学习部件的切换来实现更丰富的动画。
|
||||
|
||||
另外,可以通过Cubism3 Viewer (for OW)来查看嵌入式文件组的动画,了解完整的工作流程中使用到的数据结构。
|
||||
|
||||
|
||||
------------------------------
|
||||
素材使用许可
|
||||
------------------------------
|
||||
|
||||
普通用户以及小规模企业在同意授权协议的情况下可用于商业用途。
|
||||
中/大规模的企业只能用于非公开的内部试用。
|
||||
在使用该素材时,请确认以下的【无偿提供素材使用授权协议】中的“授权类型”、“Live2D原创角色”等的相关内容,
|
||||
并必须接受【Live2D Cubism 示例模型的使用授权要求】中的利用条件。
|
||||
|
||||
有关许可证的更多信息,请参阅以下页面。
|
||||
https://www.live2d.com/zh-CHS/download/sample-data/
|
||||
|
||||
|
||||
------------------------------
|
||||
创作者
|
||||
------------------------------
|
||||
|
||||
插画:先崎 真琴【http://senzakimakoto.com/】
|
||||
配音:小野友树【https://web.onoyuki.com/】
|
||||
(※配音数据的发布为限定发布,已于2018/06/04结束。)
|
||||
模型:Live2D
|
||||
|
||||
|
||||
------------------------------
|
||||
素材内容
|
||||
------------------------------
|
||||
|
||||
模型文件(cmo3) ※包含物理模拟的设定
|
||||
表情动画文件(can3)
|
||||
基本动画文件(can3)
|
||||
嵌入文件组(runtime文件夹)
|
||||
・模型数据(moc3)
|
||||
・表情数据(exp3.json)
|
||||
・动作数据(motion3.json)
|
||||
・模型设定文件(model3.json)
|
||||
・姿势设定文件(pose3.json)
|
||||
・物理模拟设定文件(physics3.json)
|
||||
・辅助显示的文件(cdi3.json)
|
||||
|
||||
|
||||
------------------------------
|
||||
更新记录
|
||||
------------------------------
|
||||
※配音数据的发布已于2018/06/04结束。
|
||||
|
||||
【cmo3】
|
||||
|
||||
natori_pro_t06.cmo3
|
||||
2021年6月10日 公开
|
||||
|
||||
|
||||
【can3】
|
||||
|
||||
natori_pro_exp_t03.can3
|
||||
2021年6月10日 公开
|
||||
|
||||
|
||||
【can3】
|
||||
|
||||
natori_pro_motions_t03.can3
|
||||
2021年6月10日 公开
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": -2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": -2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0.3,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0.3,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": -0.4,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": -0.4,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": -2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": -2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0.3,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0.3,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0.2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0.2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": -0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": -0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 3,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 3,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": -0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": -0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": 0.2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": 0.2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0.2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0.2,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": -0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": -0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0.1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"Type": "Live2D Expression",
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"Value": -1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"Value": 1,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"Value": 0,
|
||||
"Blend": "Add"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,44 @@
|
|||
{
|
||||
"Type": "Live2D Pose",
|
||||
"FadeInTime": 0.2,
|
||||
"Groups": [
|
||||
[
|
||||
{
|
||||
"Id": "PartArmAL",
|
||||
"Link": []
|
||||
},
|
||||
{
|
||||
"Id": "PartArmCL",
|
||||
"Link": []
|
||||
},
|
||||
{
|
||||
"Id": "PartArmDL",
|
||||
"Link": []
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"Id": "PartArmAR",
|
||||
"Link": []
|
||||
},
|
||||
{
|
||||
"Id": "PartArmBR",
|
||||
"Link": []
|
||||
},
|
||||
{
|
||||
"Id": "PartArmER",
|
||||
"Link": []
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"Id": "PartWatchA",
|
||||
"Link": []
|
||||
},
|
||||
{
|
||||
"Id": "PartWatchB",
|
||||
"Link": []
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.6 MiB |
|
|
@ -0,0 +1,711 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"Parameters": [
|
||||
{
|
||||
"Id": "ParamAngleX",
|
||||
"GroupId": "",
|
||||
"Name": "角度 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAngleY",
|
||||
"GroupId": "",
|
||||
"Name": "角度 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAngleZ",
|
||||
"GroupId": "",
|
||||
"Name": "角度 Z"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLOpen",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眼 开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLSmile",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眼 微笑"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeLForm",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眼 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeROpen",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眼 开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRSmile",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眼 微笑"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeRForm",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眼 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallX",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "眼珠 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallY",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "眼珠 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamEyeBallForm",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "眼珠 缩放"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLY",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眉 上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRY",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眉 上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLX",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眉 左右"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRX",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眉 左右"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLAngle",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眉 角度"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRAngle",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眉 角度"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眉 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowLForm2",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "左眉 变形2"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眉 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBrowRForm2",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "右眉 变形2"
|
||||
},
|
||||
{
|
||||
"Id": "ParamMouthForm",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "嘴 变形"
|
||||
},
|
||||
{
|
||||
"Id": "ParamMouthOpenY",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "嘴 开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamMouthForm2",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "嘴 变形2"
|
||||
},
|
||||
{
|
||||
"Id": "ParamTeethOn",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "牙齿的显示"
|
||||
},
|
||||
{
|
||||
"Id": "ParamCheek",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "害羞"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGlassUD",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "眼镜 上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassWhite",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "镜片 白"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlight",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "镜片 反光显示"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGrassHighlightMove",
|
||||
"GroupId": "ParamGroupExpression",
|
||||
"Name": "镜片 反光移动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyAngleX",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的旋转 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyAngleY",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的旋转 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyAngleZ",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的旋转 Z"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWaistAngleZ",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "腰的旋转 Z"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBodyPosition",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "身体的前后"
|
||||
},
|
||||
{
|
||||
"Id": "ParamBreath",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "呼吸"
|
||||
},
|
||||
{
|
||||
"Id": "ParamLeftShoulderUp",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "左肩的上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamRightShoulderUp",
|
||||
"GroupId": "ParamGroupBody",
|
||||
"Name": "右肩的上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAllX",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "整体的移动 X"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAllY",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "整体的移动 Y"
|
||||
},
|
||||
{
|
||||
"Id": "ParamAllRotate",
|
||||
"GroupId": "ParamGroup",
|
||||
"Name": "整体的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairFront",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "头发摇动 前"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairSide",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "头发摇动 侧"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairBack",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "头发摇动 后"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairFrontFuwa",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "前发 蓬松"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairSideFuwa",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "侧发 蓬松"
|
||||
},
|
||||
{
|
||||
"Id": "ParamHairBackFuwa",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "后发 蓬松"
|
||||
},
|
||||
{
|
||||
"Id": "ParamJacket",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "燕尾的摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamChainWaist",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "表链A的摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchSwingA1",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "怀表A 摇动1"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchSwingA2",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "怀表A 摇动2"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBChain",
|
||||
"GroupId": "ParamGroupSway",
|
||||
"Name": "怀表B 表链的摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchAX",
|
||||
"GroupId": "ParamGroup8",
|
||||
"Name": "怀表A 横向旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBSwitch",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 开关"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBOpen",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 表盖的开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBOpen2",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 表盘的开闭"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBX",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 横向旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBRoll",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBLR",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 左右"
|
||||
},
|
||||
{
|
||||
"Id": "ParamWatchBUD",
|
||||
"GroupId": "ParamGroup9",
|
||||
"Name": "怀表B 上下"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAL01",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "左手臂A 肩"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAL02",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "左肩A 手肘旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAL03",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "左手臂A 手腕"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAL04",
|
||||
"GroupId": "ParamGroup3",
|
||||
"Name": "左手臂A 前臂的前后"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAR01",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "右手臂A 肩的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAR02",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "右手臂A 手肘的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAR03",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "右手臂A 手腕的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmAR04",
|
||||
"GroupId": "ParamGroup2",
|
||||
"Name": "右手臂A 前臂的前后"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBR01",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手臂B 肩的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBR02",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手臂B 手肘的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBR03",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手臂B 手腕的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBRHand01",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手01 显示"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBRHand01Roll",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手01 手指弯曲"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBRHand05",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手05 显示"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBRHand05Roll1",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手05 手指弯曲1"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBRHand05Roll2",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手05 手指弯曲2"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmBRHand05Roll3",
|
||||
"GroupId": "ParamGroup4",
|
||||
"Name": "右手05 手指弯曲3"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmCR01",
|
||||
"GroupId": "ParamGroup5",
|
||||
"Name": "左手臂C 肩的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmCR02",
|
||||
"GroupId": "ParamGroup5",
|
||||
"Name": "左手臂C 手肘的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmCR03",
|
||||
"GroupId": "ParamGroup5",
|
||||
"Name": "左手臂C 手腕的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmCLHandRoll1",
|
||||
"GroupId": "ParamGroup5",
|
||||
"Name": "左手C 手指弯曲1"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmDL01",
|
||||
"GroupId": "ParamGroup6",
|
||||
"Name": "左手臂D 肩的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmDL02",
|
||||
"GroupId": "ParamGroup6",
|
||||
"Name": "左手臂D 手肘的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmDL03",
|
||||
"GroupId": "ParamGroup6",
|
||||
"Name": "左手臂D 手腕的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmDLHand03Roll",
|
||||
"GroupId": "ParamGroup6",
|
||||
"Name": "左手03 手指弯曲"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmER01",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手臂E 肩的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmER02",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手臂E 手肘的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmER03",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手臂E 手腕的旋转"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmER04",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手臂E 上臂的长度"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmERHand04",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手04 显示"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmERHand04Roll1",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手04 手指弯曲1"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmERHand04Roll2",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手04 手指弯曲2"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmERHand06",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手06 显示"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmERHand06Roll1",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手06 手指弯曲1"
|
||||
},
|
||||
{
|
||||
"Id": "ParamArmERHand06Roll2",
|
||||
"GroupId": "ParamGroup7",
|
||||
"Name": "右手06 手指弯曲2"
|
||||
}
|
||||
],
|
||||
"ParameterGroups": [
|
||||
{
|
||||
"Id": "ParamGroupExpression",
|
||||
"GroupId": "",
|
||||
"Name": "表情"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupBody",
|
||||
"GroupId": "",
|
||||
"Name": "身体"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup",
|
||||
"GroupId": "",
|
||||
"Name": "整体移动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroupSway",
|
||||
"GroupId": "",
|
||||
"Name": "摇动"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup8",
|
||||
"GroupId": "",
|
||||
"Name": "怀表A"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup9",
|
||||
"GroupId": "",
|
||||
"Name": "怀表B"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup3",
|
||||
"GroupId": "",
|
||||
"Name": "左手臂A"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup2",
|
||||
"GroupId": "",
|
||||
"Name": "右手臂A"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup4",
|
||||
"GroupId": "",
|
||||
"Name": "右手臂B"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup5",
|
||||
"GroupId": "",
|
||||
"Name": "左手臂C"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup6",
|
||||
"GroupId": "",
|
||||
"Name": "左手臂D"
|
||||
},
|
||||
{
|
||||
"Id": "ParamGroup7",
|
||||
"GroupId": "",
|
||||
"Name": "右手臂E"
|
||||
}
|
||||
],
|
||||
"Parts": [
|
||||
{
|
||||
"Id": "PartCredit",
|
||||
"Name": "名牌"
|
||||
},
|
||||
{
|
||||
"Id": "PartCore",
|
||||
"Name": "CORE"
|
||||
},
|
||||
{
|
||||
"Id": "PartGlass",
|
||||
"Name": "眼镜"
|
||||
},
|
||||
{
|
||||
"Id": "PartWatchA",
|
||||
"Name": "怀表A"
|
||||
},
|
||||
{
|
||||
"Id": "PartWatchB",
|
||||
"Name": "怀表B"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairFront",
|
||||
"Name": "前发"
|
||||
},
|
||||
{
|
||||
"Id": "PartHead",
|
||||
"Name": "头"
|
||||
},
|
||||
{
|
||||
"Id": "PartUpperBody",
|
||||
"Name": "上半身"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairBack",
|
||||
"Name": "后发"
|
||||
},
|
||||
{
|
||||
"Id": "PartLowerBody",
|
||||
"Name": "下半身"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmAL",
|
||||
"Name": "左手臂A"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmAR",
|
||||
"Name": "右手臂A"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmBR",
|
||||
"Name": "右手臂B"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmCL",
|
||||
"Name": "左手臂C"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmDL",
|
||||
"Name": "左手臂D"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmER",
|
||||
"Name": "右手臂E"
|
||||
},
|
||||
{
|
||||
"Id": "PartEyeBlow",
|
||||
"Name": "眉毛"
|
||||
},
|
||||
{
|
||||
"Id": "PartEyeR",
|
||||
"Name": "右眼"
|
||||
},
|
||||
{
|
||||
"Id": "PartEyeL",
|
||||
"Name": "左眼"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairLine",
|
||||
"Name": "发际线"
|
||||
},
|
||||
{
|
||||
"Id": "PartHairShadow",
|
||||
"Name": "头发阴影"
|
||||
},
|
||||
{
|
||||
"Id": "PartNose",
|
||||
"Name": "鼻子"
|
||||
},
|
||||
{
|
||||
"Id": "PartMouth",
|
||||
"Name": "嘴"
|
||||
},
|
||||
{
|
||||
"Id": "PartJacket",
|
||||
"Name": "燕尾服"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmALFore",
|
||||
"Name": "左手臂A 前臂"
|
||||
},
|
||||
{
|
||||
"Id": "PartArmARFore",
|
||||
"Name": "右手臂A 前臂"
|
||||
},
|
||||
{
|
||||
"Id": "PartHand11",
|
||||
"Name": "手套_1"
|
||||
},
|
||||
{
|
||||
"Id": "PartHand51",
|
||||
"Name": "手套_5"
|
||||
},
|
||||
{
|
||||
"Id": "PartHand21",
|
||||
"Name": "手套_2"
|
||||
},
|
||||
{
|
||||
"Id": "PartHand31",
|
||||
"Name": "手套_3"
|
||||
},
|
||||
{
|
||||
"Id": "PartHand41",
|
||||
"Name": "手套_4"
|
||||
},
|
||||
{
|
||||
"Id": "PartHand61",
|
||||
"Name": "手套_6"
|
||||
}
|
||||
],
|
||||
"CombinedParameters": [
|
||||
[
|
||||
"ParamAngleX",
|
||||
"ParamAngleY"
|
||||
],
|
||||
[
|
||||
"ParamEyeBallX",
|
||||
"ParamEyeBallY"
|
||||
],
|
||||
[
|
||||
"ParamMouthForm",
|
||||
"ParamMouthOpenY"
|
||||
],
|
||||
[
|
||||
"ParamBodyAngleX",
|
||||
"ParamBodyAngleY"
|
||||
],
|
||||
[
|
||||
"ParamLeftShoulderUp",
|
||||
"ParamRightShoulderUp"
|
||||
],
|
||||
[
|
||||
"ParamAllX",
|
||||
"ParamAllY"
|
||||
],
|
||||
[
|
||||
"ParamWatchSwingA1",
|
||||
"ParamWatchSwingA2"
|
||||
],
|
||||
[
|
||||
"ParamWatchBLR",
|
||||
"ParamWatchBUD"
|
||||
]
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
|
@ -0,0 +1,123 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"FileReferences": {
|
||||
"Moc": "natori_pro_t06.moc3",
|
||||
"Textures": [
|
||||
"natori_pro_t06.4096/texture_00.png"
|
||||
],
|
||||
"Physics": "natori_pro_t06.physics3.json",
|
||||
"Pose": "natori.pose3.json",
|
||||
"DisplayInfo": "natori_pro_t06.cdi3.json",
|
||||
"Expressions": [
|
||||
{
|
||||
"Name": "Angry",
|
||||
"File": "exp/Angry.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "Blushing",
|
||||
"File": "exp/Blushing.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "Normal",
|
||||
"File": "exp/Normal.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "Sad",
|
||||
"File": "exp/Sad.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "Smile",
|
||||
"File": "exp/Smile.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "Surprised",
|
||||
"File": "exp/Surprised.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "exp_01",
|
||||
"File": "exp/exp_01.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "exp_02",
|
||||
"File": "exp/exp_02.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "exp_03",
|
||||
"File": "exp/exp_03.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "exp_04",
|
||||
"File": "exp/exp_04.exp3.json"
|
||||
},
|
||||
{
|
||||
"Name": "exp_05",
|
||||
"File": "exp/exp_05.exp3.json"
|
||||
}
|
||||
],
|
||||
"Motions": {
|
||||
"Idle": [
|
||||
{
|
||||
"File": "motions/mtn_00.motion3.json"
|
||||
},
|
||||
{
|
||||
"File": "motions/mtn_01.motion3.json"
|
||||
},
|
||||
{
|
||||
"File": "motions/mtn_02.motion3.json"
|
||||
}
|
||||
],
|
||||
"Tap": [
|
||||
{
|
||||
"File": "motions/mtn_03.motion3.json"
|
||||
}
|
||||
],
|
||||
"FlickUp@Head": [
|
||||
{
|
||||
"File": "motions/mtn_04.motion3.json"
|
||||
}
|
||||
],
|
||||
"Flick@Body": [
|
||||
{
|
||||
"File": "motions/mtn_05.motion3.json"
|
||||
}
|
||||
],
|
||||
"FlickDown@Body": [
|
||||
{
|
||||
"File": "motions/mtn_06.motion3.json"
|
||||
}
|
||||
],
|
||||
"Tap@Head": [
|
||||
{
|
||||
"File": "motions/mtn_07.motion3.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"Groups": [
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Name": "LipSync",
|
||||
"Ids": [
|
||||
"ParamMouthOpenY"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Target": "Parameter",
|
||||
"Name": "EyeBlink",
|
||||
"Ids": [
|
||||
"ParamEyeLOpen",
|
||||
"ParamEyeROpen"
|
||||
]
|
||||
}
|
||||
],
|
||||
"HitAreas": [
|
||||
{
|
||||
"Id": "HitAreaHead",
|
||||
"Name": ""
|
||||
},
|
||||
{
|
||||
"Id": "HitAreaBody",
|
||||
"Name": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,966 @@
|
|||
{
|
||||
"Version": 3,
|
||||
"Meta": {
|
||||
"PhysicsSettingCount": 11,
|
||||
"TotalInputCount": 34,
|
||||
"TotalOutputCount": 12,
|
||||
"VertexCount": 23,
|
||||
"EffectiveForces": {
|
||||
"Gravity": {
|
||||
"X": 0,
|
||||
"Y": -1
|
||||
},
|
||||
"Wind": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
}
|
||||
},
|
||||
"PhysicsDictionary": [
|
||||
{
|
||||
"Id": "PhysicsSetting1",
|
||||
"Name": "前髪 揺れ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting2",
|
||||
"Name": "横髪 揺れ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting3",
|
||||
"Name": "後ろ髪 揺れ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting4",
|
||||
"Name": "前髪ふわ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting5",
|
||||
"Name": "横髪ふわ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting6",
|
||||
"Name": "後ろ髪ふわ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting7",
|
||||
"Name": "燕尾揺れ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting8",
|
||||
"Name": "懐中時計腰 揺れ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting9",
|
||||
"Name": "腰のチェーン揺れ"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting10",
|
||||
"Name": "懐中時計腰 横回転"
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting11",
|
||||
"Name": "懐中時計B チェーン揺れ"
|
||||
}
|
||||
]
|
||||
},
|
||||
"PhysicsSettings": [
|
||||
{
|
||||
"Id": "PhysicsSetting1",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleX"
|
||||
},
|
||||
"Weight": 60,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleZ"
|
||||
},
|
||||
"Weight": 60,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 40,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 40,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairFront"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 1.824,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 12.7
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 0.9,
|
||||
"Acceleration": 1,
|
||||
"Radius": 12.7
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting2",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleX"
|
||||
},
|
||||
"Weight": 60,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleZ"
|
||||
},
|
||||
"Weight": 60,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 40,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 40,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairSide"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 2,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 18.2
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 0.9,
|
||||
"Acceleration": 1,
|
||||
"Radius": 18.2
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting3",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleX"
|
||||
},
|
||||
"Weight": 60,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleZ"
|
||||
},
|
||||
"Weight": 60,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 40,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 40,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairBack"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 2,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 14.3
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 0.9,
|
||||
"Acceleration": 1.42,
|
||||
"Radius": 14.3
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting4",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleY"
|
||||
},
|
||||
"Weight": 35,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleY"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyPosition"
|
||||
},
|
||||
"Weight": 35,
|
||||
"Type": "X",
|
||||
"Reflect": true
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairFrontFuwa"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 3,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": true
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 11.9
|
||||
},
|
||||
"Mobility": 0.79,
|
||||
"Delay": 0.9,
|
||||
"Acceleration": 1,
|
||||
"Radius": 11.9
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting5",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleY"
|
||||
},
|
||||
"Weight": 35,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleY"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyPosition"
|
||||
},
|
||||
"Weight": 35,
|
||||
"Type": "X",
|
||||
"Reflect": true
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairSideFuwa"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 3.5,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": true
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 14.3
|
||||
},
|
||||
"Mobility": 0.79,
|
||||
"Delay": 0.9,
|
||||
"Acceleration": 1.1,
|
||||
"Radius": 14.3
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting6",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamAngleY"
|
||||
},
|
||||
"Weight": 35,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleY"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyPosition"
|
||||
},
|
||||
"Weight": 35,
|
||||
"Type": "X",
|
||||
"Reflect": true
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamHairBackFuwa"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 5,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": true
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 11.3
|
||||
},
|
||||
"Mobility": 0.79,
|
||||
"Delay": 0.9,
|
||||
"Acceleration": 1.16,
|
||||
"Radius": 11.3
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting7",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 100,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 70,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWaistAngleZ"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamJacket"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 1,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 31.9
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 0.8,
|
||||
"Acceleration": 0.8,
|
||||
"Radius": 31.9
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting8",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 100,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 70,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWaistAngleZ"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWatchSwingA1"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 1,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWatchSwingA2"
|
||||
},
|
||||
"VertexIndex": 2,
|
||||
"Scale": 1,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 15.4
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 1,
|
||||
"Acceleration": 0.8,
|
||||
"Radius": 15.4
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 31.9
|
||||
},
|
||||
"Mobility": 0.9,
|
||||
"Delay": 1,
|
||||
"Acceleration": 0.6,
|
||||
"Radius": 16.5
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting9",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 100,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 70,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWaistAngleZ"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamChainWaist"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 1,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 11.6
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 11.6
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting10",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleX"
|
||||
},
|
||||
"Weight": 100,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamBodyAngleZ"
|
||||
},
|
||||
"Weight": 70,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
},
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWaistAngleZ"
|
||||
},
|
||||
"Weight": 30,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWatchAX"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 2,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 72.1
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 1,
|
||||
"Acceleration": 0.2,
|
||||
"Radius": 72.1
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Id": "PhysicsSetting11",
|
||||
"Input": [
|
||||
{
|
||||
"Source": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamArmBR03"
|
||||
},
|
||||
"Weight": 100,
|
||||
"Type": "X",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Output": [
|
||||
{
|
||||
"Destination": {
|
||||
"Target": "Parameter",
|
||||
"Id": "ParamWatchBChain"
|
||||
},
|
||||
"VertexIndex": 1,
|
||||
"Scale": 2,
|
||||
"Weight": 100,
|
||||
"Type": "Angle",
|
||||
"Reflect": false
|
||||
}
|
||||
],
|
||||
"Vertices": [
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 0
|
||||
},
|
||||
"Mobility": 1,
|
||||
"Delay": 1,
|
||||
"Acceleration": 1,
|
||||
"Radius": 0
|
||||
},
|
||||
{
|
||||
"Position": {
|
||||
"X": 0,
|
||||
"Y": 13.1
|
||||
},
|
||||
"Mobility": 0.95,
|
||||
"Delay": 1,
|
||||
"Acceleration": 0.66,
|
||||
"Radius": 13.1
|
||||
}
|
||||
],
|
||||
"Normalization": {
|
||||
"Position": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
},
|
||||
"Angle": {
|
||||
"Minimum": -10,
|
||||
"Default": 0,
|
||||
"Maximum": 10
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
38
main/feedback-backend/alembic.ini
Normal file
38
main/feedback-backend/alembic.ini
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# Alembic 配置文件
|
||||
|
||||
[alembic]
|
||||
script_location = migrations
|
||||
sqlalchemy.url = mysql+pymysql://root:123456@127.0.0.1:3306/feedback_db?charset=utf8mb4
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
0
main/feedback-backend/app/__init__.py
Normal file
0
main/feedback-backend/app/__init__.py
Normal file
0
main/feedback-backend/app/agent/__init__.py
Normal file
0
main/feedback-backend/app/agent/__init__.py
Normal file
49
main/feedback-backend/app/agent/graph.py
Normal file
49
main/feedback-backend/app/agent/graph.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""轻量 Agent Graph。
|
||||
|
||||
不是完整 LangGraph 依赖,而是一个小型有向执行器:
|
||||
Intent -> Plan -> Execute skills -> Summarize。
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentStep:
|
||||
skill: str
|
||||
args: dict = field(default_factory=dict)
|
||||
risk: str = "read"
|
||||
result: Any = None
|
||||
error: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentState:
|
||||
message: str
|
||||
store_id: Optional[str] = None
|
||||
operator: str = ""
|
||||
intent: str = "unknown"
|
||||
steps: list[AgentStep] = field(default_factory=list)
|
||||
final_answer: str = ""
|
||||
route: Optional[str] = None
|
||||
data: Any = None
|
||||
trace: list[dict] = field(default_factory=list)
|
||||
|
||||
|
||||
class AgentGraph:
|
||||
def __init__(self, planner: Callable[[AgentState], AgentState], executor: Callable[[AgentState, AgentStep], Any], summarizer: Callable[[AgentState], AgentState]):
|
||||
self.planner = planner
|
||||
self.executor = executor
|
||||
self.summarizer = summarizer
|
||||
|
||||
async def run(self, state: AgentState) -> AgentState:
|
||||
state = self.planner(state)
|
||||
for step in state.steps:
|
||||
try:
|
||||
step.result = await self.executor(state, step)
|
||||
state.trace.append({"skill": step.skill, "risk": step.risk, "ok": True})
|
||||
except Exception as exc: # MVP:失败即停止
|
||||
step.error = str(exc)
|
||||
state.trace.append({"skill": step.skill, "risk": step.risk, "ok": False, "error": step.error})
|
||||
break
|
||||
return self.summarizer(state)
|
||||
0
main/feedback-backend/app/application/__init__.py
Normal file
0
main/feedback-backend/app/application/__init__.py
Normal file
502
main/feedback-backend/app/application/agent_chat_service.py
Normal file
502
main/feedback-backend/app/application/agent_chat_service.py
Normal file
|
|
@ -0,0 +1,502 @@
|
|||
"""后台 AI 助手服务 - 将自然语言路由到 CRM/统计能力。
|
||||
|
||||
当前是安全 MVP:用规则识别常见意图并调用现有应用服务。
|
||||
后续可替换为 LLM + skill/CLI 工具调用。
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.application.crm_service import CrmService
|
||||
from app.application.stats_service import StatsService
|
||||
|
||||
|
||||
class AgentChatService:
|
||||
"""后台 AI 助手服务"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.session = session
|
||||
self.crm = CrmService(session)
|
||||
self.stats = StatsService(session)
|
||||
|
||||
async def chat(self, message: str, history: Optional[list[dict]] = None, store_id: Optional[str] = None, operator: str = "") -> dict:
|
||||
from app.agent.graph import AgentGraph, AgentState
|
||||
|
||||
graph = AgentGraph(self._plan, self._execute_step, self._summarize)
|
||||
contextual_message = self._with_context(message, history or [])
|
||||
state = await graph.run(AgentState(message=contextual_message, store_id=store_id, operator=operator))
|
||||
return {"reply": state.final_answer, "data": state.data, "route": state.route, "intent": state.intent, "trace": state.trace, "action": getattr(state, "action", None)}
|
||||
|
||||
def _plan(self, state):
|
||||
from app.agent.graph import AgentStep
|
||||
|
||||
original_text = state.message
|
||||
text = self._current_user_text(original_text)
|
||||
if not text:
|
||||
state.intent = "help"
|
||||
state.steps = [AgentStep("help")]
|
||||
elif self._has(text, ["帮助", "怎么用", "help", "菜单"]):
|
||||
state.intent = "help"
|
||||
state.steps = [AgentStep("help")]
|
||||
elif self._has(text, ["kpi", "KPI", "员工统计", "员工评价", "好评", "差评排行"]):
|
||||
state.intent = "employee_kpi"
|
||||
state.steps = [AgentStep("stats.employee-kpi")]
|
||||
elif self._has(text, ["概览", "看板", "总览", "crm概况", "CRM概况"]):
|
||||
state.intent = "crm_overview"
|
||||
state.steps = [AgentStep("crm.overview")]
|
||||
elif self._is_appointment_request(text):
|
||||
state.intent = "appointment_request"
|
||||
state.steps = [AgentStep("appointment.plan", self._extract_appointment_payload(text), risk="write")]
|
||||
elif self._has(text, ["创建产品", "新增产品", "新建产品"]):
|
||||
state.intent = "product_create"
|
||||
state.steps = [AgentStep("form.open", {"form": "crm.product.create", "payload": self._extract_product_payload(text)}, risk="write")]
|
||||
elif self._has(text, ["身体变化", "身体状态", "体重", "腰围", "睡眠", "疼痛"]):
|
||||
tail = self._extract_phone_tail(text)
|
||||
if tail:
|
||||
state.intent = "member_body_status"
|
||||
state.steps = [
|
||||
AgentStep("crm.member-list", {"keyword": tail}),
|
||||
AgentStep("crm.body-status-list", {"from_previous_member": True}),
|
||||
]
|
||||
else:
|
||||
state.intent = "body_status"
|
||||
state.steps = [AgentStep("crm.body-status-list")]
|
||||
elif self._has(text, ["产品", "套餐", "养生", "减肥", "product", "package"]):
|
||||
tail = self._extract_phone_tail(text)
|
||||
if tail and self._has(text, ["剩", "还有", "几次", "多少次"]):
|
||||
state.intent = "member_package_balance"
|
||||
state.steps = [
|
||||
AgentStep("crm.member-list", {"keyword": tail}),
|
||||
AgentStep("crm.member-product-list", {"from_previous_member": True}),
|
||||
]
|
||||
elif tail and self._has(text, ["消费", "扣", "用一次", "做一次"]):
|
||||
state.intent = "member_package_consume_plan"
|
||||
state.steps = [
|
||||
AgentStep("crm.member-list", {"keyword": tail}),
|
||||
AgentStep("crm.member-product-list", {"from_previous_member": True}),
|
||||
AgentStep("confirm.required", {"action": "product_consume"}, risk="danger"),
|
||||
]
|
||||
else:
|
||||
state.intent = "products"
|
||||
state.steps = [AgentStep("crm.product-list", {"keyword": self._extract_keyword(text)})]
|
||||
elif self._has(text, ["麦凯66", "麦凯", "66字段"]):
|
||||
state.intent = "mekai66"
|
||||
state.steps = [AgentStep("crm.mekai66-fields")]
|
||||
elif self._has(text, ["建议"]):
|
||||
state.intent = "suggestions"
|
||||
state.steps = [AgentStep("crm.suggestion-list", {"status": "pending" if self._has(text, ["待处理", "未处理"]) else None})]
|
||||
elif self._has(text, ["问题", "修复", "投诉"]):
|
||||
state.intent = "issues"
|
||||
state.steps = [AgentStep("crm.issue-list", {"status": "identified" if self._has(text, ["待修复", "待处理", "未修复"]) else None})]
|
||||
elif self._has(text, ["账户流水", "流水"]):
|
||||
state.intent = "transactions"
|
||||
state.steps = [AgentStep("crm.transactions", {"member_id": self._extract_id(text, "member")})]
|
||||
elif self._has(text, ["账户", "卡", "余额", "剩余次数"]):
|
||||
state.intent = "accounts"
|
||||
state.steps = [AgentStep("crm.account-list", {"member_id": self._extract_id(text, "member")})]
|
||||
elif self._has(text, ["创建客户", "新增客户", "新建客户", "创建用户", "新增用户", "新建用户"]):
|
||||
state.intent = "member_create"
|
||||
state.steps = [AgentStep("form.open", {"form": "crm.member.create", "payload": self._extract_member_payload(text)}, risk="write")]
|
||||
else:
|
||||
tail = self._extract_phone_tail(text)
|
||||
if tail or self._has(text, ["查客户", "找客户", "客户"]):
|
||||
state.intent = "member_search"
|
||||
state.steps = [AgentStep("crm.member-list", {"keyword": tail or self._extract_keyword(text)})]
|
||||
else:
|
||||
state.intent = "unknown"
|
||||
state.steps = [AgentStep("unknown")]
|
||||
return state
|
||||
|
||||
async def _execute_step(self, state, step):
|
||||
skill = step.skill
|
||||
args = step.args
|
||||
if skill == "help":
|
||||
return self._help()["reply"]
|
||||
if skill == "unknown":
|
||||
return "我暂时没理解。你可以说:查客户尾号1234、员工KPI、CRM概览、产品套餐、待处理建议、待修复问题、账户流水。"
|
||||
if skill == "appointment.plan":
|
||||
return args
|
||||
if skill == "form.open":
|
||||
return args
|
||||
if skill == "stats.employee-kpi":
|
||||
return await self.stats.get_employee_kpi(state.store_id)
|
||||
if skill == "crm.overview":
|
||||
return await self.crm.get_overview(state.store_id)
|
||||
if skill == "crm.body-status-list":
|
||||
member_id = args.get("member_id")
|
||||
if args.get("from_previous_member") and state.steps and state.steps[0].result:
|
||||
members = state.steps[0].result.get("list") if isinstance(state.steps[0].result, dict) else []
|
||||
member_id = members[0].get("id") if members else None
|
||||
return await self.crm.list_body_statuses(page=1, page_size=10, store_id=state.store_id, member_id=member_id)
|
||||
if skill == "crm.product-create":
|
||||
if not args.get("productName"):
|
||||
return {"error": "创建产品需要产品名称,例如:创建产品 冰蚕乌酒"}
|
||||
return await self.crm.create_product({"store_id": state.store_id, **args}, state.operator)
|
||||
if skill == "crm.product-list":
|
||||
return await self.crm.list_products(page=1, page_size=10, store_id=state.store_id, keyword=args.get("keyword"))
|
||||
if skill == "crm.member-product-list":
|
||||
member_id = args.get("member_id")
|
||||
if args.get("from_previous_member") and state.steps and state.steps[0].result:
|
||||
members = state.steps[0].result.get("list") if isinstance(state.steps[0].result, dict) else []
|
||||
member_id = members[0].get("id") if members else None
|
||||
if not member_id:
|
||||
return {"list": [], "total": 0, "message": "未找到客户,无法查询已购套餐"}
|
||||
return await self.crm.list_member_products(page=1, page_size=10, store_id=state.store_id, member_id=member_id, status=1)
|
||||
if skill == "confirm.required":
|
||||
return {"needConfirmation": True, "message": "这是会减少客户套餐次数的操作,当前版本先返回待确认计划,暂不自动执行。请在客户套餐页或CLI确认后执行。"}
|
||||
if skill == "crm.mekai66-fields":
|
||||
from app.shared.mekai66 import MEKAI66_FIELDS
|
||||
return MEKAI66_FIELDS
|
||||
if skill == "crm.suggestion-list":
|
||||
return await self.crm.list_suggestions(page=1, page_size=10, store_id=state.store_id, status=args.get("status"))
|
||||
if skill == "crm.issue-list":
|
||||
return await self.crm.list_issues(page=1, page_size=10, store_id=state.store_id, status=args.get("status"))
|
||||
if skill == "crm.transactions":
|
||||
return await self.crm.list_account_transactions(page=1, page_size=10, store_id=state.store_id, member_id=args.get("member_id"))
|
||||
if skill == "crm.account-list":
|
||||
return await self.crm.list_accounts(page=1, page_size=10, store_id=state.store_id, member_id=args.get("member_id"))
|
||||
if skill == "crm.member-create":
|
||||
if not args.get("phone") and not args.get("name"):
|
||||
return {"error": "创建客户需要至少提供姓名或手机号,例如:新增客户 张女士 13800001234"}
|
||||
payload = {"store_id": state.store_id, "source": "agent", **args}
|
||||
return await self.crm.create_member(payload, state.operator)
|
||||
if skill == "crm.member-list":
|
||||
return await self.crm.list_members(page=1, page_size=10, store_id=state.store_id, keyword=args.get("keyword"))
|
||||
return {"error": f"未注册skill: {skill}"}
|
||||
|
||||
def _summarize(self, state):
|
||||
if not state.steps:
|
||||
state.final_answer = "无执行步骤。"
|
||||
return state
|
||||
step = state.steps[-1]
|
||||
data = step.result
|
||||
state.data = data
|
||||
if isinstance(data, dict) and data.get("error"):
|
||||
state.final_answer = data["error"]
|
||||
return state
|
||||
if step.skill == "help" or step.skill == "unknown":
|
||||
state.final_answer = str(data)
|
||||
elif step.skill == "form.open":
|
||||
form = data.get("form")
|
||||
state.action = {"type": "open_form", "form": form, "route": "crm", "payload": data.get("payload") or {}}
|
||||
state.final_answer = "我已识别到要填写表单,会自动打开并预填已识别的信息。请确认后保存;缺少的字段可以继续告诉我。"
|
||||
state.route = "crm"
|
||||
elif step.skill == "appointment.plan":
|
||||
state.final_answer = "我识别到这是预约需求,已帮你打开预约表单。请先选择客户,系统会自动加载客户套餐;员工和时间我会尽量预填。"
|
||||
state.action = {"type": "open_form", "form": "crm.appointment.create", "route": "crm", "payload": data}
|
||||
state.route = "crm"
|
||||
elif step.skill == "stats.employee-kpi":
|
||||
state.final_answer = self._format_employee_kpi(data)
|
||||
state.route = "dashboard"
|
||||
elif step.skill == "crm.overview":
|
||||
state.final_answer = self._format_overview(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.body-status-list":
|
||||
state.final_answer = self._format_body_statuses(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.product-create":
|
||||
state.final_answer = f"已创建产品:{data.get('productName') or '-'},分类:{data.get('category') or '-'},默认次数:{data.get('defaultCount') or 0}"
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.product-list":
|
||||
state.final_answer = self._format_products(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.member-product-list":
|
||||
state.final_answer = self._format_member_products(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "confirm.required":
|
||||
state.final_answer = data.get("message", "需要确认后执行。") if isinstance(data, dict) else "需要确认后执行。"
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.mekai66-fields":
|
||||
categories = {}
|
||||
for field in data:
|
||||
categories.setdefault(field["category"], 0)
|
||||
categories[field["category"]] += 1
|
||||
state.final_answer = "\n".join(["麦凯66字段已配置,共66项:"] + [f"- {k}: {v}项" for k, v in categories.items()])
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.suggestion-list":
|
||||
state.final_answer = self._format_suggestions(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.issue-list":
|
||||
state.final_answer = self._format_issues(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.transactions":
|
||||
state.final_answer = self._format_transactions(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.account-list":
|
||||
state.final_answer = self._format_accounts(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.member-list":
|
||||
state.final_answer = self._format_members(data)
|
||||
state.route = "crm"
|
||||
elif step.skill == "crm.member-create":
|
||||
state.final_answer = (f"已创建客户:{data.get('name') or '-'},手机号:{data.get('phone') or '-'}。\n"
|
||||
"还可以继续补充:生日、微信、客户等级、过敏史、皮肤状态、睡眠、体重/腰围、偏好技师、已购产品/套餐、服务力度偏好、下次跟进重点。")
|
||||
state.route = "crm"
|
||||
else:
|
||||
state.final_answer = "已执行。"
|
||||
return state
|
||||
|
||||
@staticmethod
|
||||
def _current_user_text(text: str) -> str:
|
||||
marker = "当前用户说:"
|
||||
if marker in (text or ""):
|
||||
return text.rsplit(marker, 1)[-1].strip()
|
||||
return (text or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def _with_context(message: str, history: list[dict]) -> str:
|
||||
"""把最近几轮短上下文拼到当前输入,辅助长聊时省略主语的表达。"""
|
||||
text = (message or "").strip()
|
||||
if not history:
|
||||
return text
|
||||
lines = []
|
||||
for item in history[-6:]:
|
||||
role = "用户" if item.get("role") == "user" else "助手"
|
||||
content = str(item.get("text") or "").strip()
|
||||
if content and content != text:
|
||||
lines.append(f"{role}: {content[:200]}")
|
||||
if not lines:
|
||||
return text
|
||||
return "最近对话上下文:\n" + "\n".join(lines) + "\n当前用户说:" + text
|
||||
|
||||
@staticmethod
|
||||
def _reply(text: str, data=None, route: Optional[str] = None) -> dict:
|
||||
return {"reply": text, "data": data, "route": route}
|
||||
|
||||
@staticmethod
|
||||
def _has(text: str, keywords: list[str]) -> bool:
|
||||
lower = text.lower()
|
||||
return any(k.lower() in lower for k in keywords)
|
||||
|
||||
@staticmethod
|
||||
def _is_appointment_request(text: str) -> bool:
|
||||
appointment_words = ["预约", "预定", "约一下", "约", "预战", "预占", "排个", "安排"]
|
||||
time_words = ["今天", "明天", "后天", "上午", "下午", "晚上", "点", "点钟"]
|
||||
service_words = ["服务", "做身体", "做一下", "过来", "到店", "员工"]
|
||||
return (any(w in text for w in appointment_words) or (any(w in text for w in time_words) and any(w in text for w in service_words)))
|
||||
|
||||
@staticmethod
|
||||
def _extract_appointment_payload(text: str) -> dict:
|
||||
normalized = AgentChatService._normalize_asr_alias(text)
|
||||
employee = ""
|
||||
patterns = [
|
||||
r"(?:让|找|由|给|约)(?:那个|这个)?([一-龥A-Za-z]{2,8})(?:一号|1号|员工|老师|服务)",
|
||||
r"([一-龥A-Za-z]{2,8})(?:一号|1号)员工",
|
||||
r"员工[:: ]*([一-龥A-Za-z]{2,8})",
|
||||
]
|
||||
for pattern in patterns:
|
||||
emp_match = re.search(pattern, normalized)
|
||||
if emp_match:
|
||||
employee = emp_match.group(1)
|
||||
break
|
||||
start_hint = ""
|
||||
time_match = re.search(r"((?:今天|明天|后天)?\s*(?:上午|下午|晚上|中午)?\s*(?:\d{1,2}|[一二两三四五六七八九十]{1,3})点(?:半|\d{1,2}分)?(?:钟)?(?:到(?:\d{1,2}|[一二两三四五六七八九十]{1,3})点(?:半|\d{1,2}分)?(?:钟)?)?)", normalized)
|
||||
if time_match:
|
||||
start_hint = time_match.group(1).strip()
|
||||
phone = re.search(r"1\d{10}|\d{4}", normalized)
|
||||
service = ""
|
||||
for kw in ["腰妍", "乌蛇", "冰蚕", "减肥", "养生", "肩颈", "身体"]:
|
||||
if kw in normalized:
|
||||
service = kw
|
||||
break
|
||||
return {"employeeName": employee, "startHint": start_hint, "memberKeyword": phone.group(0) if phone else "", "serviceKeyword": service, "raw": text, "normalized": normalized}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_asr_alias(text: str) -> str:
|
||||
aliases = {
|
||||
"预战": "预约", "预占": "预约", "场预战": "想预约", "长预战": "想预约",
|
||||
"李艾元": "李爱媛", "李艾媛": "李爱媛", "李爱元": "李爱媛",
|
||||
"一号": "1号",
|
||||
}
|
||||
for k, v in aliases.items():
|
||||
text = text.replace(k, v)
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def _extract_phone_tail(text: str) -> str:
|
||||
match = re.search(r"(?:尾号|后四位|手机号)[^0-9]{0,8}(\d{4})", text)
|
||||
if match:
|
||||
return match.group(1)
|
||||
match = re.search(r"(?<!\d)(\d{4})(?!\d)", text)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
@staticmethod
|
||||
def _extract_phone(text: str) -> str:
|
||||
match = re.search(r"1\d{10}", text)
|
||||
return match.group(0) if match else ""
|
||||
|
||||
def _extract_member_payload(self, text: str) -> dict:
|
||||
name = self._extract_name(text)
|
||||
phone = self._extract_phone(text)
|
||||
gender = 1 if self._has(text, ["男", "先生"]) else (2 if self._has(text, ["女", "女士"]) else None)
|
||||
birth_year = self._extract_birth_year(text)
|
||||
health = []
|
||||
for word in ["膝盖积液", "脚踝扭伤", "肩颈酸痛", "腰背酸痛", "睡眠不好", "皮肤干燥"]:
|
||||
if word in text:
|
||||
health.append(word)
|
||||
mekai = {}
|
||||
if birth_year:
|
||||
mekai["birthday"] = f"{birth_year}年"
|
||||
if "已婚" in text:
|
||||
mekai["marital_status"] = "已婚"
|
||||
child = re.search(r"(\d+)岁宝宝", text)
|
||||
if child:
|
||||
mekai["children"] = f"{child.group(1)}岁宝宝"
|
||||
job = re.search(r"(?:工作岗位|职业|岗位)[:: ]*([一-龥A-Za-z0-9_+-]{2,20})", text)
|
||||
if job:
|
||||
mekai["position"] = job.group(1)
|
||||
return {
|
||||
"name": name,
|
||||
"phone": phone,
|
||||
"gender": gender,
|
||||
"healthIssues": health,
|
||||
"mekaiTags": mekai,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _extract_birth_year(text: str) -> str:
|
||||
match = re.search(r"(19\d{2}|20\d{2}|\d{2})年", text)
|
||||
if not match:
|
||||
return ""
|
||||
year = match.group(1)
|
||||
if len(year) == 2:
|
||||
year = "19" + year if int(year) > 30 else "20" + year
|
||||
return year
|
||||
|
||||
@staticmethod
|
||||
def _extract_product_payload(text: str) -> dict:
|
||||
name = ""
|
||||
match = re.search(r"(?:创建产品|新增产品|新建产品)[,,:: ]*([一-龥A-Za-z0-9_+-]{2,30})", text)
|
||||
if match:
|
||||
name = match.group(1).strip()
|
||||
category = ""
|
||||
for word in ["减肥", "养生", "美容", "酒", "产品", "套餐"]:
|
||||
if word in name or word in text:
|
||||
category = word
|
||||
break
|
||||
product_type = "package" if "套餐" in text or "套餐" in name else "product"
|
||||
price = 0
|
||||
price_match = re.search(r"(?:价格|售价|卖|金额)[:: ]*(\d+(?:\.\d+)?)", text)
|
||||
if not price_match:
|
||||
price_match = re.search(r"(\d+(?:\.\d+)?)\s*元", text)
|
||||
if price_match:
|
||||
price = price_match.group(1)
|
||||
count = 1
|
||||
count_match = re.search(r"(?:默认|次数|共)?\s*(\d+)\s*次", text)
|
||||
if count_match:
|
||||
count = count_match.group(1)
|
||||
category_match = re.search(r"(?:分类|类别)[:: ]*([一-龥A-Za-z0-9_+-]{1,20})", text)
|
||||
if category_match:
|
||||
category = category_match.group(1)
|
||||
return {"productName": name, "productType": product_type, "category": category, "defaultCount": count, "price": price}
|
||||
|
||||
@staticmethod
|
||||
def _extract_name(text: str) -> str:
|
||||
patterns = [
|
||||
r"(?:姓名|名字|叫)[:: ]*([一-龥A-Za-z]{2,12})",
|
||||
r"(?:创建客户|新增客户|新建客户|创建用户|新增用户|新建用户)\s*([一-龥A-Za-z]{2,12})",
|
||||
]
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, text)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _extract_keyword(text: str) -> str:
|
||||
for word in ["查客户", "找客户", "客户", "尾号", "后四位"]:
|
||||
text = text.replace(word, " ")
|
||||
return text.strip().split()[0] if text.strip().split() else ""
|
||||
|
||||
@staticmethod
|
||||
def _extract_id(text: str, prefix: str) -> Optional[str]:
|
||||
match = re.search(rf"({prefix}[A-Za-z0-9_-]+|[a-f0-9]{{32}})", text)
|
||||
return match.group(1) if match else None
|
||||
|
||||
def _help(self) -> dict:
|
||||
return self._reply("\n".join([
|
||||
"我可以帮你管理后台:",
|
||||
"1. 查客户尾号1234 / 查客户张女士",
|
||||
"2. 新增客户 张女士 13800001234",
|
||||
"3. 员工KPI / 差评排行",
|
||||
"4. CRM概览 / 账户流水 / 账户余额",
|
||||
"5. 待处理建议 / 待修复问题",
|
||||
"6. 麦凯66字段",
|
||||
"高风险操作(销卡、删除、批量修改)建议仍通过页面或CLI确认执行。",
|
||||
]))
|
||||
|
||||
@staticmethod
|
||||
def _format_overview(data: dict) -> str:
|
||||
return (f"CRM概览:客户{data.get('members', 0)}人,到店{data.get('visits', 0)}次,"
|
||||
f"有效账户{data.get('activeAccounts', 0)}个,账户余额¥{data.get('accountBalance', 0)},"
|
||||
f"待处理建议{data.get('pendingSuggestions', 0)}条,待修复问题{data.get('openIssues', 0)}条。")
|
||||
|
||||
@staticmethod
|
||||
def _format_employee_kpi(data: list[dict]) -> str:
|
||||
if not data:
|
||||
return "暂无员工KPI数据。"
|
||||
lines = ["员工KPI:"]
|
||||
for item in data[:8]:
|
||||
lines.append(f"- {item.get('employeeName')}: 总{item.get('total')},好评{item.get('good')},中评{item.get('middle')},差评{item.get('bad')},好评率{item.get('goodRate')}%")
|
||||
return "\n".join(lines)
|
||||
|
||||
@staticmethod
|
||||
def _format_members(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "没有找到客户。"
|
||||
lines = [f"找到{data.get('total', len(rows))}个客户:"]
|
||||
for m in rows:
|
||||
lines.append(f"- {m.get('name') or '-'} {m.get('phone') or '-'},到店{m.get('totalVisits', 0)}次,消费¥{m.get('totalSpent', 0)},ID={m.get('id')}")
|
||||
return "\n".join(lines)
|
||||
|
||||
@staticmethod
|
||||
def _format_accounts(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "暂无账户/卡。"
|
||||
return "\n".join(["账户/卡:"] + [f"- {a.get('memberName') or '-'} {a.get('cardName') or a.get('accountType')}:余额¥{a.get('balanceAmount')},剩余{a.get('balanceCount')}次,ID={a.get('id')}" for a in rows])
|
||||
|
||||
@staticmethod
|
||||
def _format_transactions(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "暂无账户流水。"
|
||||
return "\n".join(["最近账户流水:"] + [f"- {t.get('createDate')} {t.get('memberName') or '-'} {t.get('transactionType')} 金额{t.get('amount')} 次数{t.get('countChange')} 备注:{t.get('notes') or '-'}" for t in rows])
|
||||
|
||||
@staticmethod
|
||||
def _format_body_statuses(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "暂无身体变化记录。"
|
||||
return "\n".join(["身体变化记录:"] + [f"- {b.get('recordDate')} {b.get('memberName') or '-'}:体重{b.get('weight') or '-'}kg,腰围{b.get('waistline') or '-'}cm,不适{b.get('painLevel') or '-'}/10,睡眠{b.get('sleepQuality') or '-'}/10,{b.get('notes') or ''}" for b in rows])
|
||||
|
||||
@staticmethod
|
||||
def _format_products(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "暂无产品/套餐。"
|
||||
return "\n".join(["产品/套餐:"] + [f"- {p.get('productName')}({p.get('category') or '-'},¥{p.get('price')},默认{p.get('defaultCount')}次,ID={p.get('id')})" for p in rows])
|
||||
|
||||
@staticmethod
|
||||
def _format_member_products(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return data.get("message") or "该客户暂无已购产品/套餐。"
|
||||
return "\n".join(["客户已购产品/套餐:"] + [f"- {p.get('productName')}:剩余{p.get('balanceCount')}/{p.get('totalCount')}次,余额¥{p.get('balanceAmount')}/¥{p.get('totalAmount')},ID={p.get('id')}" for p in rows])
|
||||
|
||||
@staticmethod
|
||||
def _format_suggestions(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "暂无建议。"
|
||||
return "\n".join(["建议:"] + [f"- {s.get('content')}({s.get('status')},出现{s.get('frequency')}次,ID={s.get('id')})" for s in rows])
|
||||
|
||||
@staticmethod
|
||||
def _format_issues(data: dict) -> str:
|
||||
rows = data.get("list") or []
|
||||
if not rows:
|
||||
return "暂无问题。"
|
||||
return "\n".join(["问题修复:"] + [f"- {i.get('title')}({i.get('status')},{i.get('severity')},负责人:{i.get('assignedTo') or '-'},ID={i.get('id')})" for i in rows])
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
"""智能体配置应用服务"""
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.domain.agent.entity import AgentConfig
|
||||
from app.infrastructure.persistence.agent_repo_impl import AgentConfigRepositoryImpl
|
||||
from app.shared.exceptions import AgentConfigNotFoundError, ValidationError
|
||||
from app.shared.utils import generate_id
|
||||
|
||||
|
||||
class AgentConfigService:
|
||||
"""智能体配置应用服务"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.repo = AgentConfigRepositoryImpl(session)
|
||||
self.session = session
|
||||
|
||||
async def get_by_id(self, config_id: str) -> AgentConfig:
|
||||
config = await self.repo.get_by_id(config_id)
|
||||
if not config:
|
||||
raise AgentConfigNotFoundError(config_id)
|
||||
return config
|
||||
|
||||
async def get_by_agent_id(self, agent_id: str) -> Optional[AgentConfig]:
|
||||
return await self.repo.get_by_agent_id(agent_id)
|
||||
|
||||
async def list_page(self, page: int = 1, page_size: int = 20) -> dict:
|
||||
return await self.repo.list_page(page, page_size)
|
||||
|
||||
async def create_config(self, agent_name: str, agent_id: Optional[str] = None,
|
||||
dialogue_rounds: int = 7, questions: Optional[list] = None,
|
||||
prompts_config: Optional[dict] = None,
|
||||
llm_config: Optional[dict] = None,
|
||||
review_config: Optional[dict] = None) -> AgentConfig:
|
||||
config = AgentConfig(
|
||||
id=generate_id(),
|
||||
agent_name=agent_name,
|
||||
agent_id=agent_id,
|
||||
dialogue_rounds=dialogue_rounds,
|
||||
questions=questions,
|
||||
prompts_config=prompts_config,
|
||||
llm_config=llm_config,
|
||||
review_config=review_config,
|
||||
)
|
||||
result = await self.repo.save(config)
|
||||
logger.info(f"创建智能体配置: name={agent_name}")
|
||||
return result
|
||||
|
||||
async def update_config(self, config_id: str, **kwargs) -> AgentConfig:
|
||||
config = await self.repo.get_by_id(config_id)
|
||||
if not config:
|
||||
raise AgentConfigNotFoundError(config_id)
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(config, key) and value is not None:
|
||||
setattr(config, key, value)
|
||||
|
||||
result = await self.repo.save(config)
|
||||
logger.info(f"更新智能体配置: id={config_id}")
|
||||
return result
|
||||
|
||||
async def delete_config(self, config_id: str) -> bool:
|
||||
config = await self.repo.get_by_id(config_id)
|
||||
if not config:
|
||||
raise AgentConfigNotFoundError(config_id)
|
||||
result = await self.repo.delete(config_id)
|
||||
logger.info(f"删除智能体配置: id={config_id}")
|
||||
return result
|
||||
211
main/feedback-backend/app/application/appointment_service.py
Normal file
211
main/feedback-backend/app/application/appointment_service.py
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
"""预约日历服务"""
|
||||
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.infrastructure.persistence.models import (
|
||||
CrmAppointmentLogModel,
|
||||
CrmAppointmentModel,
|
||||
CrmEmployeeScheduleModel,
|
||||
CrmEmployeeTimeoffModel,
|
||||
CrmMemberModel,
|
||||
CrmMemberProductModel,
|
||||
CrmProductModel,
|
||||
EmployeeModel,
|
||||
)
|
||||
from app.shared.utils import generate_id
|
||||
|
||||
ACTIVE_STATUS = ["pending", "confirmed", "arrived"]
|
||||
|
||||
|
||||
class AppointmentService:
|
||||
def __init__(self, session: Session):
|
||||
self.session = session
|
||||
|
||||
async def calendar(self, store_id: str, start_date: str, end_date: str,
|
||||
employee_id: Optional[str] = None) -> dict:
|
||||
start = self._parse_date(start_date)
|
||||
end = self._parse_date(end_date)
|
||||
emp_query = self.session.query(EmployeeModel).filter(EmployeeModel.store_id == store_id, EmployeeModel.status == 1)
|
||||
if employee_id:
|
||||
emp_query = emp_query.filter(EmployeeModel.id == employee_id)
|
||||
employees = emp_query.order_by(EmployeeModel.number).all()
|
||||
query = self.session.query(CrmAppointmentModel).filter(
|
||||
CrmAppointmentModel.store_id == store_id,
|
||||
CrmAppointmentModel.appointment_date >= start,
|
||||
CrmAppointmentModel.appointment_date <= end,
|
||||
)
|
||||
if employee_id:
|
||||
query = query.filter(CrmAppointmentModel.employee_id == employee_id)
|
||||
appointments = query.order_by(CrmAppointmentModel.start_at).all()
|
||||
return {
|
||||
"resources": [{"id": e.id, "title": e.name, "number": e.number, "type": e.employee_type} for e in employees],
|
||||
"events": [self._appointment_to_event(a) for a in appointments],
|
||||
}
|
||||
|
||||
async def availability(self, store_id: str, appointment_date: str,
|
||||
employee_id: Optional[str] = None,
|
||||
duration_minutes: int = 60) -> dict:
|
||||
day = self._parse_date(appointment_date)
|
||||
weekday = day.isoweekday()
|
||||
employees_query = self.session.query(EmployeeModel).filter(EmployeeModel.store_id == store_id, EmployeeModel.status == 1)
|
||||
if employee_id:
|
||||
employees_query = employees_query.filter(EmployeeModel.id == employee_id)
|
||||
employees = employees_query.order_by(EmployeeModel.number).all()
|
||||
slots = []
|
||||
for emp in employees:
|
||||
schedules = self.session.query(CrmEmployeeScheduleModel).filter(
|
||||
CrmEmployeeScheduleModel.employee_id == emp.id,
|
||||
CrmEmployeeScheduleModel.weekday == weekday,
|
||||
CrmEmployeeScheduleModel.status == 1,
|
||||
CrmEmployeeScheduleModel.is_working == 1,
|
||||
).all()
|
||||
if not schedules:
|
||||
schedules = [self._default_schedule(emp, weekday)]
|
||||
for schedule in schedules:
|
||||
slots.extend(self._slots_for_schedule(store_id, emp, day, schedule, duration_minutes))
|
||||
return {"date": str(day), "slots": slots}
|
||||
|
||||
async def create_appointment(self, data: dict, operator: str = "") -> dict:
|
||||
start_at = self._parse_datetime(data.get("start_at") or data.get("startAt"))
|
||||
duration = int(data.get("duration_minutes") or data.get("durationMinutes") or 60)
|
||||
end_at = self._parse_datetime(data.get("end_at") or data.get("endAt")) or (start_at + timedelta(minutes=duration))
|
||||
store_id = data.get("store_id") or data.get("storeId")
|
||||
employee_id = data.get("employee_id") or data.get("employeeId")
|
||||
if start_at <= datetime.now():
|
||||
raise ValueError("不能预约已经过去的时间")
|
||||
if self._has_conflict(employee_id, start_at, end_at):
|
||||
raise ValueError("该员工该时间段已有预约")
|
||||
member_product = self._member_product(data.get("member_product_id") or data.get("memberProductId"))
|
||||
product = self._product(data.get("product_id") or data.get("productId") or (member_product.product_id if member_product else None))
|
||||
appointment = CrmAppointmentModel(
|
||||
id=generate_id(), store_id=store_id,
|
||||
member_id=data.get("member_id") or data.get("memberId"),
|
||||
employee_id=employee_id,
|
||||
member_product_id=data.get("member_product_id") or data.get("memberProductId"),
|
||||
product_id=data.get("product_id") or data.get("productId") or (member_product.product_id if member_product else None),
|
||||
product_name=data.get("product_name") or data.get("productName") or (member_product.product_name if member_product else (product.product_name if product else None)),
|
||||
appointment_date=start_at.date(), start_at=start_at, end_at=end_at,
|
||||
duration_minutes=duration,
|
||||
source=data.get("source") or "admin",
|
||||
status=data.get("status") or "pending",
|
||||
customer_notes=data.get("customer_notes") or data.get("customerNotes"),
|
||||
store_notes=data.get("store_notes") or data.get("storeNotes"),
|
||||
created_by=operator,
|
||||
)
|
||||
self.session.add(appointment)
|
||||
self._log(appointment.id, "create", None, self._appointment_to_dict(appointment), operator)
|
||||
self.session.commit()
|
||||
self.session.refresh(appointment)
|
||||
return self._appointment_to_dict(appointment)
|
||||
|
||||
async def update_status(self, appointment_id: str, status: str, data: dict, operator: str = "") -> Optional[dict]:
|
||||
appointment = self.session.query(CrmAppointmentModel).filter(CrmAppointmentModel.id == appointment_id).first()
|
||||
if not appointment:
|
||||
return None
|
||||
before = self._appointment_to_dict(appointment)
|
||||
appointment.status = status
|
||||
if status == "confirmed":
|
||||
appointment.confirmed_by = operator
|
||||
if status == "cancelled":
|
||||
appointment.cancelled_by = operator
|
||||
appointment.cancel_reason = data.get("reason") or data.get("cancelReason")
|
||||
appointment.update_date = datetime.now()
|
||||
self._log(appointment.id, status, before, self._appointment_to_dict(appointment), operator, data.get("notes"))
|
||||
if status == "completed" and data.get("consume"):
|
||||
from app.application.crm_service import CrmService
|
||||
if appointment.member_product_id:
|
||||
CrmService(self.session).consume_member_product_sync(appointment.member_product_id, {
|
||||
"consumeCount": data.get("consumeCount") or 1,
|
||||
"consumeAmount": data.get("consumeAmount") or 0,
|
||||
"visitId": data.get("visitId"),
|
||||
"notes": f"预约完成自动消耗:{appointment.product_name or ''}",
|
||||
}, appointment.store_id, operator)
|
||||
self.session.commit()
|
||||
self.session.refresh(appointment)
|
||||
return self._appointment_to_dict(appointment)
|
||||
|
||||
def _slots_for_schedule(self, store_id, emp, day, schedule, duration_minutes):
|
||||
start_t = self._parse_time(schedule.start_time)
|
||||
end_t = self._parse_time(schedule.end_time)
|
||||
cursor = datetime.combine(day, start_t)
|
||||
end_day = datetime.combine(day, end_t)
|
||||
slots = []
|
||||
while cursor + timedelta(minutes=duration_minutes) <= end_day:
|
||||
slot_end = cursor + timedelta(minutes=duration_minutes)
|
||||
available = cursor > datetime.now() and not self._has_conflict(emp.id, cursor, slot_end) and not self._has_timeoff(emp.id, cursor, slot_end)
|
||||
slots.append({"employeeId": emp.id, "employeeName": emp.name, "start": cursor.strftime("%H:%M"), "end": slot_end.strftime("%H:%M"), "available": available})
|
||||
cursor += timedelta(minutes=30)
|
||||
return slots
|
||||
|
||||
def _has_conflict(self, employee_id: str, start_at: datetime, end_at: datetime) -> bool:
|
||||
return self.session.query(CrmAppointmentModel).filter(
|
||||
CrmAppointmentModel.employee_id == employee_id,
|
||||
CrmAppointmentModel.status.in_(ACTIVE_STATUS),
|
||||
CrmAppointmentModel.start_at < end_at,
|
||||
CrmAppointmentModel.end_at > start_at,
|
||||
).first() is not None
|
||||
|
||||
def _has_timeoff(self, employee_id: str, start_at: datetime, end_at: datetime) -> bool:
|
||||
return self.session.query(CrmEmployeeTimeoffModel).filter(
|
||||
CrmEmployeeTimeoffModel.employee_id == employee_id,
|
||||
CrmEmployeeTimeoffModel.status == 1,
|
||||
CrmEmployeeTimeoffModel.start_at < end_at,
|
||||
CrmEmployeeTimeoffModel.end_at > start_at,
|
||||
).first() is not None
|
||||
|
||||
def _default_schedule(self, emp, weekday):
|
||||
return CrmEmployeeScheduleModel(id="default", store_id=emp.store_id, employee_id=emp.id, weekday=weekday, start_time="10:00", end_time="20:00", is_working=1)
|
||||
|
||||
def _member_product(self, member_product_id):
|
||||
if not member_product_id:
|
||||
return None
|
||||
return self.session.query(CrmMemberProductModel).filter(CrmMemberProductModel.id == member_product_id).first()
|
||||
|
||||
def _product(self, product_id):
|
||||
if not product_id:
|
||||
return None
|
||||
return self.session.query(CrmProductModel).filter(CrmProductModel.id == product_id).first()
|
||||
|
||||
def _log(self, appointment_id, action, before, after, operator, notes=None):
|
||||
self.session.add(CrmAppointmentLogModel(id=generate_id(), appointment_id=appointment_id, action=action, before_json=before, after_json=after, operator=operator, notes=notes))
|
||||
|
||||
def _appointment_to_event(self, a):
|
||||
member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == a.member_id).first()
|
||||
return {
|
||||
"id": a.id, "resourceId": a.employee_id,
|
||||
"title": f"{member.name if member else '客户'} - {a.product_name or '预约'}",
|
||||
"start": a.start_at.isoformat(sep=" "), "end": a.end_at.isoformat(sep=" "),
|
||||
"status": a.status, "memberId": a.member_id, "memberName": member.name if member else None,
|
||||
"employeeId": a.employee_id, "productName": a.product_name,
|
||||
}
|
||||
|
||||
def _appointment_to_dict(self, a):
|
||||
return {
|
||||
"id": a.id, "storeId": a.store_id, "memberId": a.member_id, "employeeId": a.employee_id,
|
||||
"memberProductId": a.member_product_id, "productId": a.product_id, "productName": a.product_name,
|
||||
"appointmentDate": str(a.appointment_date), "startAt": str(a.start_at), "endAt": str(a.end_at),
|
||||
"durationMinutes": a.duration_minutes, "source": a.source, "status": a.status,
|
||||
"customerNotes": a.customer_notes, "storeNotes": a.store_notes, "cancelReason": a.cancel_reason,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _parse_date(value):
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
return datetime.fromisoformat(str(value)[:10]).date()
|
||||
|
||||
@staticmethod
|
||||
def _parse_time(value):
|
||||
h, m = str(value).split(":")[:2]
|
||||
return time(int(h), int(m))
|
||||
|
||||
@staticmethod
|
||||
def _parse_datetime(value):
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
||||
978
main/feedback-backend/app/application/crm_service.py
Normal file
978
main/feedback-backend/app/application/crm_service.py
Normal file
|
|
@ -0,0 +1,978 @@
|
|||
"""CRM 应用服务 - 客户档案、到店、账户、销卡、建议、问题闭环"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.infrastructure.persistence.models import (
|
||||
CrmAccountModel,
|
||||
CrmAccountTransactionModel,
|
||||
CrmBodyStatusModel,
|
||||
CrmCardCloseModel,
|
||||
CrmIssueModel,
|
||||
CrmMemberModel,
|
||||
CrmMemberProductModel,
|
||||
CrmProductConsumeModel,
|
||||
CrmProductModel,
|
||||
CrmSuggestionModel,
|
||||
CrmVisitModel,
|
||||
FeedbackRecordModel,
|
||||
)
|
||||
from app.shared.utils import generate_id
|
||||
|
||||
|
||||
class CrmService:
|
||||
"""CRM 应用服务"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.session = session
|
||||
|
||||
# ---- Member ----
|
||||
async def list_members(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, keyword: Optional[str] = None,
|
||||
status: Optional[int] = None) -> dict:
|
||||
query = self.session.query(CrmMemberModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmMemberModel.store_id == store_id)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter((CrmMemberModel.name.like(like)) | (CrmMemberModel.phone.like(like)))
|
||||
if status is not None:
|
||||
query = query.filter(CrmMemberModel.status == status)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmMemberModel.update_date.desc()) \
|
||||
.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._member_to_dict(m) for m in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def get_member(self, member_id: str, store_id: Optional[str] = None) -> Optional[dict]:
|
||||
query = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmMemberModel.store_id == store_id)
|
||||
member = query.first()
|
||||
if not member:
|
||||
return None
|
||||
data = self._member_to_dict(member)
|
||||
data["visits"] = [self._visit_to_dict(v) for v in self.session.query(CrmVisitModel)
|
||||
.filter(CrmVisitModel.member_id == member.id)
|
||||
.order_by(CrmVisitModel.arrive_at.desc(), CrmVisitModel.create_date.desc()).limit(10).all()]
|
||||
data["accounts"] = [self._account_to_dict(a) for a in self.session.query(CrmAccountModel)
|
||||
.filter(CrmAccountModel.member_id == member.id).order_by(CrmAccountModel.create_date.desc()).all()]
|
||||
data["transactions"] = [self._transaction_to_dict(t) for t in self.session.query(CrmAccountTransactionModel)
|
||||
.filter(CrmAccountTransactionModel.member_id == member.id)
|
||||
.order_by(CrmAccountTransactionModel.create_date.desc()).limit(20).all()]
|
||||
data["products"] = [self._member_product_to_dict(p) for p in self.session.query(CrmMemberProductModel)
|
||||
.filter(CrmMemberProductModel.member_id == member.id)
|
||||
.order_by(CrmMemberProductModel.create_date.desc()).all()]
|
||||
data["productConsumes"] = [self._product_consume_to_dict(c) for c in self.session.query(CrmProductConsumeModel)
|
||||
.filter(CrmProductConsumeModel.member_id == member.id)
|
||||
.order_by(CrmProductConsumeModel.create_date.desc()).limit(20).all()]
|
||||
data["bodyStatuses"] = [self._body_status_to_dict(b) for b in self.session.query(CrmBodyStatusModel)
|
||||
.filter(CrmBodyStatusModel.member_id == member.id)
|
||||
.order_by(CrmBodyStatusModel.record_date.desc()).limit(20).all()]
|
||||
data["feedbacks"] = [self._feedback_to_dict(r) for r in self.session.query(FeedbackRecordModel)
|
||||
.filter(FeedbackRecordModel.member_id == member.id)
|
||||
.order_by(FeedbackRecordModel.create_date.desc()).limit(10).all()]
|
||||
data["suggestions"] = [self._suggestion_to_dict(s) for s in self.session.query(CrmSuggestionModel)
|
||||
.filter(CrmSuggestionModel.member_id == member.id)
|
||||
.order_by(CrmSuggestionModel.create_date.desc()).limit(10).all()]
|
||||
data["issues"] = [self._issue_to_dict(i) for i in self.session.query(CrmIssueModel)
|
||||
.filter(CrmIssueModel.member_id == member.id)
|
||||
.order_by(CrmIssueModel.create_date.desc()).limit(10).all()]
|
||||
return data
|
||||
|
||||
async def create_member(self, data: dict, operator: str = "") -> dict:
|
||||
member = CrmMemberModel(
|
||||
id=generate_id(),
|
||||
store_id=data.get("store_id"),
|
||||
name=data.get("name"),
|
||||
phone=data.get("phone"),
|
||||
gender=data.get("gender"),
|
||||
birthday=self._parse_date(data.get("birthday")),
|
||||
wechat=data.get("wechat"),
|
||||
source=data.get("source") or "manual",
|
||||
level=data.get("level"),
|
||||
tags=data.get("tags"),
|
||||
mekai_tags=data.get("mekai_tags") or data.get("mekaiTags"),
|
||||
beauty_concerns=data.get("beauty_concerns") or data.get("beautyConcerns"),
|
||||
health_issues=data.get("health_issues") or data.get("healthIssues"),
|
||||
allergies=data.get("allergies"),
|
||||
service_preferences=data.get("service_preferences") or data.get("servicePreferences"),
|
||||
notes=data.get("notes"),
|
||||
creator=operator,
|
||||
updater=operator,
|
||||
)
|
||||
self.session.add(member)
|
||||
self.session.commit()
|
||||
self.session.refresh(member)
|
||||
return self._member_to_dict(member)
|
||||
|
||||
async def update_member(self, member_id: str, data: dict, store_id: Optional[str] = None,
|
||||
operator: str = "") -> Optional[dict]:
|
||||
query = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmMemberModel.store_id == store_id)
|
||||
member = query.first()
|
||||
if not member:
|
||||
return None
|
||||
mapping = {
|
||||
"name": "name", "phone": "phone", "gender": "gender", "wechat": "wechat",
|
||||
"level": "level", "tags": "tags", "allergies": "allergies", "notes": "notes", "status": "status",
|
||||
}
|
||||
for key, field in mapping.items():
|
||||
if key in data:
|
||||
setattr(member, field, data[key])
|
||||
if "birthday" in data:
|
||||
member.birthday = self._parse_date(data.get("birthday"))
|
||||
for key, field in [("mekai_tags", "mekai_tags"), ("mekaiTags", "mekai_tags"),
|
||||
("beauty_concerns", "beauty_concerns"), ("beautyConcerns", "beauty_concerns"),
|
||||
("health_issues", "health_issues"), ("healthIssues", "health_issues"),
|
||||
("service_preferences", "service_preferences"), ("servicePreferences", "service_preferences")]:
|
||||
if key in data:
|
||||
setattr(member, field, data[key])
|
||||
member.updater = operator
|
||||
member.update_date = datetime.now()
|
||||
self.session.commit()
|
||||
self.session.refresh(member)
|
||||
return self._member_to_dict(member)
|
||||
|
||||
# ---- Visit ----
|
||||
async def list_visits(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, member_id: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmVisitModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmVisitModel.store_id == store_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmVisitModel.member_id == member_id)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmVisitModel.arrive_at.desc(), CrmVisitModel.create_date.desc()) \
|
||||
.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._visit_to_dict(v) for v in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def create_visit(self, data: dict, operator: str = "") -> dict:
|
||||
arrive_at = self._parse_datetime(data.get("arrive_at") or data.get("arriveAt"))
|
||||
leave_at = self._parse_datetime(data.get("leave_at") or data.get("leaveAt"))
|
||||
duration = data.get("duration_minutes") or data.get("durationMinutes")
|
||||
if not duration and arrive_at and leave_at:
|
||||
duration = max(0, int((leave_at - arrive_at).total_seconds() // 60))
|
||||
visit = CrmVisitModel(
|
||||
id=generate_id(),
|
||||
store_id=data.get("store_id"),
|
||||
member_id=data.get("member_id") or data.get("memberId"),
|
||||
employee_id=data.get("employee_id") or data.get("employeeId"),
|
||||
feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"),
|
||||
session_id=data.get("session_id") or data.get("sessionId"),
|
||||
device_mac=data.get("device_mac") or data.get("deviceMac"),
|
||||
visit_type=data.get("visit_type") or data.get("visitType") or "walk_in",
|
||||
service_items=data.get("service_items") or data.get("serviceItems"),
|
||||
arrive_at=arrive_at,
|
||||
leave_at=leave_at,
|
||||
duration_minutes=duration,
|
||||
satisfaction=data.get("satisfaction"),
|
||||
consumption_amount=self._decimal(data.get("consumption_amount") or data.get("consumptionAmount")),
|
||||
notes=data.get("notes"),
|
||||
creator=operator,
|
||||
updater=operator,
|
||||
)
|
||||
self.session.add(visit)
|
||||
self._touch_member_visit_stats(visit.member_id, visit.arrive_at, visit.consumption_amount)
|
||||
self.session.commit()
|
||||
self.session.refresh(visit)
|
||||
return self._visit_to_dict(visit)
|
||||
|
||||
async def update_visit(self, visit_id: str, data: dict, store_id: Optional[str] = None,
|
||||
operator: str = "") -> Optional[dict]:
|
||||
query = self.session.query(CrmVisitModel).filter(CrmVisitModel.id == visit_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmVisitModel.store_id == store_id)
|
||||
visit = query.first()
|
||||
if not visit:
|
||||
return None
|
||||
for key, field in [("member_id", "member_id"), ("memberId", "member_id"),
|
||||
("employee_id", "employee_id"), ("employeeId", "employee_id"),
|
||||
("feedback_record_id", "feedback_record_id"), ("feedbackRecordId", "feedback_record_id"),
|
||||
("satisfaction", "satisfaction"), ("notes", "notes"),
|
||||
("service_items", "service_items"), ("serviceItems", "service_items")]:
|
||||
if key in data:
|
||||
setattr(visit, field, data[key])
|
||||
if "arrive_at" in data or "arriveAt" in data:
|
||||
visit.arrive_at = self._parse_datetime(data.get("arrive_at") or data.get("arriveAt"))
|
||||
if "leave_at" in data or "leaveAt" in data:
|
||||
visit.leave_at = self._parse_datetime(data.get("leave_at") or data.get("leaveAt"))
|
||||
if "duration_minutes" in data or "durationMinutes" in data:
|
||||
visit.duration_minutes = data.get("duration_minutes") or data.get("durationMinutes")
|
||||
elif visit.arrive_at and visit.leave_at:
|
||||
visit.duration_minutes = max(0, int((visit.leave_at - visit.arrive_at).total_seconds() // 60))
|
||||
if "consumption_amount" in data or "consumptionAmount" in data:
|
||||
visit.consumption_amount = self._decimal(data.get("consumption_amount") or data.get("consumptionAmount"))
|
||||
visit.updater = operator
|
||||
visit.update_date = datetime.now()
|
||||
self.session.commit()
|
||||
self.session.refresh(visit)
|
||||
return self._visit_to_dict(visit)
|
||||
|
||||
# ---- Account ----
|
||||
async def list_accounts(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, member_id: Optional[str] = None,
|
||||
status: Optional[int] = None) -> dict:
|
||||
query = self.session.query(CrmAccountModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmAccountModel.store_id == store_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmAccountModel.member_id == member_id)
|
||||
if status is not None:
|
||||
query = query.filter(CrmAccountModel.status == status)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmAccountModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._account_to_dict(a) for a in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def create_account(self, data: dict, operator: str = "") -> dict:
|
||||
total_amount = self._decimal(data.get("total_amount") or data.get("totalAmount"))
|
||||
balance_amount = self._decimal(data.get("balance_amount") or data.get("balanceAmount") or total_amount)
|
||||
account = CrmAccountModel(
|
||||
id=generate_id(),
|
||||
store_id=data.get("store_id"),
|
||||
member_id=data.get("member_id") or data.get("memberId"),
|
||||
account_type=data.get("account_type") or data.get("accountType") or "balance",
|
||||
card_name=data.get("card_name") or data.get("cardName"),
|
||||
total_amount=total_amount,
|
||||
balance_amount=balance_amount,
|
||||
total_count=data.get("total_count") or data.get("totalCount") or 0,
|
||||
balance_count=data.get("balance_count") or data.get("balanceCount") or data.get("total_count") or data.get("totalCount") or 0,
|
||||
valid_start=self._parse_date(data.get("valid_start") or data.get("validStart")),
|
||||
valid_end=self._parse_date(data.get("valid_end") or data.get("validEnd")),
|
||||
notes=data.get("notes"),
|
||||
creator=operator,
|
||||
updater=operator,
|
||||
)
|
||||
self.session.add(account)
|
||||
self.session.flush()
|
||||
self._add_transaction(account, "recharge", balance_amount, account.balance_count, 0, balance_amount, None, "开卡", operator)
|
||||
self.session.commit()
|
||||
self.session.refresh(account)
|
||||
return self._account_to_dict(account)
|
||||
|
||||
async def list_account_transactions(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None,
|
||||
account_id: Optional[str] = None,
|
||||
member_id: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmAccountTransactionModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmAccountTransactionModel.store_id == store_id)
|
||||
if account_id:
|
||||
query = query.filter(CrmAccountTransactionModel.account_id == account_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmAccountTransactionModel.member_id == member_id)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmAccountTransactionModel.create_date.desc()) \
|
||||
.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._transaction_to_dict(t) for t in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def consume_account(self, account_id: str, data: dict, store_id: Optional[str] = None,
|
||||
operator: str = "") -> Optional[dict]:
|
||||
account = self._get_account(account_id, store_id)
|
||||
if not account:
|
||||
return None
|
||||
amount = self._decimal(data.get("amount"))
|
||||
count_change = int(data.get("count_change") or data.get("countChange") or 0)
|
||||
before = self._decimal(account.balance_amount)
|
||||
account.balance_amount = before - amount
|
||||
account.balance_count = int(account.balance_count or 0) - count_change
|
||||
account.update_date = datetime.now()
|
||||
visit_id = data.get("visit_id") or data.get("visitId") or self._latest_visit_id(account.member_id, account.store_id)
|
||||
if visit_id:
|
||||
self._sync_visit_consumption(visit_id, amount)
|
||||
self._add_transaction(account, "consume", -amount, -count_change, before, account.balance_amount,
|
||||
visit_id, data.get("notes"), operator)
|
||||
self.session.commit()
|
||||
self.session.refresh(account)
|
||||
return self._account_to_dict(account)
|
||||
|
||||
async def close_card(self, data: dict, store_id: Optional[str] = None, operator: str = "") -> Optional[dict]:
|
||||
account = self._get_account(data.get("account_id") or data.get("accountId"), store_id)
|
||||
if not account:
|
||||
return None
|
||||
close = CrmCardCloseModel(
|
||||
id=generate_id(),
|
||||
store_id=account.store_id,
|
||||
member_id=account.member_id,
|
||||
account_id=account.id,
|
||||
feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"),
|
||||
close_type=data.get("close_type") or data.get("closeType") or "refund",
|
||||
reason=data.get("reason"),
|
||||
refund_amount=self._decimal(data.get("refund_amount") or data.get("refundAmount")),
|
||||
remaining_count=account.balance_count or 0,
|
||||
status=data.get("status") or "done",
|
||||
handled_by=operator,
|
||||
handle_notes=data.get("handle_notes") or data.get("handleNotes"),
|
||||
)
|
||||
account.status = 0
|
||||
account.closed_reason = close.reason
|
||||
account.closed_at = datetime.now()
|
||||
self.session.add(close)
|
||||
self._add_transaction(account, "close", -self._decimal(close.refund_amount), 0,
|
||||
self._decimal(account.balance_amount), self._decimal(account.balance_amount),
|
||||
None, close.reason, operator)
|
||||
if close.feedback_record_id:
|
||||
self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == close.feedback_record_id).update({
|
||||
"member_id": account.member_id,
|
||||
"card_close_id": close.id,
|
||||
})
|
||||
self.session.commit()
|
||||
self.session.refresh(close)
|
||||
return self._card_close_to_dict(close)
|
||||
|
||||
async def list_card_closes(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, member_id: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmCardCloseModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmCardCloseModel.store_id == store_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmCardCloseModel.member_id == member_id)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmCardCloseModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._card_close_to_dict(c) for c in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
# ---- Body Status ----
|
||||
async def list_body_statuses(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, member_id: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmBodyStatusModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmBodyStatusModel.store_id == store_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmBodyStatusModel.member_id == member_id)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmBodyStatusModel.record_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._body_status_to_dict(b) for b in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def create_body_status(self, data: dict, operator: str = "") -> dict:
|
||||
body_status = CrmBodyStatusModel(
|
||||
id=generate_id(), store_id=data.get("store_id"),
|
||||
member_id=data.get("member_id") or data.get("memberId"),
|
||||
visit_id=data.get("visit_id") or data.get("visitId"),
|
||||
member_product_id=data.get("member_product_id") or data.get("memberProductId"),
|
||||
record_date=self._parse_datetime(data.get("record_date") or data.get("recordDate")) or datetime.now(),
|
||||
weight=self._decimal(data.get("weight")) if data.get("weight") not in (None, "") else None,
|
||||
waistline=self._decimal(data.get("waistline")) if data.get("waistline") not in (None, "") else None,
|
||||
pain_level=data.get("pain_level") or data.get("painLevel"),
|
||||
sleep_quality=data.get("sleep_quality") or data.get("sleepQuality"),
|
||||
skin_status=data.get("skin_status") or data.get("skinStatus"),
|
||||
body_parts=data.get("body_parts") or data.get("bodyParts"),
|
||||
metrics=data.get("metrics"), notes=data.get("notes"),
|
||||
creator=operator, updater=operator,
|
||||
)
|
||||
self.session.add(body_status)
|
||||
self._merge_body_status_to_member(body_status)
|
||||
self.session.commit()
|
||||
self.session.refresh(body_status)
|
||||
return self._body_status_to_dict(body_status)
|
||||
|
||||
def _merge_body_status_to_member(self, body_status):
|
||||
member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == body_status.member_id).first()
|
||||
if not member:
|
||||
return
|
||||
issues = member.health_issues if isinstance(member.health_issues, list) else []
|
||||
if isinstance(issues, str):
|
||||
try:
|
||||
issues = json.loads(issues)
|
||||
except Exception:
|
||||
issues = [issues]
|
||||
summary = []
|
||||
metrics = body_status.metrics if isinstance(body_status.metrics, dict) else {}
|
||||
if metrics.get("name"):
|
||||
summary.append(f"{metrics.get('name')}:{metrics.get('status') or ''}{'(' + str(metrics.get('value')) + ')' if metrics.get('value') else ''}")
|
||||
if body_status.notes:
|
||||
summary.append(body_status.notes)
|
||||
if summary:
|
||||
text = ";".join(summary)
|
||||
if text not in issues:
|
||||
issues.append(text)
|
||||
member.health_issues = issues
|
||||
member.update_date = datetime.now()
|
||||
|
||||
# ---- Product / Package ----
|
||||
async def list_products(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, keyword: Optional[str] = None,
|
||||
category: Optional[str] = None, status: Optional[int] = None) -> dict:
|
||||
query = self.session.query(CrmProductModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmProductModel.store_id == store_id)
|
||||
if keyword:
|
||||
query = query.filter(CrmProductModel.product_name.like(f"%{keyword}%"))
|
||||
if category:
|
||||
query = query.filter(CrmProductModel.category == category)
|
||||
if status is not None:
|
||||
query = query.filter(CrmProductModel.status == status)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmProductModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._product_to_dict(p) for p in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def create_product(self, data: dict, operator: str = "") -> dict:
|
||||
product = CrmProductModel(
|
||||
id=generate_id(), store_id=data.get("store_id"),
|
||||
product_name=data.get("product_name") or data.get("productName"),
|
||||
product_type=data.get("product_type") or data.get("productType") or "service",
|
||||
category=data.get("category"), price=self._decimal(data.get("price")),
|
||||
default_count=int(data.get("default_count") or data.get("defaultCount") or 1),
|
||||
description=data.get("description"), creator=operator, updater=operator,
|
||||
)
|
||||
self.session.add(product)
|
||||
self.session.commit()
|
||||
self.session.refresh(product)
|
||||
return self._product_to_dict(product)
|
||||
|
||||
async def list_member_products(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, member_id: Optional[str] = None,
|
||||
status: Optional[int] = None) -> dict:
|
||||
query = self.session.query(CrmMemberProductModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmMemberProductModel.store_id == store_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmMemberProductModel.member_id == member_id)
|
||||
if status is not None:
|
||||
query = query.filter(CrmMemberProductModel.status == status)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmMemberProductModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._member_product_to_dict(p) for p in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def purchase_product(self, data: dict, operator: str = "") -> dict:
|
||||
product_id = data.get("product_id") or data.get("productId")
|
||||
product = self.session.query(CrmProductModel).filter(CrmProductModel.id == product_id).first() if product_id else None
|
||||
total_count = int(data.get("total_count") or data.get("totalCount") or data.get("purchase_count") or data.get("purchaseCount") or (product.default_count if product else 1) or 0)
|
||||
unit_price = self._decimal(data.get("unit_price") or data.get("unitPrice") or (product.price if product else 0))
|
||||
discount = self._decimal(data.get("discount") or 1)
|
||||
total_amount = self._decimal(data.get("total_amount") or data.get("totalAmount") or (unit_price * total_count * discount))
|
||||
valid_start = self._parse_date(data.get("valid_start") or data.get("validStart")) or datetime.now().date()
|
||||
valid_end = self._parse_date(data.get("valid_end") or data.get("validEnd")) or (valid_start + timedelta(days=365))
|
||||
member_product = CrmMemberProductModel(
|
||||
id=generate_id(), store_id=data.get("store_id"),
|
||||
member_id=data.get("member_id") or data.get("memberId"), product_id=product_id,
|
||||
account_id=data.get("account_id") or data.get("accountId"),
|
||||
product_name=data.get("product_name") or data.get("productName") or (product.product_name if product else "产品套餐"),
|
||||
package_items=data.get("package_items") or data.get("packageItems"),
|
||||
unit_price=unit_price, purchase_count=total_count, discount=discount,
|
||||
total_count=total_count, balance_count=int(data.get("balance_count") or data.get("balanceCount") or total_count),
|
||||
total_amount=total_amount, balance_amount=self._decimal(data.get("balance_amount") or data.get("balanceAmount") or total_amount),
|
||||
valid_start=valid_start,
|
||||
valid_end=valid_end,
|
||||
notes=data.get("notes"), creator=operator, updater=operator,
|
||||
)
|
||||
self.session.add(member_product)
|
||||
self.session.commit()
|
||||
self.session.refresh(member_product)
|
||||
return self._member_product_to_dict(member_product)
|
||||
|
||||
def consume_member_product_sync(self, member_product_id: str, data: dict,
|
||||
store_id: Optional[str] = None, operator: str = ""):
|
||||
query = self.session.query(CrmMemberProductModel).filter(CrmMemberProductModel.id == member_product_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmMemberProductModel.store_id == store_id)
|
||||
member_product = query.first()
|
||||
if not member_product:
|
||||
return None
|
||||
count = int(data.get("consume_count") or data.get("consumeCount") or 1)
|
||||
amount = self._decimal(data.get("consume_amount") or data.get("consumeAmount") or 0)
|
||||
member_product.balance_count = max(0, int(member_product.balance_count or 0) - count)
|
||||
member_product.balance_amount = max(Decimal("0"), self._decimal(member_product.balance_amount) - amount)
|
||||
if member_product.balance_count == 0 and self._decimal(member_product.balance_amount) == 0:
|
||||
member_product.status = 0
|
||||
member_product.update_date = datetime.now()
|
||||
visit_id = data.get("visit_id") or data.get("visitId") or self._latest_visit_id(member_product.member_id, member_product.store_id)
|
||||
if visit_id and amount:
|
||||
self._sync_visit_consumption(visit_id, amount)
|
||||
consume = CrmProductConsumeModel(
|
||||
id=generate_id(), store_id=member_product.store_id, member_id=member_product.member_id,
|
||||
member_product_id=member_product.id, product_id=member_product.product_id, visit_id=visit_id,
|
||||
consume_count=count, consume_amount=amount,
|
||||
balance_count_after=member_product.balance_count, balance_amount_after=member_product.balance_amount,
|
||||
notes=data.get("notes"), operator=operator,
|
||||
)
|
||||
self.session.add(consume)
|
||||
return member_product
|
||||
|
||||
async def consume_member_product(self, member_product_id: str, data: dict,
|
||||
store_id: Optional[str] = None, operator: str = "") -> Optional[dict]:
|
||||
member_product = self.consume_member_product_sync(member_product_id, data, store_id, operator)
|
||||
if not member_product:
|
||||
return None
|
||||
self.session.commit()
|
||||
self.session.refresh(member_product)
|
||||
return self._member_product_to_dict(member_product)
|
||||
|
||||
def _consume_member_product_old_unused(self, member_product_id: str, data: dict,
|
||||
store_id: Optional[str] = None, operator: str = "") -> Optional[dict]:
|
||||
query = self.session.query(CrmMemberProductModel).filter(CrmMemberProductModel.id == member_product_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmMemberProductModel.store_id == store_id)
|
||||
member_product = query.first()
|
||||
if not member_product:
|
||||
return None
|
||||
count = int(data.get("consume_count") or data.get("consumeCount") or 1)
|
||||
amount = self._decimal(data.get("consume_amount") or data.get("consumeAmount") or 0)
|
||||
member_product.balance_count = max(0, int(member_product.balance_count or 0) - count)
|
||||
member_product.balance_amount = max(Decimal("0"), self._decimal(member_product.balance_amount) - amount)
|
||||
if member_product.balance_count == 0 and self._decimal(member_product.balance_amount) == 0:
|
||||
member_product.status = 0
|
||||
member_product.update_date = datetime.now()
|
||||
visit_id = data.get("visit_id") or data.get("visitId") or self._latest_visit_id(member_product.member_id, member_product.store_id)
|
||||
if visit_id and amount:
|
||||
self._sync_visit_consumption(visit_id, amount)
|
||||
consume = CrmProductConsumeModel(
|
||||
id=generate_id(), store_id=member_product.store_id, member_id=member_product.member_id,
|
||||
member_product_id=member_product.id, product_id=member_product.product_id, visit_id=visit_id,
|
||||
consume_count=count, consume_amount=amount,
|
||||
balance_count_after=member_product.balance_count, balance_amount_after=member_product.balance_amount,
|
||||
notes=data.get("notes"), operator=operator,
|
||||
)
|
||||
self.session.add(consume)
|
||||
self.session.commit()
|
||||
self.session.refresh(member_product)
|
||||
return self._member_product_to_dict(member_product)
|
||||
|
||||
async def list_product_consumes(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None,
|
||||
member_id: Optional[str] = None,
|
||||
member_product_id: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmProductConsumeModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmProductConsumeModel.store_id == store_id)
|
||||
if member_id:
|
||||
query = query.filter(CrmProductConsumeModel.member_id == member_id)
|
||||
if member_product_id:
|
||||
query = query.filter(CrmProductConsumeModel.member_product_id == member_product_id)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmProductConsumeModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._product_consume_to_dict(c) for c in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
# ---- Suggestion / Issue ----
|
||||
async def list_suggestions(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, status: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmSuggestionModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmSuggestionModel.store_id == store_id)
|
||||
if status:
|
||||
query = query.filter(CrmSuggestionModel.status == status)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmSuggestionModel.frequency.desc(), CrmSuggestionModel.create_date.desc()) \
|
||||
.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._suggestion_to_dict(s) for s in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def create_suggestion(self, data: dict, operator: str = "") -> dict:
|
||||
content = (data.get("content") or "").strip()
|
||||
content_hash = self._content_hash(content)
|
||||
store_id = data.get("store_id")
|
||||
existing = self.session.query(CrmSuggestionModel).filter(
|
||||
CrmSuggestionModel.store_id == store_id,
|
||||
CrmSuggestionModel.content_hash == content_hash,
|
||||
).first()
|
||||
if existing:
|
||||
existing.frequency = (existing.frequency or 1) + 1
|
||||
existing.update_date = datetime.now()
|
||||
self.session.commit()
|
||||
self.session.refresh(existing)
|
||||
return self._suggestion_to_dict(existing)
|
||||
suggestion = CrmSuggestionModel(
|
||||
id=generate_id(), store_id=store_id,
|
||||
feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"),
|
||||
member_id=data.get("member_id") or data.get("memberId"),
|
||||
content=content, content_hash=content_hash,
|
||||
category=data.get("category") or self._suggestion_category(content),
|
||||
tags=data.get("tags") or self._suggestion_tags(content),
|
||||
priority=data.get("priority") or self._suggestion_priority(content),
|
||||
source=data.get("source") or "manual",
|
||||
submitter_name=data.get("submitter_name") or data.get("submitterName") or self._member_name(data.get("member_id") or data.get("memberId")),
|
||||
duplicate_group_id=generate_id(),
|
||||
status=data.get("status") or "pending", handled_by=operator,
|
||||
)
|
||||
self.session.add(suggestion)
|
||||
self.session.commit()
|
||||
self.session.refresh(suggestion)
|
||||
return self._suggestion_to_dict(suggestion)
|
||||
|
||||
async def update_suggestion_status(self, suggestion_id: str, status: str, data: dict,
|
||||
store_id: Optional[str] = None, operator: str = "") -> Optional[dict]:
|
||||
query = self.session.query(CrmSuggestionModel).filter(CrmSuggestionModel.id == suggestion_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmSuggestionModel.store_id == store_id)
|
||||
suggestion = query.first()
|
||||
if not suggestion:
|
||||
return None
|
||||
suggestion.status = status
|
||||
suggestion.handled_by = operator
|
||||
suggestion.handle_notes = data.get("handle_notes") or data.get("handleNotes") or suggestion.handle_notes
|
||||
suggestion.rejected_reason = data.get("rejected_reason") or data.get("rejectedReason") or suggestion.rejected_reason
|
||||
if status == "adopted":
|
||||
suggestion.adopted_at = datetime.now()
|
||||
suggestion.update_date = datetime.now()
|
||||
self.session.commit()
|
||||
self.session.refresh(suggestion)
|
||||
return self._suggestion_to_dict(suggestion)
|
||||
|
||||
async def list_issues(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None, status: Optional[str] = None) -> dict:
|
||||
query = self.session.query(CrmIssueModel)
|
||||
if store_id:
|
||||
query = query.filter(CrmIssueModel.store_id == store_id)
|
||||
if status:
|
||||
query = query.filter(CrmIssueModel.status == status)
|
||||
total = query.count()
|
||||
rows = query.order_by(CrmIssueModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {"list": [self._issue_to_dict(i) for i in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
async def create_issue(self, data: dict, operator: str = "") -> dict:
|
||||
issue = CrmIssueModel(
|
||||
id=generate_id(), store_id=data.get("store_id"),
|
||||
feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"),
|
||||
member_id=data.get("member_id") or data.get("memberId"),
|
||||
card_close_id=data.get("card_close_id") or data.get("cardCloseId"),
|
||||
title=data.get("title"), description=data.get("description"),
|
||||
severity=data.get("severity") or "medium", category=data.get("category"),
|
||||
status=data.get("status") or "identified",
|
||||
fix_plan=data.get("fix_plan") or data.get("fixPlan"),
|
||||
fix_deadline=self._parse_datetime(data.get("fix_deadline") or data.get("fixDeadline")),
|
||||
assigned_to=data.get("assigned_to") or data.get("assignedTo"),
|
||||
)
|
||||
self.session.add(issue)
|
||||
self.session.commit()
|
||||
self.session.refresh(issue)
|
||||
return self._issue_to_dict(issue)
|
||||
|
||||
async def update_issue(self, issue_id: str, data: dict, store_id: Optional[str] = None,
|
||||
operator: str = "") -> Optional[dict]:
|
||||
query = self.session.query(CrmIssueModel).filter(CrmIssueModel.id == issue_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmIssueModel.store_id == store_id)
|
||||
issue = query.first()
|
||||
if not issue:
|
||||
return None
|
||||
for key, field in [("title", "title"), ("description", "description"), ("severity", "severity"),
|
||||
("category", "category"), ("status", "status"), ("fix_plan", "fix_plan"),
|
||||
("fixPlan", "fix_plan"), ("fix_result", "fix_result"), ("fixResult", "fix_result"),
|
||||
("assigned_to", "assigned_to"), ("assignedTo", "assigned_to")]:
|
||||
if key in data:
|
||||
setattr(issue, field, data[key])
|
||||
if issue.status == "fixed" and not issue.fixed_at:
|
||||
issue.fixed_at = datetime.now()
|
||||
if issue.status == "closed" and not issue.closed_at:
|
||||
issue.closed_at = datetime.now()
|
||||
issue.update_date = datetime.now()
|
||||
self.session.commit()
|
||||
self.session.refresh(issue)
|
||||
return self._issue_to_dict(issue)
|
||||
|
||||
async def bind_feedback(self, feedback_id: str, data: dict, store_id: Optional[str] = None) -> Optional[dict]:
|
||||
query = self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == feedback_id)
|
||||
if store_id:
|
||||
query = query.filter(FeedbackRecordModel.store_id == store_id)
|
||||
record = query.first()
|
||||
if not record:
|
||||
return None
|
||||
for key, field in [("member_id", "member_id"), ("memberId", "member_id"),
|
||||
("visit_id", "visit_id"), ("visitId", "visit_id"),
|
||||
("card_close_id", "card_close_id"), ("cardCloseId", "card_close_id")]:
|
||||
if key in data:
|
||||
setattr(record, field, data[key])
|
||||
self.session.commit()
|
||||
self.session.refresh(record)
|
||||
return self._feedback_to_dict(record)
|
||||
|
||||
async def get_overview(self, store_id: Optional[str] = None) -> dict:
|
||||
def count(model, *filters):
|
||||
q = self.session.query(func.count(model.id))
|
||||
if store_id and hasattr(model, "store_id"):
|
||||
q = q.filter(model.store_id == store_id)
|
||||
for f in filters:
|
||||
q = q.filter(f)
|
||||
return q.scalar() or 0
|
||||
total_balance = self.session.query(func.coalesce(func.sum(CrmAccountModel.balance_amount), 0))
|
||||
if store_id:
|
||||
total_balance = total_balance.filter(CrmAccountModel.store_id == store_id)
|
||||
return {
|
||||
"members": count(CrmMemberModel),
|
||||
"visits": count(CrmVisitModel),
|
||||
"activeAccounts": count(CrmAccountModel, CrmAccountModel.status == 1),
|
||||
"accountBalance": float(total_balance.scalar() or 0),
|
||||
"cardCloses": count(CrmCardCloseModel),
|
||||
"pendingSuggestions": count(CrmSuggestionModel, CrmSuggestionModel.status == "pending"),
|
||||
"adoptedSuggestions": count(CrmSuggestionModel, CrmSuggestionModel.status == "adopted"),
|
||||
"openIssues": count(CrmIssueModel, CrmIssueModel.status.in_(["identified", "fixing"])),
|
||||
"fixedIssues": count(CrmIssueModel, CrmIssueModel.status.in_(["fixed", "closed"])),
|
||||
}
|
||||
|
||||
# ---- Helpers ----
|
||||
def _get_account(self, account_id: str, store_id: Optional[str] = None):
|
||||
query = self.session.query(CrmAccountModel).filter(CrmAccountModel.id == account_id)
|
||||
if store_id:
|
||||
query = query.filter(CrmAccountModel.store_id == store_id)
|
||||
return query.first()
|
||||
|
||||
def _latest_visit_id(self, member_id: str, store_id: str):
|
||||
if not member_id:
|
||||
return None
|
||||
visit = self.session.query(CrmVisitModel).filter(
|
||||
CrmVisitModel.member_id == member_id,
|
||||
CrmVisitModel.store_id == store_id,
|
||||
CrmVisitModel.status == 1,
|
||||
).order_by(CrmVisitModel.arrive_at.desc(), CrmVisitModel.create_date.desc()).first()
|
||||
return visit.id if visit else None
|
||||
|
||||
def _sync_visit_consumption(self, visit_id: str, amount: Decimal):
|
||||
visit = self.session.query(CrmVisitModel).filter(CrmVisitModel.id == visit_id).first()
|
||||
if visit:
|
||||
visit.consumption_amount = self._decimal(visit.consumption_amount) + self._decimal(amount)
|
||||
visit.update_date = datetime.now()
|
||||
|
||||
def _add_transaction(self, account, tx_type, amount, count_change, before, after, visit_id, notes, operator):
|
||||
self.session.add(CrmAccountTransactionModel(
|
||||
id=generate_id(), account_id=account.id, store_id=account.store_id, member_id=account.member_id,
|
||||
transaction_type=tx_type, amount=amount, count_change=count_change,
|
||||
balance_before=before, balance_after=after, related_visit_id=visit_id,
|
||||
notes=notes, operator=operator,
|
||||
))
|
||||
|
||||
def _touch_member_visit_stats(self, member_id, arrive_at, amount):
|
||||
if not member_id:
|
||||
return
|
||||
member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id).first()
|
||||
if member:
|
||||
member.total_visits = (member.total_visits or 0) + 1
|
||||
member.total_spent = self._decimal(member.total_spent) + self._decimal(amount)
|
||||
if arrive_at and (not member.last_visit_at or arrive_at > member.last_visit_at):
|
||||
member.last_visit_at = arrive_at
|
||||
member.update_date = datetime.now()
|
||||
|
||||
@staticmethod
|
||||
def _suggestion_category(content: str) -> str:
|
||||
text = content or ""
|
||||
if any(k in text for k in ["冷", "热", "空调", "房间", "环境", "卫生", "水"]):
|
||||
return "environment"
|
||||
if any(k in text for k in ["态度", "服务", "技师", "沟通"]):
|
||||
return "service"
|
||||
if any(k in text for k in ["价格", "优惠", "贵", "便宜", "活动"]):
|
||||
return "price"
|
||||
if any(k in text for k in ["产品", "项目", "效果", "套餐"]):
|
||||
return "product"
|
||||
return "other"
|
||||
|
||||
@staticmethod
|
||||
def _suggestion_tags(content: str) -> list:
|
||||
text = content or ""
|
||||
tags = []
|
||||
mapping = {
|
||||
"环境": ["冷", "热", "空调", "房间", "环境"],
|
||||
"卫生": ["卫生", "干净", "毛巾"],
|
||||
"服务": ["服务", "态度", "沟通", "技师"],
|
||||
"价格": ["价格", "优惠", "贵", "活动"],
|
||||
"产品": ["产品", "项目", "套餐", "效果"],
|
||||
"茶水": ["水", "茶", "饮品"],
|
||||
}
|
||||
for tag, keywords in mapping.items():
|
||||
if any(k in text for k in keywords):
|
||||
tags.append(tag)
|
||||
return tags or ["其他"]
|
||||
|
||||
@staticmethod
|
||||
def _suggestion_priority(content: str) -> str:
|
||||
text = content or ""
|
||||
if any(k in text for k in ["投诉", "退款", "销卡", "很差"]):
|
||||
return "urgent"
|
||||
if any(k in text for k in ["不满意", "态度", "卫生", "没效果"]):
|
||||
return "high"
|
||||
if any(k in text for k in ["建议", "希望", "可以"]):
|
||||
return "medium"
|
||||
return "low"
|
||||
|
||||
@staticmethod
|
||||
def _should_create_issue_for_close(reason: Optional[str]) -> bool:
|
||||
text = reason or ""
|
||||
return any(k in text for k in ["不满意", "没效果", "态度", "投诉", "退款", "服务", "卫生", "太冷", "太热"])
|
||||
|
||||
@staticmethod
|
||||
def _content_hash(content: str) -> str:
|
||||
normalized = re.sub(r"\s+", "", content or "").lower()
|
||||
normalized = re.sub(r"[,。!?,.!?;;::]", "", normalized)
|
||||
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def _decimal(value) -> Decimal:
|
||||
if value is None or value == "":
|
||||
return Decimal("0")
|
||||
return Decimal(str(value))
|
||||
|
||||
@staticmethod
|
||||
def _parse_date(value):
|
||||
if not value:
|
||||
return None
|
||||
if hasattr(value, "year"):
|
||||
return value
|
||||
return datetime.fromisoformat(str(value).replace("Z", "+00:00")[:10]).date()
|
||||
|
||||
@staticmethod
|
||||
def _parse_datetime(value):
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
text = str(value).replace("Z", "+00:00")
|
||||
try:
|
||||
return datetime.fromisoformat(text)
|
||||
except ValueError:
|
||||
return datetime.strptime(text[:19], "%Y-%m-%d %H:%M:%S")
|
||||
|
||||
@staticmethod
|
||||
def _json(value):
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except Exception:
|
||||
return value
|
||||
return value
|
||||
|
||||
def _member_name(self, member_id):
|
||||
if not member_id:
|
||||
return None
|
||||
member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id).first()
|
||||
return member.name if member else None
|
||||
|
||||
def _member_to_dict(self, m):
|
||||
return {
|
||||
"id": m.id, "storeId": m.store_id, "name": m.name, "phone": m.phone, "gender": m.gender,
|
||||
"birthday": str(m.birthday) if m.birthday else None, "wechat": m.wechat, "source": m.source,
|
||||
"level": m.level, "tags": self._json(m.tags), "mekaiTags": self._json(m.mekai_tags),
|
||||
"beautyConcerns": self._json(m.beauty_concerns), "healthIssues": self._json(m.health_issues),
|
||||
"allergies": m.allergies, "servicePreferences": self._json(m.service_preferences), "notes": m.notes,
|
||||
"lastVisitAt": str(m.last_visit_at) if m.last_visit_at else None,
|
||||
"totalVisits": m.total_visits or 0, "totalSpent": float(m.total_spent or 0), "status": m.status,
|
||||
"createDate": str(m.create_date) if m.create_date else None, "updateDate": str(m.update_date) if m.update_date else None,
|
||||
}
|
||||
|
||||
def _visit_to_dict(self, v):
|
||||
return {
|
||||
"id": v.id, "storeId": v.store_id, "memberId": v.member_id, "memberName": self._member_name(v.member_id), "employeeId": v.employee_id,
|
||||
"feedbackRecordId": v.feedback_record_id, "sessionId": v.session_id, "deviceMac": v.device_mac,
|
||||
"visitType": v.visit_type, "serviceItems": self._json(v.service_items),
|
||||
"arriveAt": str(v.arrive_at) if v.arrive_at else None, "leaveAt": str(v.leave_at) if v.leave_at else None,
|
||||
"durationMinutes": v.duration_minutes, "satisfaction": v.satisfaction,
|
||||
"consumptionAmount": float(v.consumption_amount or 0), "notes": v.notes, "status": v.status,
|
||||
"createDate": str(v.create_date) if v.create_date else None,
|
||||
}
|
||||
|
||||
def _account_to_dict(self, a):
|
||||
return {
|
||||
"id": a.id, "storeId": a.store_id, "memberId": a.member_id, "memberName": self._member_name(a.member_id), "accountType": a.account_type,
|
||||
"cardName": a.card_name, "totalAmount": float(a.total_amount or 0), "balanceAmount": float(a.balance_amount or 0),
|
||||
"totalCount": a.total_count or 0, "balanceCount": a.balance_count or 0,
|
||||
"validStart": str(a.valid_start) if a.valid_start else None, "validEnd": str(a.valid_end) if a.valid_end else None,
|
||||
"status": a.status, "closedReason": a.closed_reason, "closedAt": str(a.closed_at) if a.closed_at else None,
|
||||
"notes": a.notes, "createDate": str(a.create_date) if a.create_date else None,
|
||||
}
|
||||
|
||||
def _body_status_to_dict(self, b):
|
||||
return {
|
||||
"id": b.id, "storeId": b.store_id, "memberId": b.member_id,
|
||||
"memberName": self._member_name(b.member_id), "visitId": b.visit_id,
|
||||
"memberProductId": b.member_product_id,
|
||||
"recordDate": str(b.record_date) if b.record_date else None,
|
||||
"weight": float(b.weight) if b.weight is not None else None,
|
||||
"waistline": float(b.waistline) if b.waistline is not None else None,
|
||||
"painLevel": b.pain_level, "sleepQuality": b.sleep_quality,
|
||||
"skinStatus": b.skin_status, "bodyParts": self._json(b.body_parts),
|
||||
"metrics": self._json(b.metrics), "notes": b.notes,
|
||||
"createDate": str(b.create_date) if b.create_date else None,
|
||||
}
|
||||
|
||||
def _product_to_dict(self, p):
|
||||
return {
|
||||
"id": p.id, "storeId": p.store_id, "productName": p.product_name,
|
||||
"productType": p.product_type, "category": p.category,
|
||||
"price": float(p.price or 0), "defaultCount": p.default_count or 0,
|
||||
"description": p.description, "status": p.status,
|
||||
"createDate": str(p.create_date) if p.create_date else None,
|
||||
}
|
||||
|
||||
def _member_product_to_dict(self, p):
|
||||
product = self.session.query(CrmProductModel).filter(CrmProductModel.id == p.product_id).first() if p.product_id else None
|
||||
return {
|
||||
"id": p.id, "storeId": p.store_id, "memberId": p.member_id,
|
||||
"memberName": self._member_name(p.member_id), "productId": p.product_id,
|
||||
"accountId": p.account_id, "productName": p.product_name,
|
||||
"unitPrice": float(p.unit_price or 0), "purchaseCount": p.purchase_count or 0,
|
||||
"discount": float(p.discount or 1), "durationMinutes": product.duration_minutes if product else 60,
|
||||
"packageItems": self._json(p.package_items), "totalCount": p.total_count or 0,
|
||||
"balanceCount": p.balance_count or 0, "totalAmount": float(p.total_amount or 0),
|
||||
"balanceAmount": float(p.balance_amount or 0),
|
||||
"validStart": str(p.valid_start) if p.valid_start else None,
|
||||
"validEnd": str(p.valid_end) if p.valid_end else None,
|
||||
"status": p.status, "notes": p.notes,
|
||||
"createDate": str(p.create_date) if p.create_date else None,
|
||||
}
|
||||
|
||||
def _product_consume_to_dict(self, c):
|
||||
return {
|
||||
"id": c.id, "storeId": c.store_id, "memberId": c.member_id,
|
||||
"memberName": self._member_name(c.member_id), "memberProductId": c.member_product_id,
|
||||
"productId": c.product_id, "visitId": c.visit_id,
|
||||
"consumeCount": c.consume_count or 0, "consumeAmount": float(c.consume_amount or 0),
|
||||
"balanceCountAfter": c.balance_count_after or 0,
|
||||
"balanceAmountAfter": float(c.balance_amount_after or 0),
|
||||
"notes": c.notes, "operator": c.operator,
|
||||
"createDate": str(c.create_date) if c.create_date else None,
|
||||
}
|
||||
|
||||
def _transaction_to_dict(self, t):
|
||||
return {
|
||||
"id": t.id, "accountId": t.account_id, "storeId": t.store_id,
|
||||
"memberId": t.member_id, "memberName": self._member_name(t.member_id),
|
||||
"transactionType": t.transaction_type, "amount": float(t.amount or 0),
|
||||
"countChange": t.count_change or 0, "balanceBefore": float(t.balance_before or 0),
|
||||
"balanceAfter": float(t.balance_after or 0), "relatedVisitId": t.related_visit_id,
|
||||
"notes": t.notes, "operator": t.operator,
|
||||
"createDate": str(t.create_date) if t.create_date else None,
|
||||
}
|
||||
|
||||
def _card_close_to_dict(self, c):
|
||||
return {
|
||||
"id": c.id, "storeId": c.store_id, "memberId": c.member_id, "memberName": self._member_name(c.member_id), "accountId": c.account_id,
|
||||
"feedbackRecordId": c.feedback_record_id, "closeType": c.close_type, "reason": c.reason,
|
||||
"refundAmount": float(c.refund_amount or 0), "remainingCount": c.remaining_count or 0,
|
||||
"status": c.status, "handledBy": c.handled_by, "approvedBy": c.approved_by,
|
||||
"handleNotes": c.handle_notes, "createDate": str(c.create_date) if c.create_date else None,
|
||||
}
|
||||
|
||||
def _suggestion_to_dict(self, s):
|
||||
return {
|
||||
"id": s.id, "storeId": s.store_id, "feedbackRecordId": s.feedback_record_id, "memberId": s.member_id,
|
||||
"content": s.content, "category": s.category, "tags": self._json(s.tags),
|
||||
"priority": s.priority, "source": s.source, "submitterName": s.submitter_name,
|
||||
"memberName": self._member_name(s.member_id),
|
||||
"duplicateGroupId": s.duplicate_group_id,
|
||||
"frequency": s.frequency or 1, "status": s.status, "adoptedAt": str(s.adopted_at) if s.adopted_at else None,
|
||||
"rejectedReason": s.rejected_reason, "handledBy": s.handled_by, "handleNotes": s.handle_notes,
|
||||
"createDate": str(s.create_date) if s.create_date else None,
|
||||
}
|
||||
|
||||
def _issue_to_dict(self, i):
|
||||
return {
|
||||
"id": i.id, "storeId": i.store_id, "feedbackRecordId": i.feedback_record_id, "memberId": i.member_id,
|
||||
"cardCloseId": i.card_close_id, "title": i.title, "description": i.description,
|
||||
"severity": i.severity, "category": i.category, "status": i.status,
|
||||
"identifiedAt": str(i.identified_at) if i.identified_at else None,
|
||||
"fixPlan": i.fix_plan, "fixDeadline": str(i.fix_deadline) if i.fix_deadline else None,
|
||||
"fixedAt": str(i.fixed_at) if i.fixed_at else None, "fixResult": i.fix_result,
|
||||
"assignedTo": i.assigned_to, "closedAt": str(i.closed_at) if i.closed_at else None,
|
||||
"createDate": str(i.create_date) if i.create_date else None,
|
||||
}
|
||||
|
||||
def _feedback_to_dict(self, r):
|
||||
return {
|
||||
"id": r.id, "storeId": r.store_id, "memberId": r.member_id, "visitId": r.visit_id,
|
||||
"cardCloseId": r.card_close_id, "satisfaction": r.satisfaction,
|
||||
"rawAsrText": r.raw_asr_text, "cleanedText": r.cleaned_text,
|
||||
"qaJson": r.qa_json, "reviewLong": r.review_long, "reviewShort": r.review_short,
|
||||
"createDate": str(r.create_date) if r.create_date else None,
|
||||
}
|
||||
93
main/feedback-backend/app/application/employee_service.py
Normal file
93
main/feedback-backend/app/application/employee_service.py
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
"""员工应用服务 - 员工 CRUD 用例"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.domain.employee.entity import Employee
|
||||
from app.domain.employee.value_objects import EmployeeType
|
||||
from app.infrastructure.persistence.employee_repo_impl import EmployeeRepositoryImpl
|
||||
from app.shared.exceptions import EmployeeNotFoundError, StoreNotFoundError, ValidationError
|
||||
from app.shared.utils import generate_id
|
||||
|
||||
|
||||
class EmployeeService:
|
||||
"""员工应用服务"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.repo = EmployeeRepositoryImpl(session)
|
||||
self.session = session
|
||||
|
||||
async def list_by_store_id(self, store_id: str, status: Optional[int] = None) -> list:
|
||||
"""获取门店下所有员工(公开接口用)"""
|
||||
return await self.repo.list_by_store_id(store_id, status)
|
||||
|
||||
async def get_by_id(self, employee_id: str) -> Employee:
|
||||
"""根据 ID 获取员工"""
|
||||
employee = await self.repo.get_by_id(employee_id)
|
||||
if not employee:
|
||||
raise EmployeeNotFoundError(employee_id)
|
||||
return employee
|
||||
|
||||
async def list_page(self, page: int = 1, page_size: int = 20,
|
||||
store_id: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
status: Optional[int] = None) -> dict:
|
||||
"""分页查询员工"""
|
||||
return await self.repo.list_page(page, page_size, store_id, name, status)
|
||||
|
||||
async def create_employee(self, name: str, number: int, store_id: str,
|
||||
employee_type: str = "normal") -> Employee:
|
||||
"""创建员工"""
|
||||
# 验证员工类型
|
||||
if employee_type not in Employee.valid_employee_types():
|
||||
raise ValidationError(f"无效的员工类型: {employee_type}")
|
||||
|
||||
# 检查工号唯一性
|
||||
if await self.repo.exists_by_store_and_number(store_id, number):
|
||||
raise ValidationError(f"门店 {store_id} 下工号 {number} 已存在")
|
||||
|
||||
employee = Employee(
|
||||
id=generate_id(),
|
||||
name=name,
|
||||
number=number,
|
||||
store_id=store_id,
|
||||
employee_type=employee_type,
|
||||
)
|
||||
result = await self.repo.save(employee)
|
||||
logger.info(f"创建员工: name={name}, store={store_id}, number={number}")
|
||||
return result
|
||||
|
||||
async def update_employee(self, employee_id: str, **kwargs) -> Employee:
|
||||
"""更新员工"""
|
||||
employee = await self.repo.get_by_id(employee_id)
|
||||
if not employee:
|
||||
raise EmployeeNotFoundError(employee_id)
|
||||
|
||||
# 如果修改了工号,检查唯一性
|
||||
if "number" in kwargs and kwargs["number"] != employee.number:
|
||||
store_id = kwargs.get("store_id", employee.store_id)
|
||||
if await self.repo.exists_by_store_and_number(store_id, kwargs["number"], exclude_id=employee_id):
|
||||
raise ValidationError(f"工号 {kwargs['number']} 已存在")
|
||||
|
||||
if "employee_type" in kwargs:
|
||||
if kwargs["employee_type"] not in Employee.valid_employee_types():
|
||||
raise ValidationError(f"无效的员工类型: {kwargs['employee_type']}")
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(employee, key) and value is not None:
|
||||
setattr(employee, key, value)
|
||||
|
||||
result = await self.repo.save(employee)
|
||||
logger.info(f"更新员工: id={employee_id}")
|
||||
return result
|
||||
|
||||
async def delete_employee(self, employee_id: str) -> bool:
|
||||
"""删除员工"""
|
||||
employee = await self.repo.get_by_id(employee_id)
|
||||
if not employee:
|
||||
raise EmployeeNotFoundError(employee_id)
|
||||
result = await self.repo.delete(employee_id)
|
||||
logger.info(f"删除员工: id={employee_id}")
|
||||
return result
|
||||
681
main/feedback-backend/app/application/feedback_service.py
Normal file
681
main/feedback-backend/app/application/feedback_service.py
Normal file
|
|
@ -0,0 +1,681 @@
|
|||
"""反馈处理应用服务 - AI 处理管线(3步 LLM Pipeline)"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.domain.feedback.entity import FeedbackRecord
|
||||
from app.domain.feedback.value_objects import Satisfaction
|
||||
from app.infrastructure.llm.llm_service import LLMService
|
||||
from app.infrastructure.persistence.feedback_repo_impl import FeedbackRecordRepositoryImpl
|
||||
from app.infrastructure.persistence.store_repo_impl import StoreRepositoryImpl
|
||||
from app.infrastructure.persistence.agent_repo_impl import AgentConfigRepositoryImpl
|
||||
from app.shared.config import settings
|
||||
from app.shared.exceptions import StoreNotFoundError, LLMProcessingError, PromptTemplateError
|
||||
from app.shared.utils import generate_id, should_generate_review, render_prompt
|
||||
from app.infrastructure.persistence.models import (
|
||||
CrmIssueModel,
|
||||
CrmMemberModel,
|
||||
CrmSuggestionModel,
|
||||
CrmVisitModel,
|
||||
FeedbackRecordModel,
|
||||
)
|
||||
|
||||
|
||||
class FeedbackService:
|
||||
"""反馈处理应用服务 - 核心业务逻辑
|
||||
|
||||
3 步 AI Pipeline:
|
||||
1. ASR 清洗 - 去除语音填充词
|
||||
2. QA 结构化 - 提取结构化 Q&A
|
||||
3. 点评生成 - 仅满意时生成点评
|
||||
"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.record_repo = FeedbackRecordRepositoryImpl(session)
|
||||
self.store_repo = StoreRepositoryImpl(session)
|
||||
self.agent_repo = AgentConfigRepositoryImpl(session)
|
||||
self.session = session
|
||||
|
||||
def _get_prompts_dir(self) -> Path:
|
||||
"""获取提示词模板目录"""
|
||||
base_dir = Path(__file__).resolve().parent.parent.parent # feedback-backend/
|
||||
return base_dir / "prompts"
|
||||
|
||||
def _load_prompt(self, filename: str) -> str:
|
||||
"""加载提示词模板"""
|
||||
path = self._get_prompts_dir() / filename
|
||||
if not path.exists():
|
||||
raise PromptTemplateError(filename, f"模板文件不存在: {path}")
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
def _resolve_llm_service(self, agent_id: Optional[str] = None) -> LLMService:
|
||||
"""解析 LLM 服务 - 优先使用门店绑定的智能体配置"""
|
||||
if agent_id:
|
||||
# 尝试从 agent_config 获取自定义 LLM 配置
|
||||
# 注意:这里不能用 async,所以在外层处理
|
||||
pass
|
||||
# 使用默认配置
|
||||
return LLMService()
|
||||
|
||||
async def _resolve_llm_service_async(self, agent_id: Optional[str] = None) -> LLMService:
|
||||
"""异步解析 LLM 服务"""
|
||||
if agent_id:
|
||||
agent_config = await self.agent_repo.get_by_agent_id(agent_id)
|
||||
if agent_config and agent_config.llm_config:
|
||||
return LLMService(llm_config=agent_config.llm_config)
|
||||
return LLMService()
|
||||
|
||||
async def process_feedback(
|
||||
self,
|
||||
store_name: str,
|
||||
employee_number: str,
|
||||
asr_text: str,
|
||||
session_id: Optional[str] = None,
|
||||
device_mac: Optional[str] = None,
|
||||
satisfaction: Optional[str] = None,
|
||||
store_id: Optional[str] = None,
|
||||
employee_id: Optional[str] = None,
|
||||
customer_name: Optional[str] = None,
|
||||
phone_tail: Optional[str] = None,
|
||||
agent_id: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
处理客户反馈 - 完整的 3 步 AI Pipeline
|
||||
|
||||
Args:
|
||||
store_name: 门店名称
|
||||
employee_number: 技师工号
|
||||
asr_text: 原始 ASR 文本
|
||||
session_id: 会话 ID
|
||||
device_mac: 设备 MAC
|
||||
satisfaction: 满意度
|
||||
store_id: 门店 ID
|
||||
employee_id: 员工 ID
|
||||
agent_id: 智能体 ID
|
||||
|
||||
Returns:
|
||||
处理结果字典
|
||||
"""
|
||||
logger.info(f"开始处理反馈: store={store_name}, employee={employee_number}, satisfaction={satisfaction}")
|
||||
|
||||
# 验证满意度
|
||||
satisfaction_text = ""
|
||||
should_publish = False
|
||||
if satisfaction:
|
||||
try:
|
||||
sat = Satisfaction(satisfaction)
|
||||
satisfaction_text = sat.text
|
||||
should_publish = sat.is_positive
|
||||
except ValueError:
|
||||
logger.warning(f"无效的满意度值: {satisfaction}")
|
||||
|
||||
# 解析 LLM 服务
|
||||
llm = await self._resolve_llm_service_async(agent_id)
|
||||
|
||||
# Step 1: ASR 清洗
|
||||
cleaned_text = await self._step_asr_cleanup(llm, store_name, employee_number, asr_text)
|
||||
logger.info(f"ASR 清洗完成,原文 {len(asr_text)} 字 -> 清洗后 {len(cleaned_text)} 字")
|
||||
|
||||
# Step 2: QA 结构化
|
||||
qa_result = await self._step_qa_structured(llm, store_name, employee_number, cleaned_text)
|
||||
logger.info(f"QA 结构化完成")
|
||||
|
||||
# Step 3: 点评生成(仅满意时)
|
||||
review_long = None
|
||||
review_short = None
|
||||
if should_publish and should_generate_review(satisfaction):
|
||||
review_long, review_short = await self._step_review_generation(
|
||||
llm, store_name, employee_number, qa_result, satisfaction
|
||||
)
|
||||
logger.info(f"点评生成完成: 长评={len(review_long or '')}字, 短评={len(review_short or '')}字")
|
||||
|
||||
# 保存记录(通过 session_id upsert,如果 H5 已先保存了 rawAsrText,这里会更新)
|
||||
record = FeedbackRecord(
|
||||
id=generate_id(),
|
||||
store_id=store_id or "",
|
||||
session_id=session_id,
|
||||
employee_id=employee_id,
|
||||
device_mac=device_mac,
|
||||
raw_asr_text=asr_text,
|
||||
cleaned_text=cleaned_text,
|
||||
qa_json=qa_result,
|
||||
review_long=review_long,
|
||||
review_short=review_short,
|
||||
satisfaction=satisfaction,
|
||||
customer_name=(customer_name or "").strip() or None,
|
||||
phone_tail=self._normalize_phone_tail(phone_tail) or None,
|
||||
)
|
||||
try:
|
||||
# 如果已有同 session_id 的记录,更新它
|
||||
if session_id:
|
||||
existing = await self.record_repo.get_by_session_id(session_id)
|
||||
if existing:
|
||||
existing.cleaned_text = cleaned_text
|
||||
existing.qa_json = qa_result
|
||||
existing.review_long = review_long
|
||||
existing.review_short = review_short
|
||||
existing.satisfaction = satisfaction
|
||||
existing.customer_name = (customer_name or existing.customer_name or "").strip() or None
|
||||
existing.phone_tail = self._normalize_phone_tail(phone_tail) or existing.phone_tail
|
||||
record = await self.record_repo.save(existing)
|
||||
logger.info(f"反馈记录已更新: session_id={session_id}")
|
||||
else:
|
||||
record = await self.record_repo.save(record)
|
||||
logger.info(f"反馈记录已保存: id={record.id}")
|
||||
else:
|
||||
record = await self.record_repo.save(record)
|
||||
logger.info(f"反馈记录已保存: id={record.id}")
|
||||
except Exception as e:
|
||||
logger.error(f"反馈记录保存失败: {e}")
|
||||
# 记录保存失败不影响返回结果
|
||||
|
||||
self._auto_link_feedback_to_crm(record, cleaned_text, qa_result, satisfaction)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"cleaned_text": cleaned_text,
|
||||
"qa_result": qa_result,
|
||||
"review_long": review_long,
|
||||
"review_short": review_short,
|
||||
"satisfaction": satisfaction,
|
||||
"satisfaction_text": satisfaction_text,
|
||||
"should_publish": should_publish,
|
||||
"customer_name": record.customer_name,
|
||||
"phone_tail": record.phone_tail,
|
||||
"member_id": record.member_id,
|
||||
"member_match_status": record.member_match_status,
|
||||
"member_match_candidates": record.member_match_candidates or [],
|
||||
}
|
||||
|
||||
def _auto_link_feedback_to_crm(self, record: FeedbackRecord, cleaned_text: str,
|
||||
qa_result: str, satisfaction: Optional[str]):
|
||||
"""根据已有反馈结构化内容自动关联 CRM。"""
|
||||
if not record or not record.store_id:
|
||||
return
|
||||
try:
|
||||
phone_tail = record.phone_tail or self._extract_phone_tail(qa_result or cleaned_text or "")
|
||||
record.phone_tail = phone_tail or None
|
||||
customer_name = record.customer_name or self._extract_customer_name(qa_result or cleaned_text or "")
|
||||
record.customer_name = customer_name or None
|
||||
match_result = self._match_member_by_identity(record.store_id, phone_tail, customer_name)
|
||||
member = match_result.get("member")
|
||||
record.member_match_status = match_result.get("status")
|
||||
record.member_match_candidates = match_result.get("candidates") or []
|
||||
if member:
|
||||
record.member_id = member.id
|
||||
self._merge_member_profile(member, qa_result)
|
||||
|
||||
visit = self._create_or_update_visit(record, qa_result, satisfaction)
|
||||
if visit:
|
||||
record.visit_id = visit.id
|
||||
|
||||
self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == record.id).update({
|
||||
"member_id": record.member_id,
|
||||
"visit_id": record.visit_id,
|
||||
"customer_name": record.customer_name,
|
||||
"phone_tail": record.phone_tail,
|
||||
"member_match_status": record.member_match_status,
|
||||
"member_match_candidates": record.member_match_candidates,
|
||||
})
|
||||
self._auto_create_suggestion(record, qa_result)
|
||||
self.session.commit()
|
||||
except Exception as e:
|
||||
self.session.rollback()
|
||||
logger.warning(f"自动关联 CRM 失败: {e}")
|
||||
# 问题修复模块已从主流程下线:反馈只进入建议/客户档案/到店,不再自动创建问题。
|
||||
|
||||
def _match_member_by_identity(self, store_id: str, phone_tail: str, customer_name: str = "") -> dict:
|
||||
phone_tail = self._normalize_phone_tail(phone_tail)
|
||||
if not phone_tail:
|
||||
return {"status": None, "member": None, "candidates": []}
|
||||
candidates = self.session.query(CrmMemberModel).filter(
|
||||
CrmMemberModel.store_id == store_id,
|
||||
CrmMemberModel.phone.like(f"%{phone_tail}"),
|
||||
CrmMemberModel.status == 1,
|
||||
).order_by(CrmMemberModel.update_date.desc()).all()
|
||||
candidate_list = [self._member_candidate(m) for m in candidates]
|
||||
if not candidates:
|
||||
return {"status": "not_found", "member": None, "candidates": []}
|
||||
if len(candidates) == 1:
|
||||
return {"status": "matched", "member": candidates[0], "candidates": candidate_list}
|
||||
name = (customer_name or "").strip()
|
||||
if name:
|
||||
name_matches = [m for m in candidates if self._name_matches(name, m)]
|
||||
if len(name_matches) == 1:
|
||||
return {"status": "matched", "member": name_matches[0], "candidates": candidate_list}
|
||||
return {"status": "conflict", "member": None, "candidates": candidate_list}
|
||||
|
||||
@staticmethod
|
||||
def _member_candidate(member) -> dict:
|
||||
return {
|
||||
"id": member.id,
|
||||
"name": member.name,
|
||||
"phone": member.phone,
|
||||
"phoneTail": (member.phone or "")[-4:],
|
||||
"nickname": (member.mekai_tags or {}).get("nickname") if isinstance(member.mekai_tags, dict) else None,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_phone_tail(value: str) -> str:
|
||||
import re
|
||||
digits = re.sub(r"\D", "", value or "")
|
||||
return digits[-4:] if len(digits) >= 4 else ""
|
||||
|
||||
@staticmethod
|
||||
def _name_matches(customer_name: str, member) -> bool:
|
||||
name = (customer_name or "").strip()
|
||||
if not name:
|
||||
return False
|
||||
candidates = [member.name or ""]
|
||||
if isinstance(member.mekai_tags, dict):
|
||||
candidates.append(member.mekai_tags.get("nickname") or "")
|
||||
normalized = name.replace("女士", "").replace("先生", "").replace("姐", "").replace("哥", "").strip()
|
||||
for item in candidates:
|
||||
item = (item or "").strip()
|
||||
item_norm = item.replace("女士", "").replace("先生", "").replace("姐", "").replace("哥", "").strip()
|
||||
if name and (name in item or item in name):
|
||||
return True
|
||||
if normalized and item_norm and (normalized in item_norm or item_norm in normalized):
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _extract_customer_name(text: str) -> str:
|
||||
import re
|
||||
patterns = [
|
||||
r"(?:怎么称呼您|如何称呼您|称呼您|您的称呼|您怎么称呼)[^\n::,,。]{0,12}[::]?\s*([一-龥A-Za-z]{1,12})",
|
||||
r"(?:我叫|我是|叫我)([一-龥A-Za-z]{1,12})",
|
||||
r"Q9[^\n]*\n?A9[::]\s*([^\n,,。]+)",
|
||||
r"Q9[^A]*A9[::]\s*([^\n,,。]+)",
|
||||
]
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, text or "")
|
||||
if match:
|
||||
name = match.group(1).strip()
|
||||
if name and name not in {"未提及", "用户未作答", "不知道"} and not re.fullmatch(r"\d+", name):
|
||||
return name[:12]
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _extract_phone_tail(text: str) -> str:
|
||||
import re
|
||||
match = re.search(r"(?:手机号后四位|手机尾号|尾号|后四位)[^0-9]{0,8}(\d{4})", text or "")
|
||||
if match:
|
||||
return match.group(1)
|
||||
matches = re.findall(r"(?<!\d)(\d{4})(?!\d)", text or "")
|
||||
return matches[-1] if matches else ""
|
||||
|
||||
def _merge_member_profile(self, member, qa_result: str):
|
||||
discomfort = self._extract_qa_answer(qa_result, "Q5") or self._extract_qa_answer(qa_result, "不舒服")
|
||||
if discomfort:
|
||||
existing = member.health_issues if isinstance(member.health_issues, list) else []
|
||||
if isinstance(existing, str):
|
||||
try:
|
||||
existing = json.loads(existing)
|
||||
except Exception:
|
||||
existing = [existing]
|
||||
if discomfort not in existing:
|
||||
existing.append(discomfort)
|
||||
member.health_issues = existing
|
||||
member.update_date = datetime.now()
|
||||
|
||||
def _create_or_update_visit(self, record: FeedbackRecord, qa_result: str, satisfaction: Optional[str]):
|
||||
visit_time = self._extract_qa_answer(qa_result, "Q4") or self._extract_qa_answer(qa_result, "时间")
|
||||
service_item = self._extract_qa_answer(qa_result, "Q3") or self._extract_qa_answer(qa_result, "项目")
|
||||
existing = None
|
||||
if record.session_id:
|
||||
existing = self.session.query(CrmVisitModel).filter(CrmVisitModel.session_id == record.session_id).first()
|
||||
visit = existing or CrmVisitModel(id=generate_id(), store_id=record.store_id, session_id=record.session_id)
|
||||
visit.member_id = record.member_id
|
||||
visit.employee_id = record.employee_id
|
||||
visit.feedback_record_id = record.id
|
||||
visit.device_mac = record.device_mac
|
||||
visit.satisfaction = satisfaction
|
||||
if service_item:
|
||||
visit.service_items = [service_item]
|
||||
if visit_time and not visit.arrive_at:
|
||||
visit.arrive_at = self._parse_visit_time(visit_time)
|
||||
if not existing:
|
||||
self.session.add(visit)
|
||||
return visit
|
||||
|
||||
def _auto_create_suggestion(self, record: FeedbackRecord, qa_result: str):
|
||||
suggestion_text = self._extract_qa_answer(qa_result, "Q10") or self._extract_qa_answer(qa_result, "Q8") or self._extract_qa_answer(qa_result, "建议")
|
||||
if not suggestion_text:
|
||||
return
|
||||
content_hash = self._content_hash(suggestion_text)
|
||||
existing = self.session.query(CrmSuggestionModel).filter(
|
||||
CrmSuggestionModel.store_id == record.store_id,
|
||||
CrmSuggestionModel.content_hash == content_hash,
|
||||
).first()
|
||||
if existing:
|
||||
existing.frequency = (existing.frequency or 1) + 1
|
||||
existing.member_id = existing.member_id or record.member_id
|
||||
existing.feedback_record_id = existing.feedback_record_id or record.id
|
||||
existing.update_date = datetime.now()
|
||||
return
|
||||
self.session.add(CrmSuggestionModel(
|
||||
id=generate_id(),
|
||||
store_id=record.store_id,
|
||||
feedback_record_id=record.id,
|
||||
member_id=record.member_id,
|
||||
content=suggestion_text,
|
||||
content_hash=content_hash,
|
||||
category="feedback",
|
||||
tags=["反馈建议"],
|
||||
priority="medium",
|
||||
source="feedback",
|
||||
submitter_name=self._member_name(record.member_id),
|
||||
duplicate_group_id=generate_id(),
|
||||
status="pending",
|
||||
))
|
||||
|
||||
def _member_name(self, member_id: Optional[str]) -> Optional[str]:
|
||||
if not member_id:
|
||||
return None
|
||||
member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id).first()
|
||||
return member.name if member else None
|
||||
|
||||
@staticmethod
|
||||
def _content_hash(content: str) -> str:
|
||||
import hashlib
|
||||
import re
|
||||
normalized = re.sub(r"\s+", "", content or "").lower()
|
||||
normalized = re.sub(r"[,。!?,.!?;;::]", "", normalized)
|
||||
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def _parse_visit_time(text: str):
|
||||
import re
|
||||
now = datetime.now()
|
||||
match = re.search(r"(\d{1,2})[点::](\d{1,2})?", text or "")
|
||||
if match:
|
||||
hour = int(match.group(1))
|
||||
minute = int(match.group(2) or 0)
|
||||
if 0 <= hour <= 23 and 0 <= minute <= 59:
|
||||
return now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
return None
|
||||
|
||||
def _auto_create_feedback_issue(self, record: FeedbackRecord, cleaned_text: str,
|
||||
qa_result: str, satisfaction: Optional[str]):
|
||||
"""基于已有反馈自动生成待修复问题。"""
|
||||
if not record or not record.store_id:
|
||||
return
|
||||
negative = satisfaction in ("unsatisfied", "very_bad")
|
||||
text = f"{cleaned_text or ''}\n{qa_result or ''}"
|
||||
keywords = ["退款", "销卡", "投诉", "没效果", "不满意", "很差", "态度", "卫生", "太冷", "太热"]
|
||||
if not negative and not any(k in text for k in keywords):
|
||||
return
|
||||
try:
|
||||
from app.infrastructure.persistence.models import CrmIssueModel
|
||||
|
||||
title = "客户反馈待修复问题"
|
||||
if "销卡" in text or "退款" in text:
|
||||
title = "客户存在销卡/退款风险"
|
||||
elif "态度" in text:
|
||||
title = "客户反馈服务态度问题"
|
||||
elif "太冷" in text or "太热" in text:
|
||||
title = "客户反馈环境温度问题"
|
||||
elif "没效果" in text:
|
||||
title = "客户反馈项目效果问题"
|
||||
exists = self.session.query(CrmIssueModel).filter(
|
||||
CrmIssueModel.feedback_record_id == record.id,
|
||||
CrmIssueModel.title == title,
|
||||
).first()
|
||||
if exists:
|
||||
return
|
||||
issue = CrmIssueModel(
|
||||
id=generate_id(),
|
||||
store_id=record.store_id,
|
||||
feedback_record_id=record.id,
|
||||
member_id=record.member_id,
|
||||
title=title,
|
||||
description=text[:1000] if text else None,
|
||||
severity="high" if satisfaction == "very_bad" else "medium",
|
||||
category="feedback",
|
||||
status="identified",
|
||||
)
|
||||
self.session.add(issue)
|
||||
self.session.commit()
|
||||
logger.info(f"已从反馈自动创建问题: feedback_id={record.id}, issue_id={issue.id}")
|
||||
except Exception as e:
|
||||
self.session.rollback()
|
||||
logger.warning(f"自动创建反馈问题失败: {e}")
|
||||
|
||||
async def _step_asr_cleanup(self, llm: LLMService, store_name: str,
|
||||
employee_number: str, asr_text: str) -> str:
|
||||
"""Step 1: ASR 清洗 - 去除语音填充词"""
|
||||
try:
|
||||
template = self._load_prompt("asr-cleanup.txt")
|
||||
prompt = render_prompt(
|
||||
template,
|
||||
门店名称=store_name,
|
||||
技师工号=employee_number,
|
||||
用户全部语音原话=asr_text,
|
||||
)
|
||||
result = await llm.chat(
|
||||
system_prompt="你是一位专业的语音文本清洗专家。",
|
||||
user_message=prompt,
|
||||
temperature=0.1,
|
||||
)
|
||||
return result.strip()
|
||||
except PromptTemplateError:
|
||||
# 模板不存在时,直接使用简单清洗
|
||||
logger.warning("ASR 清洗模板不存在,使用简单清洗")
|
||||
return asr_text.strip()
|
||||
except Exception as e:
|
||||
logger.error(f"ASR 清洗失败: {e}")
|
||||
raise LLMProcessingError(f"ASR 清洗失败: {e}")
|
||||
|
||||
async def _step_qa_structured(self, llm: LLMService, store_name: str,
|
||||
employee_number: str, cleaned_text: str) -> str:
|
||||
"""Step 2: QA 结构化 - 提取结构化 Q&A"""
|
||||
try:
|
||||
template = self._load_prompt("qa-structured.txt")
|
||||
prompt = render_prompt(
|
||||
template,
|
||||
门店名称=store_name,
|
||||
技师编号=employee_number,
|
||||
消费项目="",
|
||||
规整后ASR文本=cleaned_text,
|
||||
)
|
||||
result = await llm.chat(
|
||||
system_prompt="你是一位专业的客户反馈分析师。",
|
||||
user_message=prompt,
|
||||
temperature=0.2,
|
||||
)
|
||||
return result.strip()
|
||||
except PromptTemplateError:
|
||||
logger.warning("QA 结构化模板不存在,跳过结构化")
|
||||
return cleaned_text
|
||||
except Exception as e:
|
||||
logger.error(f"QA 结构化失败: {e}")
|
||||
raise LLMProcessingError(f"QA 结构化失败: {e}")
|
||||
|
||||
async def _step_review_generation(self, llm: LLMService, store_name: str,
|
||||
employee_number: str, qa_result: str,
|
||||
satisfaction: str) -> tuple:
|
||||
"""Step 3: 点评生成 - 生成标准版和精简版点评"""
|
||||
try:
|
||||
template = self._load_prompt("review-generation.txt")
|
||||
|
||||
# 从 QA 结果中提取信息(解析 Q1-Q8 格式)
|
||||
consumption_item = self._extract_qa_answer(qa_result, "Q3") or self._extract_qa_answer(qa_result, "项目")
|
||||
duration = self._extract_qa_answer(qa_result, "Q2") or self._extract_qa_answer(qa_result, "多久")
|
||||
visit_time = self._extract_qa_answer(qa_result, "Q4") or self._extract_qa_answer(qa_result, "时间")
|
||||
discomfort = self._extract_qa_answer(qa_result, "Q5") or self._extract_qa_answer(qa_result, "不舒服")
|
||||
problem_solved = self._extract_qa_answer(qa_result, "Q6") or self._extract_qa_answer(qa_result, "解决")
|
||||
satisfaction_level = Satisfaction(satisfaction).text if satisfaction else ""
|
||||
|
||||
prompt = render_prompt(
|
||||
template,
|
||||
门店名称=store_name,
|
||||
技师编号=employee_number,
|
||||
消费项目=consumption_item or "未提及",
|
||||
到店时长=duration or "未提及",
|
||||
到店时间=visit_time or "未提及",
|
||||
身体不舒服症状=discomfort or "未提及",
|
||||
问题是否解决=problem_solved or "未提及",
|
||||
满意程度=satisfaction_level or "满意",
|
||||
)
|
||||
|
||||
# 将完整的 QA 结果附加到 prompt 中,作为上下文参考
|
||||
full_prompt = prompt + "\n\n以下是客户的完整QA反馈记录,请严格基于这些QA内容生成点评(注意区分【客户】和【技师】的归属,不要张冠李戴):\n" + qa_result
|
||||
|
||||
result = await llm.chat(
|
||||
system_prompt="你是一位专业的点评撰写专家,擅长根据客户反馈撰写真实自然的消费点评。你必须严格基于QA记录中的信息撰写,特别注意区分客户本人和技师的属性(比如来店3年是客户的消费时长,不是技师的工作时长)。",
|
||||
user_message=full_prompt,
|
||||
temperature=0.7,
|
||||
max_tokens=1000,
|
||||
)
|
||||
|
||||
# 解析点评结果
|
||||
review_long, review_short = self._parse_review_result(result)
|
||||
return review_long, review_short
|
||||
|
||||
except PromptTemplateError:
|
||||
logger.warning("点评生成模板不存在,跳过点评生成")
|
||||
return None, None
|
||||
except Exception as e:
|
||||
logger.error(f"点评生成失败: {e}")
|
||||
return None, None
|
||||
|
||||
@staticmethod
|
||||
def _parse_review_result(result: str) -> tuple:
|
||||
"""解析 LLM 返回的点评结果 - 支持多种格式"""
|
||||
import re
|
||||
review_long = None
|
||||
review_short = None
|
||||
|
||||
# 清理 markdown 格式符号
|
||||
cleaned = re.sub(r'^#{1,6}\s*', '', result, flags=re.MULTILINE)
|
||||
cleaned = re.sub(r'^---+\s*$', '', cleaned, flags=re.MULTILINE)
|
||||
|
||||
# 策略1: 【标准版点评】...【精简短评】...
|
||||
long_match = re.search(r"【标准版点评】[::\s]*(.*?)(?=【精简短评】|$)", cleaned, re.DOTALL)
|
||||
short_match = re.search(r"【精简短评】[::\s]*(.*?)$", cleaned, re.DOTALL)
|
||||
|
||||
# 策略2: 标准版点评:...精简短评:...
|
||||
if not long_match:
|
||||
long_match = re.search(r"标准版点评[::\s]*(.*?)(?=精简短评|$)", cleaned, re.DOTALL)
|
||||
if not short_match:
|
||||
short_match = re.search(r"精简短评[::\s]*(.*?)$", cleaned, re.DOTALL)
|
||||
|
||||
# 策略3: 长评:...短评:...
|
||||
if not long_match:
|
||||
long_match = re.search(r"长评[::\s]*(.*?)(?=短评|$)", cleaned, re.DOTALL)
|
||||
if not short_match:
|
||||
short_match = re.search(r"短评[::\s]*(.*?)$", cleaned, re.DOTALL)
|
||||
|
||||
if long_match:
|
||||
review_long = long_match.group(1).strip()
|
||||
if short_match:
|
||||
review_short = short_match.group(1).strip()
|
||||
|
||||
# 如果没有标准格式,整段作为长评
|
||||
if not review_long and not review_short:
|
||||
review_long = result.strip()
|
||||
|
||||
return review_long, review_short
|
||||
|
||||
@staticmethod
|
||||
def _extract_qa_answer(qa_text: str, question_key: str) -> str:
|
||||
"""从 QA 结构化文本中提取指定问题的答案
|
||||
|
||||
支持多种格式:
|
||||
- Q1: xxx A1: xxx
|
||||
- Q1:xxx A1:xxx
|
||||
- 技师工号是多少?xxx => 用关键词匹配
|
||||
"""
|
||||
import re
|
||||
|
||||
if not qa_text:
|
||||
return ""
|
||||
|
||||
lines = qa_text.strip().split('\n')
|
||||
|
||||
# 尝试按 Q编号 + A编号 格式匹配
|
||||
# 先找 question_key 对应的 Q 编号
|
||||
if question_key.startswith('Q'):
|
||||
q_num = question_key[1:]
|
||||
# 匹配 A{n}: 或 A{n}:格式
|
||||
pattern = rf'A{q_num}\s*[::]\s*(.+?)$'
|
||||
for line in lines:
|
||||
match = re.search(pattern, line.strip())
|
||||
if match:
|
||||
answer = match.group(1).strip()
|
||||
if answer and answer != '未提及' and answer != '用户未作答':
|
||||
return answer
|
||||
|
||||
# 关键词匹配模式
|
||||
for line in lines:
|
||||
if question_key in line:
|
||||
# 提取 A: 后面的部分
|
||||
match = re.search(r'A\d*\s*[::]\s*(.+?)$', line.strip())
|
||||
if match:
|
||||
answer = match.group(1).strip()
|
||||
if answer and answer != '未提及' and answer != '用户未作答':
|
||||
return answer
|
||||
|
||||
return ""
|
||||
|
||||
async def save_record(self, record_data: Dict[str, Any]) -> FeedbackRecord:
|
||||
"""保存反馈记录(H5 前端直接调用)
|
||||
|
||||
支持 upsert 逻辑:
|
||||
- 如果传了 session_id 且已有该 session 的记录,则更新(补全 AI 处理结果)
|
||||
- 否则创建新记录
|
||||
"""
|
||||
# 尝试通过 session_id 查找已有记录
|
||||
existing = None
|
||||
session_id = record_data.get("session_id")
|
||||
if session_id:
|
||||
existing = await self.record_repo.get_by_session_id(session_id)
|
||||
|
||||
if existing:
|
||||
# 更新已有记录(仅覆盖非空字段)
|
||||
if record_data.get("raw_asr_text"):
|
||||
existing.raw_asr_text = record_data["raw_asr_text"]
|
||||
if record_data.get("cleaned_text"):
|
||||
existing.cleaned_text = record_data["cleaned_text"]
|
||||
if record_data.get("qa_json"):
|
||||
existing.qa_json = record_data["qa_json"]
|
||||
if record_data.get("review_long"):
|
||||
existing.review_long = record_data["review_long"]
|
||||
if record_data.get("review_short"):
|
||||
existing.review_short = record_data["review_short"]
|
||||
if record_data.get("satisfaction"):
|
||||
existing.satisfaction = record_data["satisfaction"]
|
||||
if record_data.get("customer_name"):
|
||||
existing.customer_name = record_data["customer_name"].strip()
|
||||
if record_data.get("phone_tail"):
|
||||
existing.phone_tail = self._normalize_phone_tail(record_data["phone_tail"])
|
||||
return await self.record_repo.save(existing)
|
||||
else:
|
||||
# 创建新记录
|
||||
record = FeedbackRecord(
|
||||
id=generate_id(),
|
||||
store_id=record_data.get("store_id", ""),
|
||||
session_id=session_id,
|
||||
employee_id=record_data.get("employee_id"),
|
||||
device_mac=record_data.get("device_mac"),
|
||||
raw_asr_text=record_data.get("raw_asr_text"),
|
||||
cleaned_text=record_data.get("cleaned_text"),
|
||||
qa_json=record_data.get("qa_json"),
|
||||
review_long=record_data.get("review_long"),
|
||||
review_short=record_data.get("review_short"),
|
||||
satisfaction=record_data.get("satisfaction"),
|
||||
customer_name=(record_data.get("customer_name") or "").strip() or None,
|
||||
phone_tail=self._normalize_phone_tail(record_data.get("phone_tail")),
|
||||
)
|
||||
return await self.record_repo.save(record)
|
||||
|
||||
async def list_records(self, page: int = 1, page_size: int = 20, **filters) -> dict:
|
||||
"""查询反馈记录"""
|
||||
return await self.record_repo.list_page(page, page_size, **filters)
|
||||
184
main/feedback-backend/app/application/stats_service.py
Normal file
184
main/feedback-backend/app/application/stats_service.py
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
"""统计分析应用服务 - 后台管理统计用例"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.infrastructure.persistence.models import EmployeeModel, FeedbackRecordModel
|
||||
from app.infrastructure.persistence.feedback_repo_impl import FeedbackRecordRepositoryImpl
|
||||
from app.infrastructure.persistence.store_repo_impl import StoreRepositoryImpl
|
||||
from app.infrastructure.persistence.employee_repo_impl import EmployeeRepositoryImpl
|
||||
|
||||
|
||||
class StatsService:
|
||||
"""统计分析应用服务"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.session = session
|
||||
self.record_repo = FeedbackRecordRepositoryImpl(session)
|
||||
self.store_repo = StoreRepositoryImpl(session)
|
||||
self.employee_repo = EmployeeRepositoryImpl(session)
|
||||
|
||||
async def get_overview(self, store_id: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None) -> Dict:
|
||||
"""获取统计概览"""
|
||||
# 满意度分布
|
||||
satisfaction_stats = await self.record_repo.count_by_satisfaction(
|
||||
store_id, start_date, end_date
|
||||
)
|
||||
|
||||
# 总记录数
|
||||
total = sum(satisfaction_stats.values())
|
||||
|
||||
# 满意率
|
||||
positive = satisfaction_stats.get("very_satisfied", 0) + satisfaction_stats.get("satisfied", 0)
|
||||
satisfaction_rate = round(positive / total * 100, 1) if total > 0 else 0
|
||||
|
||||
return {
|
||||
"total_records": total,
|
||||
"satisfaction_distribution": satisfaction_stats,
|
||||
"satisfaction_rate": satisfaction_rate,
|
||||
"very_satisfied": satisfaction_stats.get("very_satisfied", 0),
|
||||
"satisfied": satisfaction_stats.get("satisfied", 0),
|
||||
"unsatisfied": satisfaction_stats.get("unsatisfied", 0),
|
||||
"very_bad": satisfaction_stats.get("very_bad", 0),
|
||||
}
|
||||
|
||||
async def get_daily_stats(self, store_id: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None) -> List[Dict]:
|
||||
"""获取按天统计"""
|
||||
return await self.record_repo.get_daily_stats(store_id, start_date, end_date)
|
||||
|
||||
async def get_employee_kpi(self, store_id: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None) -> List[Dict]:
|
||||
"""按员工统计好/中/差评,用于店长 KPI。"""
|
||||
query = self.session.query(
|
||||
FeedbackRecordModel.employee_id,
|
||||
EmployeeModel.name.label("employee_name"),
|
||||
EmployeeModel.number.label("employee_number"),
|
||||
FeedbackRecordModel.satisfaction,
|
||||
func.count(FeedbackRecordModel.id).label("count"),
|
||||
).outerjoin(EmployeeModel, FeedbackRecordModel.employee_id == EmployeeModel.id)
|
||||
if store_id:
|
||||
query = query.filter(FeedbackRecordModel.store_id == store_id)
|
||||
if start_date:
|
||||
query = query.filter(FeedbackRecordModel.create_date >= start_date)
|
||||
if end_date:
|
||||
query = query.filter(FeedbackRecordModel.create_date <= end_date)
|
||||
rows = query.group_by(
|
||||
FeedbackRecordModel.employee_id,
|
||||
EmployeeModel.name,
|
||||
EmployeeModel.number,
|
||||
FeedbackRecordModel.satisfaction,
|
||||
).all()
|
||||
|
||||
grouped = {}
|
||||
for row in rows:
|
||||
key = row.employee_id or "unknown"
|
||||
item = grouped.setdefault(key, {
|
||||
"employeeId": row.employee_id,
|
||||
"employeeName": row.employee_name or "未绑定员工",
|
||||
"employeeNumber": row.employee_number,
|
||||
"good": 0,
|
||||
"middle": 0,
|
||||
"bad": 0,
|
||||
"verySatisfied": 0,
|
||||
"satisfied": 0,
|
||||
"unsatisfied": 0,
|
||||
"veryBad": 0,
|
||||
"total": 0,
|
||||
"goodRate": 0,
|
||||
})
|
||||
count = row.count or 0
|
||||
sat = row.satisfaction
|
||||
item["total"] += count
|
||||
if sat == "very_satisfied":
|
||||
item["verySatisfied"] += count
|
||||
item["good"] += count
|
||||
elif sat == "satisfied":
|
||||
item["satisfied"] += count
|
||||
item["good"] += count
|
||||
elif sat == "unsatisfied":
|
||||
item["unsatisfied"] += count
|
||||
item["middle"] += count
|
||||
elif sat == "very_bad":
|
||||
item["veryBad"] += count
|
||||
item["bad"] += count
|
||||
result = list(grouped.values())
|
||||
for item in result:
|
||||
item["goodRate"] = round(item["good"] / item["total"] * 100, 1) if item["total"] else 0
|
||||
return sorted(result, key=lambda x: (x["goodRate"], x["good"], -x["bad"]), reverse=True)
|
||||
|
||||
async def get_employee_records(self, employee_id: str, store_id: Optional[str] = None,
|
||||
satisfaction_group: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
page: int = 1, page_size: int = 20) -> Dict:
|
||||
"""查询某员工完整评价列表。"""
|
||||
query = self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.employee_id == employee_id)
|
||||
if store_id:
|
||||
query = query.filter(FeedbackRecordModel.store_id == store_id)
|
||||
if start_date:
|
||||
query = query.filter(FeedbackRecordModel.create_date >= start_date)
|
||||
if end_date:
|
||||
query = query.filter(FeedbackRecordModel.create_date <= end_date)
|
||||
if satisfaction_group == "good":
|
||||
query = query.filter(FeedbackRecordModel.satisfaction.in_(["very_satisfied", "satisfied"]))
|
||||
elif satisfaction_group == "middle":
|
||||
query = query.filter(FeedbackRecordModel.satisfaction == "unsatisfied")
|
||||
elif satisfaction_group == "bad":
|
||||
query = query.filter(FeedbackRecordModel.satisfaction == "very_bad")
|
||||
total = query.count()
|
||||
rows = query.order_by(FeedbackRecordModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {
|
||||
"list": [{
|
||||
"id": r.id,
|
||||
"employeeId": r.employee_id,
|
||||
"storeId": r.store_id,
|
||||
"satisfaction": r.satisfaction,
|
||||
"reviewLong": r.review_long,
|
||||
"reviewShort": r.review_short,
|
||||
"cleanedText": r.cleaned_text,
|
||||
"rawAsrText": r.raw_asr_text,
|
||||
"qaJson": r.qa_json,
|
||||
"memberId": r.member_id,
|
||||
"visitId": r.visit_id,
|
||||
"createDate": str(r.create_date) if r.create_date else None,
|
||||
} for r in rows],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
async def get_single_store_stats(self, store_id: str, start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None) -> List[Dict]:
|
||||
"""获取单门店统计"""
|
||||
store = await self.store_repo.get_by_id(store_id)
|
||||
if not store:
|
||||
return []
|
||||
count = await self.record_repo.count_by_store(store.id, start_date, end_date)
|
||||
satisfaction = await self.record_repo.count_by_satisfaction(store.id, start_date, end_date)
|
||||
total = sum(satisfaction.values())
|
||||
positive = satisfaction.get("very_satisfied", 0) + satisfaction.get("satisfied", 0)
|
||||
rate = round(positive / total * 100, 1) if total > 0 else 0
|
||||
return [{
|
||||
"store_id": store.id,
|
||||
"store_name": store.store_name,
|
||||
"store_code": store.store_code,
|
||||
"total_records": count,
|
||||
"satisfaction_rate": rate,
|
||||
"satisfaction_distribution": satisfaction,
|
||||
}]
|
||||
|
||||
async def get_store_stats(self, start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None) -> List[Dict]:
|
||||
"""获取按门店统计"""
|
||||
stores = await self.store_repo.list_all(status=1)
|
||||
result = []
|
||||
for store in stores:
|
||||
result.extend(await self.get_single_store_stats(store.id, start_date, end_date))
|
||||
return result
|
||||
114
main/feedback-backend/app/application/store_service.py
Normal file
114
main/feedback-backend/app/application/store_service.py
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
"""门店应用服务 - 门店 CRUD 用例"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.domain.store.entity import Store
|
||||
from app.domain.store.value_objects import StoreCode
|
||||
from app.infrastructure.persistence.store_repo_impl import StoreRepositoryImpl
|
||||
from app.shared.exceptions import StoreNotFoundError, ValidationError
|
||||
from app.shared.utils import generate_id, is_valid_store_code
|
||||
|
||||
|
||||
class StoreService:
|
||||
"""门店应用服务"""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self.repo = StoreRepositoryImpl(session)
|
||||
self.session = session
|
||||
|
||||
async def get_by_store_code(self, store_code: str) -> Store:
|
||||
"""根据门店编码获取门店(公开接口用)"""
|
||||
if not is_valid_store_code(store_code):
|
||||
raise ValidationError(f"门店编码格式错误: {store_code},应为6位数字")
|
||||
|
||||
store = await self.repo.get_by_store_code(store_code)
|
||||
if not store:
|
||||
raise StoreNotFoundError(store_code)
|
||||
if not store.is_enabled():
|
||||
raise StoreNotFoundError(store_code)
|
||||
return store
|
||||
|
||||
async def get_by_id(self, store_id: str) -> Store:
|
||||
"""根据 ID 获取门店"""
|
||||
store = await self.repo.get_by_id(store_id)
|
||||
if not store:
|
||||
raise StoreNotFoundError(store_id)
|
||||
return store
|
||||
|
||||
async def list_page(self, page: int = 1, page_size: int = 20,
|
||||
store_name: Optional[str] = None,
|
||||
status: Optional[int] = None) -> dict:
|
||||
"""分页查询门店"""
|
||||
return await self.repo.list_page(page, page_size, store_name, status)
|
||||
|
||||
async def list_all(self, status: Optional[int] = None) -> list:
|
||||
"""获取所有门店"""
|
||||
return await self.repo.list_all(status)
|
||||
|
||||
async def create_store(self, store_code: str, store_name: str,
|
||||
manager: Optional[str] = None,
|
||||
shareholders: Optional[str] = None,
|
||||
agent_id: Optional[str] = None) -> Store:
|
||||
"""创建门店"""
|
||||
# 验证门店编码
|
||||
if not is_valid_store_code(store_code):
|
||||
raise ValidationError(f"门店编码格式错误: {store_code},应为6位数字")
|
||||
|
||||
# 检查编码唯一性
|
||||
if await self.repo.exists_by_store_code(store_code):
|
||||
raise ValidationError(f"门店编码已存在: {store_code}")
|
||||
|
||||
store = Store(
|
||||
id=generate_id(),
|
||||
store_code=store_code,
|
||||
store_name=store_name,
|
||||
manager=manager,
|
||||
shareholders=shareholders,
|
||||
agent_id=agent_id,
|
||||
)
|
||||
result = await self.repo.save(store)
|
||||
logger.info(f"创建门店: code={store_code}, name={store_name}")
|
||||
return result
|
||||
|
||||
async def update_store(self, store_id: str, **kwargs) -> Store:
|
||||
"""更新门店"""
|
||||
store = await self.repo.get_by_id(store_id)
|
||||
if not store:
|
||||
raise StoreNotFoundError(store_id)
|
||||
|
||||
# 如果修改了 store_code,检查唯一性
|
||||
if "store_code" in kwargs and kwargs["store_code"] != store.store_code:
|
||||
if not is_valid_store_code(kwargs["store_code"]):
|
||||
raise ValidationError(f"门店编码格式错误: {kwargs['store_code']}")
|
||||
if await self.repo.exists_by_store_code(kwargs["store_code"], exclude_id=store_id):
|
||||
raise ValidationError(f"门店编码已存在: {kwargs['store_code']}")
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(store, key) and value is not None:
|
||||
setattr(store, key, value)
|
||||
|
||||
result = await self.repo.save(store)
|
||||
logger.info(f"更新门店: id={store_id}")
|
||||
return result
|
||||
|
||||
async def delete_store(self, store_id: str) -> bool:
|
||||
"""删除门店"""
|
||||
store = await self.repo.get_by_id(store_id)
|
||||
if not store:
|
||||
raise StoreNotFoundError(store_id)
|
||||
result = await self.repo.delete(store_id)
|
||||
logger.info(f"删除门店: id={store_id}")
|
||||
return result
|
||||
|
||||
async def bind_agent(self, store_id: str, agent_id: str) -> Store:
|
||||
"""绑定智能体"""
|
||||
store = await self.repo.get_by_id(store_id)
|
||||
if not store:
|
||||
raise StoreNotFoundError(store_id)
|
||||
store.bind_agent(agent_id)
|
||||
result = await self.repo.save(store)
|
||||
logger.info(f"门店绑定智能体: store={store_id}, agent={agent_id}")
|
||||
return result
|
||||
0
main/feedback-backend/app/domain/__init__.py
Normal file
0
main/feedback-backend/app/domain/__init__.py
Normal file
0
main/feedback-backend/app/domain/agent/__init__.py
Normal file
0
main/feedback-backend/app/domain/agent/__init__.py
Normal file
51
main/feedback-backend/app/domain/agent/entity.py
Normal file
51
main/feedback-backend/app/domain/agent/entity.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""智能体配置领域实体"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentConfig:
|
||||
"""智能体配置实体 - 管理对话轮次、提示词、LLM 等可配置项"""
|
||||
id: str
|
||||
agent_name: str
|
||||
agent_id: Optional[str] = None # 对应 xiaozhi-server 的智能体 ID
|
||||
dialogue_rounds: int = 7 # 对话轮次(问几个问题)
|
||||
questions: Optional[List[str]] = None # 问题列表
|
||||
prompts_config: Optional[Dict[str, Any]] = None # 提示词配置
|
||||
llm_config: Optional[Dict[str, Any]] = None # LLM 配置
|
||||
review_config: Optional[Dict[str, Any]] = None # 点评生成规则
|
||||
status: int = 1
|
||||
create_date: Optional[datetime] = None
|
||||
update_date: Optional[datetime] = None
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
return self.status == 1
|
||||
|
||||
def get_questions(self) -> List[str]:
|
||||
"""获取问题列表,如果没有自定义则返回空列表"""
|
||||
return self.questions or []
|
||||
|
||||
def get_prompt_path(self, prompt_type: str) -> Optional[str]:
|
||||
"""获取指定类型的提示词模板路径"""
|
||||
if self.prompts_config and prompt_type in self.prompts_config:
|
||||
return self.prompts_config[prompt_type]
|
||||
return None
|
||||
|
||||
def get_llm_provider(self) -> Optional[str]:
|
||||
"""获取 LLM 提供商"""
|
||||
if self.llm_config:
|
||||
return self.llm_config.get("provider")
|
||||
return None
|
||||
|
||||
def get_review_length(self, review_type: str) -> dict:
|
||||
"""获取点评长度限制"""
|
||||
if self.review_config and review_type in self.review_config:
|
||||
return self.review_config[review_type]
|
||||
# 默认长度
|
||||
defaults = {
|
||||
"long": {"min": 80, "max": 150},
|
||||
"short": {"min": 30, "max": 60},
|
||||
}
|
||||
return defaults.get(review_type, {})
|
||||
34
main/feedback-backend/app/domain/agent/repository.py
Normal file
34
main/feedback-backend/app/domain/agent/repository.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
"""智能体配置仓储接口"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Optional
|
||||
|
||||
from .entity import AgentConfig
|
||||
|
||||
|
||||
class IAgentConfigRepository(ABC):
|
||||
"""智能体配置仓储接口"""
|
||||
|
||||
@abstractmethod
|
||||
async def get_by_id(self, config_id: str) -> Optional[AgentConfig]:
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def get_by_agent_id(self, agent_id: str) -> Optional[AgentConfig]:
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def list_all(self, status: Optional[int] = None) -> List[AgentConfig]:
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def list_page(self, page: int = 1, page_size: int = 20) -> dict:
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def save(self, config: AgentConfig) -> AgentConfig:
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def delete(self, config_id: str) -> bool:
|
||||
...
|
||||
33
main/feedback-backend/app/domain/agent/value_objects.py
Normal file
33
main/feedback-backend/app/domain/agent/value_objects.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""智能体配置值对象"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DialogueConfig:
|
||||
"""对话配置值对象"""
|
||||
rounds: int = 7
|
||||
questions: Optional[tuple] = None # 使用 tuple 保证不可变
|
||||
|
||||
def __post_init__(self):
|
||||
if self.rounds < 1 or self.rounds > 20:
|
||||
raise ValueError(f"对话轮次必须在 1-20 之间,当前值: {self.rounds}")
|
||||
|
||||
def get_questions(self) -> List[str]:
|
||||
"""获取前 N 个问题"""
|
||||
if not self.questions:
|
||||
return []
|
||||
return list(self.questions[:self.rounds])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LLMProviderConfig:
|
||||
"""LLM 提供商配置值对象"""
|
||||
provider: str
|
||||
api_key: str
|
||||
base_url: Optional[str] = None
|
||||
model: Optional[str] = None
|
||||
|
||||
def is_valid(self) -> bool:
|
||||
return bool(self.provider and self.api_key)
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue