You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_dashbord.go 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. package repo
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. "os"
  8. "path"
  9. "strconv"
  10. "time"
  11. "github.com/360EntSecGroup-Skylar/excelize/v2"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/setting"
  16. )
  17. const DEFAULT_PAGE_SIZE = 10
  18. const DATE_FORMAT = "2006-01-02"
  19. const EXCEL_DATE_FORMAT = "20060102"
  20. type ProjectsPeriodData struct {
  21. RecordBeginTime string `json:"recordBeginTime"`
  22. LastUpdatedTime string `json:"lastUpdatedTime"`
  23. PageSize int `json:"pageSize"`
  24. TotalPage int `json:"totalPage"`
  25. TotalCount int64 `json:"totalCount"`
  26. PageRecords []*models.RepoStatistic `json:"pageRecords"`
  27. }
  28. type UserInfo struct {
  29. User string `json:"user"`
  30. Mode int `json:"mode"`
  31. PR int64 `json:"pr"`
  32. Commit int `json:"commit"`
  33. RelAvatarLink string `json:"relAvatarLink"`
  34. Email string `json:"email"`
  35. }
  36. type ProjectLatestData struct {
  37. RecordBeginTime string `json:"recordBeginTime"`
  38. LastUpdatedTime string `json:"lastUpdatedTime"`
  39. CreatTime string `json:"creatTime"`
  40. OpenI float64 `json:"openi"`
  41. Comment int64 `json:"comment"`
  42. View int64 `json:"view"`
  43. Download int64 `json:"download"`
  44. IssueClosedRatio float32 `json:"issueClosedRatio"`
  45. Impact float64 `json:"impact"`
  46. Completeness float64 `json:"completeness"`
  47. Liveness float64 `json:"liveness"`
  48. ProjectHealth float64 `json:"projectHealth"`
  49. TeamHealth float64 `json:"teamHealth"`
  50. Growth float64 `json:"growth"`
  51. Description string `json:"description"`
  52. Top10 []UserInfo `json:"top10"`
  53. }
  54. func RestoreForkNumber(ctx *context.Context) {
  55. repos, err := models.GetAllRepositories()
  56. if err != nil {
  57. log.Error("GetAllRepositories failed: %v", err.Error())
  58. return
  59. }
  60. for _, repo := range repos {
  61. models.RestoreRepoStatFork(int64(repo.NumForks), repo.ID)
  62. }
  63. ctx.JSON(http.StatusOK, struct{}{})
  64. }
  65. func GetAllProjectsPeriodStatistics(ctx *context.Context) {
  66. recordBeginTime, err := getRecordBeginTime()
  67. if err != nil {
  68. log.Error("Can not get record begin time", err)
  69. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  70. return
  71. }
  72. beginTime, endTime, err := getTimePeroid(ctx, recordBeginTime)
  73. if err != nil {
  74. log.Error("Parameter is wrong", err)
  75. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.parameter_is_wrong"))
  76. return
  77. }
  78. q := ctx.QueryTrim("q")
  79. page := ctx.QueryInt("page")
  80. if page <= 0 {
  81. page = 1
  82. }
  83. pageSize := ctx.QueryInt("pagesize")
  84. if pageSize <= 0 {
  85. pageSize = DEFAULT_PAGE_SIZE
  86. }
  87. orderBy := getOrderBy(ctx)
  88. latestUpdatedTime, latestDate, err := models.GetRepoStatLastUpdatedTime()
  89. if err != nil {
  90. log.Error("Can not query the last updated time.", err)
  91. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.last_update_time_error"))
  92. return
  93. }
  94. countSql := generateCountSql(beginTime, endTime, latestDate, q)
  95. total, err := models.CountRepoStatByRawSql(countSql)
  96. if err != nil {
  97. log.Error("Can not query total count.", err)
  98. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.total_count_get_error"))
  99. return
  100. }
  101. sql := generateSqlByType(ctx, beginTime, endTime, latestDate, q, orderBy, page, pageSize)
  102. projectsPeriodData := ProjectsPeriodData{
  103. RecordBeginTime: recordBeginTime.Format(DATE_FORMAT),
  104. PageSize: pageSize,
  105. TotalPage: getTotalPage(total, pageSize),
  106. TotalCount: total,
  107. LastUpdatedTime: latestUpdatedTime,
  108. PageRecords: models.GetRepoStatisticByRawSql(sql),
  109. }
  110. ctx.JSON(http.StatusOK, projectsPeriodData)
  111. }
  112. func generateSqlByType(ctx *context.Context, beginTime time.Time, endTime time.Time, latestDate string, q string, orderBy string, page int, pageSize int) string {
  113. sql := ""
  114. if ctx.QueryTrim("type") == "all" {
  115. sql = generateTypeAllSql(beginTime, endTime, latestDate, q, orderBy, page, pageSize)
  116. } else {
  117. sql = generatePageSql(beginTime, endTime, latestDate, q, orderBy, page, pageSize)
  118. }
  119. return sql
  120. }
  121. func ServeAllProjectsPeriodStatisticsFile(ctx *context.Context) {
  122. recordBeginTime, err := getRecordBeginTime()
  123. if err != nil {
  124. log.Error("Can not get record begin time", err)
  125. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  126. return
  127. }
  128. beginTime, endTime, err := getTimePeroid(ctx, recordBeginTime)
  129. if err != nil {
  130. log.Error("Parameter is wrong", err)
  131. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.parameter_is_wrong"))
  132. return
  133. }
  134. q := ctx.QueryTrim("q")
  135. page := ctx.QueryInt("page")
  136. if page <= 0 {
  137. page = 1
  138. }
  139. pageSize := 1000
  140. orderBy := getOrderBy(ctx)
  141. _, latestDate, err := models.GetRepoStatLastUpdatedTime()
  142. if err != nil {
  143. log.Error("Can not query the last updated time.", err)
  144. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.last_update_time_error"))
  145. return
  146. }
  147. countSql := generateCountSql(beginTime, endTime, latestDate, q)
  148. total, err := models.CountRepoStatByRawSql(countSql)
  149. if err != nil {
  150. log.Error("Can not query total count.", err)
  151. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.total_count_get_error"))
  152. return
  153. }
  154. var projectAnalysis = ctx.Tr("repo.repo_stat_inspect")
  155. fileName, frontName := getFileName(ctx, beginTime, endTime, projectAnalysis)
  156. if err := os.MkdirAll(setting.RadarMap.Path, os.ModePerm); err != nil {
  157. ctx.Error(http.StatusBadRequest, fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err).Error())
  158. }
  159. totalPage := getTotalPage(total, pageSize)
  160. f := excelize.NewFile()
  161. index := f.NewSheet(projectAnalysis)
  162. for k, v := range allProjectsPeroidHeader(ctx) {
  163. f.SetCellValue(projectAnalysis, k, v)
  164. }
  165. var row = 2
  166. for i := 0; i <= totalPage; i++ {
  167. pageRecords := models.GetRepoStatisticByRawSql(generateSqlByType(ctx, beginTime, endTime, latestDate, q, orderBy, i+1, pageSize))
  168. for _, record := range pageRecords {
  169. for k, v := range allProjectsPeroidValues(row, record, ctx) {
  170. f.SetCellValue(projectAnalysis, k, v)
  171. }
  172. row++
  173. }
  174. }
  175. f.SetActiveSheet(index)
  176. f.DeleteSheet("Sheet1")
  177. if err := f.SaveAs(fileName); err != nil {
  178. log.Error("Can not generate file.", err)
  179. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.generate_statistic_file_error"))
  180. return
  181. }
  182. ctx.ServeFile(fileName, url.QueryEscape(frontName))
  183. }
  184. func getFileName(ctx *context.Context, beginTime time.Time, endTime time.Time, projectAnalysis string) (string, string) {
  185. baseName := setting.RadarMap.Path + "/" + projectAnalysis + "_"
  186. if ctx.QueryTrim("q") != "" {
  187. baseName = baseName + ctx.QueryTrim("q") + "_"
  188. }
  189. if ctx.QueryTrim("type") == "all" {
  190. baseName = baseName + ctx.Tr("repo.all")
  191. } else {
  192. baseName = baseName + beginTime.AddDate(0, 0, -1).Format(EXCEL_DATE_FORMAT) + "_" + endTime.AddDate(0, 0, -1).Format(EXCEL_DATE_FORMAT)
  193. }
  194. frontName := baseName + ".xlsx"
  195. localName := baseName + "_" + strconv.FormatInt(time.Now().Unix(), 10) + ".xlsx"
  196. return localName, path.Base(frontName)
  197. }
  198. func ClearUnusedStatisticsFile() {
  199. fileInfos, err := ioutil.ReadDir(setting.RadarMap.Path)
  200. if err != nil {
  201. log.Warn("can not read dir: "+setting.RadarMap.Path, err)
  202. return
  203. }
  204. for _, fileInfo := range fileInfos {
  205. if !fileInfo.IsDir() && fileInfo.ModTime().Before(time.Now().AddDate(0, 0, -1)) {
  206. os.Remove(path.Join(setting.RadarMap.Path, fileInfo.Name()))
  207. }
  208. }
  209. }
  210. func allProjectsPeroidHeader(ctx *context.Context) map[string]string {
  211. return map[string]string{"A1": ctx.Tr("admin.repos.id"), "B1": ctx.Tr("admin.repos.projectName"), "C1": ctx.Tr("admin.repos.isPrivate"), "D1": ctx.Tr("admin.repos.openi"), "E1": ctx.Tr("admin.repos.visit"), "F1": ctx.Tr("admin.repos.download"), "G1": ctx.Tr("admin.repos.pr"), "H1": ctx.Tr("admin.repos.commit"),
  212. "I1": ctx.Tr("admin.repos.watches"), "J1": ctx.Tr("admin.repos.stars"), "K1": ctx.Tr("admin.repos.forks"), "L1": ctx.Tr("admin.repos.issues"), "M1": ctx.Tr("admin.repos.closedIssues"), "N1": ctx.Tr("admin.repos.contributor")}
  213. }
  214. func allProjectsPeroidValues(row int, rs *models.RepoStatistic, ctx *context.Context) map[string]string {
  215. return map[string]string{getCellName("A", row): strconv.FormatInt(rs.RepoID, 10), getCellName("B", row): constructDistinctName(rs), getCellName("C", row): getIsPrivateDisplay(rs.IsPrivate, ctx), getCellName("D", row): strconv.FormatFloat(rs.RadarTotal, 'f', 2, 64),
  216. getCellName("E", row): strconv.FormatInt(rs.NumVisits, 10), getCellName("F", row): strconv.FormatInt(rs.NumDownloads, 10), getCellName("G", row): strconv.FormatInt(rs.NumPulls, 10), getCellName("H", row): strconv.FormatInt(rs.NumCommits, 10),
  217. getCellName("I", row): strconv.FormatInt(rs.NumWatches, 10), getCellName("J", row): strconv.FormatInt(rs.NumStars, 10), getCellName("K", row): strconv.FormatInt(rs.NumForks, 10), getCellName("L", row): strconv.FormatInt(rs.NumIssues, 10),
  218. getCellName("M", row): strconv.FormatInt(rs.NumClosedIssues, 10), getCellName("N", row): strconv.FormatInt(rs.NumContributor, 10),
  219. }
  220. }
  221. func getCellName(col string, row int) string {
  222. return col + strconv.Itoa(row)
  223. }
  224. func constructDistinctName(rs *models.RepoStatistic) string {
  225. if rs.OwnerName == "" {
  226. return rs.Name
  227. }
  228. return rs.OwnerName + "/" + rs.Name
  229. }
  230. func getIsPrivateDisplay(private bool, ctx *context.Context) string {
  231. if private {
  232. return ctx.Tr("admin.repos.yes")
  233. } else {
  234. return ctx.Tr("admin.repos.no")
  235. }
  236. }
  237. func GetProjectLatestStatistics(ctx *context.Context) {
  238. repoId := ctx.Params(":id")
  239. recordBeginTime, err := getRecordBeginTime()
  240. if err != nil {
  241. log.Error("Can not get record begin time", err)
  242. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  243. return
  244. }
  245. latestUpdatedTime, latestDate, err := models.GetRepoStatLastUpdatedTime(repoId)
  246. repoIdInt, _ := strconv.ParseInt(repoId, 10, 64)
  247. repoStat, err := models.GetRepoStatisticByDateAndRepoId(latestDate, repoIdInt)
  248. if err != nil {
  249. log.Error("Can not get the repo statistics "+repoId, err)
  250. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.get_repo_stat_error"))
  251. return
  252. }
  253. repository, err := models.GetRepositoryByID(repoIdInt)
  254. if err != nil {
  255. log.Error("Can not get the repo info "+repoId, err)
  256. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.get_repo_info_error"))
  257. return
  258. }
  259. projectLatestData := ProjectLatestData{
  260. RecordBeginTime: recordBeginTime.Format(DATE_FORMAT),
  261. CreatTime: time.Unix(int64(repository.CreatedUnix), 0).Format(DATE_FORMAT),
  262. LastUpdatedTime: latestUpdatedTime,
  263. OpenI: repoStat.RadarTotal,
  264. Comment: repoStat.NumComments,
  265. View: repoStat.NumVisits,
  266. Download: repoStat.NumDownloads,
  267. IssueClosedRatio: repoStat.IssueFixedRate,
  268. Impact: repoStat.Impact,
  269. Completeness: repoStat.Completeness,
  270. Liveness: repoStat.Liveness,
  271. ProjectHealth: repoStat.ProjectHealth,
  272. TeamHealth: repoStat.TeamHealth,
  273. Growth: repoStat.Growth,
  274. Description: repository.Description,
  275. }
  276. contributors, err := models.GetTop10Contributor(repository.RepoPath())
  277. if err != nil {
  278. log.Error("can not get contributors", err)
  279. }
  280. users := make([]UserInfo, 0)
  281. for _, contributor := range contributors {
  282. mode := repository.GetCollaboratorMode(contributor.UserId)
  283. if mode == -1 {
  284. if contributor.IsAdmin {
  285. mode = int(models.AccessModeAdmin)
  286. }
  287. if contributor.UserId == repository.OwnerID {
  288. mode = int(models.AccessModeOwner)
  289. }
  290. }
  291. pr := models.GetPullCountByUserAndRepoId(repoIdInt, contributor.UserId)
  292. userInfo := UserInfo{
  293. User: contributor.Committer,
  294. Commit: contributor.CommitCnt,
  295. Mode: mode,
  296. PR: pr,
  297. RelAvatarLink: contributor.RelAvatarLink,
  298. }
  299. users = append(users, userInfo)
  300. }
  301. projectLatestData.Top10 = users
  302. ctx.JSON(http.StatusOK, projectLatestData)
  303. }
  304. func GetProjectPeriodStatistics(ctx *context.Context) {
  305. repoId := ctx.Params(":id")
  306. recordBeginTime, err := getRecordBeginTime()
  307. if err != nil {
  308. log.Error("Can not get record begin time", err)
  309. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  310. return
  311. }
  312. repoIdInt, _ := strconv.ParseInt(repoId, 10, 64)
  313. if err != nil {
  314. log.Error("Can not get record begin time", err)
  315. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  316. return
  317. }
  318. beginTime, endTime, err := getTimePeroid(ctx, recordBeginTime)
  319. isOpenI := ctx.QueryBool("openi")
  320. var repositorys []*models.RepoStatistic
  321. if isOpenI {
  322. repositorys = models.GetRepoStatisticByRawSql(generateRadarSql(beginTime, endTime, repoIdInt))
  323. } else {
  324. repositorys = models.GetRepoStatisticByRawSql(generateTargetSql(beginTime, endTime, repoIdInt))
  325. }
  326. ctx.JSON(http.StatusOK, repositorys)
  327. }
  328. func generateRadarSql(beginTime time.Time, endTime time.Time, repoId int64) string {
  329. sql := "SELECT date, impact, completeness, liveness, project_health, team_health, growth, radar_total FROM repo_statistic" +
  330. " where repo_id=" + strconv.FormatInt(repoId, 10) + " and created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  331. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10)
  332. return sql
  333. }
  334. func generateTargetSql(beginTime time.Time, endTime time.Time, repoId int64) string {
  335. sql := "SELECT date, num_visits,num_downloads,num_commits FROM repo_statistic" +
  336. " where repo_id=" + strconv.FormatInt(repoId, 10) + " and created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  337. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10)
  338. return sql
  339. }
  340. func generateCountSql(beginTime time.Time, endTime time.Time, latestDate string, q string) string {
  341. countSql := "SELECT count(*) FROM " +
  342. "(SELECT repo_id FROM repo_statistic where created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  343. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " group by repo_id) A," +
  344. "(SELECT repo_id,name,is_private,radar_total from public.repo_statistic where date='" + latestDate + "') B" +
  345. " where A.repo_id=B.repo_id"
  346. if q != "" {
  347. countSql = countSql + " and B.name like '%" + q + "%'"
  348. }
  349. return countSql
  350. }
  351. func generateTypeAllSql(beginTime time.Time, endTime time.Time, latestDate string, q string, orderBy string, page int, pageSize int) string {
  352. sql := "SELECT A.repo_id,name,owner_name,is_private,radar_total,num_watches,num_visits,num_downloads,num_pulls,num_commits,num_stars,num_forks,num_issues,num_closed_issues,num_contributor FROM " +
  353. "(SELECT repo_id,sum(num_visits) as num_visits " +
  354. " FROM repo_statistic where created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  355. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " group by repo_id) A," +
  356. "(SELECT repo_id,name,owner_name,is_private,radar_total,num_watches,num_downloads,num_pulls,num_commits,num_stars,num_forks,num_issues,num_closed_issues,num_contributor from public.repo_statistic where date='" + latestDate + "') B" +
  357. " where A.repo_id=B.repo_id"
  358. if q != "" {
  359. sql = sql + " and name like '%" + q + "%'"
  360. }
  361. sql = sql + " order by " + orderBy + " desc,repo_id" + " limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa((page-1)*pageSize)
  362. return sql
  363. }
  364. func generatePageSql(beginTime time.Time, endTime time.Time, latestDate string, q string, orderBy string, page int, pageSize int) string {
  365. sql := "SELECT A.repo_id,name,owner_name,is_private,radar_total,num_watches,num_visits,num_downloads,num_pulls,num_commits,num_stars,num_forks,num_issues,num_closed_issues,num_contributor FROM " +
  366. "(SELECT repo_id,sum(num_watches_added) as num_watches,sum(num_visits) as num_visits, sum(num_downloads_added) as num_downloads,sum(num_pulls_added) as num_pulls,sum(num_commits_added) as num_commits,sum(num_stars_added) as num_stars,sum(num_forks_added) num_forks,sum(num_issues_added) as num_issues,sum(num_closed_issues_added) as num_closed_issues,sum(num_contributor_added) as num_contributor " +
  367. " FROM repo_statistic where created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  368. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " group by repo_id) A," +
  369. "(SELECT repo_id,name,owner_name,is_private,radar_total from public.repo_statistic where date='" + latestDate + "') B" +
  370. " where A.repo_id=B.repo_id"
  371. if q != "" {
  372. sql = sql + " and B.name like '%" + q + "%'"
  373. }
  374. sql = sql + " order by " + orderBy + " desc,A.repo_id" + " limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa((page-1)*pageSize)
  375. return sql
  376. }
  377. func getOrderBy(ctx *context.Context) string {
  378. orderBy := ""
  379. switch ctx.Query("sort") {
  380. case "openi":
  381. orderBy = "B.radar_total"
  382. case "view":
  383. orderBy = "A.num_visits"
  384. case "download":
  385. orderBy = "A.num_downloads"
  386. case "pr":
  387. orderBy = "A.num_pulls"
  388. case "commit":
  389. orderBy = "A.num_commits"
  390. case "watch":
  391. orderBy = "A.num_watches"
  392. case "star":
  393. orderBy = "A.num_stars"
  394. case "fork":
  395. orderBy = "A.num_forks"
  396. case "issue":
  397. orderBy = "A.num_issues"
  398. case "issue_closed":
  399. orderBy = "A.num_closed_issues"
  400. case "contributor":
  401. orderBy = "A.num_contributor"
  402. default:
  403. orderBy = "B.radar_total"
  404. }
  405. return orderBy
  406. }
  407. func getTimePeroid(ctx *context.Context, recordBeginTime time.Time) (time.Time, time.Time, error) {
  408. queryType := ctx.QueryTrim("type")
  409. now := time.Now()
  410. recordBeginTimeTemp := recordBeginTime.AddDate(0, 0, 1)
  411. beginTimeStr := ctx.QueryTrim("beginTime")
  412. endTimeStr := ctx.QueryTrim("endTime")
  413. var beginTime time.Time
  414. var endTime time.Time
  415. var err error
  416. if queryType != "" {
  417. if queryType == "all" {
  418. beginTime = recordBeginTimeTemp
  419. endTime = now
  420. } else if queryType == "yesterday" {
  421. endTime = now
  422. beginTime = time.Date(endTime.Year(), endTime.Month(), endTime.Day(), 0, 0, 0, 0, now.Location())
  423. } else if queryType == "current_week" {
  424. beginTime = now.AddDate(0, 0, -int(time.Now().Weekday())+2) //begin from monday
  425. beginTime = time.Date(beginTime.Year(), beginTime.Month(), beginTime.Day(), 0, 0, 0, 0, now.Location())
  426. endTime = now
  427. } else if queryType == "current_month" {
  428. endTime = now
  429. beginTime = time.Date(endTime.Year(), endTime.Month(), 2, 0, 0, 0, 0, now.Location())
  430. } else if queryType == "monthly" {
  431. endTime = now
  432. beginTime = now.AddDate(0, -1, 1)
  433. beginTime = time.Date(beginTime.Year(), beginTime.Month(), beginTime.Day(), 0, 0, 0, 0, now.Location())
  434. } else if queryType == "current_year" {
  435. endTime = now
  436. beginTime = time.Date(endTime.Year(), 1, 2, 0, 0, 0, 0, now.Location())
  437. } else if queryType == "last_month" {
  438. lastMonthTime := now.AddDate(0, -1, 0)
  439. beginTime = time.Date(lastMonthTime.Year(), lastMonthTime.Month(), 2, 0, 0, 0, 0, now.Location())
  440. endTime = time.Date(now.Year(), now.Month(), 2, 0, 0, 0, 0, now.Location())
  441. } else {
  442. return now, now, fmt.Errorf("The value of type parameter is wrong.")
  443. }
  444. } else {
  445. if beginTimeStr == "" || endTimeStr == "" {
  446. //如果查询类型和开始时间结束时间都未设置,按queryType=all处理
  447. beginTime = recordBeginTimeTemp
  448. endTime = now
  449. } else {
  450. beginTime, err = time.Parse("2006-01-02", beginTimeStr)
  451. if err != nil {
  452. return now, now, err
  453. }
  454. endTime, err = time.Parse("2006-01-02", endTimeStr)
  455. if err != nil {
  456. return now, now, err
  457. }
  458. beginTime = beginTime.AddDate(0, 0, 1)
  459. endTime = endTime.AddDate(0, 0, 1)
  460. }
  461. }
  462. if beginTime.Before(recordBeginTimeTemp) {
  463. beginTime = recordBeginTimeTemp
  464. }
  465. return beginTime, endTime, nil
  466. }
  467. func getRecordBeginTime() (time.Time, error) {
  468. return time.Parse(DATE_FORMAT, setting.RadarMap.RecordBeginTime)
  469. }
  470. func getTotalPage(total int64, pageSize int) int {
  471. another := 0
  472. if int(total)%pageSize != 0 {
  473. another = 1
  474. }
  475. return int(total)/pageSize + another
  476. }