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 25 kB

4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. package repo
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/360EntSecGroup-Skylar/excelize/v2"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/setting"
  14. )
  15. const DEFAULT_PAGE_SIZE = 10
  16. const DATE_FORMAT = "2006-01-02"
  17. const EXCEL_DATE_FORMAT = "20060102"
  18. type ProjectsPeriodData struct {
  19. RecordBeginTime string `json:"recordBeginTime"`
  20. LastUpdatedTime string `json:"lastUpdatedTime"`
  21. PageSize int `json:"pageSize"`
  22. TotalPage int `json:"totalPage"`
  23. TotalCount int64 `json:"totalCount"`
  24. PageRecords []*models.RepoStatistic `json:"pageRecords"`
  25. }
  26. type UserInfo struct {
  27. User string `json:"user"`
  28. Mode int `json:"mode"`
  29. PR int64 `json:"pr"`
  30. Commit int `json:"commit"`
  31. RelAvatarLink string `json:"relAvatarLink"`
  32. Email string `json:"email"`
  33. }
  34. type ProjectLatestData struct {
  35. RecordBeginTime string `json:"recordBeginTime"`
  36. LastUpdatedTime string `json:"lastUpdatedTime"`
  37. CreatTime string `json:"creatTime"`
  38. OpenI float64 `json:"openi"`
  39. Comment int64 `json:"comment"`
  40. View int64 `json:"view"`
  41. Download int64 `json:"download"`
  42. IssueClosedRatio float32 `json:"issueClosedRatio"`
  43. Impact float64 `json:"impact"`
  44. Completeness float64 `json:"completeness"`
  45. Liveness float64 `json:"liveness"`
  46. ProjectHealth float64 `json:"projectHealth"`
  47. TeamHealth float64 `json:"teamHealth"`
  48. Growth float64 `json:"growth"`
  49. Description string `json:"description"`
  50. Top10 []UserInfo `json:"top10"`
  51. }
  52. func RestoreForkNumber(ctx *context.Context) {
  53. repos, err := models.GetAllRepositories()
  54. if err != nil {
  55. log.Error("GetAllRepositories failed: %v", err.Error())
  56. return
  57. }
  58. for _, repo := range repos {
  59. models.RestoreRepoStatFork(int64(repo.NumForks), repo.ID)
  60. }
  61. ctx.JSON(http.StatusOK, struct{}{})
  62. }
  63. func GetAllProjectsPeriodStatistics(ctx *context.Context) {
  64. recordBeginTime, err := getRecordBeginTime()
  65. if err != nil {
  66. log.Error("Can not get record begin time", err)
  67. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  68. return
  69. }
  70. beginTime, endTime, err := getTimePeroid(ctx, recordBeginTime)
  71. if err != nil {
  72. log.Error("Parameter is wrong", err)
  73. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.parameter_is_wrong"))
  74. return
  75. }
  76. q := ctx.QueryTrim("q")
  77. page := ctx.QueryInt("page")
  78. if page <= 0 {
  79. page = 1
  80. }
  81. pageSize := ctx.QueryInt("pagesize")
  82. if pageSize <= 0 {
  83. pageSize = DEFAULT_PAGE_SIZE
  84. }
  85. orderBy := getOrderBy(ctx)
  86. latestUpdatedTime, latestDate, err := models.GetRepoStatLastUpdatedTime()
  87. if err != nil {
  88. log.Error("Can not query the last updated time.", err)
  89. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.last_update_time_error"))
  90. return
  91. }
  92. countSql := generateCountSql(beginTime, endTime, latestDate, q)
  93. total, err := models.CountRepoStatByRawSql(countSql)
  94. if err != nil {
  95. log.Error("Can not query total count.", err)
  96. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.total_count_get_error"))
  97. return
  98. }
  99. sql := generateSqlByType(ctx, beginTime, endTime, latestDate, q, orderBy, page, pageSize)
  100. projectsPeriodData := ProjectsPeriodData{
  101. RecordBeginTime: recordBeginTime.Format(DATE_FORMAT),
  102. PageSize: pageSize,
  103. TotalPage: getTotalPage(total, pageSize),
  104. TotalCount: total,
  105. LastUpdatedTime: latestUpdatedTime,
  106. PageRecords: models.GetRepoStatisticByRawSql(sql),
  107. }
  108. ctx.JSON(http.StatusOK, projectsPeriodData)
  109. }
  110. func generateSqlByType(ctx *context.Context, beginTime time.Time, endTime time.Time, latestDate string, q string, orderBy string, page int, pageSize int) string {
  111. sql := ""
  112. if ctx.QueryTrim("type") == "all" {
  113. sql = generateTypeAllSql(beginTime, endTime, latestDate, q, orderBy, page, pageSize)
  114. } else {
  115. sql = generatePageSql(beginTime, endTime, latestDate, q, orderBy, page, pageSize)
  116. }
  117. return sql
  118. }
  119. func ServeAllProjectsPeriodStatisticsFile(ctx *context.Context) {
  120. recordBeginTime, err := getRecordBeginTime()
  121. if err != nil {
  122. log.Error("Can not get record begin time", err)
  123. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  124. return
  125. }
  126. beginTime, endTime, err := getTimePeroid(ctx, recordBeginTime)
  127. if err != nil {
  128. log.Error("Parameter is wrong", err)
  129. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.parameter_is_wrong"))
  130. return
  131. }
  132. q := ctx.QueryTrim("q")
  133. page := ctx.QueryInt("page")
  134. if page <= 0 {
  135. page = 1
  136. }
  137. pageSize := 1000
  138. orderBy := getOrderBy(ctx)
  139. _, latestDate, err := models.GetRepoStatLastUpdatedTime()
  140. if err != nil {
  141. log.Error("Can not query the last updated time.", err)
  142. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.last_update_time_error"))
  143. return
  144. }
  145. countSql := generateCountSql(beginTime, endTime, latestDate, q)
  146. total, err := models.CountRepoStatByRawSql(countSql)
  147. if err != nil {
  148. log.Error("Can not query total count.", err)
  149. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.total_count_get_error"))
  150. return
  151. }
  152. var projectAnalysis = ctx.Tr("repo.repo_stat_inspect")
  153. fileName := getFileName(ctx, beginTime, endTime, projectAnalysis)
  154. totalPage := getTotalPage(total, pageSize)
  155. f := excelize.NewFile()
  156. index := f.NewSheet(projectAnalysis)
  157. f.DeleteSheet("Sheet1")
  158. for k, v := range allProjectsPeroidHeader(ctx) {
  159. f.SetCellValue(projectAnalysis, k, v)
  160. }
  161. var row = 2
  162. for i := 0; i <= totalPage; i++ {
  163. pageRecords := models.GetRepoStatisticByRawSql(generateSqlByType(ctx, beginTime, endTime, latestDate, q, orderBy, i+1, pageSize))
  164. for _, record := range pageRecords {
  165. for k, v := range allProjectsPeroidValues(row, record, ctx) {
  166. f.SetCellValue(projectAnalysis, k, v)
  167. }
  168. row++
  169. }
  170. }
  171. f.SetActiveSheet(index)
  172. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(fileName))
  173. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  174. f.WriteTo(ctx.Resp)
  175. }
  176. func ServeAllProjectsOpenIStatisticsFile(ctx *context.Context) {
  177. page := ctx.QueryInt("page")
  178. if page <= 0 {
  179. page = 1
  180. }
  181. pageSize := 1000
  182. _, latestDate, err := models.GetRepoStatLastUpdatedTime()
  183. if err != nil {
  184. log.Error("Can not query the last updated time.", err)
  185. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.last_update_time_error"))
  186. return
  187. }
  188. date := ctx.QueryTrim("date")
  189. if date == "" {
  190. date = latestDate
  191. }
  192. countSql := generateOpenICountSql(date)
  193. total, err := models.CountRepoStatByRawSql(countSql)
  194. if err != nil {
  195. log.Error("Can not query total count.", err)
  196. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.total_count_get_error"))
  197. return
  198. }
  199. var projectAnalysis = ctx.Tr("repo.repo_stat_inspect")
  200. fileName := "项目分析_OPENI_" + date + ".xlsx"
  201. totalPage := getTotalPage(total, pageSize)
  202. f := excelize.NewFile()
  203. index := f.NewSheet(projectAnalysis)
  204. f.DeleteSheet("Sheet1")
  205. for k, v := range allProjectsOpenIHeader() {
  206. f.SetCellValue(projectAnalysis, k, v)
  207. }
  208. var row = 2
  209. for i := 0; i <= totalPage; i++ {
  210. pageRecords := models.GetRepoStatisticByRawSql(generateTypeAllOpenISql(date, i+1, pageSize))
  211. for _, record := range pageRecords {
  212. for k, v := range allProjectsOpenIValues(row, record, ctx) {
  213. f.SetCellValue(projectAnalysis, k, v)
  214. }
  215. row++
  216. }
  217. }
  218. f.SetActiveSheet(index)
  219. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(fileName))
  220. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  221. f.WriteTo(ctx.Resp)
  222. }
  223. func getFileName(ctx *context.Context, beginTime time.Time, endTime time.Time, projectAnalysis string) string {
  224. baseName := projectAnalysis + "_"
  225. if ctx.QueryTrim("q") != "" {
  226. baseName = baseName + ctx.QueryTrim("q") + "_"
  227. }
  228. if ctx.QueryTrim("type") == "all" {
  229. baseName = baseName + ctx.Tr("repo.all")
  230. } else {
  231. baseName = baseName + beginTime.AddDate(0, 0, -1).Format(EXCEL_DATE_FORMAT) + "_" + endTime.AddDate(0, 0, -1).Format(EXCEL_DATE_FORMAT)
  232. }
  233. frontName := baseName + ".xlsx"
  234. return frontName
  235. }
  236. func allProjectsPeroidHeader(ctx *context.Context) map[string]string {
  237. return map[string]string{"A1": ctx.Tr("admin.repos.id"), "B1": ctx.Tr("admin.repos.projectName"), "C1": ctx.Tr("repo.owner"), "D1": ctx.Tr("admin.repos.isPrivate"), "E1": ctx.Tr("admin.repos.openi"), "F1": ctx.Tr("admin.repos.visit"), "G1": ctx.Tr("admin.repos.download"), "H1": ctx.Tr("admin.repos.pr"), "I1": ctx.Tr("admin.repos.commit"),
  238. "J1": ctx.Tr("admin.repos.watches"), "K1": ctx.Tr("admin.repos.stars"), "L1": ctx.Tr("admin.repos.forks"), "M1": ctx.Tr("admin.repos.issues"), "N1": ctx.Tr("admin.repos.closedIssues"), "O1": ctx.Tr("admin.repos.contributor")}
  239. }
  240. func allProjectsPeroidValues(row int, rs *models.RepoStatistic, ctx *context.Context) map[string]string {
  241. return map[string]string{getCellName("A", row): strconv.FormatInt(rs.RepoID, 10), getCellName("B", row): rs.Name, getCellName("C", row): rs.OwnerName, getCellName("D", row): getIsPrivateDisplay(rs.IsPrivate, ctx), getCellName("E", row): strconv.FormatFloat(rs.RadarTotal, 'f', 2, 64),
  242. getCellName("F", row): strconv.FormatInt(rs.NumVisits, 10), getCellName("G", row): strconv.FormatInt(rs.NumDownloads, 10), getCellName("H", row): strconv.FormatInt(rs.NumPulls, 10), getCellName("I", row): strconv.FormatInt(rs.NumCommits, 10),
  243. getCellName("J", row): strconv.FormatInt(rs.NumWatches, 10), getCellName("K", row): strconv.FormatInt(rs.NumStars, 10), getCellName("L", row): strconv.FormatInt(rs.NumForks, 10), getCellName("M", row): strconv.FormatInt(rs.NumIssues, 10),
  244. getCellName("N", row): strconv.FormatInt(rs.NumClosedIssues, 10), getCellName("O", row): strconv.FormatInt(rs.NumContributor, 10),
  245. }
  246. }
  247. func allProjectsOpenIHeader() map[string]string {
  248. return map[string]string{"A1": "ID", "B1": "项目名称", "C1": "拥有者", "D1": "是否私有", "E1": "OpenI指数",
  249. "F1": "影响力", "G1": "成熟度", "H1": "活跃度", "I1": "项目健康度", "J1": "团队健康度", "K1": "项目发展趋势",
  250. "L1": "关注数", "M1": "点赞数", "N1": "派生数", "O1": "代码下载量", "P1": "评论数", "Q1": "浏览量", "R1": "已解决任务数", "S1": "版本发布数量", "T1": "有效开发年龄",
  251. "U1": "数据集", "V1": "模型数", "W1": "百科页面数量", "X1": "提交数", "Y1": "任务数", "Z1": "PR数", "AA1": "版本发布数量", "AB1": "任务完成比例", "AC1": "贡献者数", "AD1": "关键贡献者数",
  252. "AE1": "新人增长量", "AF1": "代码规模增长量", "AG1": "任务增长量", "AH1": "新人增长量", "AI1": "提交增长量", "AJ1": "评论增长量",
  253. }
  254. }
  255. func allProjectsOpenIValues(row int, rs *models.RepoStatistic, ctx *context.Context) map[string]string {
  256. return map[string]string{getCellName("A", row): strconv.FormatInt(rs.RepoID, 10), getCellName("B", row): rs.Name, getCellName("C", row): rs.OwnerName, getCellName("D", row): getIsPrivateDisplay(rs.IsPrivate, ctx), getCellName("E", row): strconv.FormatFloat(rs.RadarTotal, 'f', 2, 64),
  257. getCellName("F", row): strconv.FormatFloat(rs.Impact, 'f', 2, 64), getCellName("G", row): strconv.FormatFloat(rs.Completeness, 'f', 2, 64), getCellName("H", row): strconv.FormatFloat(rs.Liveness, 'f', 2, 64), getCellName("I", row): strconv.FormatFloat(rs.ProjectHealth, 'f', 2, 64), getCellName("J", row): strconv.FormatFloat(rs.TeamHealth, 'f', 2, 64), getCellName("K", row): strconv.FormatFloat(rs.Growth, 'f', 2, 64),
  258. getCellName("L", row): strconv.FormatInt(rs.NumWatches, 10), getCellName("M", row): strconv.FormatInt(rs.NumStars, 10), getCellName("N", row): strconv.FormatInt(rs.NumForks, 10), getCellName("O", row): strconv.FormatInt(rs.NumDownloads, 10),
  259. getCellName("P", row): strconv.FormatInt(rs.NumComments, 10), getCellName("Q", row): strconv.FormatInt(rs.NumVisits, 10), getCellName("R", row): strconv.FormatInt(rs.NumClosedIssues, 10), getCellName("S", row): strconv.FormatInt(rs.NumVersions, 10),
  260. getCellName("T", row): strconv.FormatInt(rs.NumDevMonths, 10), getCellName("U", row): strconv.FormatInt(rs.DatasetSize, 10), getCellName("V", row): strconv.FormatInt(rs.NumModels, 10), getCellName("W", row): strconv.FormatInt(rs.NumWikiViews, 10),
  261. getCellName("X", row): strconv.FormatInt(rs.NumCommits, 10), getCellName("Y", row): strconv.FormatInt(rs.NumIssues, 10), getCellName("Z", row): strconv.FormatInt(rs.NumPulls, 10), getCellName("AA", row): strconv.FormatInt(rs.NumVersions, 10),
  262. getCellName("AB", row): strconv.FormatFloat(float64(rs.IssueFixedRate), 'f', 2, 64), getCellName("AC", row): strconv.FormatInt(rs.NumContributor, 10), getCellName("AD", row): strconv.FormatInt(rs.NumKeyContributor, 10), getCellName("AE", row): strconv.FormatInt(rs.NumContributorsGrowth, 10),
  263. getCellName("AF", row): strconv.FormatInt(rs.NumCommitLinesGrowth, 10), getCellName("AG", row): strconv.FormatInt(rs.NumIssuesGrowth, 10), getCellName("AH", row): strconv.FormatInt(rs.NumContributorsGrowth, 10), getCellName("AI", row): strconv.FormatInt(rs.NumCommitsGrowth, 10), getCellName("AJ", row): strconv.FormatInt(rs.NumCommentsGrowth, 10),
  264. }
  265. }
  266. func getCellName(col string, row int) string {
  267. return col + strconv.Itoa(row)
  268. }
  269. func getIsPrivateDisplay(private bool, ctx *context.Context) string {
  270. if private {
  271. return ctx.Tr("admin.repos.yes")
  272. } else {
  273. return ctx.Tr("admin.repos.no")
  274. }
  275. }
  276. func GetProjectLatestStatistics(ctx *context.Context) {
  277. repoId := ctx.Params(":id")
  278. recordBeginTime, err := getRecordBeginTime()
  279. if err != nil {
  280. log.Error("Can not get record begin time", err)
  281. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  282. return
  283. }
  284. latestUpdatedTime, latestDate, err := models.GetRepoStatLastUpdatedTime(repoId)
  285. repoIdInt, _ := strconv.ParseInt(repoId, 10, 64)
  286. repoStat, err := models.GetRepoStatisticByDateAndRepoId(latestDate, repoIdInt)
  287. if err != nil {
  288. log.Error("Can not get the repo statistics "+repoId, err)
  289. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.get_repo_stat_error"))
  290. return
  291. }
  292. repository, err := models.GetRepositoryByID(repoIdInt)
  293. if err != nil {
  294. log.Error("Can not get the repo info "+repoId, err)
  295. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.get_repo_info_error"))
  296. return
  297. }
  298. projectLatestData := ProjectLatestData{
  299. RecordBeginTime: recordBeginTime.Format(DATE_FORMAT),
  300. CreatTime: time.Unix(int64(repository.CreatedUnix), 0).Format(DATE_FORMAT),
  301. LastUpdatedTime: latestUpdatedTime,
  302. OpenI: repoStat.RadarTotal,
  303. Comment: repoStat.NumComments,
  304. View: repoStat.NumVisits,
  305. Download: repoStat.NumDownloads,
  306. IssueClosedRatio: repoStat.IssueFixedRate,
  307. Impact: repoStat.Impact,
  308. Completeness: repoStat.Completeness,
  309. Liveness: repoStat.Liveness,
  310. ProjectHealth: repoStat.ProjectHealth,
  311. TeamHealth: repoStat.TeamHealth,
  312. Growth: repoStat.Growth,
  313. Description: repository.Description,
  314. }
  315. contributors, err := models.GetTop10Contributor(repository.RepoPath())
  316. if err != nil {
  317. log.Error("can not get contributors", err)
  318. }
  319. users := make([]UserInfo, 0)
  320. for _, contributor := range contributors {
  321. mode := repository.GetCollaboratorMode(contributor.UserId)
  322. if mode == -1 {
  323. if contributor.IsAdmin {
  324. mode = int(models.AccessModeAdmin)
  325. }
  326. if contributor.UserId == repository.OwnerID {
  327. mode = int(models.AccessModeOwner)
  328. }
  329. }
  330. pr := models.GetPullCountByUserAndRepoId(repoIdInt, contributor.UserId)
  331. userInfo := UserInfo{
  332. User: contributor.Committer,
  333. Commit: contributor.CommitCnt,
  334. Mode: mode,
  335. PR: pr,
  336. RelAvatarLink: contributor.RelAvatarLink,
  337. Email: contributor.Email,
  338. }
  339. users = append(users, userInfo)
  340. }
  341. projectLatestData.Top10 = users
  342. ctx.JSON(http.StatusOK, projectLatestData)
  343. }
  344. func GetProjectPeriodStatistics(ctx *context.Context) {
  345. repoId := ctx.Params(":id")
  346. recordBeginTime, err := getRecordBeginTime()
  347. if err != nil {
  348. log.Error("Can not get record begin time", err)
  349. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  350. return
  351. }
  352. repoIdInt, _ := strconv.ParseInt(repoId, 10, 64)
  353. if err != nil {
  354. log.Error("Can not get record begin time", err)
  355. ctx.Error(http.StatusBadRequest, ctx.Tr("repo.record_begintime_get_err"))
  356. return
  357. }
  358. beginTime, endTime, err := getTimePeroid(ctx, recordBeginTime)
  359. isOpenI := ctx.QueryBool("openi")
  360. var repositorys []*models.RepoStatistic
  361. if isOpenI {
  362. repositorys = models.GetRepoStatisticByRawSql(generateRadarSql(beginTime, endTime, repoIdInt))
  363. } else {
  364. repositorys = models.GetRepoStatisticByRawSql(generateTargetSql(beginTime, endTime, repoIdInt))
  365. }
  366. ctx.JSON(http.StatusOK, repositorys)
  367. }
  368. func generateRadarSql(beginTime time.Time, endTime time.Time, repoId int64) string {
  369. sql := "SELECT date, impact, completeness, liveness, project_health, team_health, growth, radar_total FROM repo_statistic" +
  370. " where repo_id=" + strconv.FormatInt(repoId, 10) + " and created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  371. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " order by created_unix"
  372. return sql
  373. }
  374. func generateTargetSql(beginTime time.Time, endTime time.Time, repoId int64) string {
  375. sql := "SELECT date, num_visits,num_downloads_added as num_downloads,num_commits_added as num_commits FROM repo_statistic" +
  376. " where repo_id=" + strconv.FormatInt(repoId, 10) + " and created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  377. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " order by created_unix desc"
  378. return sql
  379. }
  380. func generateCountSql(beginTime time.Time, endTime time.Time, latestDate string, q string) string {
  381. countSql := "SELECT count(*) FROM " +
  382. "(SELECT repo_id FROM repo_statistic where created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  383. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " group by repo_id) A," +
  384. "(SELECT repo_id,name,is_private,radar_total from public.repo_statistic where date='" + latestDate + "') B" +
  385. " where A.repo_id=B.repo_id"
  386. if q != "" {
  387. countSql = countSql + " and LOWER(B.name) like '%" + strings.ToLower(q) + "%'"
  388. }
  389. return countSql
  390. }
  391. func generateOpenICountSql(latestDate string) string {
  392. countSql := "SELECT count(*) FROM " +
  393. "public.repo_statistic where date='" + latestDate + "'"
  394. return countSql
  395. }
  396. func generateTypeAllSql(beginTime time.Time, endTime time.Time, latestDate string, q string, orderBy string, page int, pageSize int) string {
  397. 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 " +
  398. "(SELECT repo_id,sum(num_visits) as num_visits " +
  399. " FROM repo_statistic where created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  400. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " group by repo_id) A," +
  401. "(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" +
  402. " where A.repo_id=B.repo_id"
  403. if q != "" {
  404. sql = sql + " and LOWER(name) like '%" + strings.ToLower(q) + "%'"
  405. }
  406. sql = sql + " order by " + orderBy + " desc,repo_id" + " limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa((page-1)*pageSize)
  407. return sql
  408. }
  409. func generateTypeAllOpenISql(latestDate string, page int, pageSize int) string {
  410. sql := "SELECT id, repo_id, date, num_watches, num_stars, num_forks, num_downloads, num_comments, num_visits, num_closed_issues, num_versions, num_dev_months, repo_size, dataset_size, num_models, num_wiki_views, num_commits, num_issues, num_pulls, issue_fixed_rate, num_contributor, num_key_contributor, num_contributors_growth, num_commits_growth, num_commit_lines_growth, num_issues_growth, num_comments_growth, impact, completeness, liveness, project_health, team_health, growth, radar_total, name, is_private, owner_name FROM " +
  411. " public.repo_statistic where date='" + latestDate + "'"
  412. sql = sql + " order by radar_total desc,repo_id" + " limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa((page-1)*pageSize)
  413. return sql
  414. }
  415. func generatePageSql(beginTime time.Time, endTime time.Time, latestDate string, q string, orderBy string, page int, pageSize int) string {
  416. 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 " +
  417. "(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 " +
  418. " FROM repo_statistic where created_unix >=" + strconv.FormatInt(beginTime.Unix(), 10) +
  419. " and created_unix<" + strconv.FormatInt(endTime.Unix(), 10) + " group by repo_id) A," +
  420. "(SELECT repo_id,name,owner_name,is_private,radar_total from public.repo_statistic where date='" + latestDate + "') B" +
  421. " where A.repo_id=B.repo_id"
  422. if q != "" {
  423. sql = sql + " and LOWER(B.name) like '%" + strings.ToLower(q) + "%'"
  424. }
  425. sql = sql + " order by " + orderBy + " desc,A.repo_id" + " limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa((page-1)*pageSize)
  426. return sql
  427. }
  428. func getOrderBy(ctx *context.Context) string {
  429. orderBy := ""
  430. switch ctx.Query("sort") {
  431. case "openi":
  432. orderBy = "B.radar_total"
  433. case "view":
  434. orderBy = "A.num_visits"
  435. case "download":
  436. orderBy = "A.num_downloads"
  437. case "pr":
  438. orderBy = "A.num_pulls"
  439. case "commit":
  440. orderBy = "A.num_commits"
  441. case "watch":
  442. orderBy = "A.num_watches"
  443. case "star":
  444. orderBy = "A.num_stars"
  445. case "fork":
  446. orderBy = "A.num_forks"
  447. case "issue":
  448. orderBy = "A.num_issues"
  449. case "issue_closed":
  450. orderBy = "A.num_closed_issues"
  451. case "contributor":
  452. orderBy = "A.num_contributor"
  453. default:
  454. orderBy = "B.radar_total"
  455. }
  456. return orderBy
  457. }
  458. func getTimePeroid(ctx *context.Context, recordBeginTime time.Time) (time.Time, time.Time, error) {
  459. queryType := ctx.QueryTrim("type")
  460. now := time.Now()
  461. recordBeginTimeTemp := recordBeginTime.AddDate(0, 0, 1)
  462. beginTimeStr := ctx.QueryTrim("beginTime")
  463. endTimeStr := ctx.QueryTrim("endTime")
  464. var beginTime time.Time
  465. var endTime time.Time
  466. var err error
  467. if queryType != "" {
  468. if queryType == "all" {
  469. beginTime = recordBeginTimeTemp
  470. endTime = now
  471. } else if queryType == "yesterday" {
  472. endTime = now
  473. beginTime = time.Date(endTime.Year(), endTime.Month(), endTime.Day(), 0, 0, 0, 0, now.Location())
  474. } else if queryType == "current_week" {
  475. beginTime = now.AddDate(0, 0, -int(time.Now().Weekday())+2) //begin from monday
  476. beginTime = time.Date(beginTime.Year(), beginTime.Month(), beginTime.Day(), 0, 0, 0, 0, now.Location())
  477. endTime = now
  478. } else if queryType == "current_month" {
  479. endTime = now
  480. beginTime = time.Date(endTime.Year(), endTime.Month(), 2, 0, 0, 0, 0, now.Location())
  481. } else if queryType == "monthly" {
  482. endTime = now
  483. beginTime = now.AddDate(0, -1, 1)
  484. beginTime = time.Date(beginTime.Year(), beginTime.Month(), beginTime.Day(), 0, 0, 0, 0, now.Location())
  485. } else if queryType == "current_year" {
  486. endTime = now
  487. beginTime = time.Date(endTime.Year(), 1, 2, 0, 0, 0, 0, now.Location())
  488. } else if queryType == "last_month" {
  489. lastMonthTime := now.AddDate(0, -1, 0)
  490. beginTime = time.Date(lastMonthTime.Year(), lastMonthTime.Month(), 2, 0, 0, 0, 0, now.Location())
  491. endTime = time.Date(now.Year(), now.Month(), 2, 0, 0, 0, 0, now.Location())
  492. } else {
  493. return now, now, fmt.Errorf("The value of type parameter is wrong.")
  494. }
  495. } else {
  496. if beginTimeStr == "" || endTimeStr == "" {
  497. //如果查询类型和开始时间结束时间都未设置,按queryType=all处理
  498. beginTime = recordBeginTimeTemp
  499. endTime = now
  500. } else {
  501. beginTime, err = time.ParseInLocation("2006-01-02", beginTimeStr, time.Local)
  502. if err != nil {
  503. return now, now, err
  504. }
  505. endTime, err = time.ParseInLocation("2006-01-02", endTimeStr, time.Local)
  506. if err != nil {
  507. return now, now, err
  508. }
  509. beginTime = beginTime.AddDate(0, 0, 1)
  510. endTime = endTime.AddDate(0, 0, 1)
  511. }
  512. }
  513. if beginTime.Before(recordBeginTimeTemp) {
  514. beginTime = recordBeginTimeTemp
  515. }
  516. return beginTime, endTime, nil
  517. }
  518. func getRecordBeginTime() (time.Time, error) {
  519. return time.ParseInLocation(DATE_FORMAT, setting.RadarMap.RecordBeginTime, time.Local)
  520. }
  521. func getTotalPage(total int64, pageSize int) int {
  522. another := 0
  523. if int(total)%pageSize != 0 {
  524. another = 1
  525. }
  526. return int(total)/pageSize + another
  527. }