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

633 lines
16 KiB

Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/modules/setting"
  9. api "code.gitea.io/gitea/modules/structs"
  10. "code.gitea.io/gitea/modules/timeutil"
  11. "xorm.io/builder"
  12. "xorm.io/xorm"
  13. )
  14. // Milestone represents a milestone of repository.
  15. type Milestone struct {
  16. ID int64 `xorm:"pk autoincr"`
  17. RepoID int64 `xorm:"INDEX"`
  18. Repo *Repository `xorm:"-"`
  19. Name string
  20. Content string `xorm:"TEXT"`
  21. RenderedContent string `xorm:"-"`
  22. IsClosed bool
  23. NumIssues int
  24. NumClosedIssues int
  25. NumOpenIssues int `xorm:"-"`
  26. Completeness int // Percentage(1-100).
  27. IsOverdue bool `xorm:"-"`
  28. DeadlineString string `xorm:"-"`
  29. DeadlineUnix timeutil.TimeStamp
  30. ClosedDateUnix timeutil.TimeStamp
  31. TotalTrackedTime int64 `xorm:"-"`
  32. }
  33. // BeforeUpdate is invoked from XORM before updating this object.
  34. func (m *Milestone) BeforeUpdate() {
  35. if m.NumIssues > 0 {
  36. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  37. } else {
  38. m.Completeness = 0
  39. }
  40. }
  41. // AfterLoad is invoked from XORM after setting the value of a field of
  42. // this object.
  43. func (m *Milestone) AfterLoad() {
  44. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  45. if m.DeadlineUnix.Year() == 9999 {
  46. return
  47. }
  48. m.DeadlineString = m.DeadlineUnix.Format("2006-01-02")
  49. if timeutil.TimeStampNow() >= m.DeadlineUnix {
  50. m.IsOverdue = true
  51. }
  52. }
  53. // State returns string representation of milestone status.
  54. func (m *Milestone) State() api.StateType {
  55. if m.IsClosed {
  56. return api.StateClosed
  57. }
  58. return api.StateOpen
  59. }
  60. // APIFormat returns this Milestone in API format.
  61. func (m *Milestone) APIFormat() *api.Milestone {
  62. apiMilestone := &api.Milestone{
  63. ID: m.ID,
  64. State: m.State(),
  65. Title: m.Name,
  66. Description: m.Content,
  67. OpenIssues: m.NumOpenIssues,
  68. ClosedIssues: m.NumClosedIssues,
  69. }
  70. if m.IsClosed {
  71. apiMilestone.Closed = m.ClosedDateUnix.AsTimePtr()
  72. }
  73. if m.DeadlineUnix.Year() < 9999 {
  74. apiMilestone.Deadline = m.DeadlineUnix.AsTimePtr()
  75. }
  76. return apiMilestone
  77. }
  78. // NewMilestone creates new milestone of repository.
  79. func NewMilestone(m *Milestone) (err error) {
  80. sess := x.NewSession()
  81. defer sess.Close()
  82. if err = sess.Begin(); err != nil {
  83. return err
  84. }
  85. m.Name = strings.TrimSpace(m.Name)
  86. if _, err = sess.Insert(m); err != nil {
  87. return err
  88. }
  89. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  90. return err
  91. }
  92. return sess.Commit()
  93. }
  94. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  95. m := &Milestone{
  96. ID: id,
  97. RepoID: repoID,
  98. }
  99. has, err := e.Get(m)
  100. if err != nil {
  101. return nil, err
  102. } else if !has {
  103. return nil, ErrMilestoneNotExist{id, repoID}
  104. }
  105. return m, nil
  106. }
  107. // GetMilestoneByRepoID returns the milestone in a repository.
  108. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  109. return getMilestoneByRepoID(x, repoID, id)
  110. }
  111. // GetMilestoneByID returns the milestone via id .
  112. func GetMilestoneByID(id int64) (*Milestone, error) {
  113. var m Milestone
  114. has, err := x.ID(id).Get(&m)
  115. if err != nil {
  116. return nil, err
  117. } else if !has {
  118. return nil, ErrMilestoneNotExist{id, 0}
  119. }
  120. return &m, nil
  121. }
  122. // MilestoneList is a list of milestones offering additional functionality
  123. type MilestoneList []*Milestone
  124. func (milestones MilestoneList) loadTotalTrackedTimes(e Engine) error {
  125. type totalTimesByMilestone struct {
  126. MilestoneID int64
  127. Time int64
  128. }
  129. if len(milestones) == 0 {
  130. return nil
  131. }
  132. var trackedTimes = make(map[int64]int64, len(milestones))
  133. // Get total tracked time by milestone_id
  134. rows, err := e.Table("issue").
  135. Join("INNER", "milestone", "issue.milestone_id = milestone.id").
  136. Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id").
  137. Where("tracked_time.deleted = ?", false).
  138. Select("milestone_id, sum(time) as time").
  139. In("milestone_id", milestones.getMilestoneIDs()).
  140. GroupBy("milestone_id").
  141. Rows(new(totalTimesByMilestone))
  142. if err != nil {
  143. return err
  144. }
  145. defer rows.Close()
  146. for rows.Next() {
  147. var totalTime totalTimesByMilestone
  148. err = rows.Scan(&totalTime)
  149. if err != nil {
  150. return err
  151. }
  152. trackedTimes[totalTime.MilestoneID] = totalTime.Time
  153. }
  154. for _, milestone := range milestones {
  155. milestone.TotalTrackedTime = trackedTimes[milestone.ID]
  156. }
  157. return nil
  158. }
  159. func (m *Milestone) loadTotalTrackedTime(e Engine) error {
  160. type totalTimesByMilestone struct {
  161. MilestoneID int64
  162. Time int64
  163. }
  164. totalTime := &totalTimesByMilestone{MilestoneID: m.ID}
  165. has, err := e.Table("issue").
  166. Join("INNER", "milestone", "issue.milestone_id = milestone.id").
  167. Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id").
  168. Where("tracked_time.deleted = ?", false).
  169. Select("milestone_id, sum(time) as time").
  170. Where("milestone_id = ?", m.ID).
  171. GroupBy("milestone_id").
  172. Get(totalTime)
  173. if err != nil {
  174. return err
  175. } else if !has {
  176. return nil
  177. }
  178. m.TotalTrackedTime = totalTime.Time
  179. return nil
  180. }
  181. // LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request
  182. func (milestones MilestoneList) LoadTotalTrackedTimes() error {
  183. return milestones.loadTotalTrackedTimes(x)
  184. }
  185. // LoadTotalTrackedTime loads the tracked time for the milestone
  186. func (m *Milestone) LoadTotalTrackedTime() error {
  187. return m.loadTotalTrackedTime(x)
  188. }
  189. func (milestones MilestoneList) getMilestoneIDs() []int64 {
  190. var ids = make([]int64, 0, len(milestones))
  191. for _, ms := range milestones {
  192. ids = append(ids, ms.ID)
  193. }
  194. return ids
  195. }
  196. // GetMilestonesByRepoID returns all opened milestones of a repository.
  197. func GetMilestonesByRepoID(repoID int64, state api.StateType, listOptions ListOptions) (MilestoneList, error) {
  198. sess := x.Where("repo_id = ?", repoID)
  199. switch state {
  200. case api.StateClosed:
  201. sess = sess.And("is_closed = ?", true)
  202. case api.StateAll:
  203. break
  204. case api.StateOpen:
  205. fallthrough
  206. default:
  207. sess = sess.And("is_closed = ?", false)
  208. }
  209. if listOptions.Page != 0 {
  210. sess = listOptions.setSessionPagination(sess)
  211. }
  212. miles := make([]*Milestone, 0, listOptions.PageSize)
  213. return miles, sess.Asc("deadline_unix").Asc("id").Find(&miles)
  214. }
  215. // GetMilestones returns a list of milestones of given repository and status.
  216. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) (MilestoneList, error) {
  217. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  218. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  219. if page > 0 {
  220. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  221. }
  222. switch sortType {
  223. case "furthestduedate":
  224. sess.Desc("deadline_unix")
  225. case "leastcomplete":
  226. sess.Asc("completeness")
  227. case "mostcomplete":
  228. sess.Desc("completeness")
  229. case "leastissues":
  230. sess.Asc("num_issues")
  231. case "mostissues":
  232. sess.Desc("num_issues")
  233. default:
  234. sess.Asc("deadline_unix")
  235. }
  236. return miles, sess.Find(&miles)
  237. }
  238. func updateMilestone(e Engine, m *Milestone) error {
  239. m.Name = strings.TrimSpace(m.Name)
  240. _, err := e.ID(m.ID).AllCols().
  241. SetExpr("num_issues", builder.Select("count(*)").From("issue").Where(
  242. builder.Eq{"milestone_id": m.ID},
  243. )).
  244. SetExpr("num_closed_issues", builder.Select("count(*)").From("issue").Where(
  245. builder.Eq{
  246. "milestone_id": m.ID,
  247. "is_closed": true,
  248. },
  249. )).
  250. Update(m)
  251. return err
  252. }
  253. // UpdateMilestone updates information of given milestone.
  254. func UpdateMilestone(m *Milestone, oldIsClosed bool) error {
  255. sess := x.NewSession()
  256. defer sess.Close()
  257. if err := sess.Begin(); err != nil {
  258. return err
  259. }
  260. if m.IsClosed && !oldIsClosed {
  261. m.ClosedDateUnix = timeutil.TimeStampNow()
  262. }
  263. if err := updateMilestone(sess, m); err != nil {
  264. return err
  265. }
  266. if err := updateMilestoneCompleteness(sess, m.ID); err != nil {
  267. return err
  268. }
  269. // if IsClosed changed, update milestone numbers of repository
  270. if oldIsClosed != m.IsClosed {
  271. if err := updateRepoMilestoneNum(sess, m.RepoID); err != nil {
  272. return err
  273. }
  274. }
  275. return sess.Commit()
  276. }
  277. func updateMilestoneCompleteness(e Engine, milestoneID int64) error {
  278. _, err := e.Exec("UPDATE `milestone` SET completeness=100*num_closed_issues/(CASE WHEN num_issues > 0 THEN num_issues ELSE 1 END) WHERE id=?",
  279. milestoneID,
  280. )
  281. return err
  282. }
  283. func countRepoMilestones(e Engine, repoID int64) (int64, error) {
  284. return e.
  285. Where("repo_id=?", repoID).
  286. Count(new(Milestone))
  287. }
  288. func countRepoClosedMilestones(e Engine, repoID int64) (int64, error) {
  289. return e.
  290. Where("repo_id=? AND is_closed=?", repoID, true).
  291. Count(new(Milestone))
  292. }
  293. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  294. func CountRepoClosedMilestones(repoID int64) (int64, error) {
  295. return countRepoClosedMilestones(x, repoID)
  296. }
  297. // MilestoneStats returns number of open and closed milestones of given repository.
  298. func MilestoneStats(repoID int64) (open int64, closed int64, err error) {
  299. open, err = x.
  300. Where("repo_id=? AND is_closed=?", repoID, false).
  301. Count(new(Milestone))
  302. if err != nil {
  303. return 0, 0, nil
  304. }
  305. closed, err = CountRepoClosedMilestones(repoID)
  306. return open, closed, err
  307. }
  308. // ChangeMilestoneStatus changes the milestone open/closed status.
  309. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  310. sess := x.NewSession()
  311. defer sess.Close()
  312. if err = sess.Begin(); err != nil {
  313. return err
  314. }
  315. m.IsClosed = isClosed
  316. if isClosed {
  317. m.ClosedDateUnix = timeutil.TimeStampNow()
  318. }
  319. if _, err := sess.ID(m.ID).Cols("is_closed", "closed_date_unix").Update(m); err != nil {
  320. return err
  321. }
  322. if err := updateRepoMilestoneNum(sess, m.RepoID); err != nil {
  323. return err
  324. }
  325. return sess.Commit()
  326. }
  327. func updateRepoMilestoneNum(e Engine, repoID int64) error {
  328. _, err := e.Exec("UPDATE `repository` SET num_milestones=(SELECT count(*) FROM milestone WHERE repo_id=?),num_closed_milestones=(SELECT count(*) FROM milestone WHERE repo_id=? AND is_closed=?) WHERE id=?",
  329. repoID,
  330. repoID,
  331. true,
  332. repoID,
  333. )
  334. return err
  335. }
  336. func updateMilestoneTotalNum(e Engine, milestoneID int64) (err error) {
  337. if _, err = e.Exec("UPDATE `milestone` SET num_issues=(SELECT count(*) FROM issue WHERE milestone_id=?) WHERE id=?",
  338. milestoneID,
  339. milestoneID,
  340. ); err != nil {
  341. return
  342. }
  343. return updateMilestoneCompleteness(e, milestoneID)
  344. }
  345. func updateMilestoneClosedNum(e Engine, milestoneID int64) (err error) {
  346. if _, err = e.Exec("UPDATE `milestone` SET num_closed_issues=(SELECT count(*) FROM issue WHERE milestone_id=? AND is_closed=?) WHERE id=?",
  347. milestoneID,
  348. true,
  349. milestoneID,
  350. ); err != nil {
  351. return
  352. }
  353. return updateMilestoneCompleteness(e, milestoneID)
  354. }
  355. func changeMilestoneAssign(e *xorm.Session, doer *User, issue *Issue, oldMilestoneID int64) error {
  356. if err := updateIssueCols(e, issue, "milestone_id"); err != nil {
  357. return err
  358. }
  359. if oldMilestoneID > 0 {
  360. if err := updateMilestoneTotalNum(e, oldMilestoneID); err != nil {
  361. return err
  362. }
  363. if issue.IsClosed {
  364. if err := updateMilestoneClosedNum(e, oldMilestoneID); err != nil {
  365. return err
  366. }
  367. }
  368. }
  369. if issue.MilestoneID > 0 {
  370. if err := updateMilestoneTotalNum(e, issue.MilestoneID); err != nil {
  371. return err
  372. }
  373. if issue.IsClosed {
  374. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  375. return err
  376. }
  377. }
  378. }
  379. if oldMilestoneID > 0 || issue.MilestoneID > 0 {
  380. if err := issue.loadRepo(e); err != nil {
  381. return err
  382. }
  383. var opts = &CreateCommentOptions{
  384. Type: CommentTypeMilestone,
  385. Doer: doer,
  386. Repo: issue.Repo,
  387. Issue: issue,
  388. OldMilestoneID: oldMilestoneID,
  389. MilestoneID: issue.MilestoneID,
  390. }
  391. if _, err := createComment(e, opts); err != nil {
  392. return err
  393. }
  394. }
  395. return nil
  396. }
  397. // ChangeMilestoneAssign changes assignment of milestone for issue.
  398. func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) {
  399. sess := x.NewSession()
  400. defer sess.Close()
  401. if err = sess.Begin(); err != nil {
  402. return err
  403. }
  404. if err = changeMilestoneAssign(sess, doer, issue, oldMilestoneID); err != nil {
  405. return err
  406. }
  407. if err = sess.Commit(); err != nil {
  408. return fmt.Errorf("Commit: %v", err)
  409. }
  410. return nil
  411. }
  412. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  413. func DeleteMilestoneByRepoID(repoID, id int64) error {
  414. m, err := GetMilestoneByRepoID(repoID, id)
  415. if err != nil {
  416. if IsErrMilestoneNotExist(err) {
  417. return nil
  418. }
  419. return err
  420. }
  421. repo, err := GetRepositoryByID(m.RepoID)
  422. if err != nil {
  423. return err
  424. }
  425. sess := x.NewSession()
  426. defer sess.Close()
  427. if err = sess.Begin(); err != nil {
  428. return err
  429. }
  430. if _, err = sess.ID(m.ID).Delete(new(Milestone)); err != nil {
  431. return err
  432. }
  433. numMilestones, err := countRepoMilestones(sess, repo.ID)
  434. if err != nil {
  435. return err
  436. }
  437. numClosedMilestones, err := countRepoClosedMilestones(sess, repo.ID)
  438. if err != nil {
  439. return err
  440. }
  441. repo.NumMilestones = int(numMilestones)
  442. repo.NumClosedMilestones = int(numClosedMilestones)
  443. if _, err = sess.ID(repo.ID).Cols("num_milestones, num_closed_milestones").Update(repo); err != nil {
  444. return err
  445. }
  446. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  447. return err
  448. }
  449. return sess.Commit()
  450. }
  451. // CountMilestones map from repo conditions to number of milestones matching the options`
  452. func CountMilestones(repoCond builder.Cond, isClosed bool) (map[int64]int64, error) {
  453. sess := x.Where("is_closed = ?", isClosed)
  454. if repoCond.IsValid() {
  455. sess.In("repo_id", builder.Select("id").From("repository").Where(repoCond))
  456. }
  457. countsSlice := make([]*struct {
  458. RepoID int64
  459. Count int64
  460. }, 0, 10)
  461. if err := sess.GroupBy("repo_id").
  462. Select("repo_id AS repo_id, COUNT(*) AS count").
  463. Table("milestone").
  464. Find(&countsSlice); err != nil {
  465. return nil, err
  466. }
  467. countMap := make(map[int64]int64, len(countsSlice))
  468. for _, c := range countsSlice {
  469. countMap[c.RepoID] = c.Count
  470. }
  471. return countMap, nil
  472. }
  473. // CountMilestonesByRepoIDs map from repoIDs to number of milestones matching the options`
  474. func CountMilestonesByRepoIDs(repoIDs []int64, isClosed bool) (map[int64]int64, error) {
  475. return CountMilestones(
  476. builder.In("repo_id", repoIDs),
  477. isClosed,
  478. )
  479. }
  480. // SearchMilestones search milestones
  481. func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType string) (MilestoneList, error) {
  482. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  483. sess := x.Where("is_closed = ?", isClosed)
  484. if repoCond.IsValid() {
  485. sess.In("repo_id", builder.Select("id").From("repository").Where(repoCond))
  486. }
  487. if page > 0 {
  488. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  489. }
  490. switch sortType {
  491. case "furthestduedate":
  492. sess.Desc("deadline_unix")
  493. case "leastcomplete":
  494. sess.Asc("completeness")
  495. case "mostcomplete":
  496. sess.Desc("completeness")
  497. case "leastissues":
  498. sess.Asc("num_issues")
  499. case "mostissues":
  500. sess.Desc("num_issues")
  501. default:
  502. sess.Asc("deadline_unix")
  503. }
  504. return miles, sess.Find(&miles)
  505. }
  506. // GetMilestonesByRepoIDs returns a list of milestones of given repositories and status.
  507. func GetMilestonesByRepoIDs(repoIDs []int64, page int, isClosed bool, sortType string) (MilestoneList, error) {
  508. return SearchMilestones(
  509. builder.In("repo_id", repoIDs),
  510. page,
  511. isClosed,
  512. sortType,
  513. )
  514. }
  515. // MilestonesStats represents milestone statistic information.
  516. type MilestonesStats struct {
  517. OpenCount, ClosedCount int64
  518. }
  519. // Total returns the total counts of milestones
  520. func (m MilestonesStats) Total() int64 {
  521. return m.OpenCount + m.ClosedCount
  522. }
  523. // GetMilestonesStats returns milestone statistic information for dashboard by given conditions.
  524. func GetMilestonesStats(repoCond builder.Cond) (*MilestonesStats, error) {
  525. var err error
  526. stats := &MilestonesStats{}
  527. sess := x.Where("is_closed = ?", false)
  528. if repoCond.IsValid() {
  529. sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond)))
  530. }
  531. stats.OpenCount, err = sess.Count(new(Milestone))
  532. if err != nil {
  533. return nil, err
  534. }
  535. sess = x.Where("is_closed = ?", true)
  536. if repoCond.IsValid() {
  537. sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond)))
  538. }
  539. stats.ClosedCount, err = sess.Count(new(Milestone))
  540. if err != nil {
  541. return nil, err
  542. }
  543. return stats, nil
  544. }