GetUserStatistics 获取按用户统计的数据
(startTimestamp, endTimestamp int, username, tokenName, modelName string, channel int, group, defaultTime string)
| 266 | |
| 267 | // GetUserStatistics 获取按用户统计的数据 |
| 268 | func GetUserStatistics(startTimestamp, endTimestamp int, username, tokenName, modelName string, channel int, group, defaultTime string) ([]UserStatistics, error) { |
| 269 | var statistics []UserStatistics |
| 270 | |
| 271 | // 构建查询条件 |
| 272 | tx := LOG_DB.Table("logs").Select(` |
| 273 | created_at, |
| 274 | username, |
| 275 | COUNT(*) as count, |
| 276 | SUM(quota) as quota |
| 277 | `).Where("type = ?", 2) // LogTypeConsume = 2 |
| 278 | |
| 279 | if username != "" { |
| 280 | tx = tx.Where("username = ?", username) |
| 281 | } |
| 282 | if tokenName != "" { |
| 283 | tx = tx.Where("token_name = ?", tokenName) |
| 284 | } |
| 285 | if modelName != "" { |
| 286 | tx = tx.Where("model_name LIKE ?", "%"+modelName+"%") |
| 287 | } |
| 288 | if channel != 0 { |
| 289 | tx = tx.Where("channel_id = ?", channel) |
| 290 | } |
| 291 | if group != "" { |
| 292 | tx = tx.Where("`group` = ?", group) |
| 293 | } |
| 294 | if startTimestamp != 0 { |
| 295 | tx = tx.Where("created_at >= ?", startTimestamp) |
| 296 | } |
| 297 | if endTimestamp != 0 { |
| 298 | tx = tx.Where("created_at <= ?", endTimestamp) |
| 299 | } |
| 300 | |
| 301 | // 按时间粒度分组 - 使用数据库无关的函数 |
| 302 | var groupBy string |
| 303 | switch defaultTime { |
| 304 | case "hour": |
| 305 | if common.UsingMySQL { |
| 306 | groupBy = "username, DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d %H:00:00')" |
| 307 | } else if common.UsingPostgreSQL { |
| 308 | groupBy = "username, TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY-MM-DD HH24:00:00')" |
| 309 | } else { |
| 310 | // SQLite |
| 311 | groupBy = "username, strftime('%Y-%m-%d %H:00:00', datetime(created_at, 'unixepoch'))" |
| 312 | } |
| 313 | case "day": |
| 314 | if common.UsingMySQL { |
| 315 | groupBy = "username, DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d')" |
| 316 | } else if common.UsingPostgreSQL { |
| 317 | groupBy = "username, TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY-MM-DD')" |
| 318 | } else { |
| 319 | // SQLite |
| 320 | groupBy = "username, strftime('%Y-%m-%d', datetime(created_at, 'unixepoch'))" |
| 321 | } |
| 322 | case "week": |
| 323 | if common.UsingMySQL { |
| 324 | groupBy = "username, DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%U')" |
| 325 | } else if common.UsingPostgreSQL { |
no test coverage detected