1、优化营收分析,修复当前月没有推广数据时,当前月数据不显示的缺陷;

This commit is contained in:
chenlin 2025-03-04 16:34:10 +08:00
parent 5ff7aeab26
commit caa48b88f5

View File

@ -2165,19 +2165,55 @@ func (e MiGuDeployService) CalculateRevenueAnalysis(c *gin.Context) {
// return // return
//} //}
// 确保有数据
if len(result) <= 0 {
resp := models.RetentionMonthsResp{}
response.OK(c, resp, "查询成功")
}
earliestMonth := result[0].Month // 从查询结果中获取最早的月份
currentMonth := time.Now().Format("2006-01") // 获取当前月份
// 生成所有月份列表
allMonths := generateMonthRange(earliestMonth, currentMonth)
// 用 map 记录已有数据
monthMap := make(map[string]models.MonthlyRetention)
for _, data := range result {
monthMap[data.Month] = data
}
// 确保所有月份都有数据
var completeResult []models.MonthlyRetention
for _, month := range allMonths {
if data, exists := monthMap[month]; exists {
completeResult = append(completeResult, data)
} else {
// 补全没有数据的月份
completeResult = append(completeResult, models.MonthlyRetention{
Month: month,
NewUserCount: 0,
ValidUsersCount: 0,
RetainedUsersCount: 0,
TotalValidUsersCount: 0,
})
}
}
result = completeResult // 更新最终结果
// 查询每个月的上个月未退订用户数 // 查询每个月的上个月未退订用户数
for i := 0; i < len(result); i++ { for i := 0; i < len(result); i++ {
currentMonth := result[i].Month tempCurrentMonth := result[i].Month
// 查询当前月之前所有月份未退订的用户数 // 查询当前月之前所有月份未退订的用户数
totalValidUsers, err := GetTotalValidUsers(e.Orm, currentMonth) totalValidUsers, err := GetTotalValidUsers(e.Orm, tempCurrentMonth)
if err != nil { if err != nil {
response.Error(c, http.StatusInternalServerError, err, "未退订用户查询失败") response.Error(c, http.StatusInternalServerError, err, "未退订用户查询失败")
return return
} }
// 查询当前月之前所有月份在本月2号之后退订的用户数 // 查询当前月之前所有月份在本月2号之后退订的用户数
totalUnsubscribedUsers, err := GetTotalUnsubscribedUsers(e.Orm, currentMonth) totalUnsubscribedUsers, err := GetTotalUnsubscribedUsers(e.Orm, tempCurrentMonth)
if err != nil { if err != nil {
response.Error(c, http.StatusInternalServerError, err, "退订用户查询失败") response.Error(c, http.StatusInternalServerError, err, "退订用户查询失败")
return return
@ -2237,6 +2273,18 @@ func (e MiGuDeployService) CalculateRevenueAnalysis(c *gin.Context) {
response.OK(c, resp, "查询成功") response.OK(c, resp, "查询成功")
} }
// 生成从 start 到 end 之间的所有月份
func generateMonthRange(start, end string) []string {
startTime, _ := time.Parse("2006-01", start)
endTime, _ := time.Parse("2006-01", end)
var months []string
for t := startTime; !t.After(endTime); t = t.AddDate(0, 1, 0) {
months = append(months, t.Format("2006-01"))
}
return months
}
// GetTotalValidUsers 计算所有之前月份的未退订用户总数 // GetTotalValidUsers 计算所有之前月份的未退订用户总数
func GetTotalValidUsers(db *gorm.DB, currentMonth string) (int, error) { func GetTotalValidUsers(db *gorm.DB, currentMonth string) (int, error) {
var totalValidUsers int var totalValidUsers int