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

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