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.

issue_tracked_time.go 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. "context"
  7. "time"
  8. "code.gitea.io/gitea/models/db"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/util"
  12. "xorm.io/builder"
  13. )
  14. // TrackedTime represents a time that was spent for a specific issue.
  15. type TrackedTime struct {
  16. ID int64 `xorm:"pk autoincr"`
  17. IssueID int64 `xorm:"INDEX"`
  18. Issue *Issue `xorm:"-"`
  19. UserID int64 `xorm:"INDEX"`
  20. User *user_model.User `xorm:"-"`
  21. Created time.Time `xorm:"-"`
  22. CreatedUnix int64 `xorm:"created"`
  23. Time int64 `xorm:"NOT NULL"`
  24. Deleted bool `xorm:"NOT NULL DEFAULT false"`
  25. }
  26. func init() {
  27. db.RegisterModel(new(TrackedTime))
  28. }
  29. // TrackedTimeList is a List of TrackedTime's
  30. type TrackedTimeList []*TrackedTime
  31. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  32. func (t *TrackedTime) AfterLoad() {
  33. t.Created = time.Unix(t.CreatedUnix, 0).In(setting.DefaultUILocation)
  34. }
  35. // LoadAttributes load Issue, User
  36. func (t *TrackedTime) LoadAttributes() (err error) {
  37. return t.loadAttributes(db.DefaultContext)
  38. }
  39. func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
  40. if t.Issue == nil {
  41. t.Issue, err = getIssueByID(ctx, t.IssueID)
  42. if err != nil {
  43. return
  44. }
  45. err = t.Issue.LoadRepo(ctx)
  46. if err != nil {
  47. return
  48. }
  49. }
  50. if t.User == nil {
  51. t.User, err = user_model.GetUserByIDCtx(ctx, t.UserID)
  52. if err != nil {
  53. return
  54. }
  55. }
  56. return
  57. }
  58. // LoadAttributes load Issue, User
  59. func (tl TrackedTimeList) LoadAttributes() (err error) {
  60. for _, t := range tl {
  61. if err = t.LoadAttributes(); err != nil {
  62. return err
  63. }
  64. }
  65. return
  66. }
  67. // FindTrackedTimesOptions represent the filters for tracked times. If an ID is 0 it will be ignored.
  68. type FindTrackedTimesOptions struct {
  69. db.ListOptions
  70. IssueID int64
  71. UserID int64
  72. RepositoryID int64
  73. MilestoneID int64
  74. CreatedAfterUnix int64
  75. CreatedBeforeUnix int64
  76. }
  77. // toCond will convert each condition into a xorm-Cond
  78. func (opts *FindTrackedTimesOptions) toCond() builder.Cond {
  79. cond := builder.NewCond().And(builder.Eq{"tracked_time.deleted": false})
  80. if opts.IssueID != 0 {
  81. cond = cond.And(builder.Eq{"issue_id": opts.IssueID})
  82. }
  83. if opts.UserID != 0 {
  84. cond = cond.And(builder.Eq{"user_id": opts.UserID})
  85. }
  86. if opts.RepositoryID != 0 {
  87. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepositoryID})
  88. }
  89. if opts.MilestoneID != 0 {
  90. cond = cond.And(builder.Eq{"issue.milestone_id": opts.MilestoneID})
  91. }
  92. if opts.CreatedAfterUnix != 0 {
  93. cond = cond.And(builder.Gte{"tracked_time.created_unix": opts.CreatedAfterUnix})
  94. }
  95. if opts.CreatedBeforeUnix != 0 {
  96. cond = cond.And(builder.Lte{"tracked_time.created_unix": opts.CreatedBeforeUnix})
  97. }
  98. return cond
  99. }
  100. // toSession will convert the given options to a xorm Session by using the conditions from toCond and joining with issue table if required
  101. func (opts *FindTrackedTimesOptions) toSession(e db.Engine) db.Engine {
  102. sess := e
  103. if opts.RepositoryID > 0 || opts.MilestoneID > 0 {
  104. sess = e.Join("INNER", "issue", "issue.id = tracked_time.issue_id")
  105. }
  106. sess = sess.Where(opts.toCond())
  107. if opts.Page != 0 {
  108. sess = db.SetEnginePagination(sess, opts)
  109. }
  110. return sess
  111. }
  112. // GetTrackedTimes returns all tracked times that fit to the given options.
  113. func GetTrackedTimes(ctx context.Context, options *FindTrackedTimesOptions) (trackedTimes TrackedTimeList, err error) {
  114. err = options.toSession(db.GetEngine(ctx)).Find(&trackedTimes)
  115. return
  116. }
  117. // CountTrackedTimes returns count of tracked times that fit to the given options.
  118. func CountTrackedTimes(opts *FindTrackedTimesOptions) (int64, error) {
  119. sess := db.GetEngine(db.DefaultContext).Where(opts.toCond())
  120. if opts.RepositoryID > 0 || opts.MilestoneID > 0 {
  121. sess = sess.Join("INNER", "issue", "issue.id = tracked_time.issue_id")
  122. }
  123. return sess.Count(&TrackedTime{})
  124. }
  125. // GetTrackedSeconds return sum of seconds
  126. func GetTrackedSeconds(ctx context.Context, opts FindTrackedTimesOptions) (trackedSeconds int64, err error) {
  127. return opts.toSession(db.GetEngine(ctx)).SumInt(&TrackedTime{}, "time")
  128. }
  129. // AddTime will add the given time (in seconds) to the issue
  130. func AddTime(user *user_model.User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) {
  131. ctx, committer, err := db.TxContext()
  132. if err != nil {
  133. return nil, err
  134. }
  135. defer committer.Close()
  136. t, err := addTime(ctx, user, issue, amount, created)
  137. if err != nil {
  138. return nil, err
  139. }
  140. if err := issue.LoadRepo(ctx); err != nil {
  141. return nil, err
  142. }
  143. if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{
  144. Issue: issue,
  145. Repo: issue.Repo,
  146. Doer: user,
  147. Content: util.SecToTime(amount),
  148. Type: CommentTypeAddTimeManual,
  149. TimeID: t.ID,
  150. }); err != nil {
  151. return nil, err
  152. }
  153. return t, committer.Commit()
  154. }
  155. func addTime(ctx context.Context, user *user_model.User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) {
  156. if created.IsZero() {
  157. created = time.Now()
  158. }
  159. tt := &TrackedTime{
  160. IssueID: issue.ID,
  161. UserID: user.ID,
  162. Time: amount,
  163. Created: created,
  164. }
  165. return tt, db.Insert(ctx, tt)
  166. }
  167. // TotalTimes returns the spent time for each user by an issue
  168. func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string, error) {
  169. trackedTimes, err := GetTrackedTimes(db.DefaultContext, options)
  170. if err != nil {
  171. return nil, err
  172. }
  173. // Adding total time per user ID
  174. totalTimesByUser := make(map[int64]int64)
  175. for _, t := range trackedTimes {
  176. totalTimesByUser[t.UserID] += t.Time
  177. }
  178. totalTimes := make(map[*user_model.User]string)
  179. // Fetching User and making time human readable
  180. for userID, total := range totalTimesByUser {
  181. user, err := user_model.GetUserByID(userID)
  182. if err != nil {
  183. if user_model.IsErrUserNotExist(err) {
  184. continue
  185. }
  186. return nil, err
  187. }
  188. totalTimes[user] = util.SecToTime(total)
  189. }
  190. return totalTimes, nil
  191. }
  192. // DeleteIssueUserTimes deletes times for issue
  193. func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error {
  194. ctx, committer, err := db.TxContext()
  195. if err != nil {
  196. return err
  197. }
  198. defer committer.Close()
  199. opts := FindTrackedTimesOptions{
  200. IssueID: issue.ID,
  201. UserID: user.ID,
  202. }
  203. removedTime, err := deleteTimes(ctx, opts)
  204. if err != nil {
  205. return err
  206. }
  207. if removedTime == 0 {
  208. return db.ErrNotExist{}
  209. }
  210. if err := issue.LoadRepo(ctx); err != nil {
  211. return err
  212. }
  213. if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{
  214. Issue: issue,
  215. Repo: issue.Repo,
  216. Doer: user,
  217. Content: "- " + util.SecToTime(removedTime),
  218. Type: CommentTypeDeleteTimeManual,
  219. }); err != nil {
  220. return err
  221. }
  222. return committer.Commit()
  223. }
  224. // DeleteTime delete a specific Time
  225. func DeleteTime(t *TrackedTime) error {
  226. ctx, committer, err := db.TxContext()
  227. if err != nil {
  228. return err
  229. }
  230. defer committer.Close()
  231. if err := t.loadAttributes(ctx); err != nil {
  232. return err
  233. }
  234. if err := deleteTime(ctx, t); err != nil {
  235. return err
  236. }
  237. if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{
  238. Issue: t.Issue,
  239. Repo: t.Issue.Repo,
  240. Doer: t.User,
  241. Content: "- " + util.SecToTime(t.Time),
  242. Type: CommentTypeDeleteTimeManual,
  243. }); err != nil {
  244. return err
  245. }
  246. return committer.Commit()
  247. }
  248. func deleteTimes(ctx context.Context, opts FindTrackedTimesOptions) (removedTime int64, err error) {
  249. removedTime, err = GetTrackedSeconds(ctx, opts)
  250. if err != nil || removedTime == 0 {
  251. return
  252. }
  253. _, err = opts.toSession(db.GetEngine(ctx)).Table("tracked_time").Cols("deleted").Update(&TrackedTime{Deleted: true})
  254. return
  255. }
  256. func deleteTime(ctx context.Context, t *TrackedTime) error {
  257. if t.Deleted {
  258. return db.ErrNotExist{ID: t.ID}
  259. }
  260. t.Deleted = true
  261. _, err := db.GetEngine(ctx).ID(t.ID).Cols("deleted").Update(t)
  262. return err
  263. }
  264. // GetTrackedTimeByID returns raw TrackedTime without loading attributes by id
  265. func GetTrackedTimeByID(id int64) (*TrackedTime, error) {
  266. time := new(TrackedTime)
  267. has, err := db.GetEngine(db.DefaultContext).ID(id).Get(time)
  268. if err != nil {
  269. return nil, err
  270. } else if !has {
  271. return nil, db.ErrNotExist{ID: id}
  272. }
  273. return time, nil
  274. }