feat: channels/audit UI unify, apply flow hardening, bump v1.1.12
This commit is contained in:
2
Makefile
2
Makefile
@@ -1,5 +1,5 @@
|
||||
APP_NAME := xiaji-go
|
||||
VERSION := 1.1.0
|
||||
VERSION := 1.1.12
|
||||
GIT_COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
|
||||
BUILD_TIME := $(shell date -u '+%Y-%m-%dT%H:%M:%SZ')
|
||||
LDFLAGS := -X xiaji-go/version.Version=$(VERSION) \
|
||||
|
||||
60
cmd/main.go
60
cmd/main.go
@@ -11,18 +11,20 @@ import (
|
||||
|
||||
"xiaji-go/config"
|
||||
"xiaji-go/internal/bot"
|
||||
"xiaji-go/internal/channel"
|
||||
"xiaji-go/internal/feishu"
|
||||
"xiaji-go/internal/qq"
|
||||
"xiaji-go/internal/service"
|
||||
"xiaji-go/internal/web"
|
||||
"xiaji-go/models"
|
||||
"xiaji-go/version"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 版本信息
|
||||
if len(os.Args) > 1 && (os.Args[1] == "-v" || os.Args[1] == "--version" || os.Args[1] == "version") {
|
||||
fmt.Println(version.Info())
|
||||
return
|
||||
@@ -30,7 +32,6 @@ func main() {
|
||||
|
||||
log.Printf("🦞 %s", version.Info())
|
||||
|
||||
// 1. 加载配置
|
||||
cfgPath := "config.yaml"
|
||||
if len(os.Args) > 1 {
|
||||
cfgPath = os.Args[1]
|
||||
@@ -41,28 +42,32 @@ func main() {
|
||||
log.Fatalf("无法加载配置: %v", err)
|
||||
}
|
||||
|
||||
// 2. 初始化数据库
|
||||
db, err := gorm.Open(sqlite.Open(cfg.Database.Path), &gorm.Config{})
|
||||
if err != nil {
|
||||
log.Fatalf("无法连接数据库: %v", err)
|
||||
}
|
||||
|
||||
// 3. 自动迁移表结构
|
||||
if err := models.Migrate(db); err != nil {
|
||||
log.Fatalf("数据库迁移失败: %v", err)
|
||||
}
|
||||
|
||||
// 4. 初始化核心服务
|
||||
if err := channel.InitSecretCipher(cfg.Server.Key); err != nil {
|
||||
log.Fatalf("初始化渠道密钥加密失败: %v", err)
|
||||
}
|
||||
|
||||
// DB 渠道配置覆盖 YAML 配置
|
||||
if err := channel.ApplyChannelConfig(db, cfg); err != nil {
|
||||
log.Printf("⚠️ 渠道配置加载失败,继续使用 YAML: %v", err)
|
||||
}
|
||||
|
||||
finance := service.NewFinanceService(db)
|
||||
defer finance.Close()
|
||||
|
||||
// 全局 context,用于优雅退出
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// 5. 启动 Telegram Bot
|
||||
if cfg.Telegram.Enabled {
|
||||
tgBot, err := bot.NewTGBot(cfg.Telegram.Token, finance)
|
||||
tgBot, err := bot.NewTGBot(db, cfg.Telegram.Token, finance)
|
||||
if err != nil {
|
||||
log.Printf("⚠️ TG Bot 启动失败: %v", err)
|
||||
} else {
|
||||
@@ -70,29 +75,48 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 启动 QQ Bot
|
||||
if cfg.QQBot.Enabled {
|
||||
qqBot := qq.NewQQBot(cfg.QQBot.AppID, cfg.QQBot.Secret, finance)
|
||||
qqBot := qq.NewQQBot(db, cfg.QQBot.AppID, cfg.QQBot.Secret, finance)
|
||||
go qqBot.Start(ctx)
|
||||
}
|
||||
|
||||
// 7. 启动 Web 后台
|
||||
webServer := web.NewWebServer(db, cfg.Server.Port, cfg.Admin.Username, cfg.Admin.Password)
|
||||
go webServer.Start()
|
||||
engine := gin.New()
|
||||
engine.Use(gin.Recovery())
|
||||
engine.Use(gin.Logger())
|
||||
|
||||
reloadFn := func() (string, error) {
|
||||
if err := channel.ApplyChannelConfig(db, cfg); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("reload ok: tg=%v qq=%v feishu=%v", cfg.Telegram.Enabled, cfg.QQBot.Enabled, cfg.Feishu.Enabled), nil
|
||||
}
|
||||
|
||||
webServer := web.NewWebServer(db, finance, cfg.Server.Port, cfg.Admin.Username, cfg.Admin.Password, cfg.Server.Key, reloadFn)
|
||||
webServer.RegisterRoutes(engine)
|
||||
|
||||
if cfg.Feishu.Enabled {
|
||||
fsBot := feishu.NewBot(db, finance, cfg.Feishu.AppID, cfg.Feishu.AppSecret, cfg.Feishu.VerificationToken, cfg.Feishu.EncryptKey)
|
||||
fsBot.RegisterRoutes(engine)
|
||||
go fsBot.Start(ctx)
|
||||
}
|
||||
|
||||
go func() {
|
||||
logAddr := fmt.Sprintf(":%d", cfg.Server.Port)
|
||||
log.Printf("🌐 Web后台运行在 http://127.0.0.1%s", logAddr)
|
||||
if err := engine.Run(logAddr); err != nil {
|
||||
log.Printf("❌ Web服务启动失败: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 8. 优雅关闭
|
||||
log.Println("🦞 Xiaji-Go 已全面启动")
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-sig
|
||||
|
||||
log.Println("⏳ 正在关闭服务...")
|
||||
cancel() // 通知所有 goroutine 停止
|
||||
|
||||
// 等待一点时间让 goroutine 退出
|
||||
cancel()
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// 关闭数据库连接
|
||||
sqlDB, err := db.DB()
|
||||
if err == nil {
|
||||
sqlDB.Close()
|
||||
|
||||
@@ -17,3 +17,10 @@ qqbot:
|
||||
enabled: false
|
||||
appid: "YOUR_QQ_BOT_APPID"
|
||||
secret: "YOUR_QQ_BOT_SECRET"
|
||||
|
||||
feishu:
|
||||
enabled: false
|
||||
app_id: "YOUR_FEISHU_APP_ID"
|
||||
app_secret: "YOUR_FEISHU_APP_SECRET"
|
||||
verification_token: "YOUR_FEISHU_VERIFICATION_TOKEN"
|
||||
encrypt_key: "YOUR_FEISHU_ENCRYPT_KEY"
|
||||
|
||||
@@ -24,6 +24,13 @@ type Config struct {
|
||||
AppID string `yaml:"appid"`
|
||||
Secret string `yaml:"secret"`
|
||||
} `yaml:"qqbot"`
|
||||
Feishu struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
AppID string `yaml:"app_id"`
|
||||
AppSecret string `yaml:"app_secret"`
|
||||
VerificationToken string `yaml:"verification_token"`
|
||||
EncryptKey string `yaml:"encrypt_key"`
|
||||
} `yaml:"feishu"`
|
||||
Admin struct {
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
@@ -71,5 +78,10 @@ func (c *Config) Validate() error {
|
||||
return fmt.Errorf("qqbot 已启用但 appid 或 secret 为空")
|
||||
}
|
||||
}
|
||||
if c.Feishu.Enabled {
|
||||
if c.Feishu.AppID == "" || c.Feishu.AppSecret == "" {
|
||||
return fmt.Errorf("feishu 已启用但 app_id 或 app_secret 为空")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
72
docs/multi-platform-channel-deploy.md
Normal file
72
docs/multi-platform-channel-deploy.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# Xiaji-Go 多平台渠道配置与回调部署说明
|
||||
|
||||
## 已支持平台
|
||||
- 官方 QQ Bot(qqbot_official)
|
||||
- Telegram Bot(telegram)
|
||||
- 飞书 Bot(feishu)
|
||||
|
||||
## 配置优先级
|
||||
- 启动时:`数据库 channel_configs` > `config.yaml`
|
||||
- 建议使用后台页面维护渠道配置:`/channels`
|
||||
|
||||
## 后台入口
|
||||
- 渠道配置页:`/channels`
|
||||
- 渠道 API:
|
||||
- `GET /api/v1/admin/channels`
|
||||
- `PATCH /api/v1/admin/channels/:platform`
|
||||
- `POST /api/v1/admin/channels/:platform/test`
|
||||
- 审计查询:`GET /api/v1/admin/audit`
|
||||
|
||||
## 回调地址
|
||||
- 飞书 webhook: `POST /webhook/feishu`
|
||||
|
||||
### 飞书事件订阅配置
|
||||
1. 在飞书开发者后台启用事件订阅
|
||||
2. 请求网址填:`https://<你的域名>/webhook/feishu`
|
||||
3. 订阅事件:`im.message.receive_v1`
|
||||
4. 将 `verification_token`、`app_id`、`app_secret` 写入渠道 secrets JSON
|
||||
|
||||
## 渠道 secrets JSON 示例
|
||||
|
||||
### telegram
|
||||
```json
|
||||
{
|
||||
"token": "123456:ABCDEF"
|
||||
}
|
||||
```
|
||||
|
||||
### qqbot_official
|
||||
```json
|
||||
{
|
||||
"appid": "102857798",
|
||||
"secret": "xxxxxx"
|
||||
}
|
||||
```
|
||||
|
||||
### feishu
|
||||
```json
|
||||
{
|
||||
"app_id": "cli_xxx",
|
||||
"app_secret": "xxx",
|
||||
"verification_token": "xxx",
|
||||
"encrypt_key": "optional"
|
||||
}
|
||||
```
|
||||
|
||||
## 连接测试说明
|
||||
- Telegram:调用 `getMe`
|
||||
- QQ:调用 `getAppAccessToken`
|
||||
- 飞书:调用 `tenant_access_token/internal`
|
||||
|
||||
测试成功会把渠道状态写成 `ok`,失败写成 `error`。
|
||||
|
||||
## 幂等去重
|
||||
- 三平台入站统一落 `message_dedup`,避免重复处理:
|
||||
- telegram: `tg:<update_id>`
|
||||
- qqbot_official: `qq:<type>:<message_id>`
|
||||
- feishu: `event_id`(回退 message_id)
|
||||
|
||||
## 运行建议
|
||||
- 对公网暴露前请加 HTTPS(飞书回调必需)
|
||||
- 建议将管理后台放在内网或反代鉴权后访问
|
||||
- 定期审计 `audit_logs` 里渠道配置修改记录
|
||||
@@ -9,8 +9,10 @@ import (
|
||||
|
||||
xchart "xiaji-go/internal/chart"
|
||||
"xiaji-go/internal/service"
|
||||
"xiaji-go/models"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DefaultUserID 统一用户ID,使所有平台共享同一份账本
|
||||
@@ -19,14 +21,15 @@ const DefaultUserID int64 = 1
|
||||
type TGBot struct {
|
||||
api *tgbotapi.BotAPI
|
||||
finance *service.FinanceService
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTGBot(token string, finance *service.FinanceService) (*TGBot, error) {
|
||||
func NewTGBot(db *gorm.DB, token string, finance *service.FinanceService) (*TGBot, error) {
|
||||
bot, err := tgbotapi.NewBotAPI(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &TGBot{api: bot, finance: finance}, nil
|
||||
return &TGBot{api: bot, finance: finance, db: db}, nil
|
||||
}
|
||||
|
||||
func (b *TGBot) Start(ctx context.Context) {
|
||||
@@ -49,11 +52,29 @@ func (b *TGBot) Start(ctx context.Context) {
|
||||
if update.Message == nil || update.Message.Text == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
eventID := fmt.Sprintf("tg:%d", update.UpdateID)
|
||||
if b.isDuplicate(eventID) {
|
||||
continue
|
||||
}
|
||||
log.Printf("📩 inbound platform=telegram event=%s chat=%d user=%d text=%q", eventID, update.Message.Chat.ID, update.Message.From.ID, strings.TrimSpace(update.Message.Text))
|
||||
b.handleMessage(update.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *TGBot) isDuplicate(eventID string) bool {
|
||||
if b.db == nil || strings.TrimSpace(eventID) == "" {
|
||||
return false
|
||||
}
|
||||
var existed models.MessageDedup
|
||||
if err := b.db.Where("platform = ? AND event_id = ?", "telegram", eventID).First(&existed).Error; err == nil {
|
||||
return true
|
||||
}
|
||||
_ = b.db.Create(&models.MessageDedup{Platform: "telegram", EventID: eventID, ProcessedAt: time.Now()}).Error
|
||||
return false
|
||||
}
|
||||
|
||||
func (b *TGBot) handleMessage(msg *tgbotapi.Message) {
|
||||
text := msg.Text
|
||||
chatID := msg.Chat.ID
|
||||
@@ -113,7 +134,6 @@ func (b *TGBot) handleMessage(msg *tgbotapi.Message) {
|
||||
reply = "❓ 未知命令,输入 /help 查看帮助"
|
||||
|
||||
default:
|
||||
// 记账逻辑
|
||||
amount, category, err := b.finance.AddTransaction(DefaultUserID, text)
|
||||
if err != nil {
|
||||
reply = "❌ 记账失败,请稍后重试"
|
||||
@@ -132,7 +152,6 @@ func (b *TGBot) handleMessage(msg *tgbotapi.Message) {
|
||||
}
|
||||
}
|
||||
|
||||
// sendMonthlyChart 发送本月分类饼图
|
||||
func (b *TGBot) sendMonthlyChart(chatID int64) {
|
||||
now := time.Now()
|
||||
dateFrom := now.Format("2006-01") + "-01"
|
||||
@@ -154,7 +173,6 @@ func (b *TGBot) sendMonthlyChart(chatID int64) {
|
||||
return
|
||||
}
|
||||
|
||||
// 计算总计文字
|
||||
var total int64
|
||||
var totalCount int
|
||||
for _, s := range stats {
|
||||
@@ -170,7 +188,6 @@ func (b *TGBot) sendMonthlyChart(chatID int64) {
|
||||
}
|
||||
}
|
||||
|
||||
// sendWeeklyChart 发送近7天每日消费柱状图
|
||||
func (b *TGBot) sendWeeklyChart(chatID int64) {
|
||||
now := time.Now()
|
||||
dateFrom := now.AddDate(0, 0, -6).Format("2006-01-02")
|
||||
@@ -192,7 +209,6 @@ func (b *TGBot) sendWeeklyChart(chatID int64) {
|
||||
return
|
||||
}
|
||||
|
||||
// 总计
|
||||
var total int64
|
||||
var totalCount int
|
||||
for _, s := range stats {
|
||||
|
||||
394
internal/channel/channel.go
Normal file
394
internal/channel/channel.go
Normal file
@@ -0,0 +1,394 @@
|
||||
package channel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xiaji-go/config"
|
||||
"xiaji-go/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UnifiedMessage struct {
|
||||
Platform string `json:"platform"`
|
||||
EventID string `json:"event_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
var secretCipher *cipherContext
|
||||
|
||||
type cipherContext struct {
|
||||
aead cipher.AEAD
|
||||
}
|
||||
|
||||
func InitSecretCipher(key string) error {
|
||||
k := deriveKey32(key)
|
||||
block, err := aes.NewCipher(k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secretCipher = &cipherContext{aead: aead}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deriveKey32(s string) []byte {
|
||||
b := []byte(s)
|
||||
out := make([]byte, 32)
|
||||
if len(b) >= 32 {
|
||||
copy(out, b[:32])
|
||||
return out
|
||||
}
|
||||
copy(out, b)
|
||||
for i := len(b); i < 32; i++ {
|
||||
out[i] = byte((i * 131) % 251)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func encryptString(plain string) (string, error) {
|
||||
if secretCipher == nil {
|
||||
return plain, errors.New("cipher not initialized")
|
||||
}
|
||||
nonce := make([]byte, secretCipher.aead.NonceSize())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ciphertext := secretCipher.aead.Seal(nil, nonce, []byte(plain), nil)
|
||||
buf := append(nonce, ciphertext...)
|
||||
return "enc:v1:" + base64.StdEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func decryptString(raw string) (string, error) {
|
||||
if !strings.HasPrefix(raw, "enc:v1:") {
|
||||
return raw, nil
|
||||
}
|
||||
if secretCipher == nil {
|
||||
return "", errors.New("cipher not initialized")
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(raw, "enc:v1:"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ns := secretCipher.aead.NonceSize()
|
||||
if len(data) <= ns {
|
||||
return "", errors.New("invalid ciphertext")
|
||||
}
|
||||
nonce := data[:ns]
|
||||
ct := data[ns:]
|
||||
pt, err := secretCipher.aead.Open(nil, nonce, ct, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(pt), nil
|
||||
}
|
||||
|
||||
func maybeDecrypt(raw string) string {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return raw
|
||||
}
|
||||
pt, err := decryptString(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return pt
|
||||
}
|
||||
|
||||
func MaybeDecryptPublic(raw string) string {
|
||||
return maybeDecrypt(raw)
|
||||
}
|
||||
|
||||
func EncryptSecretJSON(raw string) string {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return raw
|
||||
}
|
||||
if strings.HasPrefix(raw, "enc:v1:") {
|
||||
return raw
|
||||
}
|
||||
if secretCipher == nil {
|
||||
return raw
|
||||
}
|
||||
enc, err := encryptString(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return enc
|
||||
}
|
||||
|
||||
type telegramSecret struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
type qqSecret struct {
|
||||
AppID string `json:"appid"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
type feishuSecret struct {
|
||||
AppID string `json:"app_id"`
|
||||
AppSecret string `json:"app_secret"`
|
||||
VerificationToken string `json:"verification_token"`
|
||||
EncryptKey string `json:"encrypt_key"`
|
||||
}
|
||||
|
||||
func parseJSON(raw string, out any) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), out)
|
||||
}
|
||||
|
||||
// ApplyChannelConfig 从数据库渠道配置覆盖运行时配置(优先级:DB > YAML)
|
||||
func ApplyChannelConfig(db *gorm.DB, cfg *config.Config) error {
|
||||
var rows []models.ChannelConfig
|
||||
if err := db.Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
switch row.Platform {
|
||||
case "telegram":
|
||||
sec := telegramSecret{}
|
||||
parseJSON(maybeDecrypt(row.SecretJSON), &sec)
|
||||
cfg.Telegram.Enabled = row.Enabled
|
||||
if strings.TrimSpace(sec.Token) != "" {
|
||||
cfg.Telegram.Token = strings.TrimSpace(sec.Token)
|
||||
}
|
||||
case "qqbot_official":
|
||||
sec := qqSecret{}
|
||||
parseJSON(maybeDecrypt(row.SecretJSON), &sec)
|
||||
cfg.QQBot.Enabled = row.Enabled
|
||||
if strings.TrimSpace(sec.AppID) != "" {
|
||||
cfg.QQBot.AppID = strings.TrimSpace(sec.AppID)
|
||||
}
|
||||
if strings.TrimSpace(sec.Secret) != "" {
|
||||
cfg.QQBot.Secret = strings.TrimSpace(sec.Secret)
|
||||
}
|
||||
case "feishu":
|
||||
sec := feishuSecret{}
|
||||
parseJSON(maybeDecrypt(row.SecretJSON), &sec)
|
||||
cfg.Feishu.Enabled = row.Enabled
|
||||
if strings.TrimSpace(sec.AppID) != "" {
|
||||
cfg.Feishu.AppID = strings.TrimSpace(sec.AppID)
|
||||
}
|
||||
if strings.TrimSpace(sec.AppSecret) != "" {
|
||||
cfg.Feishu.AppSecret = strings.TrimSpace(sec.AppSecret)
|
||||
}
|
||||
if strings.TrimSpace(sec.VerificationToken) != "" {
|
||||
cfg.Feishu.VerificationToken = strings.TrimSpace(sec.VerificationToken)
|
||||
}
|
||||
if strings.TrimSpace(sec.EncryptKey) != "" {
|
||||
cfg.Feishu.EncryptKey = strings.TrimSpace(sec.EncryptKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func httpClient() *http.Client {
|
||||
return &http.Client{Timeout: 8 * time.Second}
|
||||
}
|
||||
|
||||
func TestChannelConnectivity(ctx context.Context, row models.ChannelConfig) (status, detail string) {
|
||||
if !row.Enabled {
|
||||
return "disabled", "渠道未启用"
|
||||
}
|
||||
switch row.Platform {
|
||||
case "telegram":
|
||||
sec := telegramSecret{}
|
||||
parseJSON(maybeDecrypt(row.SecretJSON), &sec)
|
||||
if strings.TrimSpace(sec.Token) == "" {
|
||||
return "error", "telegram token 为空"
|
||||
}
|
||||
url := fmt.Sprintf("https://api.telegram.org/bot%s/getMe", strings.TrimSpace(sec.Token))
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return "error", err.Error()
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode != 200 || !strings.Contains(string(body), `"ok":true`) {
|
||||
return "error", fmt.Sprintf("telegram getMe失败: http=%d", resp.StatusCode)
|
||||
}
|
||||
return "ok", "telegram getMe 成功"
|
||||
|
||||
case "qqbot_official":
|
||||
sec := qqSecret{}
|
||||
parseJSON(maybeDecrypt(row.SecretJSON), &sec)
|
||||
if strings.TrimSpace(sec.AppID) == "" || strings.TrimSpace(sec.Secret) == "" {
|
||||
return "error", "qq appid/secret 为空"
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"appId": strings.TrimSpace(sec.AppID), "clientSecret": strings.TrimSpace(sec.Secret)})
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://bots.qq.com/app/getAppAccessToken", bytes.NewReader(payload))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return "error", err.Error()
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode != 200 || !strings.Contains(string(body), "access_token") {
|
||||
return "error", fmt.Sprintf("qq access token 获取失败: http=%d", resp.StatusCode)
|
||||
}
|
||||
return "ok", "qq access token 获取成功"
|
||||
|
||||
case "feishu":
|
||||
sec := feishuSecret{}
|
||||
parseJSON(maybeDecrypt(row.SecretJSON), &sec)
|
||||
if strings.TrimSpace(sec.AppID) == "" || strings.TrimSpace(sec.AppSecret) == "" {
|
||||
return "error", "feishu app_id/app_secret 为空"
|
||||
}
|
||||
tk, err := GetFeishuTenantToken(ctx, strings.TrimSpace(sec.AppID), strings.TrimSpace(sec.AppSecret))
|
||||
if err != nil || strings.TrimSpace(tk) == "" {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("token 为空")
|
||||
}
|
||||
return "error", err.Error()
|
||||
}
|
||||
return "ok", "feishu tenant_access_token 获取成功"
|
||||
default:
|
||||
return "error", "未知平台"
|
||||
}
|
||||
}
|
||||
|
||||
func ParseFeishuInbound(body []byte, verificationToken string) (*UnifiedMessage, string, error) {
|
||||
// url_verification
|
||||
var verifyReq struct {
|
||||
Type string `json:"type"`
|
||||
Challenge string `json:"challenge"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &verifyReq); err == nil && verifyReq.Type == "url_verification" {
|
||||
if strings.TrimSpace(verificationToken) != "" && verifyReq.Token != verificationToken {
|
||||
return nil, "", fmt.Errorf("verification token mismatch")
|
||||
}
|
||||
return nil, verifyReq.Challenge, nil
|
||||
}
|
||||
|
||||
var event struct {
|
||||
Header struct {
|
||||
EventID string `json:"event_id"`
|
||||
EventType string `json:"event_type"`
|
||||
} `json:"header"`
|
||||
Event struct {
|
||||
Sender struct {
|
||||
SenderID struct {
|
||||
OpenID string `json:"open_id"`
|
||||
} `json:"sender_id"`
|
||||
} `json:"sender"`
|
||||
Message struct {
|
||||
MessageID string `json:"message_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"event"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &event); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if event.Header.EventType != "im.message.receive_v1" {
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
eventID := strings.TrimSpace(event.Header.EventID)
|
||||
if eventID == "" {
|
||||
eventID = strings.TrimSpace(event.Event.Message.MessageID)
|
||||
}
|
||||
if eventID == "" {
|
||||
return nil, "", fmt.Errorf("missing event id")
|
||||
}
|
||||
|
||||
var content struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(event.Event.Message.Content), &content)
|
||||
text := strings.TrimSpace(content.Text)
|
||||
if text == "" {
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
return &UnifiedMessage{
|
||||
Platform: "feishu",
|
||||
EventID: eventID,
|
||||
ChatID: strings.TrimSpace(event.Event.Message.ChatID),
|
||||
UserID: strings.TrimSpace(event.Event.Sender.SenderID.OpenID),
|
||||
Text: text,
|
||||
}, "", nil
|
||||
}
|
||||
|
||||
func GetFeishuTenantToken(ctx context.Context, appID, appSecret string) (string, error) {
|
||||
payload, _ := json.Marshal(map[string]string{"app_id": appID, "app_secret": appSecret})
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", bytes.NewReader(payload))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8192))
|
||||
if resp.StatusCode != 200 {
|
||||
return "", fmt.Errorf("http=%d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var out struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
TenantAccessToken string `json:"tenant_access_token"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if out.Code != 0 || strings.TrimSpace(out.TenantAccessToken) == "" {
|
||||
if out.Msg == "" {
|
||||
out.Msg = "获取token失败"
|
||||
}
|
||||
return "", fmt.Errorf(out.Msg)
|
||||
}
|
||||
return out.TenantAccessToken, nil
|
||||
}
|
||||
|
||||
func SendFeishuText(ctx context.Context, tenantToken, receiveID, text string) error {
|
||||
contentBytes, _ := json.Marshal(map[string]string{"text": text})
|
||||
payload, _ := json.Marshal(map[string]string{
|
||||
"receive_id": receiveID,
|
||||
"msg_type": "text",
|
||||
"content": string(contentBytes),
|
||||
})
|
||||
url := "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id"
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+tenantToken)
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8192))
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("http=%d", resp.StatusCode)
|
||||
}
|
||||
if !strings.Contains(string(body), `"code":0`) {
|
||||
return fmt.Errorf("feishu send failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
130
internal/feishu/feishu.go
Normal file
130
internal/feishu/feishu.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package feishu
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xiaji-go/internal/channel"
|
||||
"xiaji-go/internal/service"
|
||||
"xiaji-go/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DefaultUserID 统一用户ID,使所有平台共享同一份账本
|
||||
const DefaultUserID int64 = 1
|
||||
|
||||
type Bot struct {
|
||||
db *gorm.DB
|
||||
finance *service.FinanceService
|
||||
appID string
|
||||
appSecret string
|
||||
verificationToken string
|
||||
encryptKey string
|
||||
}
|
||||
|
||||
func NewBot(db *gorm.DB, finance *service.FinanceService, appID, appSecret, verificationToken, encryptKey string) *Bot {
|
||||
return &Bot{
|
||||
db: db,
|
||||
finance: finance,
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
verificationToken: verificationToken,
|
||||
encryptKey: encryptKey,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) Start(ctx context.Context) {
|
||||
log.Printf("🚀 Feishu Bot 已启用 app_id=%s", maskID(b.appID))
|
||||
<-ctx.Done()
|
||||
log.Printf("⏳ Feishu Bot 已停止")
|
||||
}
|
||||
|
||||
func (b *Bot) RegisterRoutes(r *gin.Engine) {
|
||||
r.POST("/webhook/feishu", b.handleWebhook)
|
||||
}
|
||||
|
||||
func (b *Bot) handleWebhook(c *gin.Context) {
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
||||
return
|
||||
}
|
||||
|
||||
// 统一走 channel 包解析,便于后续扩展验签/解密
|
||||
msg, verifyChallenge, err := channel.ParseFeishuInbound(body, b.verificationToken)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if verifyChallenge != "" {
|
||||
c.JSON(http.StatusOK, gin.H{"challenge": verifyChallenge})
|
||||
return
|
||||
}
|
||||
if msg == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0})
|
||||
return
|
||||
}
|
||||
|
||||
// 幂等去重
|
||||
var existed models.MessageDedup
|
||||
if err := b.db.Where("platform = ? AND event_id = ?", "feishu", msg.EventID).First(&existed).Error; err == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0})
|
||||
return
|
||||
}
|
||||
_ = b.db.Create(&models.MessageDedup{Platform: "feishu", EventID: msg.EventID, ProcessedAt: time.Now()}).Error
|
||||
|
||||
reply := b.handleText(msg.Text)
|
||||
if reply != "" && msg.UserID != "" {
|
||||
tk, err := channel.GetFeishuTenantToken(c.Request.Context(), b.appID, b.appSecret)
|
||||
if err == nil {
|
||||
_ = channel.SendFeishuText(c.Request.Context(), tk, msg.UserID, reply)
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0})
|
||||
}
|
||||
|
||||
func (b *Bot) handleText(text string) string {
|
||||
trim := strings.TrimSpace(text)
|
||||
switch trim {
|
||||
case "帮助", "help", "/help", "菜单", "功能", "/start":
|
||||
return "🦞 虾记记账\n\n直接发送消费描述即可记账:\n• 午饭 25元\n• 打车 ¥30\n\n📋 命令:记录/查看、今日/今天、统计"
|
||||
case "查看", "记录", "列表", "最近":
|
||||
items, err := b.finance.GetTransactions(DefaultUserID, 10)
|
||||
if err != nil {
|
||||
return "❌ 查询失败"
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return "📭 暂无记录"
|
||||
}
|
||||
var sb strings.Builder
|
||||
sb.WriteString("📋 最近记录:\n\n")
|
||||
for _, item := range items {
|
||||
sb.WriteString(fmt.Sprintf("%s %s %.2f元\n", item.Date, item.Category, item.AmountYuan()))
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
amount, category, err := b.finance.AddTransaction(DefaultUserID, trim)
|
||||
if err != nil {
|
||||
return "❌ 记账失败,请稍后重试"
|
||||
}
|
||||
if amount == 0 {
|
||||
return "📍 没看到金额,这笔花了多少钱?"
|
||||
}
|
||||
return fmt.Sprintf("✅ 已记入【%s】:%.2f元\n📝 备注:%s", category, float64(amount)/100.0, trim)
|
||||
}
|
||||
|
||||
func maskID(s string) string {
|
||||
if len(s) <= 6 {
|
||||
return "***"
|
||||
}
|
||||
return s[:3] + "***" + s[len(s)-3:]
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"xiaji-go/internal/service"
|
||||
"xiaji-go/models"
|
||||
|
||||
"github.com/tencent-connect/botgo"
|
||||
"github.com/tencent-connect/botgo/dto"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"github.com/tencent-connect/botgo/event"
|
||||
"github.com/tencent-connect/botgo/openapi"
|
||||
"github.com/tencent-connect/botgo/token"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DefaultUserID 统一用户ID,使所有平台共享同一份账本
|
||||
@@ -24,10 +26,12 @@ type QQBot struct {
|
||||
api openapi.OpenAPI
|
||||
finance *service.FinanceService
|
||||
credentials *token.QQBotCredentials
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewQQBot(appID string, secret string, finance *service.FinanceService) *QQBot {
|
||||
func NewQQBot(db *gorm.DB, appID string, secret string, finance *service.FinanceService) *QQBot {
|
||||
return &QQBot{
|
||||
db: db,
|
||||
finance: finance,
|
||||
credentials: &token.QQBotCredentials{
|
||||
AppID: appID,
|
||||
@@ -37,42 +41,35 @@ func NewQQBot(appID string, secret string, finance *service.FinanceService) *QQB
|
||||
}
|
||||
|
||||
func (b *QQBot) Start(ctx context.Context) {
|
||||
// 创建 token source 并启动自动刷新
|
||||
tokenSource := token.NewQQBotTokenSource(b.credentials)
|
||||
if err := token.StartRefreshAccessToken(ctx, tokenSource); err != nil {
|
||||
log.Printf("❌ QQ Bot Token 刷新失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 初始化 OpenAPI
|
||||
b.api = botgo.NewOpenAPI(b.credentials.AppID, tokenSource).WithTimeout(5 * time.Second)
|
||||
|
||||
// 注册事件处理器
|
||||
_ = event.RegisterHandlers(
|
||||
b.groupATMessageHandler(),
|
||||
b.c2cMessageHandler(),
|
||||
b.channelATMessageHandler(),
|
||||
)
|
||||
|
||||
// 获取 WebSocket 接入信息
|
||||
wsInfo, err := b.api.WS(ctx, nil, "")
|
||||
if err != nil {
|
||||
log.Printf("❌ QQ Bot 获取 WS 信息失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置 intents: 群聊和C2C (1<<25) + 公域消息 (1<<30)
|
||||
intent := dto.Intent(1<<25 | 1<<30)
|
||||
|
||||
log.Printf("🚀 QQ Bot 已启动 (WebSocket, shards=%d)", wsInfo.Shards)
|
||||
|
||||
// 启动 session manager (阻塞)
|
||||
if err := botgo.NewSessionManager().Start(wsInfo, tokenSource, &intent); err != nil {
|
||||
log.Printf("❌ QQ Bot WebSocket 断开: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// isCommand 判断是否匹配命令关键词
|
||||
func isCommand(text string, keywords ...string) bool {
|
||||
for _, kw := range keywords {
|
||||
if text == kw {
|
||||
@@ -82,7 +79,18 @@ func isCommand(text string, keywords ...string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// processAndReply 通用记账处理
|
||||
func (b *QQBot) isDuplicate(eventID string) bool {
|
||||
if b.db == nil || strings.TrimSpace(eventID) == "" {
|
||||
return false
|
||||
}
|
||||
var existed models.MessageDedup
|
||||
if err := b.db.Where("platform = ? AND event_id = ?", "qqbot_official", eventID).First(&existed).Error; err == nil {
|
||||
return true
|
||||
}
|
||||
_ = b.db.Create(&models.MessageDedup{Platform: "qqbot_official", EventID: eventID, ProcessedAt: time.Now()}).Error
|
||||
return false
|
||||
}
|
||||
|
||||
func (b *QQBot) processAndReply(userID string, content string) string {
|
||||
text := strings.TrimSpace(message.ETLInput(content))
|
||||
if text == "" {
|
||||
@@ -91,7 +99,6 @@ func (b *QQBot) processAndReply(userID string, content string) string {
|
||||
|
||||
today := time.Now().Format("2006-01-02")
|
||||
|
||||
// 命令处理
|
||||
switch {
|
||||
case isCommand(text, "帮助", "help", "/help", "/start", "菜单", "功能"):
|
||||
return "🦞 虾记记账\n\n" +
|
||||
@@ -173,17 +180,18 @@ func (b *QQBot) processAndReply(userID string, content string) string {
|
||||
return fmt.Sprintf("✅ 已记入【%s】:%.2f元\n📝 备注:%s", category, amountYuan, text)
|
||||
}
|
||||
|
||||
// channelATMessageHandler 频道@机器人消息
|
||||
func (b *QQBot) channelATMessageHandler() event.ATMessageEventHandler {
|
||||
return func(ev *dto.WSPayload, data *dto.WSATMessageData) error {
|
||||
eventID := "qq:channel:" + strings.TrimSpace(data.ID)
|
||||
if b.isDuplicate(eventID) {
|
||||
return nil
|
||||
}
|
||||
log.Printf("📩 inbound platform=qqbot_official event=%s chat=%s user=%s text=%q", eventID, data.ChannelID, data.Author.ID, strings.TrimSpace(message.ETLInput(data.Content)))
|
||||
reply := b.processAndReply(data.Author.ID, data.Content)
|
||||
if reply == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := b.api.PostMessage(context.Background(), data.ChannelID, &dto.MessageToCreate{
|
||||
MsgID: data.ID,
|
||||
Content: reply,
|
||||
})
|
||||
_, err := b.api.PostMessage(context.Background(), data.ChannelID, &dto.MessageToCreate{MsgID: data.ID, Content: reply})
|
||||
if err != nil {
|
||||
log.Printf("QQ频道消息发送失败: %v", err)
|
||||
}
|
||||
@@ -191,17 +199,18 @@ func (b *QQBot) channelATMessageHandler() event.ATMessageEventHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// groupATMessageHandler 群@机器人消息
|
||||
func (b *QQBot) groupATMessageHandler() event.GroupATMessageEventHandler {
|
||||
return func(ev *dto.WSPayload, data *dto.WSGroupATMessageData) error {
|
||||
eventID := "qq:group:" + strings.TrimSpace(data.ID)
|
||||
if b.isDuplicate(eventID) {
|
||||
return nil
|
||||
}
|
||||
log.Printf("📩 inbound platform=qqbot_official event=%s chat=%s user=%s text=%q", eventID, data.GroupID, data.Author.ID, strings.TrimSpace(message.ETLInput(data.Content)))
|
||||
reply := b.processAndReply(data.Author.ID, data.Content)
|
||||
if reply == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := b.api.PostGroupMessage(context.Background(), data.GroupID, dto.MessageToCreate{
|
||||
MsgID: data.ID,
|
||||
Content: reply,
|
||||
})
|
||||
_, err := b.api.PostGroupMessage(context.Background(), data.GroupID, dto.MessageToCreate{MsgID: data.ID, Content: reply})
|
||||
if err != nil {
|
||||
log.Printf("QQ群消息发送失败: %v", err)
|
||||
}
|
||||
@@ -209,17 +218,18 @@ func (b *QQBot) groupATMessageHandler() event.GroupATMessageEventHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// c2cMessageHandler C2C 私聊消息
|
||||
func (b *QQBot) c2cMessageHandler() event.C2CMessageEventHandler {
|
||||
return func(ev *dto.WSPayload, data *dto.WSC2CMessageData) error {
|
||||
eventID := "qq:c2c:" + strings.TrimSpace(data.ID)
|
||||
if b.isDuplicate(eventID) {
|
||||
return nil
|
||||
}
|
||||
log.Printf("📩 inbound platform=qqbot_official event=%s chat=%s user=%s text=%q", eventID, data.Author.ID, data.Author.ID, strings.TrimSpace(message.ETLInput(data.Content)))
|
||||
reply := b.processAndReply(data.Author.ID, data.Content)
|
||||
if reply == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := b.api.PostC2CMessage(context.Background(), data.Author.ID, dto.MessageToCreate{
|
||||
MsgID: data.ID,
|
||||
Content: reply,
|
||||
})
|
||||
_, err := b.api.PostC2CMessage(context.Background(), data.Author.ID, dto.MessageToCreate{MsgID: data.ID, Content: reply})
|
||||
if err != nil {
|
||||
log.Printf("QQ私聊消息发送失败: %v", err)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
114
models/models.go
114
models/models.go
@@ -24,14 +24,126 @@ type CategoryKeyword struct {
|
||||
Category string `gorm:"size:50"`
|
||||
}
|
||||
|
||||
// FeatureFlag 高风险能力开关(默认关闭)
|
||||
type FeatureFlag struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Key string `gorm:"uniqueIndex;size:100" json:"key"`
|
||||
Enabled bool `gorm:"default:false" json:"enabled"`
|
||||
RiskLevel string `gorm:"size:20" json:"risk_level"` // low|medium|high
|
||||
Description string `gorm:"size:255" json:"description"`
|
||||
RequireReason bool `gorm:"default:false" json:"require_reason"`
|
||||
UpdatedBy int64 `json:"updated_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// FeatureFlagHistory 开关变更历史
|
||||
type FeatureFlagHistory struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
FlagKey string `gorm:"index;size:100" json:"flag_key"`
|
||||
OldValue bool `json:"old_value"`
|
||||
NewValue bool `json:"new_value"`
|
||||
ChangedBy int64 `json:"changed_by"`
|
||||
Reason string `gorm:"size:255" json:"reason"`
|
||||
RequestID string `gorm:"size:100" json:"request_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ChannelConfig 渠道接入配置(平台适配层参数)
|
||||
type ChannelConfig struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Platform string `gorm:"uniqueIndex;size:32" json:"platform"` // qqbot_official|telegram|feishu
|
||||
Name string `gorm:"size:64" json:"name"`
|
||||
Enabled bool `gorm:"default:false" json:"enabled"`
|
||||
Status string `gorm:"size:20;default:'disabled'" json:"status"` // ok|error|disabled
|
||||
ConfigJSON string `gorm:"type:text" json:"config_json"` // 生效配置 JSON
|
||||
SecretJSON string `gorm:"type:text" json:"-"` // 生效密钥 JSON(建议加密)
|
||||
DraftConfigJSON string `gorm:"type:text" json:"draft_config_json"` // 草稿配置 JSON
|
||||
DraftSecretJSON string `gorm:"type:text" json:"-"` // 草稿密钥 JSON(建议加密)
|
||||
LastCheck *time.Time `json:"last_check_at"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
UpdatedBy int64 `json:"updated_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AuditLog 通用审计日志
|
||||
type AuditLog struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
ActorID int64 `gorm:"index" json:"actor_id"`
|
||||
Action string `gorm:"size:64;index" json:"action"`
|
||||
TargetType string `gorm:"size:64;index" json:"target_type"`
|
||||
TargetID string `gorm:"size:128;index" json:"target_id"`
|
||||
BeforeJSON string `gorm:"type:text" json:"before_json"`
|
||||
AfterJSON string `gorm:"type:text" json:"after_json"`
|
||||
Note string `gorm:"size:255" json:"note"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MessageDedup 入站事件幂等去重
|
||||
type MessageDedup struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Platform string `gorm:"size:32;index:idx_platform_event,unique" json:"platform"`
|
||||
EventID string `gorm:"size:128;index:idx_platform_event,unique" json:"event_id"`
|
||||
ProcessedAt time.Time `json:"processed_at"`
|
||||
}
|
||||
|
||||
// AmountYuan 返回元为单位的金额(显示用)
|
||||
func (t *Transaction) AmountYuan() float64 {
|
||||
return float64(t.Amount) / 100.0
|
||||
}
|
||||
|
||||
func seedDefaultFeatureFlags(db *gorm.DB) error {
|
||||
defaults := []FeatureFlag{
|
||||
{Key: "allow_cross_user_read", Enabled: false, RiskLevel: "high", Description: "允许读取非本人账本数据", RequireReason: true},
|
||||
{Key: "allow_cross_user_delete", Enabled: false, RiskLevel: "high", Description: "允许删除非本人账本记录", RequireReason: true},
|
||||
{Key: "allow_export_all_users", Enabled: false, RiskLevel: "high", Description: "允许导出全量用户账本数据", RequireReason: true},
|
||||
{Key: "allow_manual_role_grant", Enabled: false, RiskLevel: "medium", Description: "允许人工授予角色", RequireReason: true},
|
||||
{Key: "allow_bot_admin_commands", Enabled: false, RiskLevel: "medium", Description: "允许 Bot 侧执行管理命令", RequireReason: true},
|
||||
}
|
||||
|
||||
for _, ff := range defaults {
|
||||
if err := db.Where("key = ?", ff.Key).FirstOrCreate(&ff).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func seedDefaultChannels(db *gorm.DB) error {
|
||||
defaults := []ChannelConfig{
|
||||
{Platform: "qqbot_official", Name: "QQ 官方 Bot", Enabled: false, Status: "disabled", ConfigJSON: "{}", SecretJSON: "{}", DraftConfigJSON: "{}", DraftSecretJSON: "{}"},
|
||||
{Platform: "telegram", Name: "Telegram Bot", Enabled: false, Status: "disabled", ConfigJSON: "{}", SecretJSON: "{}", DraftConfigJSON: "{}", DraftSecretJSON: "{}"},
|
||||
{Platform: "feishu", Name: "飞书 Bot", Enabled: false, Status: "disabled", ConfigJSON: "{}", SecretJSON: "{}", DraftConfigJSON: "{}", DraftSecretJSON: "{}"},
|
||||
}
|
||||
|
||||
for _, ch := range defaults {
|
||||
if err := db.Where("platform = ?", ch.Platform).FirstOrCreate(&ch).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Migrate 自动迁移数据库表结构并初始化分类关键词
|
||||
func Migrate(db *gorm.DB) error {
|
||||
if err := db.AutoMigrate(&Transaction{}, &CategoryKeyword{}); err != nil {
|
||||
if err := db.AutoMigrate(
|
||||
&Transaction{},
|
||||
&CategoryKeyword{},
|
||||
&FeatureFlag{},
|
||||
&FeatureFlagHistory{},
|
||||
&ChannelConfig{},
|
||||
&AuditLog{},
|
||||
&MessageDedup{},
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := seedDefaultFeatureFlags(db); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := seedDefaultChannels(db); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
135
templates/audit.html
Normal file
135
templates/audit.html
Normal file
@@ -0,0 +1,135 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🧾 审计日志 - 虾记</title>
|
||||
<style>
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#f0f2f5;color:#333;min-height:100vh}
|
||||
.header{background:linear-gradient(135deg,#ff6b6b,#ee5a24);color:#fff;padding:20px;position:sticky;top:0;z-index:100;box-shadow:0 2px 10px rgba(0,0,0,.15);display:flex;justify-content:space-between;align-items:center;gap:10px}
|
||||
.header .title{font-weight:700}
|
||||
.header .sub{font-size:12px;opacity:.9}
|
||||
.header a{color:#fff;text-decoration:none;background:rgba(255,255,255,.2);padding:6px 10px;border-radius:8px;font-size:13px}
|
||||
.header a:hover{background:rgba(255,255,255,.35)}
|
||||
|
||||
.wrap{max-width:600px;margin:0 auto;padding:15px}
|
||||
.filters{background:#fff;border-radius:12px;padding:12px;box-shadow:0 1px 4px rgba(0,0,0,.05);margin-bottom:10px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
|
||||
.filters input,.filters select{width:100%;padding:8px;border:1px solid #ddd;border-radius:8px;font-size:13px;background:#fff}
|
||||
small{color:#6b7280}
|
||||
|
||||
.actions{margin:0 0 10px;display:flex;gap:8px;flex-wrap:wrap}
|
||||
button{border:none;border-radius:8px;padding:8px 12px;cursor:pointer;color:#fff;background:#ee5a24;font-size:13px}
|
||||
button:hover{background:#d63031}
|
||||
button.secondary{background:#6b7280}
|
||||
button.secondary:hover{background:#4b5563}
|
||||
|
||||
.list{display:flex;flex-direction:column;gap:10px}
|
||||
.log-card{background:#fff;border-radius:12px;padding:12px;box-shadow:0 1px 4px rgba(0,0,0,.05)}
|
||||
.row{display:flex;justify-content:space-between;gap:8px;align-items:flex-start}
|
||||
.tag{display:inline-block;padding:2px 8px;border-radius:999px;font-size:12px}
|
||||
.tag.success{background:#dcfce7;color:#166534}
|
||||
.tag.failed{background:#fee2e2;color:#991b1b}
|
||||
.tag.denied{background:#fef3c7;color:#92400e}
|
||||
.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:#4b5563;word-break:break-all}
|
||||
.note{font-size:13px;color:#374151;margin-top:6px;white-space:pre-wrap;word-break:break-word}
|
||||
.empty{text-align:center;padding:40px 10px;color:#999}
|
||||
|
||||
@media(max-width:640px){
|
||||
.header{padding:14px 12px 10px;align-items:flex-start;flex-direction:column}
|
||||
.header>div:last-child{display:flex;gap:8px}
|
||||
.wrap{padding:12px}
|
||||
.filters{grid-template-columns:1fr}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div>
|
||||
<div class="title">🧾 审计日志</div>
|
||||
<div class="sub">{{.version}}</div>
|
||||
</div>
|
||||
<div>
|
||||
<a href="/">返回首页</a>
|
||||
<a href="/channels">渠道配置</a>
|
||||
<a href="/logout">退出</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wrap">
|
||||
<div class="filters">
|
||||
<div><small>操作类型</small><input id="fAction" placeholder="如:record.delete.self"></div>
|
||||
<div><small>目标类型</small><input id="fTarget" placeholder="如:transaction"></div>
|
||||
<div><small>结果</small><select id="fResult"><option value="">全部</option><option value="success">成功</option><option value="denied">拒绝</option><option value="failed">失败</option></select></div>
|
||||
<div><small>操作人ID</small><input id="fActor" placeholder="如:1"></div>
|
||||
<div><small>开始时间(RFC3339)</small><input id="fFrom" placeholder="2026-03-09T00:00:00+08:00"></div>
|
||||
<div><small>结束时间(RFC3339)</small><input id="fTo" placeholder="2026-03-10T00:00:00+08:00"></div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button onclick="loadAudit()">查询</button>
|
||||
<button class="secondary" onclick="resetFilters()">重置</button>
|
||||
</div>
|
||||
<div id="list" class="list"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function esc(s){return String(s||'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}
|
||||
function qs(id){return document.getElementById(id).value.trim();}
|
||||
|
||||
const actionMap={
|
||||
'auth.login.success':'登录成功','auth.login.failed':'登录失败','auth.logout':'退出登录',
|
||||
'record.delete.self':'删除本人记录','record.delete.all':'删除全员记录','record.export':'导出记录',
|
||||
'flag.update':'修改高级开关',
|
||||
'channel_update_draft':'更新渠道草稿','channel_publish':'发布渠道草稿','channel_reload':'热加载渠道',
|
||||
'channel_disable_all':'一键关闭全部渠道','channel_enable':'启用渠道','channel_disable':'停用渠道','channel_test':'测试渠道连接'
|
||||
};
|
||||
const targetMap={
|
||||
'transaction':'记账记录','feature_flag':'高级开关','channel':'渠道','user':'用户','system':'系统'
|
||||
};
|
||||
|
||||
function actionLabel(v){return actionMap[v]||v||'-';}
|
||||
function targetLabel(v){return targetMap[v]||v||'-';}
|
||||
function parseResult(note){
|
||||
const m=String(note||'').match(/result=(success|failed|denied)/);
|
||||
return m?m[1]:'';
|
||||
}
|
||||
function resultLabel(r){
|
||||
if(r==='success') return '成功';
|
||||
if(r==='failed') return '失败';
|
||||
if(r==='denied') return '拒绝';
|
||||
return '未标注';
|
||||
}
|
||||
|
||||
function resetFilters(){['fAction','fTarget','fResult','fActor','fFrom','fTo'].forEach(id=>document.getElementById(id).value='');loadAudit();}
|
||||
|
||||
async function loadAudit(){
|
||||
const p=new URLSearchParams();
|
||||
const m={action:qs('fAction'),target_type:qs('fTarget'),result:qs('fResult'),actor_id:qs('fActor'),from:qs('fFrom'),to:qs('fTo')};
|
||||
Object.entries(m).forEach(([k,v])=>{if(v)p.set(k,v)});
|
||||
p.set('limit','200');
|
||||
|
||||
const listEl=document.getElementById('list');
|
||||
listEl.innerHTML='<div class="empty">加载中...</div>';
|
||||
|
||||
const r=await fetch('/api/v1/admin/audit?'+p.toString());
|
||||
const data=await r.json().catch(()=>[]);
|
||||
const list=Array.isArray(data)?data:[];
|
||||
if(!list.length){listEl.innerHTML='<div class="empty">暂无审计记录</div>';return;}
|
||||
|
||||
listEl.innerHTML=list.map(it=>{
|
||||
const result=parseResult(it.note);
|
||||
const resultClass=result||'success';
|
||||
const note=String(it.note||'').replace(/\s*\|\s*result=(success|failed|denied)\s*$/,'').trim();
|
||||
return `<div class="log-card">
|
||||
<div class="row"><strong>${actionLabel(it.action)}</strong><span class="tag ${resultClass}">${resultLabel(result)}</span></div>
|
||||
<div class="mono" style="margin-top:4px;">#${it.id} · ${esc(it.created_at||'')}</div>
|
||||
<div class="mono" style="margin-top:2px;">操作人: ${it.actor_id} · 目标: ${targetLabel(it.target_type)} (${esc(it.target_id||'')})</div>
|
||||
<div class="note">${esc(note||'(无备注)')}</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
loadAudit();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
282
templates/channels.html
Normal file
282
templates/channels.html
Normal file
@@ -0,0 +1,282 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>渠道配置 - 虾记</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; min-height: 100vh; }
|
||||
.header { background: linear-gradient(135deg, #ff6b6b, #ee5a24); color: #fff; padding: 20px; position: sticky; top: 0; z-index: 100; box-shadow: 0 2px 10px rgba(0,0,0,.15); display:flex; justify-content:space-between; align-items:center; gap:10px; }
|
||||
.header a { color: #fff; text-decoration:none; background: rgba(255,255,255,.2); padding:6px 10px; border-radius:8px; font-size:13px; }
|
||||
.header a:hover { background: rgba(255,255,255,.35); }
|
||||
.wrap { max-width: 600px; margin: 0 auto; padding: 15px; }
|
||||
.toolbar { display:flex; gap:8px; margin-bottom:10px; flex-wrap:wrap; }
|
||||
.tip { color:#6b7280; font-size:12px; margin-bottom:10px; }
|
||||
.card { background:#fff; border-radius:12px; padding:14px; margin-bottom:10px; box-shadow:0 1px 4px rgba(0,0,0,.05); }
|
||||
.row { display:flex; gap:8px; align-items:center; margin:8px 0; flex-wrap:wrap; }
|
||||
.row label { width:110px; color:#4b5563; font-size:13px; }
|
||||
.row input, .row textarea { flex:1; min-width:220px; padding:8px; border:1px solid #ddd; border-radius:8px; font-size:13px; }
|
||||
.row textarea { min-height:74px; }
|
||||
.btns { display:flex; gap:8px; margin-top:8px; flex-wrap:wrap; }
|
||||
button { border:none; border-radius:8px; padding:8px 12px; cursor:pointer; color:#fff; font-size:13px; }
|
||||
button:disabled { opacity:.65; cursor:not-allowed; }
|
||||
.btn-apply, .btn-save, .btn-publish, .btn-test, .btn-reload, .btn-enable { background:#ee5a24; }
|
||||
.btn-apply:hover, .btn-save:hover, .btn-publish:hover, .btn-test:hover, .btn-reload:hover, .btn-enable:hover { background:#d63031; }
|
||||
.btn-disable { background:#9b2c2c; }
|
||||
.btn-disable:hover { background:#7f1d1d; }
|
||||
.badge { display:inline-block; font-size:12px; border-radius:999px; padding:2px 8px; }
|
||||
.state { display:inline-block; font-size:12px; border-radius:999px; padding:2px 8px; margin-left:6px; }
|
||||
.ok { background:#dcfce7; color:#166534; }
|
||||
.error { background:#fee2e2; color:#991b1b; }
|
||||
.disabled { background:#e5e7eb; color:#374151; }
|
||||
small { color:#6b7280; }
|
||||
|
||||
@media(max-width:640px){
|
||||
.header { padding: 14px 12px 10px; align-items:flex-start; flex-direction:column; }
|
||||
.header > div:last-child { display:flex; gap:8px; }
|
||||
.wrap { padding:12px; }
|
||||
.toolbar button { flex: 1 1 calc(50% - 4px); }
|
||||
.row label { width:100%; }
|
||||
.row input, .row textarea { min-width:100%; }
|
||||
.btns button { flex: 1 1 calc(50% - 4px); }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div>🦞 渠道配置中心(草稿/发布) · {{.version}}</div>
|
||||
<div><a href="/">返回首页</a><a href="/logout">退出</a></div>
|
||||
</div>
|
||||
<div class="wrap">
|
||||
<div class="toolbar">
|
||||
<button class="btn-disable" onclick="disableAll()">一键全部关闭</button>
|
||||
<button class="btn-reload" onclick="reloadRuntime()">热加载运行参数</button>
|
||||
</div>
|
||||
<div class="tip">默认推荐:直接点“保存并立即生效”。高级场景再用“保存草稿 / 发布草稿 / 热加载”。</div>
|
||||
<div id="app"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const app = document.getElementById('app');
|
||||
|
||||
function renderError(msg) {
|
||||
app.innerHTML = `<div class="card" style="border:1px solid #fecaca;background:#fef2f2;color:#991b1b;">${msg}</div>`;
|
||||
}
|
||||
|
||||
function pretty(objStr) {
|
||||
try { return JSON.stringify(JSON.parse(objStr || '{}'), null, 2); } catch { return '{}'; }
|
||||
}
|
||||
|
||||
function statusBadge(status) {
|
||||
const s = (status || 'disabled');
|
||||
const cls = s === 'ok' ? 'ok' : (s === 'error' ? 'error' : 'disabled');
|
||||
return `<span class="badge ${cls}">${s}</span>`;
|
||||
}
|
||||
|
||||
function runtimeState(ch) {
|
||||
if (!ch.enabled) return '<span class="state disabled">已关闭</span>';
|
||||
if ((ch.status || '').toLowerCase() === 'ok') return '<span class="state ok">运行中</span>';
|
||||
if ((ch.status || '').toLowerCase() === 'error') return '<span class="state error">配置异常</span>';
|
||||
return '<span class="state disabled">待检测</span>';
|
||||
}
|
||||
|
||||
function parseJSONSafe(text) {
|
||||
try { return JSON.parse(text || '{}'); } catch { return null; }
|
||||
}
|
||||
|
||||
async function fetchChannels() {
|
||||
const r = await fetch('/api/v1/admin/channels');
|
||||
if (!r.ok) {
|
||||
throw new Error('加载渠道失败: HTTP ' + r.status);
|
||||
}
|
||||
const data = await r.json();
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error('渠道返回格式异常');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function render(channels) {
|
||||
app.innerHTML = channels.map(ch => {
|
||||
const draftCfg = pretty(ch.draft_config_json || ch.config_json);
|
||||
const draftSec = pretty(ch.draft_secrets || ch.secrets);
|
||||
return `<div class="card" data-platform="${ch.platform}">
|
||||
<h3>${ch.name || ch.platform} ${statusBadge(ch.status)} ${runtimeState(ch)} ${ch.has_draft ? '<span class="badge" style="background:#fef3c7;color:#92400e">draft</span>' : ''}</h3>
|
||||
<small>平台:${ch.platform} | 发布:${ch.published_at || '-'} | 最近检测:${ch.last_check_at || '-'}</small>
|
||||
<div class="row"><label>启用</label><input type="checkbox" class="enabled" ${ch.enabled ? 'checked' : ''}></div>
|
||||
<div class="row"><label>显示名称</label><input class="name" value="${(ch.name||'').replace(/"/g,'"')}"></div>
|
||||
<div class="row"><label>草稿 config(JSON)</label><textarea class="config">${draftCfg}</textarea></div>
|
||||
<div class="row"><label>草稿 secrets(JSON)</label><textarea class="secrets">${draftSec}</textarea></div>
|
||||
<div class="btns">
|
||||
<button class="btn-apply" onclick="applyNow('${ch.platform}')">保存并立即生效</button>
|
||||
<button class="btn-save" onclick="saveDraft('${ch.platform}')">保存草稿</button>
|
||||
<button class="btn-publish" onclick="publishDraft('${ch.platform}')">发布草稿</button>
|
||||
<button class="btn-test" onclick="testConn('${ch.platform}')">测试连接</button>
|
||||
${ch.enabled ? `<button class="btn-disable" onclick="toggleChannel('${ch.platform}', false)">关闭通道</button>` : `<button class="btn-enable" onclick="toggleChannel('${ch.platform}', true)">开启通道</button>`}
|
||||
</div>
|
||||
<small class="msg"></small>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function collectChannelForm(platform) {
|
||||
const card = document.querySelector(`[data-platform="${platform}"]`);
|
||||
const name = card.querySelector('.name').value.trim();
|
||||
const enabled = card.querySelector('.enabled').checked;
|
||||
const configText = card.querySelector('.config').value;
|
||||
const secretsText = card.querySelector('.secrets').value;
|
||||
const msg = card.querySelector('.msg');
|
||||
|
||||
const config = parseJSONSafe(configText);
|
||||
const secrets = parseJSONSafe(secretsText);
|
||||
if (!config || !secrets) {
|
||||
msg.textContent = 'JSON 格式错误,请检查 config/secrets';
|
||||
return null;
|
||||
}
|
||||
|
||||
return { card, msg, payload: { name, enabled, config, secrets } };
|
||||
}
|
||||
|
||||
async function apiJSON(url, options = {}) {
|
||||
const r = await fetch(url, options);
|
||||
const out = await r.json().catch(() => ({}));
|
||||
if (!r.ok) {
|
||||
throw new Error(out.error || ('HTTP ' + r.status));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function msgOf(platform) {
|
||||
return document.querySelector(`[data-platform="${platform}"] .msg`);
|
||||
}
|
||||
|
||||
function setCardBusy(card, busy) {
|
||||
if (!card) return;
|
||||
card.querySelectorAll('button').forEach(btn => { btn.disabled = busy; });
|
||||
}
|
||||
|
||||
async function applyNow(platform) {
|
||||
const f = collectChannelForm(platform);
|
||||
if (!f) return;
|
||||
const { card, msg, payload } = f;
|
||||
const applyBtn = card.querySelector('.btn-apply');
|
||||
const oldText = applyBtn ? applyBtn.textContent : '';
|
||||
|
||||
setCardBusy(card, true);
|
||||
if (applyBtn) applyBtn.textContent = '生效中...';
|
||||
|
||||
try {
|
||||
msg.textContent = '保存并生效中...';
|
||||
await apiJSON('/api/v1/admin/channels/' + platform + '/apply', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
msg.textContent = '已生效';
|
||||
await reload();
|
||||
} catch (e) {
|
||||
msg.textContent = '失败:' + (e && e.message ? e.message : e);
|
||||
} finally {
|
||||
setCardBusy(card, false);
|
||||
if (applyBtn) applyBtn.textContent = oldText || '保存并立即生效';
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDraft(platform) {
|
||||
const f = collectChannelForm(platform);
|
||||
if (!f) return;
|
||||
const { msg, payload } = f;
|
||||
|
||||
try {
|
||||
await apiJSON('/api/v1/admin/channels/' + platform, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
msg.textContent = '草稿已保存';
|
||||
await reload();
|
||||
} catch (e) {
|
||||
msg.textContent = '保存失败:' + (e && e.message ? e.message : e);
|
||||
}
|
||||
}
|
||||
|
||||
async function publishDraft(platform) {
|
||||
const msg = msgOf(platform);
|
||||
try {
|
||||
await apiJSON('/api/v1/admin/channels/' + platform + '/publish', { method: 'POST' });
|
||||
msg.textContent = '发布成功,建议点“热加载运行参数”';
|
||||
await reload();
|
||||
} catch (e) {
|
||||
msg.textContent = '发布失败:' + (e && e.message ? e.message : e);
|
||||
}
|
||||
}
|
||||
|
||||
async function testConn(platform) {
|
||||
const msg = msgOf(platform);
|
||||
try {
|
||||
msg.textContent = '正在测试...';
|
||||
const out = await apiJSON('/api/v1/admin/channels/' + platform + '/test', { method: 'POST' });
|
||||
msg.textContent = `测试结果:${out.status} ${out.detail ? ' / ' + out.detail : ''}`;
|
||||
await reload();
|
||||
} catch (e) {
|
||||
msg.textContent = '测试失败:' + (e && e.message ? e.message : e);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleChannel(platform, enable) {
|
||||
const msg = msgOf(platform);
|
||||
try {
|
||||
msg.textContent = enable ? '正在开启...' : '正在关闭...';
|
||||
await apiJSON('/api/v1/admin/channels/' + platform + (enable ? '/enable' : '/disable'), { method: 'POST' });
|
||||
msg.textContent = enable ? '已开启(请点热加载生效)' : '已关闭(请点热加载生效)';
|
||||
await reload();
|
||||
} catch (e) {
|
||||
msg.textContent = (enable ? '开启失败:' : '关闭失败:') + (e && e.message ? e.message : e);
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadRuntime() {
|
||||
try {
|
||||
const out = await apiJSON('/api/v1/admin/channels/reload', { method: 'POST' });
|
||||
alert('热加载成功:' + (out.detail || 'ok'));
|
||||
await reload();
|
||||
} catch (e) {
|
||||
alert('热加载失败:' + (e && e.message ? e.message : e));
|
||||
}
|
||||
}
|
||||
|
||||
async function disableAll() {
|
||||
if (!confirm('确认要关闭所有通道吗?')) return;
|
||||
try {
|
||||
const out = await apiJSON('/api/v1/admin/channels/disable-all', { method: 'POST' });
|
||||
alert('已关闭通道数:' + (out.affected || 0) + ',请点热加载生效。');
|
||||
await reload();
|
||||
} catch (e) {
|
||||
alert('批量关闭失败:' + (e && e.message ? e.message : e));
|
||||
}
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
try {
|
||||
const channels = await fetchChannels();
|
||||
render(channels);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
renderError('页面加载失败:' + (e && e.message ? e.message : e));
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('error', (e) => {
|
||||
renderError('前端脚本异常:' + (e && e.message ? e.message : 'unknown'));
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (e) => {
|
||||
const msg = e && e.reason && e.reason.message ? e.reason.message : String(e.reason || 'unknown');
|
||||
renderError('前端请求异常:' + msg);
|
||||
});
|
||||
|
||||
reload();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -5,95 +5,91 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🦞 虾记记账</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; min-height: 100vh; }
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#f0f2f5;color:#333;min-height:100vh}
|
||||
.header{background:linear-gradient(135deg,#ff6b6b,#ee5a24);color:#fff;padding:20px;text-align:center;position:sticky;top:0;z-index:100;box-shadow:0 2px 10px rgba(0,0,0,.15);position:relative}
|
||||
.header h1{font-size:24px;margin-bottom:4px}
|
||||
.header .subtitle{font-size:13px;opacity:.9}
|
||||
.logout-btn{position:absolute;right:16px;top:50%;transform:translateY(-50%);background:rgba(255,255,255,.2);color:#fff;text-decoration:none;padding:5px 14px;border-radius:6px;font-size:13px}
|
||||
.logout-btn:hover{background:rgba(255,255,255,.35)}
|
||||
|
||||
.header { background: linear-gradient(135deg, #ff6b6b, #ee5a24); color: #fff; padding: 20px; text-align: center; position: sticky; top: 0; z-index: 100; box-shadow: 0 2px 10px rgba(0,0,0,.15); }
|
||||
.header h1 { font-size: 24px; margin-bottom: 4px; }
|
||||
.header .subtitle { font-size: 13px; opacity: .85; }
|
||||
.header { position: relative; }
|
||||
.logout-btn { position: absolute; right: 16px; top: 50%; transform: translateY(-50%); background: rgba(255,255,255,.2); color: #fff; text-decoration: none; padding: 5px 14px; border-radius: 6px; font-size: 13px; transition: background .2s; }
|
||||
.logout-btn:hover { background: rgba(255,255,255,.35); }
|
||||
.stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;padding:15px;max-width:600px;margin:0 auto}
|
||||
.stat-card{background:#fff;border-radius:12px;padding:15px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.06)}
|
||||
.stat-card .num{font-size:22px;font-weight:700;color:#ee5a24}
|
||||
.stat-card .label{font-size:12px;color:#999;margin-top:4px}
|
||||
|
||||
.stats { display: flex; gap: 10px; padding: 15px; overflow-x: auto; }
|
||||
.stat-card { flex: 1; min-width: 120px; background: #fff; border-radius: 12px; padding: 15px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,.06); }
|
||||
.stat-card .num { font-size: 22px; font-weight: 700; color: #ee5a24; }
|
||||
.stat-card .label { font-size: 12px; color: #999; margin-top: 4px; }
|
||||
.toolbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:0 15px 10px;max-width:600px;margin:0 auto}
|
||||
.toolbar .spacer{flex:1}
|
||||
.filter-select{padding:8px 12px;border:1px solid #ddd;border-radius:8px;font-size:13px;background:#fff;min-width:110px}
|
||||
.toolbar a{padding:8px 12px;background:#ee5a24;color:#fff;border-radius:8px;text-decoration:none;font-size:13px;white-space:nowrap}
|
||||
.toolbar a:hover{background:#d63031}
|
||||
|
||||
.toolbar { display: flex; gap: 10px; padding: 0 15px 10px; align-items: center; }
|
||||
.toolbar a { padding: 8px 16px; background: #ee5a24; color: #fff; border-radius: 8px; text-decoration: none; font-size: 13px; white-space: nowrap; }
|
||||
.toolbar a:hover { background: #d63031; }
|
||||
.toolbar .spacer { flex: 1; }
|
||||
.filter-select { padding: 8px 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 13px; background: #fff; }
|
||||
#flagsPanel{display:none;max-width:600px;margin:0 auto 12px;background:#fff;border-radius:12px;padding:12px 14px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
|
||||
#flagsList{display:flex;flex-direction:column;gap:8px}
|
||||
|
||||
.tx-list { padding: 0 15px 80px; }
|
||||
.tx-card { background: #fff; border-radius: 12px; padding: 14px 16px; margin-bottom: 10px; box-shadow: 0 1px 4px rgba(0,0,0,.05); display: flex; align-items: center; gap: 12px; transition: transform .15s; }
|
||||
.tx-card:active { transform: scale(.98); }
|
||||
.tx-icon { width: 42px; height: 42px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; flex-shrink: 0; }
|
||||
.tx-info { flex: 1; min-width: 0; }
|
||||
.tx-category { font-weight: 600; font-size: 15px; }
|
||||
.tx-note { font-size: 12px; color: #999; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.tx-right { text-align: right; flex-shrink: 0; }
|
||||
.tx-amount { font-size: 17px; font-weight: 700; color: #e74c3c; }
|
||||
.tx-date { font-size: 11px; color: #bbb; margin-top: 2px; }
|
||||
.tx-actions { margin-top: 4px; }
|
||||
.btn-del { background: none; border: 1px solid #e74c3c; color: #e74c3c; border-radius: 4px; padding: 2px 8px; font-size: 11px; cursor: pointer; }
|
||||
.btn-del:hover { background: #e74c3c; color: #fff; }
|
||||
.tx-list{padding:0 15px 80px;max-width:600px;margin:0 auto}
|
||||
.tx-card{background:#fff;border-radius:12px;padding:14px 16px;margin-bottom:10px;box-shadow:0 1px 4px rgba(0,0,0,.05);display:flex;align-items:center;gap:12px}
|
||||
.tx-icon{width:42px;height:42px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0}
|
||||
.tx-info{flex:1;min-width:0}
|
||||
.tx-category{font-weight:600;font-size:15px}
|
||||
.tx-note{font-size:12px;color:#999;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.tx-right{text-align:right;flex-shrink:0}
|
||||
.tx-amount{font-size:17px;font-weight:700;color:#e74c3c}
|
||||
.tx-date{font-size:11px;color:#bbb;margin-top:2px}
|
||||
.btn-del{background:none;border:1px solid #e74c3c;color:#e74c3c;border-radius:4px;padding:2px 8px;font-size:11px;cursor:pointer;margin-top:4px}
|
||||
.btn-del:hover{background:#e74c3c;color:#fff}
|
||||
|
||||
.empty { text-align: center; padding: 60px 20px; color: #999; }
|
||||
.empty .icon { font-size: 48px; margin-bottom: 10px; }
|
||||
.empty{text-align:center;padding:60px 20px;color:#999}
|
||||
.empty .icon{font-size:48px;margin-bottom:10px}
|
||||
.cat-餐饮{background:#fff3e0}.cat-交通{background:#e3f2fd}.cat-购物{background:#fce4ec}.cat-娱乐{background:#f3e5f5}.cat-其他{background:#f5f5f5}
|
||||
|
||||
.cat-餐饮 { background: #fff3e0; }
|
||||
.cat-交通 { background: #e3f2fd; }
|
||||
.cat-购物 { background: #fce4ec; }
|
||||
.cat-娱乐 { background: #f3e5f5; }
|
||||
.cat-其他 { background: #f5f5f5; }
|
||||
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:200;align-items:center;justify-content:center}
|
||||
.modal.show{display:flex}
|
||||
.modal-body{background:#fff;border-radius:16px;padding:24px;width:280px;text-align:center}
|
||||
.modal-body .btns{display:flex;gap:10px;margin-top:16px}
|
||||
.modal-body .btns button{flex:1;padding:10px;border:none;border-radius:8px;cursor:pointer}
|
||||
|
||||
.modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 200; align-items: center; justify-content: center; }
|
||||
.modal.show { display: flex; }
|
||||
.modal-body { background: #fff; border-radius: 16px; padding: 24px; width: 280px; text-align: center; }
|
||||
.modal-body h3 { margin-bottom: 12px; }
|
||||
.modal-body .btns { display: flex; gap: 10px; margin-top: 16px; }
|
||||
.modal-body .btns button { flex: 1; padding: 10px; border: none; border-radius: 8px; font-size: 14px; cursor: pointer; }
|
||||
.modal-body .btn-cancel { background: #f0f0f0; }
|
||||
.modal-body .btn-confirm { background: #e74c3c; color: #fff; }
|
||||
|
||||
@media(min-width:600px) {
|
||||
.tx-list { max-width: 600px; margin: 0 auto; }
|
||||
.stats { max-width: 600px; margin: 0 auto; }
|
||||
.toolbar { max-width: 600px; margin: 0 auto; }
|
||||
@media(max-width:640px){
|
||||
.header{padding:14px 12px 10px;text-align:left}
|
||||
.header h1{font-size:20px;margin-right:90px}
|
||||
.header .subtitle{font-size:12px;margin-right:90px}
|
||||
.logout-btn{right:10px;top:14px;transform:none;padding:4px 10px;font-size:12px}
|
||||
.stats{grid-template-columns:1fr;padding:12px}
|
||||
.stat-card{text-align:left;padding:12px}
|
||||
.toolbar{padding:0 12px 10px}
|
||||
.toolbar .spacer{display:none}
|
||||
.toolbar a,.filter-select{flex:1 1 calc(50% - 4px);text-align:center}
|
||||
#flagsPanel{margin:0 12px 12px}
|
||||
.tx-list{padding:0 12px 72px}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="header">
|
||||
<h1>🦞 虾记记账</h1>
|
||||
<div class="subtitle">Xiaji-Go 记账管理</div>
|
||||
<a href="/logout" class="logout-btn" title="退出登录">退出</a>
|
||||
<div class="subtitle">{{.version}}</div>
|
||||
<a href="/logout" class="logout-btn">退出</a>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat-card">
|
||||
<div class="num" id="todayTotal">0.00</div>
|
||||
<div class="label">今日支出</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="num" id="monthTotal">0.00</div>
|
||||
<div class="label">本月支出</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="num" id="txCount">0</div>
|
||||
<div class="label">总记录数</div>
|
||||
</div>
|
||||
<div class="stat-card"><div class="num" id="todayTotal">0.00</div><div class="label">今日支出</div></div>
|
||||
<div class="stat-card"><div class="num" id="monthTotal">0.00</div><div class="label">本月支出</div></div>
|
||||
<div class="stat-card"><div class="num" id="txCount">0</div><div class="label">总记录数</div></div>
|
||||
</div>
|
||||
|
||||
<div class="toolbar">
|
||||
<select class="filter-select" id="catFilter" onchange="filterList()">
|
||||
<option value="">全部分类</option>
|
||||
</select>
|
||||
<select class="filter-select" id="catFilter" onchange="filterList()"><option value="">全部分类</option></select>
|
||||
<select class="filter-select" id="scopeFilter" onchange="loadData()" style="display:none;"><option value="self">仅本人</option><option value="all">全员</option></select>
|
||||
<div class="spacer"></div>
|
||||
<a href="/export">📥 导出CSV</a>
|
||||
<a href="#" id="btnFlags" style="display:none;">⚙️ 高级功能</a>
|
||||
<a href="/audit" id="btnAudit" style="display:none;">🧾 审计日志</a>
|
||||
<a href="/channels" id="btnChannels" style="display:none;">🔌 渠道配置</a>
|
||||
<a href="#" id="btnExport">📥 导出CSV</a>
|
||||
</div>
|
||||
|
||||
<div id="flagsPanel">
|
||||
<div style="font-weight:600;margin-bottom:8px;">高级功能开关(高风险默认关闭)</div>
|
||||
<div id="flagsList"></div>
|
||||
</div>
|
||||
|
||||
<div class="tx-list" id="txList"></div>
|
||||
@@ -103,36 +99,99 @@ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-
|
||||
<h3>确认删除?</h3>
|
||||
<p id="delInfo" style="font-size:13px;color:#666;"></p>
|
||||
<div class="btns">
|
||||
<button class="btn-cancel" onclick="closeModal()">取消</button>
|
||||
<button class="btn-confirm" onclick="confirmDelete()">删除</button>
|
||||
<button onclick="closeModal()">取消</button>
|
||||
<button style="background:#e74c3c;color:#fff" onclick="confirmDelete()">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const catIcons={ '餐饮':'🍜','交通':'🚗','购物':'🛒','娱乐':'🎮','住房':'🏠','通讯':'📱','医疗':'💊','教育':'📚','其他':'📦' };
|
||||
let allData = [];
|
||||
let deleteId = null;
|
||||
let allData=[],deleteId=null,me=null,flags=[];
|
||||
function esc(s){return String(s||'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}
|
||||
|
||||
async function loadMe(){ const r=await fetch('/api/v1/me'); if(!r.ok) throw new Error('读取用户信息失败'); me=await r.json(); }
|
||||
|
||||
function initPermissionUI(){
|
||||
const caps=(me&&me.effective_capabilities)||{};
|
||||
const scopeSel=document.getElementById('scopeFilter');
|
||||
const btnChannels=document.getElementById('btnChannels');
|
||||
const btnAudit=document.getElementById('btnAudit');
|
||||
const btnFlags=document.getElementById('btnFlags');
|
||||
|
||||
scopeSel.style.display=(caps.can_read_all || (me.flags&&me.flags.allow_cross_user_read===false)) ? '' : 'none';
|
||||
btnChannels.style.display=caps.can_view_channels ? '' : 'none';
|
||||
btnAudit.style.display=caps.can_view_audit ? '' : 'none';
|
||||
btnFlags.style.display=caps.can_view_flags ? '' : 'none';
|
||||
|
||||
btnFlags.onclick=async (e)=>{
|
||||
e.preventDefault();
|
||||
const p=document.getElementById('flagsPanel');
|
||||
p.style.display=(p.style.display==='none'||!p.style.display)?'block':'none';
|
||||
if(p.style.display==='block'){ await loadFlags(); renderFlags(); }
|
||||
};
|
||||
|
||||
document.getElementById('btnExport').onclick=(e)=>{
|
||||
e.preventDefault();
|
||||
const scope=document.getElementById('scopeFilter').value||'self';
|
||||
if(scope==='all'&&!caps.can_export_all){ alert('没有导出全员权限或开关未启用'); return; }
|
||||
if(scope==='self'&&!caps.can_export_self){ alert('没有导出本人权限'); return; }
|
||||
window.location.href='/api/v1/export?scope='+encodeURIComponent(scope);
|
||||
};
|
||||
}
|
||||
|
||||
async function loadFlags(){
|
||||
const caps=(me&&me.effective_capabilities)||{};
|
||||
if(!caps.can_view_flags) return;
|
||||
const r=await fetch('/api/v1/admin/settings/flags');
|
||||
const data=await r.json();
|
||||
flags=Array.isArray(data)?data:[];
|
||||
}
|
||||
|
||||
function renderFlags(){
|
||||
const list=document.getElementById('flagsList');
|
||||
const caps=(me&&me.effective_capabilities)||{};
|
||||
list.innerHTML=flags.map(f=>{
|
||||
const disabled=!caps.can_edit_flags?'disabled':'';
|
||||
return `<label style="display:flex;align-items:center;justify-content:space-between;border:1px solid #eef2f7;border-radius:8px;padding:8px 10px;">
|
||||
<span><strong>${esc(f.key)}</strong><br><small>${esc(f.description||'')}(${esc(f.risk_level||'unknown')})</small></span>
|
||||
<input type="checkbox" ${f.enabled?'checked':''} ${disabled} onchange="toggleFlag('${esc(f.key)}',this.checked)">
|
||||
</label>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function toggleFlag(key,enabled){
|
||||
const caps=(me&&me.effective_capabilities)||{};
|
||||
if(!caps.can_edit_flags){ alert('无修改权限'); return; }
|
||||
const reason=prompt('请输入修改原因(审计必填)')||'';
|
||||
const r=await fetch('/api/v1/admin/settings/flags/'+encodeURIComponent(key),{
|
||||
method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled,reason})
|
||||
});
|
||||
const out=await r.json().catch(()=>({}));
|
||||
if(!r.ok){ alert(out.error||'修改失败'); }
|
||||
await loadMe(); await loadFlags(); renderFlags();
|
||||
}
|
||||
|
||||
async function loadData(){
|
||||
try{
|
||||
const r = await fetch('/api/records');
|
||||
const caps=(me&&me.effective_capabilities)||{};
|
||||
const scopeEl=document.getElementById('scopeFilter');
|
||||
let scope=scopeEl.value||'self';
|
||||
if(scope==='all'&&!caps.can_read_all){ alert('没有查看全员数据权限或开关未启用'); scope='self'; scopeEl.value='self'; }
|
||||
const r=await fetch('/api/v1/records?scope='+encodeURIComponent(scope));
|
||||
allData=await r.json();
|
||||
if(!Array.isArray(allData)) allData=[];
|
||||
renderStats();
|
||||
renderList(allData);
|
||||
populateFilter();
|
||||
} catch(e) { console.error(e); }
|
||||
renderStats(); renderList(allData); populateFilter();
|
||||
}catch(e){
|
||||
console.error(e);
|
||||
document.getElementById('txList').innerHTML='<div class="empty"><div class="icon">⚠️</div>数据加载失败</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderStats(){
|
||||
const today = new Date().toISOString().slice(0,10);
|
||||
const month = today.slice(0,7);
|
||||
const today=new Date().toISOString().slice(0,10), month=today.slice(0,7);
|
||||
let todaySum=0,monthSum=0;
|
||||
allData.forEach(tx => {
|
||||
if (tx.date === today) todaySum += tx.amount;
|
||||
if (tx.date && tx.date.startsWith(month)) monthSum += tx.amount;
|
||||
});
|
||||
allData.forEach(tx=>{ const amt=Number(tx.amount||0); if(tx.date===today) todaySum+=amt; if(tx.date&&tx.date.startsWith(month)) monthSum+=amt; });
|
||||
document.getElementById('todayTotal').textContent=todaySum.toFixed(2);
|
||||
document.getElementById('monthTotal').textContent=monthSum.toFixed(2);
|
||||
document.getElementById('txCount').textContent=allData.length;
|
||||
@@ -140,58 +199,39 @@ function renderStats() {
|
||||
|
||||
function renderList(data){
|
||||
const el=document.getElementById('txList');
|
||||
if (!data.length) {
|
||||
el.innerHTML = '<div class="empty"><div class="icon">📭</div>暂无记录<br><small>通过 Telegram/QQ 发送消息记账</small></div>';
|
||||
return;
|
||||
}
|
||||
const caps=(me&&me.effective_capabilities)||{};
|
||||
if(!data.length){ el.innerHTML='<div class="empty"><div class="icon">📭</div>暂无记录<br><small>通过 Telegram/QQ 发送消息记账</small></div>'; return; }
|
||||
el.innerHTML=data.map(tx=>{
|
||||
const icon = catIcons[tx.category] || '📦';
|
||||
const catClass = 'cat-' + (tx.category || '其他');
|
||||
return `<div class="tx-card">
|
||||
<div class="tx-icon ${catClass}">${icon}</div>
|
||||
<div class="tx-info">
|
||||
<div class="tx-category">${tx.category || '其他'}</div>
|
||||
<div class="tx-note" title="${esc(tx.note)}">${esc(tx.note)}</div>
|
||||
</div>
|
||||
<div class="tx-right">
|
||||
<div class="tx-amount">-${tx.amount.toFixed(2)}</div>
|
||||
<div class="tx-date">${tx.date}</div>
|
||||
<div class="tx-actions"><button class="btn-del" onclick="showDelete(${tx.id},'${esc(tx.note)}',${tx.amount})">删除</button></div>
|
||||
</div>
|
||||
</div>`;
|
||||
const icon=catIcons[tx.category]||'📦', cls='cat-'+(tx.category||'其他');
|
||||
const amount=Number(tx.amount||0), note=esc(tx.note), canDelete=caps.can_delete_self||caps.can_delete_all;
|
||||
const delBtn=canDelete ? `<button class="btn-del" onclick="showDelete(${tx.id},'${note.replace(/'/g,"'")}',${amount})">删除</button>` : `<button class="btn-del" style="opacity:.45;cursor:not-allowed;" onclick="alert('无删除权限')">删除</button>`;
|
||||
return `<div class="tx-card"><div class="tx-icon ${cls}">${icon}</div><div class="tx-info"><div class="tx-category">${esc(tx.category||'其他')}</div><div class="tx-note" title="${note}">${note}</div></div><div class="tx-right"><div class="tx-amount">-${amount.toFixed(2)}</div><div class="tx-date">${esc(tx.date||'')}</div>${delBtn}</div></div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function esc(s) { return String(s||'').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||||
|
||||
function populateFilter(){
|
||||
const cats = [...new Set(allData.map(t => t.category))].sort();
|
||||
const sel = document.getElementById('catFilter');
|
||||
const cur = sel.value;
|
||||
sel.innerHTML = '<option value="">全部分类</option>' + cats.map(c => `<option value="${c}">${c}</option>`).join('');
|
||||
const cats=[...new Set(allData.map(t=>t.category).filter(Boolean))].sort();
|
||||
const sel=document.getElementById('catFilter'), cur=sel.value;
|
||||
sel.innerHTML='<option value="">全部分类</option>'+cats.map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('');
|
||||
sel.value=cur;
|
||||
}
|
||||
|
||||
function filterList() {
|
||||
const cat = document.getElementById('catFilter').value;
|
||||
renderList(cat ? allData.filter(t => t.category === cat) : allData);
|
||||
}
|
||||
|
||||
function showDelete(id, note, amount) {
|
||||
deleteId = id;
|
||||
document.getElementById('delInfo').textContent = `${note} (${amount.toFixed(2)}元)`;
|
||||
document.getElementById('delModal').classList.add('show');
|
||||
}
|
||||
function filterList(){ const cat=document.getElementById('catFilter').value; renderList(cat?allData.filter(t=>t.category===cat):allData); }
|
||||
function showDelete(id,note,amount){ deleteId=id; document.getElementById('delInfo').textContent=`${note} (${Number(amount).toFixed(2)}元)`; document.getElementById('delModal').classList.add('show'); }
|
||||
function closeModal(){ document.getElementById('delModal').classList.remove('show'); deleteId=null; }
|
||||
|
||||
async function confirmDelete(){
|
||||
if(!deleteId) return;
|
||||
await fetch('/delete/' + deleteId, { method: 'POST' });
|
||||
closeModal();
|
||||
loadData();
|
||||
const r=await fetch('/api/v1/records/'+deleteId+'/delete',{method:'POST'});
|
||||
const out=await r.json().catch(()=>({}));
|
||||
if(!r.ok) alert(out.error||'删除失败');
|
||||
closeModal(); loadData();
|
||||
}
|
||||
|
||||
loadData();
|
||||
setInterval(loadData, 30000);
|
||||
(async function(){
|
||||
try{ await loadMe(); initPermissionUI(); await loadData(); setInterval(loadData,30000); }
|
||||
catch(e){ console.error(e); document.getElementById('txList').innerHTML='<div class="empty"><div class="icon">⚠️</div>页面初始化失败</div>'; }
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -103,7 +103,7 @@ body {
|
||||
<div class="login-logo">
|
||||
<div class="icon">🦞</div>
|
||||
<h1>虾记记账</h1>
|
||||
<div class="subtitle">Xiaji-Go 管理后台</div>
|
||||
<div class="subtitle">{{.version}}</div>
|
||||
</div>
|
||||
|
||||
{{if .error}}
|
||||
|
||||
Reference in New Issue
Block a user