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.

issue.go 46 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 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>
7 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>
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 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>
7 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>
7 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>
7 years ago
10 years ago
9 years ago
9 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. // Copyright 2014 The Gogs 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. "path"
  8. "regexp"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/util"
  15. api "code.gitea.io/sdk/gitea"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/builder"
  18. "github.com/go-xorm/xorm"
  19. )
  20. // Issue represents an issue or pull request of repository.
  21. type Issue struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  24. Repo *Repository `xorm:"-"`
  25. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  26. PosterID int64 `xorm:"INDEX"`
  27. Poster *User `xorm:"-"`
  28. Title string `xorm:"name"`
  29. Content string `xorm:"TEXT"`
  30. RenderedContent string `xorm:"-"`
  31. Labels []*Label `xorm:"-"`
  32. MilestoneID int64 `xorm:"INDEX"`
  33. Milestone *Milestone `xorm:"-"`
  34. Priority int
  35. AssigneeID int64 `xorm:"-"`
  36. Assignee *User `xorm:"-"`
  37. IsClosed bool `xorm:"INDEX"`
  38. IsRead bool `xorm:"-"`
  39. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  40. PullRequest *PullRequest `xorm:"-"`
  41. NumComments int
  42. Ref string
  43. DeadlineUnix util.TimeStamp `xorm:"INDEX"`
  44. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  45. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  46. ClosedUnix util.TimeStamp `xorm:"INDEX"`
  47. Attachments []*Attachment `xorm:"-"`
  48. Comments []*Comment `xorm:"-"`
  49. Reactions ReactionList `xorm:"-"`
  50. TotalTrackedTime int64 `xorm:"-"`
  51. Assignees []*User `xorm:"-"`
  52. // IsLocked limits commenting abilities to users on an issue
  53. // with write access
  54. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  55. }
  56. var (
  57. issueTasksPat *regexp.Regexp
  58. issueTasksDonePat *regexp.Regexp
  59. )
  60. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  61. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  62. func init() {
  63. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  64. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  65. }
  66. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  67. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  68. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  69. if err != nil {
  70. return err
  71. }
  72. return nil
  73. }
  74. // IsOverdue checks if the issue is overdue
  75. func (issue *Issue) IsOverdue() bool {
  76. return util.TimeStampNow() >= issue.DeadlineUnix
  77. }
  78. // LoadRepo loads issue's repository
  79. func (issue *Issue) LoadRepo() error {
  80. return issue.loadRepo(x)
  81. }
  82. func (issue *Issue) loadRepo(e Engine) (err error) {
  83. if issue.Repo == nil {
  84. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  85. if err != nil {
  86. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  87. }
  88. }
  89. return nil
  90. }
  91. // IsTimetrackerEnabled returns true if the repo enables timetracking
  92. func (issue *Issue) IsTimetrackerEnabled() bool {
  93. return issue.isTimetrackerEnabled(x)
  94. }
  95. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  96. if err := issue.loadRepo(e); err != nil {
  97. log.Error(4, fmt.Sprintf("loadRepo: %v", err))
  98. return false
  99. }
  100. return issue.Repo.IsTimetrackerEnabled()
  101. }
  102. // GetPullRequest returns the issue pull request
  103. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  104. if !issue.IsPull {
  105. return nil, fmt.Errorf("Issue is not a pull request")
  106. }
  107. pr, err = getPullRequestByIssueID(x, issue.ID)
  108. if err != nil {
  109. return nil, err
  110. }
  111. pr.Issue = issue
  112. return
  113. }
  114. func (issue *Issue) loadLabels(e Engine) (err error) {
  115. if issue.Labels == nil {
  116. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  117. if err != nil {
  118. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  119. }
  120. }
  121. return nil
  122. }
  123. // LoadPoster loads poster
  124. func (issue *Issue) LoadPoster() error {
  125. return issue.loadPoster(x)
  126. }
  127. func (issue *Issue) loadPoster(e Engine) (err error) {
  128. if issue.Poster == nil {
  129. issue.Poster, err = getUserByID(e, issue.PosterID)
  130. if err != nil {
  131. issue.PosterID = -1
  132. issue.Poster = NewGhostUser()
  133. if !IsErrUserNotExist(err) {
  134. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  135. }
  136. err = nil
  137. return
  138. }
  139. }
  140. return
  141. }
  142. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  143. if issue.IsPull && issue.PullRequest == nil {
  144. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  145. if err != nil {
  146. if IsErrPullRequestNotExist(err) {
  147. return err
  148. }
  149. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  150. }
  151. issue.PullRequest.Issue = issue
  152. }
  153. return nil
  154. }
  155. // LoadPullRequest loads pull request info
  156. func (issue *Issue) LoadPullRequest() error {
  157. return issue.loadPullRequest(x)
  158. }
  159. func (issue *Issue) loadComments(e Engine) (err error) {
  160. if issue.Comments != nil {
  161. return nil
  162. }
  163. issue.Comments, err = findComments(e, FindCommentsOptions{
  164. IssueID: issue.ID,
  165. Type: CommentTypeUnknown,
  166. })
  167. return err
  168. }
  169. func (issue *Issue) loadReactions(e Engine) (err error) {
  170. if issue.Reactions != nil {
  171. return nil
  172. }
  173. reactions, err := findReactions(e, FindReactionsOptions{
  174. IssueID: issue.ID,
  175. })
  176. if err != nil {
  177. return err
  178. }
  179. // Load reaction user data
  180. if _, err := ReactionList(reactions).loadUsers(e); err != nil {
  181. return err
  182. }
  183. // Cache comments to map
  184. comments := make(map[int64]*Comment)
  185. for _, comment := range issue.Comments {
  186. comments[comment.ID] = comment
  187. }
  188. // Add reactions either to issue or comment
  189. for _, react := range reactions {
  190. if react.CommentID == 0 {
  191. issue.Reactions = append(issue.Reactions, react)
  192. } else if comment, ok := comments[react.CommentID]; ok {
  193. comment.Reactions = append(comment.Reactions, react)
  194. }
  195. }
  196. return nil
  197. }
  198. func (issue *Issue) loadAttributes(e Engine) (err error) {
  199. if err = issue.loadRepo(e); err != nil {
  200. return
  201. }
  202. if err = issue.loadPoster(e); err != nil {
  203. return
  204. }
  205. if err = issue.loadLabels(e); err != nil {
  206. return
  207. }
  208. if issue.Milestone == nil && issue.MilestoneID > 0 {
  209. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  210. if err != nil && !IsErrMilestoneNotExist(err) {
  211. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  212. }
  213. }
  214. if err = issue.loadAssignees(e); err != nil {
  215. return
  216. }
  217. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  218. // It is possible pull request is not yet created.
  219. return err
  220. }
  221. if issue.Attachments == nil {
  222. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  223. if err != nil {
  224. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  225. }
  226. }
  227. if err = issue.loadComments(e); err != nil {
  228. return err
  229. }
  230. if issue.isTimetrackerEnabled(e) {
  231. if err = issue.loadTotalTimes(e); err != nil {
  232. return err
  233. }
  234. }
  235. return issue.loadReactions(e)
  236. }
  237. // LoadAttributes loads the attribute of this issue.
  238. func (issue *Issue) LoadAttributes() error {
  239. return issue.loadAttributes(x)
  240. }
  241. // GetIsRead load the `IsRead` field of the issue
  242. func (issue *Issue) GetIsRead(userID int64) error {
  243. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  244. if has, err := x.Get(issueUser); err != nil {
  245. return err
  246. } else if !has {
  247. issue.IsRead = false
  248. return nil
  249. }
  250. issue.IsRead = issueUser.IsRead
  251. return nil
  252. }
  253. // APIURL returns the absolute APIURL to this issue.
  254. func (issue *Issue) APIURL() string {
  255. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  256. }
  257. // HTMLURL returns the absolute URL to this issue.
  258. func (issue *Issue) HTMLURL() string {
  259. var path string
  260. if issue.IsPull {
  261. path = "pulls"
  262. } else {
  263. path = "issues"
  264. }
  265. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  266. }
  267. // DiffURL returns the absolute URL to this diff
  268. func (issue *Issue) DiffURL() string {
  269. if issue.IsPull {
  270. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  271. }
  272. return ""
  273. }
  274. // PatchURL returns the absolute URL to this patch
  275. func (issue *Issue) PatchURL() string {
  276. if issue.IsPull {
  277. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  278. }
  279. return ""
  280. }
  281. // State returns string representation of issue status.
  282. func (issue *Issue) State() api.StateType {
  283. if issue.IsClosed {
  284. return api.StateClosed
  285. }
  286. return api.StateOpen
  287. }
  288. // APIFormat assumes some fields assigned with values:
  289. // Required - Poster, Labels,
  290. // Optional - Milestone, Assignee, PullRequest
  291. func (issue *Issue) APIFormat() *api.Issue {
  292. return issue.apiFormat(x)
  293. }
  294. func (issue *Issue) apiFormat(e Engine) *api.Issue {
  295. issue.loadLabels(e)
  296. apiLabels := make([]*api.Label, len(issue.Labels))
  297. for i := range issue.Labels {
  298. apiLabels[i] = issue.Labels[i].APIFormat()
  299. }
  300. issue.loadPoster(e)
  301. issue.loadRepo(e)
  302. apiIssue := &api.Issue{
  303. ID: issue.ID,
  304. URL: issue.APIURL(),
  305. Index: issue.Index,
  306. Poster: issue.Poster.APIFormat(),
  307. Title: issue.Title,
  308. Body: issue.Content,
  309. Labels: apiLabels,
  310. State: issue.State(),
  311. Comments: issue.NumComments,
  312. Created: issue.CreatedUnix.AsTime(),
  313. Updated: issue.UpdatedUnix.AsTime(),
  314. }
  315. if issue.ClosedUnix != 0 {
  316. apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
  317. }
  318. if issue.Milestone != nil {
  319. apiIssue.Milestone = issue.Milestone.APIFormat()
  320. }
  321. issue.loadAssignees(e)
  322. if len(issue.Assignees) > 0 {
  323. for _, assignee := range issue.Assignees {
  324. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  325. }
  326. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  327. }
  328. if issue.IsPull {
  329. issue.loadPullRequest(e)
  330. apiIssue.PullRequest = &api.PullRequestMeta{
  331. HasMerged: issue.PullRequest.HasMerged,
  332. }
  333. if issue.PullRequest.HasMerged {
  334. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  335. }
  336. }
  337. if issue.DeadlineUnix != 0 {
  338. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  339. }
  340. return apiIssue
  341. }
  342. // HashTag returns unique hash tag for issue.
  343. func (issue *Issue) HashTag() string {
  344. return "issue-" + com.ToStr(issue.ID)
  345. }
  346. // IsPoster returns true if given user by ID is the poster.
  347. func (issue *Issue) IsPoster(uid int64) bool {
  348. return issue.PosterID == uid
  349. }
  350. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  351. return hasIssueLabel(e, issue.ID, labelID)
  352. }
  353. // HasLabel returns true if issue has been labeled by given ID.
  354. func (issue *Issue) HasLabel(labelID int64) bool {
  355. return issue.hasLabel(x, labelID)
  356. }
  357. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  358. var err error
  359. if err = issue.loadRepo(x); err != nil {
  360. log.Error(4, "loadRepo: %v", err)
  361. return
  362. }
  363. if err = issue.loadPoster(x); err != nil {
  364. log.Error(4, "loadPoster: %v", err)
  365. return
  366. }
  367. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  368. if issue.IsPull {
  369. if err = issue.loadPullRequest(x); err != nil {
  370. log.Error(4, "loadPullRequest: %v", err)
  371. return
  372. }
  373. if err = issue.PullRequest.LoadIssue(); err != nil {
  374. log.Error(4, "LoadIssue: %v", err)
  375. return
  376. }
  377. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  378. Action: api.HookIssueLabelUpdated,
  379. Index: issue.Index,
  380. PullRequest: issue.PullRequest.APIFormat(),
  381. Repository: issue.Repo.APIFormat(AccessModeNone),
  382. Sender: doer.APIFormat(),
  383. })
  384. } else {
  385. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  386. Action: api.HookIssueLabelUpdated,
  387. Index: issue.Index,
  388. Issue: issue.APIFormat(),
  389. Repository: issue.Repo.APIFormat(mode),
  390. Sender: doer.APIFormat(),
  391. })
  392. }
  393. if err != nil {
  394. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  395. } else {
  396. go HookQueue.Add(issue.RepoID)
  397. }
  398. }
  399. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  400. return newIssueLabel(e, issue, label, doer)
  401. }
  402. // AddLabel adds a new label to the issue.
  403. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  404. if err := NewIssueLabel(issue, label, doer); err != nil {
  405. return err
  406. }
  407. issue.sendLabelUpdatedWebhook(doer)
  408. return nil
  409. }
  410. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  411. return newIssueLabels(e, issue, labels, doer)
  412. }
  413. // AddLabels adds a list of new labels to the issue.
  414. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  415. if err := NewIssueLabels(issue, labels, doer); err != nil {
  416. return err
  417. }
  418. issue.sendLabelUpdatedWebhook(doer)
  419. return nil
  420. }
  421. func (issue *Issue) getLabels(e Engine) (err error) {
  422. if len(issue.Labels) > 0 {
  423. return nil
  424. }
  425. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  426. if err != nil {
  427. return fmt.Errorf("getLabelsByIssueID: %v", err)
  428. }
  429. return nil
  430. }
  431. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  432. return deleteIssueLabel(e, issue, label, doer)
  433. }
  434. // RemoveLabel removes a label from issue by given ID.
  435. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  436. if err := issue.loadRepo(x); err != nil {
  437. return err
  438. }
  439. perm, err := GetUserRepoPermission(issue.Repo, doer)
  440. if err != nil {
  441. return err
  442. }
  443. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  444. return ErrLabelNotExist{}
  445. }
  446. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  447. return err
  448. }
  449. issue.sendLabelUpdatedWebhook(doer)
  450. return nil
  451. }
  452. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  453. if err = issue.getLabels(e); err != nil {
  454. return fmt.Errorf("getLabels: %v", err)
  455. }
  456. for i := range issue.Labels {
  457. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  458. return fmt.Errorf("removeLabel: %v", err)
  459. }
  460. }
  461. return nil
  462. }
  463. // ClearLabels removes all issue labels as the given user.
  464. // Triggers appropriate WebHooks, if any.
  465. func (issue *Issue) ClearLabels(doer *User) (err error) {
  466. sess := x.NewSession()
  467. defer sess.Close()
  468. if err = sess.Begin(); err != nil {
  469. return err
  470. }
  471. if err := issue.loadRepo(sess); err != nil {
  472. return err
  473. } else if err = issue.loadPullRequest(sess); err != nil {
  474. return err
  475. }
  476. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  477. if err != nil {
  478. return err
  479. }
  480. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  481. return ErrLabelNotExist{}
  482. }
  483. if err = issue.clearLabels(sess, doer); err != nil {
  484. return err
  485. }
  486. if err = sess.Commit(); err != nil {
  487. return fmt.Errorf("Commit: %v", err)
  488. }
  489. if err = issue.loadPoster(x); err != nil {
  490. return fmt.Errorf("loadPoster: %v", err)
  491. }
  492. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  493. if issue.IsPull {
  494. err = issue.PullRequest.LoadIssue()
  495. if err != nil {
  496. log.Error(4, "LoadIssue: %v", err)
  497. return
  498. }
  499. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  500. Action: api.HookIssueLabelCleared,
  501. Index: issue.Index,
  502. PullRequest: issue.PullRequest.APIFormat(),
  503. Repository: issue.Repo.APIFormat(mode),
  504. Sender: doer.APIFormat(),
  505. })
  506. } else {
  507. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  508. Action: api.HookIssueLabelCleared,
  509. Index: issue.Index,
  510. Issue: issue.APIFormat(),
  511. Repository: issue.Repo.APIFormat(mode),
  512. Sender: doer.APIFormat(),
  513. })
  514. }
  515. if err != nil {
  516. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  517. } else {
  518. go HookQueue.Add(issue.RepoID)
  519. }
  520. return nil
  521. }
  522. type labelSorter []*Label
  523. func (ts labelSorter) Len() int {
  524. return len([]*Label(ts))
  525. }
  526. func (ts labelSorter) Less(i, j int) bool {
  527. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  528. }
  529. func (ts labelSorter) Swap(i, j int) {
  530. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  531. }
  532. // ReplaceLabels removes all current labels and add new labels to the issue.
  533. // Triggers appropriate WebHooks, if any.
  534. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  535. sess := x.NewSession()
  536. defer sess.Close()
  537. if err = sess.Begin(); err != nil {
  538. return err
  539. }
  540. if err = issue.loadLabels(sess); err != nil {
  541. return err
  542. }
  543. sort.Sort(labelSorter(labels))
  544. sort.Sort(labelSorter(issue.Labels))
  545. var toAdd, toRemove []*Label
  546. addIndex, removeIndex := 0, 0
  547. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  548. addLabel := labels[addIndex]
  549. removeLabel := issue.Labels[removeIndex]
  550. if addLabel.ID == removeLabel.ID {
  551. addIndex++
  552. removeIndex++
  553. } else if addLabel.ID < removeLabel.ID {
  554. toAdd = append(toAdd, addLabel)
  555. addIndex++
  556. } else {
  557. toRemove = append(toRemove, removeLabel)
  558. removeIndex++
  559. }
  560. }
  561. toAdd = append(toAdd, labels[addIndex:]...)
  562. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  563. if len(toAdd) > 0 {
  564. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  565. return fmt.Errorf("addLabels: %v", err)
  566. }
  567. }
  568. for _, l := range toRemove {
  569. if err = issue.removeLabel(sess, doer, l); err != nil {
  570. return fmt.Errorf("removeLabel: %v", err)
  571. }
  572. }
  573. return sess.Commit()
  574. }
  575. // ReadBy sets issue to be read by given user.
  576. func (issue *Issue) ReadBy(userID int64) error {
  577. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  578. return err
  579. }
  580. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  581. }
  582. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  583. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  584. return err
  585. }
  586. UpdateIssueIndexerCols(issue.ID, cols...)
  587. return nil
  588. }
  589. // UpdateIssueCols only updates values of specific columns for given issue.
  590. func UpdateIssueCols(issue *Issue, cols ...string) error {
  591. return updateIssueCols(x, issue, cols...)
  592. }
  593. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  594. // Nothing should be performed if current status is same as target status
  595. if issue.IsClosed == isClosed {
  596. return nil
  597. }
  598. // Check for open dependencies
  599. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  600. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  601. noDeps, err := issueNoDependenciesLeft(e, issue)
  602. if err != nil {
  603. return err
  604. }
  605. if !noDeps {
  606. return ErrDependenciesLeft{issue.ID}
  607. }
  608. }
  609. issue.IsClosed = isClosed
  610. if isClosed {
  611. issue.ClosedUnix = util.TimeStampNow()
  612. } else {
  613. issue.ClosedUnix = 0
  614. }
  615. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  616. return err
  617. }
  618. // Update issue count of labels
  619. if err = issue.getLabels(e); err != nil {
  620. return err
  621. }
  622. for idx := range issue.Labels {
  623. if issue.IsClosed {
  624. issue.Labels[idx].NumClosedIssues++
  625. } else {
  626. issue.Labels[idx].NumClosedIssues--
  627. }
  628. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  629. return err
  630. }
  631. }
  632. // Update issue count of milestone
  633. if err = changeMilestoneIssueStats(e, issue); err != nil {
  634. return err
  635. }
  636. // New action comment
  637. if _, err = createStatusComment(e, doer, issue); err != nil {
  638. return err
  639. }
  640. return nil
  641. }
  642. // ChangeStatus changes issue status to open or closed.
  643. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  644. sess := x.NewSession()
  645. defer sess.Close()
  646. if err = sess.Begin(); err != nil {
  647. return err
  648. }
  649. if err = issue.loadRepo(sess); err != nil {
  650. return err
  651. }
  652. if err = issue.loadPoster(sess); err != nil {
  653. return err
  654. }
  655. if err = issue.changeStatus(sess, doer, isClosed); err != nil {
  656. return err
  657. }
  658. if err = sess.Commit(); err != nil {
  659. return fmt.Errorf("Commit: %v", err)
  660. }
  661. sess.Close()
  662. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  663. if issue.IsPull {
  664. if err = issue.loadPullRequest(sess); err != nil {
  665. return err
  666. }
  667. // Merge pull request calls issue.changeStatus so we need to handle separately.
  668. apiPullRequest := &api.PullRequestPayload{
  669. Index: issue.Index,
  670. PullRequest: issue.PullRequest.APIFormat(),
  671. Repository: issue.Repo.APIFormat(mode),
  672. Sender: doer.APIFormat(),
  673. }
  674. if isClosed {
  675. apiPullRequest.Action = api.HookIssueClosed
  676. } else {
  677. apiPullRequest.Action = api.HookIssueReOpened
  678. }
  679. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  680. } else {
  681. apiIssue := &api.IssuePayload{
  682. Index: issue.Index,
  683. Issue: issue.APIFormat(),
  684. Repository: issue.Repo.APIFormat(mode),
  685. Sender: doer.APIFormat(),
  686. }
  687. if isClosed {
  688. apiIssue.Action = api.HookIssueClosed
  689. } else {
  690. apiIssue.Action = api.HookIssueReOpened
  691. }
  692. err = PrepareWebhooks(issue.Repo, HookEventIssues, apiIssue)
  693. }
  694. if err != nil {
  695. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  696. } else {
  697. go HookQueue.Add(issue.Repo.ID)
  698. }
  699. return nil
  700. }
  701. // ChangeTitle changes the title of this issue, as the given user.
  702. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  703. oldTitle := issue.Title
  704. issue.Title = title
  705. sess := x.NewSession()
  706. defer sess.Close()
  707. if err = sess.Begin(); err != nil {
  708. return err
  709. }
  710. if err = updateIssueCols(sess, issue, "name"); err != nil {
  711. return fmt.Errorf("updateIssueCols: %v", err)
  712. }
  713. if err = issue.loadRepo(sess); err != nil {
  714. return fmt.Errorf("loadRepo: %v", err)
  715. }
  716. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  717. return fmt.Errorf("createChangeTitleComment: %v", err)
  718. }
  719. if err = sess.Commit(); err != nil {
  720. return err
  721. }
  722. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  723. if issue.IsPull {
  724. if err = issue.loadPullRequest(sess); err != nil {
  725. return fmt.Errorf("loadPullRequest: %v", err)
  726. }
  727. issue.PullRequest.Issue = issue
  728. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  729. Action: api.HookIssueEdited,
  730. Index: issue.Index,
  731. Changes: &api.ChangesPayload{
  732. Title: &api.ChangesFromPayload{
  733. From: oldTitle,
  734. },
  735. },
  736. PullRequest: issue.PullRequest.APIFormat(),
  737. Repository: issue.Repo.APIFormat(mode),
  738. Sender: doer.APIFormat(),
  739. })
  740. } else {
  741. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  742. Action: api.HookIssueEdited,
  743. Index: issue.Index,
  744. Changes: &api.ChangesPayload{
  745. Title: &api.ChangesFromPayload{
  746. From: oldTitle,
  747. },
  748. },
  749. Issue: issue.APIFormat(),
  750. Repository: issue.Repo.APIFormat(mode),
  751. Sender: issue.Poster.APIFormat(),
  752. })
  753. }
  754. if err != nil {
  755. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  756. } else {
  757. go HookQueue.Add(issue.RepoID)
  758. }
  759. return nil
  760. }
  761. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  762. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  763. issue, err := getIssueByID(x, issueID)
  764. if err != nil {
  765. return err
  766. }
  767. sess := x.NewSession()
  768. defer sess.Close()
  769. if err := sess.Begin(); err != nil {
  770. return err
  771. }
  772. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  773. return err
  774. }
  775. return sess.Commit()
  776. }
  777. // ChangeContent changes issue content, as the given user.
  778. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  779. oldContent := issue.Content
  780. issue.Content = content
  781. if err = UpdateIssueCols(issue, "content"); err != nil {
  782. return fmt.Errorf("UpdateIssueCols: %v", err)
  783. }
  784. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  785. if issue.IsPull {
  786. issue.PullRequest.Issue = issue
  787. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  788. Action: api.HookIssueEdited,
  789. Index: issue.Index,
  790. Changes: &api.ChangesPayload{
  791. Body: &api.ChangesFromPayload{
  792. From: oldContent,
  793. },
  794. },
  795. PullRequest: issue.PullRequest.APIFormat(),
  796. Repository: issue.Repo.APIFormat(mode),
  797. Sender: doer.APIFormat(),
  798. })
  799. } else {
  800. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  801. Action: api.HookIssueEdited,
  802. Index: issue.Index,
  803. Changes: &api.ChangesPayload{
  804. Body: &api.ChangesFromPayload{
  805. From: oldContent,
  806. },
  807. },
  808. Issue: issue.APIFormat(),
  809. Repository: issue.Repo.APIFormat(mode),
  810. Sender: doer.APIFormat(),
  811. })
  812. }
  813. if err != nil {
  814. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  815. } else {
  816. go HookQueue.Add(issue.RepoID)
  817. }
  818. return nil
  819. }
  820. // GetTasks returns the amount of tasks in the issues content
  821. func (issue *Issue) GetTasks() int {
  822. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  823. }
  824. // GetTasksDone returns the amount of completed tasks in the issues content
  825. func (issue *Issue) GetTasksDone() int {
  826. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  827. }
  828. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  829. func (issue *Issue) GetLastEventTimestamp() util.TimeStamp {
  830. if issue.IsClosed {
  831. return issue.ClosedUnix
  832. }
  833. return issue.CreatedUnix
  834. }
  835. // GetLastEventLabel returns the localization label for the current issue.
  836. func (issue *Issue) GetLastEventLabel() string {
  837. if issue.IsClosed {
  838. if issue.IsPull && issue.PullRequest.HasMerged {
  839. return "repo.pulls.merged_by"
  840. }
  841. return "repo.issues.closed_by"
  842. }
  843. return "repo.issues.opened_by"
  844. }
  845. // NewIssueOptions represents the options of a new issue.
  846. type NewIssueOptions struct {
  847. Repo *Repository
  848. Issue *Issue
  849. LabelIDs []int64
  850. AssigneeIDs []int64
  851. Attachments []string // In UUID format.
  852. IsPull bool
  853. }
  854. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  855. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  856. opts.Issue.Index = opts.Repo.NextIssueIndex()
  857. if opts.Issue.MilestoneID > 0 {
  858. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  859. if err != nil && !IsErrMilestoneNotExist(err) {
  860. return fmt.Errorf("getMilestoneByID: %v", err)
  861. }
  862. // Assume milestone is invalid and drop silently.
  863. opts.Issue.MilestoneID = 0
  864. if milestone != nil {
  865. opts.Issue.MilestoneID = milestone.ID
  866. opts.Issue.Milestone = milestone
  867. }
  868. }
  869. // Keep the old assignee id thingy for compatibility reasons
  870. if opts.Issue.AssigneeID > 0 {
  871. isAdded := false
  872. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  873. for _, aID := range opts.AssigneeIDs {
  874. if aID == opts.Issue.AssigneeID {
  875. isAdded = true
  876. break
  877. }
  878. }
  879. if !isAdded {
  880. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  881. }
  882. }
  883. // Check for and validate assignees
  884. if len(opts.AssigneeIDs) > 0 {
  885. for _, assigneeID := range opts.AssigneeIDs {
  886. user, err := getUserByID(e, assigneeID)
  887. if err != nil {
  888. return fmt.Errorf("getUserByID [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  889. }
  890. valid, err := canBeAssigned(e, user, opts.Repo)
  891. if err != nil {
  892. return fmt.Errorf("canBeAssigned [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  893. }
  894. if !valid {
  895. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  896. }
  897. }
  898. }
  899. // Milestone and assignee validation should happen before insert actual object.
  900. if _, err = e.Insert(opts.Issue); err != nil {
  901. return err
  902. }
  903. if opts.Issue.MilestoneID > 0 {
  904. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  905. return err
  906. }
  907. }
  908. // Insert the assignees
  909. for _, assigneeID := range opts.AssigneeIDs {
  910. err = opts.Issue.changeAssignee(e, doer, assigneeID, true)
  911. if err != nil {
  912. return err
  913. }
  914. }
  915. if opts.IsPull {
  916. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  917. } else {
  918. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  919. }
  920. if err != nil {
  921. return err
  922. }
  923. if len(opts.LabelIDs) > 0 {
  924. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  925. // So we have to get all needed labels first.
  926. labels := make([]*Label, 0, len(opts.LabelIDs))
  927. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  928. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  929. }
  930. if err = opts.Issue.loadPoster(e); err != nil {
  931. return err
  932. }
  933. for _, label := range labels {
  934. // Silently drop invalid labels.
  935. if label.RepoID != opts.Repo.ID {
  936. continue
  937. }
  938. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  939. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  940. }
  941. }
  942. }
  943. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  944. return err
  945. }
  946. if len(opts.Attachments) > 0 {
  947. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  948. if err != nil {
  949. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  950. }
  951. for i := 0; i < len(attachments); i++ {
  952. attachments[i].IssueID = opts.Issue.ID
  953. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  954. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  955. }
  956. }
  957. }
  958. return opts.Issue.loadAttributes(e)
  959. }
  960. // NewIssue creates new issue with labels for repository.
  961. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  962. sess := x.NewSession()
  963. defer sess.Close()
  964. if err = sess.Begin(); err != nil {
  965. return err
  966. }
  967. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  968. Repo: repo,
  969. Issue: issue,
  970. LabelIDs: labelIDs,
  971. Attachments: uuids,
  972. AssigneeIDs: assigneeIDs,
  973. }); err != nil {
  974. if IsErrUserDoesNotHaveAccessToRepo(err) {
  975. return err
  976. }
  977. return fmt.Errorf("newIssue: %v", err)
  978. }
  979. if err = sess.Commit(); err != nil {
  980. return fmt.Errorf("Commit: %v", err)
  981. }
  982. if err = NotifyWatchers(&Action{
  983. ActUserID: issue.Poster.ID,
  984. ActUser: issue.Poster,
  985. OpType: ActionCreateIssue,
  986. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  987. RepoID: repo.ID,
  988. Repo: repo,
  989. IsPrivate: repo.IsPrivate,
  990. }); err != nil {
  991. log.Error(4, "NotifyWatchers: %v", err)
  992. }
  993. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  994. if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuePayload{
  995. Action: api.HookIssueOpened,
  996. Index: issue.Index,
  997. Issue: issue.APIFormat(),
  998. Repository: repo.APIFormat(mode),
  999. Sender: issue.Poster.APIFormat(),
  1000. }); err != nil {
  1001. log.Error(4, "PrepareWebhooks: %v", err)
  1002. } else {
  1003. go HookQueue.Add(issue.RepoID)
  1004. }
  1005. return nil
  1006. }
  1007. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  1008. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  1009. issue := &Issue{
  1010. RepoID: repoID,
  1011. Index: index,
  1012. }
  1013. has, err := x.Get(issue)
  1014. if err != nil {
  1015. return nil, err
  1016. } else if !has {
  1017. return nil, ErrIssueNotExist{0, repoID, index}
  1018. }
  1019. return issue, nil
  1020. }
  1021. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  1022. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  1023. issue, err := GetIssueByIndex(repoID, index)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. return issue, issue.LoadAttributes()
  1028. }
  1029. func getIssueByID(e Engine, id int64) (*Issue, error) {
  1030. issue := new(Issue)
  1031. has, err := e.ID(id).Get(issue)
  1032. if err != nil {
  1033. return nil, err
  1034. } else if !has {
  1035. return nil, ErrIssueNotExist{id, 0, 0}
  1036. }
  1037. return issue, nil
  1038. }
  1039. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  1040. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  1041. issue, err := getIssueByID(x, id)
  1042. if err != nil {
  1043. return nil, err
  1044. }
  1045. return issue, issue.loadAttributes(x)
  1046. }
  1047. // GetIssueByID returns an issue by given ID.
  1048. func GetIssueByID(id int64) (*Issue, error) {
  1049. return getIssueByID(x, id)
  1050. }
  1051. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  1052. issues := make([]*Issue, 0, 10)
  1053. return issues, e.In("id", issueIDs).Find(&issues)
  1054. }
  1055. // GetIssuesByIDs return issues with the given IDs.
  1056. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  1057. return getIssuesByIDs(x, issueIDs)
  1058. }
  1059. // IssuesOptions represents options of an issue.
  1060. type IssuesOptions struct {
  1061. RepoIDs []int64 // include all repos if empty
  1062. AssigneeID int64
  1063. PosterID int64
  1064. MentionedID int64
  1065. MilestoneID int64
  1066. Page int
  1067. PageSize int
  1068. IsClosed util.OptionalBool
  1069. IsPull util.OptionalBool
  1070. LabelIDs []int64
  1071. SortType string
  1072. IssueIDs []int64
  1073. }
  1074. // sortIssuesSession sort an issues-related session based on the provided
  1075. // sortType string
  1076. func sortIssuesSession(sess *xorm.Session, sortType string) {
  1077. switch sortType {
  1078. case "oldest":
  1079. sess.Asc("issue.created_unix")
  1080. case "recentupdate":
  1081. sess.Desc("issue.updated_unix")
  1082. case "leastupdate":
  1083. sess.Asc("issue.updated_unix")
  1084. case "mostcomment":
  1085. sess.Desc("issue.num_comments")
  1086. case "leastcomment":
  1087. sess.Asc("issue.num_comments")
  1088. case "priority":
  1089. sess.Desc("issue.priority")
  1090. default:
  1091. sess.Desc("issue.created_unix")
  1092. }
  1093. }
  1094. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  1095. if opts.Page >= 0 && opts.PageSize > 0 {
  1096. var start int
  1097. if opts.Page == 0 {
  1098. start = 0
  1099. } else {
  1100. start = (opts.Page - 1) * opts.PageSize
  1101. }
  1102. sess.Limit(opts.PageSize, start)
  1103. }
  1104. if len(opts.IssueIDs) > 0 {
  1105. sess.In("issue.id", opts.IssueIDs)
  1106. }
  1107. if len(opts.RepoIDs) > 0 {
  1108. // In case repository IDs are provided but actually no repository has issue.
  1109. sess.In("issue.repo_id", opts.RepoIDs)
  1110. }
  1111. switch opts.IsClosed {
  1112. case util.OptionalBoolTrue:
  1113. sess.And("issue.is_closed=?", true)
  1114. case util.OptionalBoolFalse:
  1115. sess.And("issue.is_closed=?", false)
  1116. }
  1117. if opts.AssigneeID > 0 {
  1118. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1119. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1120. }
  1121. if opts.PosterID > 0 {
  1122. sess.And("issue.poster_id=?", opts.PosterID)
  1123. }
  1124. if opts.MentionedID > 0 {
  1125. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1126. And("issue_user.is_mentioned = ?", true).
  1127. And("issue_user.uid = ?", opts.MentionedID)
  1128. }
  1129. if opts.MilestoneID > 0 {
  1130. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1131. }
  1132. switch opts.IsPull {
  1133. case util.OptionalBoolTrue:
  1134. sess.And("issue.is_pull=?", true)
  1135. case util.OptionalBoolFalse:
  1136. sess.And("issue.is_pull=?", false)
  1137. }
  1138. if opts.LabelIDs != nil {
  1139. for i, labelID := range opts.LabelIDs {
  1140. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1141. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1142. }
  1143. }
  1144. return nil
  1145. }
  1146. // CountIssuesByRepo map from repoID to number of issues matching the options
  1147. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1148. sess := x.NewSession()
  1149. defer sess.Close()
  1150. if err := opts.setupSession(sess); err != nil {
  1151. return nil, err
  1152. }
  1153. countsSlice := make([]*struct {
  1154. RepoID int64
  1155. Count int64
  1156. }, 0, 10)
  1157. if err := sess.GroupBy("issue.repo_id").
  1158. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1159. Table("issue").
  1160. Find(&countsSlice); err != nil {
  1161. return nil, err
  1162. }
  1163. countMap := make(map[int64]int64, len(countsSlice))
  1164. for _, c := range countsSlice {
  1165. countMap[c.RepoID] = c.Count
  1166. }
  1167. return countMap, nil
  1168. }
  1169. // Issues returns a list of issues by given conditions.
  1170. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1171. sess := x.NewSession()
  1172. defer sess.Close()
  1173. if err := opts.setupSession(sess); err != nil {
  1174. return nil, err
  1175. }
  1176. sortIssuesSession(sess, opts.SortType)
  1177. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1178. if err := sess.Find(&issues); err != nil {
  1179. return nil, fmt.Errorf("Find: %v", err)
  1180. }
  1181. if err := IssueList(issues).LoadAttributes(); err != nil {
  1182. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1183. }
  1184. return issues, nil
  1185. }
  1186. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1187. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1188. return getParticipantsByIssueID(x, issueID)
  1189. }
  1190. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1191. userIDs := make([]int64, 0, 5)
  1192. if err := e.Table("comment").Cols("poster_id").
  1193. Where("`comment`.issue_id = ?", issueID).
  1194. And("`comment`.type = ?", CommentTypeComment).
  1195. And("`user`.is_active = ?", true).
  1196. And("`user`.prohibit_login = ?", false).
  1197. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1198. Distinct("poster_id").
  1199. Find(&userIDs); err != nil {
  1200. return nil, fmt.Errorf("get poster IDs: %v", err)
  1201. }
  1202. if len(userIDs) == 0 {
  1203. return nil, nil
  1204. }
  1205. users := make([]*User, 0, len(userIDs))
  1206. return users, e.In("id", userIDs).Find(&users)
  1207. }
  1208. // UpdateIssueMentions extracts mentioned people from content and
  1209. // updates issue-user relations for them.
  1210. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1211. if len(mentions) == 0 {
  1212. return nil
  1213. }
  1214. for i := range mentions {
  1215. mentions[i] = strings.ToLower(mentions[i])
  1216. }
  1217. users := make([]*User, 0, len(mentions))
  1218. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1219. return fmt.Errorf("find mentioned users: %v", err)
  1220. }
  1221. ids := make([]int64, 0, len(mentions))
  1222. for _, user := range users {
  1223. ids = append(ids, user.ID)
  1224. if !user.IsOrganization() || user.NumMembers == 0 {
  1225. continue
  1226. }
  1227. memberIDs := make([]int64, 0, user.NumMembers)
  1228. orgUsers, err := getOrgUsersByOrgID(e, user.ID)
  1229. if err != nil {
  1230. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1231. }
  1232. for _, orgUser := range orgUsers {
  1233. memberIDs = append(memberIDs, orgUser.ID)
  1234. }
  1235. ids = append(ids, memberIDs...)
  1236. }
  1237. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1238. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1239. }
  1240. return nil
  1241. }
  1242. // IssueStats represents issue statistic information.
  1243. type IssueStats struct {
  1244. OpenCount, ClosedCount int64
  1245. YourRepositoriesCount int64
  1246. AssignCount int64
  1247. CreateCount int64
  1248. MentionCount int64
  1249. }
  1250. // Filter modes.
  1251. const (
  1252. FilterModeAll = iota
  1253. FilterModeAssign
  1254. FilterModeCreate
  1255. FilterModeMention
  1256. )
  1257. func parseCountResult(results []map[string][]byte) int64 {
  1258. if len(results) == 0 {
  1259. return 0
  1260. }
  1261. for _, result := range results[0] {
  1262. return com.StrTo(string(result)).MustInt64()
  1263. }
  1264. return 0
  1265. }
  1266. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1267. type IssueStatsOptions struct {
  1268. RepoID int64
  1269. Labels string
  1270. MilestoneID int64
  1271. AssigneeID int64
  1272. MentionedID int64
  1273. PosterID int64
  1274. IsPull util.OptionalBool
  1275. IssueIDs []int64
  1276. }
  1277. // GetIssueStats returns issue statistic information by given conditions.
  1278. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1279. stats := &IssueStats{}
  1280. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1281. sess := x.
  1282. Where("issue.repo_id = ?", opts.RepoID)
  1283. if len(opts.IssueIDs) > 0 {
  1284. sess.In("issue.id", opts.IssueIDs)
  1285. }
  1286. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1287. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1288. if err != nil {
  1289. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1290. } else {
  1291. for i, labelID := range labelIDs {
  1292. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1293. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1294. }
  1295. }
  1296. }
  1297. if opts.MilestoneID > 0 {
  1298. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1299. }
  1300. if opts.AssigneeID > 0 {
  1301. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1302. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1303. }
  1304. if opts.PosterID > 0 {
  1305. sess.And("issue.poster_id = ?", opts.PosterID)
  1306. }
  1307. if opts.MentionedID > 0 {
  1308. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1309. And("issue_user.uid = ?", opts.MentionedID).
  1310. And("issue_user.is_mentioned = ?", true)
  1311. }
  1312. switch opts.IsPull {
  1313. case util.OptionalBoolTrue:
  1314. sess.And("issue.is_pull=?", true)
  1315. case util.OptionalBoolFalse:
  1316. sess.And("issue.is_pull=?", false)
  1317. }
  1318. return sess
  1319. }
  1320. var err error
  1321. stats.OpenCount, err = countSession(opts).
  1322. And("issue.is_closed = ?", false).
  1323. Count(new(Issue))
  1324. if err != nil {
  1325. return stats, err
  1326. }
  1327. stats.ClosedCount, err = countSession(opts).
  1328. And("issue.is_closed = ?", true).
  1329. Count(new(Issue))
  1330. return stats, err
  1331. }
  1332. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1333. type UserIssueStatsOptions struct {
  1334. UserID int64
  1335. RepoID int64
  1336. UserRepoIDs []int64
  1337. FilterMode int
  1338. IsPull bool
  1339. IsClosed bool
  1340. }
  1341. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1342. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1343. var err error
  1344. stats := &IssueStats{}
  1345. cond := builder.NewCond()
  1346. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1347. if opts.RepoID > 0 {
  1348. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1349. }
  1350. switch opts.FilterMode {
  1351. case FilterModeAll:
  1352. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1353. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1354. Count(new(Issue))
  1355. if err != nil {
  1356. return nil, err
  1357. }
  1358. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1359. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1360. Count(new(Issue))
  1361. if err != nil {
  1362. return nil, err
  1363. }
  1364. case FilterModeAssign:
  1365. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1366. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1367. And("issue_assignees.assignee_id = ?", opts.UserID).
  1368. Count(new(Issue))
  1369. if err != nil {
  1370. return nil, err
  1371. }
  1372. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1373. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1374. And("issue_assignees.assignee_id = ?", opts.UserID).
  1375. Count(new(Issue))
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. case FilterModeCreate:
  1380. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1381. And("poster_id = ?", opts.UserID).
  1382. Count(new(Issue))
  1383. if err != nil {
  1384. return nil, err
  1385. }
  1386. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1387. And("poster_id = ?", opts.UserID).
  1388. Count(new(Issue))
  1389. if err != nil {
  1390. return nil, err
  1391. }
  1392. }
  1393. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1394. stats.AssignCount, err = x.Where(cond).
  1395. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1396. And("issue_assignees.assignee_id = ?", opts.UserID).
  1397. Count(new(Issue))
  1398. if err != nil {
  1399. return nil, err
  1400. }
  1401. stats.CreateCount, err = x.Where(cond).
  1402. And("poster_id = ?", opts.UserID).
  1403. Count(new(Issue))
  1404. if err != nil {
  1405. return nil, err
  1406. }
  1407. stats.YourRepositoriesCount, err = x.Where(cond).
  1408. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1409. Count(new(Issue))
  1410. if err != nil {
  1411. return nil, err
  1412. }
  1413. return stats, nil
  1414. }
  1415. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1416. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1417. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1418. sess := x.
  1419. Where("is_closed = ?", isClosed).
  1420. And("is_pull = ?", isPull).
  1421. And("repo_id = ?", repoID)
  1422. return sess
  1423. }
  1424. openCountSession := countSession(false, isPull, repoID)
  1425. closedCountSession := countSession(true, isPull, repoID)
  1426. switch filterMode {
  1427. case FilterModeAssign:
  1428. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1429. And("issue_assignees.assignee_id = ?", uid)
  1430. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1431. And("issue_assignees.assignee_id = ?", uid)
  1432. case FilterModeCreate:
  1433. openCountSession.And("poster_id = ?", uid)
  1434. closedCountSession.And("poster_id = ?", uid)
  1435. }
  1436. openResult, _ := openCountSession.Count(new(Issue))
  1437. closedResult, _ := closedCountSession.Count(new(Issue))
  1438. return openResult, closedResult
  1439. }
  1440. func updateIssue(e Engine, issue *Issue) error {
  1441. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1442. if err != nil {
  1443. return err
  1444. }
  1445. return nil
  1446. }
  1447. // UpdateIssue updates all fields of given issue.
  1448. func UpdateIssue(issue *Issue) error {
  1449. return updateIssue(x, issue)
  1450. }
  1451. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1452. func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
  1453. // if the deadline hasn't changed do nothing
  1454. if issue.DeadlineUnix == deadlineUnix {
  1455. return nil
  1456. }
  1457. sess := x.NewSession()
  1458. defer sess.Close()
  1459. if err := sess.Begin(); err != nil {
  1460. return err
  1461. }
  1462. // Update the deadline
  1463. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1464. return err
  1465. }
  1466. // Make the comment
  1467. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1468. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1469. }
  1470. return sess.Commit()
  1471. }
  1472. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1473. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1474. return issueDeps, e.
  1475. Table("issue_dependency").
  1476. Select("issue.*").
  1477. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1478. Where("issue_id = ?", issue.ID).
  1479. Find(&issueDeps)
  1480. }
  1481. // Get Blocking Dependencies, aka all issues this issue blocks.
  1482. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1483. return issueDeps, e.
  1484. Table("issue_dependency").
  1485. Select("issue.*").
  1486. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1487. Where("dependency_id = ?", issue.ID).
  1488. Find(&issueDeps)
  1489. }
  1490. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1491. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1492. return issue.getBlockedByDependencies(x)
  1493. }
  1494. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1495. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1496. return issue.getBlockingDependencies(x)
  1497. }