Browse Source

feat: Majority Judgment Polls (2020)

Add `Poll` model and `CreatePoll` function.

The poll is ineffective, no one can vote. (yet)

Add `Judgment` creation and update.

There can be at most one judgment per trio of poll, judge and candidate.
Each Judge may emit one Judgment per Candidate of a Poll.

Mop up and oust a reminiscent bug.

Add the Poll Create, Update and Delete forms and logic.

We can't tally a Poll yet.
Nor can we judge issues.

Add the Judgment forms for each Poll of each issue.

Everything works so far without javascript.
We added CSS like monkeys, until we figure out what to do with it.

Use emotes Chromium can print as well.

Fix some warnings.

Prepare for the far future.

Add scoring pseudo-code for fast deliberation.

This was entertaining, but it's perhaps wrong,
although we can't find any reason why so far.
We contacted the world's top specialist on the matter.
…

Three gods, A, B, and C are called,
in no particular order, True, False, and Random.

True always speaks truly, False always speaks falsely,
but whether Random speaks truly or falsely is a
completely random matter.

Your task is to determine the identities of A, B, and C
by asking three yes-no questions; each question
must be put to exactly one god. The gods understand
English, but will answer all questions in
their own language, in which the words for yes
and no are da and ja, in some order.

You do not know which word means which.

Add a naive tallier.

I wish I had a feature suite in Gherkin here…

Add some tests to the deliberator and implement them.

Still waiting for input from the specialist(s)
before delving into implementation details.

Use unsigned integers where it makes sense.

(or not)

Provision more tests for the deliberator.

We've got some answers — still confused, though.

Implement a very naive deliberator.

Fix a fix for the label's hover area.

Let's barf as little as possible on existing CSS.

Fill the missing judgments as REJECT judgments.

This should be optional.

Add a battery of tests to GetMedian

We're now going to be able to implement it properly,
not like the cheap cheat we had so far.

Adapt label color to median grade.

This is a cheap implementation that will probably need a rewrite
for complete support of other gradations.

Add more tests to expose the limitations of the current scoring implementation.

Now we can work some more on the scoring.

Implement a less naive score calculus.

So far it holds.
The score is a bit long (90chars = 15 chars per possible grade)
but it won't get any longer with more judges,
unless we have to go over 500 billion judges.

Fix poll's CRUD subheaders I18N.

Make sure judgments can be emitted with keyboard only.

`:focus-within` <3 U CSS

Add a basic page to view a poll.

Move Poll CSS to LESS.

Clean up.

Tease about what will come next.

Add a repo header nav item for polls.

Ideally this whole thing should be a plugin and not a fork.
Not sure how to add new Db models and Routes.
We'd also need a custom spot in the issue view template,
but that can probably be merged upstream.

Clean up.

We'd love to move the routes to their own file.
And then being able to add them via `custom/`.

Disable event sourcing until /user/events do not hang for a minute,
because it makes browsing gitea rapidly impossible.

Add french translations for the polling UI.

Rename `Judgment` into `PollJudgment`.

After careful consideration, it's probably best to namespace.
Also, explicit is better than implicit.   :)

BREAKING CHANGE:  Not sure how the migrations will operate here.
This is why it's best to do it now than once we're actually using it.

Tweak the poll's labels for mobile with a CSS media query.

Thanks @pierre-louis for the bug report !

Review.

docs: explicit is better than implicit

chore: "missing" is more explicit than "lost"

feat: add radial merit profiles, in SVG

Ignore the gitea-repositories directory.

chore: clean up the radial merit profile SVG template

test: expose an issue with the tally

The returned amounts for each grade are wrong.
How could this happen, you ask?
Lack of unit-testing, that's why!
(also, shallow copy shenanigans)

chore: spacing

Still experimenting with the spacing in templates.
I know Gitea does not use spaces.
My sight is not getting any better,
and spacing helps a lot.

Yes, I'm already using bigger fonts.

test: refine the tests about the critical bug found

… so that it does not happen again!

fix: elbow grease the copy mechanism to fix The Bug®

fix: hide the description if none is provided.

Should we mention that it is a bad practice ?
It feels like it is.  … To deliberate.

chore: review naive deliberator

feat: add the issue title to the list of issues of a poll

Also naive and inefficient, but if we paginate, we'll be ok.
And if not, we can probably improve this by batching the queries.

fix: remove a debugging tweak that was overlooked

Also, remove the need to translate the word `Issue`.
Oddly enough, it is never translated by itself,
it is only in plural form opr inside a sentence.

feat: add the merit profile behind the median grade

Usual CSS woes
- Really not confident about positioning top and left with `em`.
- Z-index shenanigans to skip unexpected offset in positioning,
  where the absolute of a child in a relative container
  won't point to top left but to bottom of other child in static
  (try moving the merit profile below the input.emote, and remove z-indices)

Right now the merit profile is shown to all logged in, whether they judged or not.  This is not the intended final behavior.  Ideally we'd have settings fdr this.

chore: clean up before the next stage
mj-v1.14.3
domi41 2 years ago
parent
commit
ee1f6b80d0
  1. 1
      .gitignore
  2. 40
      models/error.go
  3. 2
      models/models.go
  4. 331
      models/poll.go
  5. 81
      models/poll_candidate_merit_profile.go
  6. 167
      models/poll_deliberator.go
  7. 159
      models/poll_deliberator_test.go
  8. 187
      models/poll_judgment.go
  9. 76
      models/poll_judgment_test.go
  10. 78
      models/poll_result.go
  11. 214
      models/poll_tally.go
  12. 139
      models/poll_tally_test.go
  13. 30
      models/poll_test.go
  14. 4
      models/repo.go
  15. 17
      modules/auth/poll_form.go
  16. 30
      options/locale/locale_en-US.ini
  17. 30
      options/locale/locale_fr-FR.ini
  18. 7
      routers/repo/issue.go
  19. 181
      routers/repo/poll.go
  20. 100
      routers/repo/poll_judgment.go
  21. 7
      templates/repo/header.tmpl
  22. 5
      templates/repo/issue/view_title.tmpl
  23. 65
      templates/repo/polls/merit_radial.tmpl
  24. 66
      templates/repo/polls/poll_badge.tmpl
  25. 89
      templates/repo/polls/polls_index.tmpl
  26. 78
      templates/repo/polls/polls_new.tmpl
  27. 62
      templates/repo/polls/polls_view.tmpl
  28. 1
      web_src/js/features/notification.js
  29. 181
      web_src/less/_poll.less
  30. 1
      web_src/less/index.less

1
.gitignore

@ -45,6 +45,7 @@ coverage.all
/gitea
/gitea-vet
/gitea-repositories
/debug
/integrations.test

40
models/error.go

@ -2136,3 +2136,43 @@ func IsErrOAuthApplicationNotFound(err error) bool {
func (err ErrOAuthApplicationNotFound) Error() string {
return fmt.Sprintf("OAuth application not found [ID: %d]", err.ID)
}
// ___ _ _ __ _ _ _
// | _ \___| | | / _|___ _ | |_ _ __| |__ _ _ __ ___ _ _| |_
// | _/ _ \ | | > _|_ _| | || | || / _` / _` | ' \/ -_) ' \ _|
// |_| \___/_|_| \_____| \__/ \_,_\__,_\__, |_|_|_\___|_||_\__|
// |___/
// ErrPollNotFound represents a "PollNotFound" kind of error.
type ErrPollNotFound struct {
ID int64
RepoID int64
}
// IsErrPollNotFound checks if an error is a ErrPollNotFound.
func IsErrPollNotFound(err error) bool {
_, ok := err.(ErrPollNotFound)
return ok
}
func (err ErrPollNotFound) Error() string {
return fmt.Sprintf("poll not found [id: %d, repo_id: %d]", err.ID, err.RepoID)
}
type ErrJudgmentNotFound struct {
Judge *User
Poll *Poll
CandidateID int64
}
func IsErrJudgmentNotFound(err error) bool {
_, ok := err.(ErrJudgmentNotFound)
return ok
}
func (err ErrJudgmentNotFound) Error() string {
return fmt.Sprintf("Judgment not found.")
//return fmt.Sprintf("Judgment not found" +
// " for judge %d, poll %d and candidate %d.",
// err.Judge.ID, err.Poll.ID, err.CandidateID)
}

2
models/models.go

@ -134,6 +134,8 @@ func init() {
new(ProjectIssue),
new(Session),
new(RepoTransfer),
new(Poll),
new(PollJudgment),
)
gonicNames := []string{"SSL", "UID"}

331
models/poll.go

@ -0,0 +1,331 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"code.gitea.io/gitea/modules/setting"
"fmt"
"strings"
//"code.gitea.io/gitea/modules/references"
"code.gitea.io/gitea/modules/timeutil"
//"fmt"
"xorm.io/xorm"
)
// A Poll on <Subject> with the issues of a repository as candidates.
type Poll struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"`
Repo *Repository `xorm:"-"`
AuthorID int64 `xorm:"INDEX"`
Author *User `xorm:"-"`
//Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
// When the poll is applied to all the issues, the subject should be an issue's trait.
// eg: Quality, Importance, Urgency, Wholeness, Relevance…
Subject string `xorm:"name"`
// Description may be used to describe at length the constitutive details of that poll.
// Eg: Rationale, Deliberation Consequences, Schedule, Modus Operandi…
// It can be written in the usual gitea-flavored markdown.
Description string `xorm:"TEXT"`
RenderedDescription string `xorm:"-"`
Ref string // Do we need this? Are we even using it? WHat is it?
Gradation string `xorm:"-"`
AreCandidatesIssues bool // unused
DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
// No idea how xorm works -- help!
//Judgments []*PollJudgment `xorm:"-"`
//Judgments JudgmentList `xorm:"-"`
}
// PollList is a list of polls offering additional functionality (perhaps)
type PollList []*Poll
func (poll *Poll) GetGradationList() []string {
list := make([]string, 0, 6)
// Placeholder until user customization somehow (poll.Gradation?)
// - 🤮😒😐🙂😀🤩
// - 😫😒😐😌😀😍 (more support, apparently)
// - …
list = append(list, "😫")
list = append(list, "😒")
list = append(list, "😐")
list = append(list, "😌")
list = append(list, "😀")
list = append(list, "😍")
return list
}
func (poll *Poll) GetGradeColorWord(grade uint8) (_ string) {
// Another placeholder, bypassing the dragon for now
switch grade {
case 0:
return "red"
case 1:
return "red"
case 2:
return "orange"
case 3:
return "yellow"
case 4:
return "olive"
case 5:
return "green"
default:
return "green"
}
}
func (poll *Poll) GetGradeColorCode(grade uint8) (_ string) {
// Another placeholder, bypassing the dragon for now
switch grade {
case 0:
return "#E0361C"
case 1:
return "#EE6E00"
case 2:
return "#FDB200"
case 3:
return "#C6D700"
case 4:
return "#7EC239"
case 5:
return "#02AB58"
case 6:
return "#007E3D"
default:
return "#007E3D"
}
}
func (poll *Poll) GetCandidatesIDs() (_ []int64, err error) {
ids := make([]int64, 0, 10)
if err := x.Table("poll_judgment").
Select("DISTINCT `poll_judgment`.`candidate_id`").
Where("`poll_judgment`.`poll_id` = ?", poll.ID).
OrderBy("`poll_judgment`.`candidate_id` ASC").
Find(&ids); err != nil {
return nil, err
}
return ids, nil
}
func (poll *Poll) GetJudgmentOnCandidate(judge *User, candidateID int64) (judgmernt *PollJudgment) {
judgment, err := getJudgmentOfJudgeOnPollCandidate(x, judge.ID, poll.ID, candidateID)
if nil != err {
return nil
}
return judgment
}
func (poll *Poll) GetResult() (results *PollResult) {
// The deliberator should probably be a parameter of this function,
// and upstream we could fetch it from context or settings.
deliberator := &PollNaiveDeliberator{
UseHighMean: false,
}
results, err := deliberator.Deliberate(poll)
if nil != err {
return nil // What should we do here?
}
return results
}
func (poll *Poll) CountGrades(candidateID int64, grade uint8) (_ uint64, err error) {
rows := make([]int64, 0, 2)
if err := x.Table("poll_judgment").
Select("COUNT(*) as amount").
Where("`poll_judgment`.`poll_id` = ?", poll.ID).
And("`poll_judgment`.`candidate_id` = ?", candidateID).
And("`poll_judgment`.`grade` = ?", grade).
// Use Get() perhaps?
Find(&rows); err != nil {
return 0, err
}
if 1 != len(rows) {
return 0, fmt.Errorf("wrong amount of COUNT()")
}
amount := uint64(rows[0])
return amount, nil
}
// $ figlet -w 120 "Create"
// ____ _
// / ___|_ __ ___ __ _| |_ ___
// | | | '__/ _ \/ _` | __/ _ \
// | |___| | | __/ (_| | || __/
// \____|_| \___|\__,_|\__\___|
//
type CreatePollOptions struct {
//Type PollType // for inline polls with their own candidates?
Author *User
Repo *Repository
Subject string
Description string
//Grades string
}
func CreatePoll(opts *CreatePollOptions) (poll *Poll, err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
poll, err = createPoll(sess, opts)
if err != nil {
return nil, err
}
if err = sess.Commit(); err != nil {
return nil, err
}
return poll, nil
}
func createPoll(e *xorm.Session, opts *CreatePollOptions) (_ *Poll, err error) {
poll := &Poll{
AuthorID: opts.Author.ID,
Author: opts.Author,
RepoID: opts.Repo.ID,
Repo: opts.Repo,
Subject: opts.Subject,
Description: opts.Description,
AreCandidatesIssues: true,
}
if _, err = e.Insert(poll); err != nil {
return nil, err
}
if err = opts.Repo.getOwner(e); err != nil {
return nil, err
}
//if err = updatePollInfos(e, opts, poll); err != nil {
// return nil, err
//}
return poll, nil
}
// ____ _
// | _ \ ___ __ _ __| |
// | |_) / _ \/ _` |/ _` |
// | _ < __/ (_| | (_| |
// |_| \_\___|\__,_|\__,_|
//
// GetPolls returns the (paginated) list of polls of a given repository and status.
func GetPolls(repoID int64, page int) (PollList, error) {
polls := make([]*Poll, 0, setting.UI.IssuePagingNum)
sess := x.Where("repo_id = ?", repoID)
//sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
if page > 0 {
sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
}
return polls, sess.Find(&polls)
}
func getPollByRepoID(e Engine, repoID, id int64) (*Poll, error) {
m := new(Poll)
has, err := e.ID(id).Where("repo_id = ?", repoID).Get(m)
if err != nil {
return nil, err
} else if !has {
return nil, ErrPollNotFound{ID: id, RepoID: repoID}
}
return m, nil
}
// GetPollByRepoID returns the poll in a repository.
func GetPollByRepoID(repoID, id int64) (*Poll, error) {
return getPollByRepoID(x, repoID, id)
}
// _ _ _ _
// | | | |_ __ __| | __ _| |_ ___
// | | | | '_ \ / _` |/ _` | __/ _ \
// | |_| | |_) | (_| | (_| | || __/
// \___/| .__/ \__,_|\__,_|\__\___|
// |_|
func updatePoll(e Engine, m *Poll) error {
m.Subject = strings.TrimSpace(m.Subject)
_, err := e.ID(m.ID).AllCols().
// Do some extra work here, like updating stats?
//SetExpr("num_closed_issues", builder.Select("count(*)").From("issue").Where(
// builder.Eq{
// "poll_id": m.ID,
// "is_closed": true,
// },
//)).
Update(m)
return err
}
// UpdatePoll updates information of given poll.
func UpdatePoll(m *Poll) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if err := updatePoll(sess, m); err != nil {
return err
}
//if err := updatePollCompleteness(sess, m.ID); err != nil {
// return err
//}
return sess.Commit()
}
// ____ _ _
// | _ \ ___| | ___| |_ ___
// | | | |/ _ \ |/ _ \ __/ _ \
// | |_| | __/ | __/ || __/
// |____/ \___|_|\___|\__\___|
//
// DeletePollByRepoID deletes a poll from a repository.
func DeletePollByRepoID(repoID, id int64) error {
m, err := GetPollByRepoID(repoID, id)
if err != nil {
if IsErrPollNotFound(err) {
return nil // not very confident in this ; yelling is best?
}
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(m.ID).Delete(new(Poll)); err != nil {
return err
}
return sess.Commit()
}

81
models/poll_candidate_merit_profile.go

@ -0,0 +1,81 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"code.gitea.io/gitea/modules/timeutil"
"math"
)
type PollCandidateMeritProfile struct {
Poll *Poll
CandidateID int64 // Issue Index (or internal candidate index, later on)
Position uint64 // Two Candidates may share the same Position (perfect equality)
Grades []uint64 // Amount of Judgments per Grade
JudgmentsAmount uint64
//HalfJudgmentsAmount uint64 // Hack for the template, since we can't do arithmetic
CreatedUnix timeutil.TimeStamp
}
// ____
// / ___|_ ____ _
// \___ \ \ / / _` |
// ___) \ V / (_| |
// |____/ \_/ \__, |
// |___/
//
type CartesianVector2 struct {
X float64
Y float64
}
type TwoCirclePoints struct {
Start *CartesianVector2
End *CartesianVector2
}
func (merit *PollCandidateMeritProfile) GetGradeAngle(gradeID int, gapHalfAngle float64) (_ float64) {
TAU := 6.283185307179586 // Sigh ; how is this not in Golang yet?
totalAngle := TAU - gapHalfAngle*2.0
return totalAngle * float64(merit.Grades[gradeID]) / float64(merit.JudgmentsAmount)
}
func (merit *PollCandidateMeritProfile) GetCirclePoints(gradeID int, radius float64, halfGap float64) (_ *TwoCirclePoints) {
TAU := 6.283185307179586 // Sigh ; how is this not in Golang yet?
gapHalfAngle := halfGap
//gapHalfAngle = 0.39192267544687825 * 0.96 // asin(GOLDEN_RATIO-1)
//gapHalfAngle = TAU / 4.0 // Hemicycle
//gapHalfAngle = 0.0 // Camembert (du fromage!)
totalAngle := TAU - gapHalfAngle*2.0
lowerGradeJudgmentsAmount := uint64(0)
for i := 0; i < gradeID; i++ {
lowerGradeJudgmentsAmount += merit.Grades[i]
}
totalJudgments := float64(merit.JudgmentsAmount)
startingAngle := gapHalfAngle + totalAngle*float64(lowerGradeJudgmentsAmount)/totalJudgments
angle := totalAngle * float64(merit.Grades[gradeID]) / totalJudgments
endingAngle := startingAngle + angle
//println("Angles", gradeID, merit.Grades[gradeID], totalJudgments, startingAngle, endingAngle)
return &TwoCirclePoints{
Start: &CartesianVector2{
X: radius * math.Cos(startingAngle),
Y: radius * math.Sin(startingAngle),
},
End: &CartesianVector2{
X: radius * math.Cos(endingAngle),
Y: radius * math.Sin(endingAngle),
},
}
}
func (merit *PollCandidateMeritProfile) GetColorWord(gradeID int) (_ string) {
return merit.Poll.GetGradeColorWord(uint8(gradeID))
}
func (merit *PollCandidateMeritProfile) GetColorCode(gradeID int) (_ string) {
return merit.Poll.GetGradeColorCode(uint8(gradeID))
}

167
models/poll_deliberator.go

@ -0,0 +1,167 @@
// Copyright 2020 The Macronavirus. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"code.gitea.io/gitea/modules/timeutil"
"fmt"
"sort"
)
type PollDeliberator interface {
Deliberate(poll *Poll) (result *PollResult, err error)
}
// _ _ _
// | \ | | __ _(_)_ _____
// | \| |/ _` | \ \ / / _ \
// | |\ | (_| | |\ V / __/
// |_| \_|\__,_|_| \_/ \___|
//
type PollNaiveDeliberator struct {
UseHighMean bool // should default to false ; strategy for even number of judgments
}
func (deli *PollNaiveDeliberator) Deliberate(poll *Poll) (_ *PollResult, err error) {
naiveTallier := &PollNaiveTallier{}
pollTally, err := naiveTallier.Tally(poll)
if nil != err {
return nil, err
}
// Consider missing judgments as TO_REJECT judgments
// One reason why we need many algorithms, and options on each
for _, candidateTally := range pollTally.Candidates {
missing := pollTally.MaxJudgmentsAmount - candidateTally.JudgmentsAmount
if 0 < missing {
candidateTally.JudgmentsAmount = pollTally.MaxJudgmentsAmount
candidateTally.Grades[0].Amount += missing
//println("Added the missing TO REJECT judgments", missing)
}
}
amountOfGrades := len(poll.GetGradationList())
candidates := make(PollCandidateResults, 0, 64) // /!. 5k issues repos exist
creationTime := timeutil.TimeStampNow()
for _, candidateTally := range pollTally.Candidates {
medianGrade := candidateTally.GetMedian()
candidateScore := deli.GetScore(candidateTally)
gradesProfile := make([]uint64, 0, amountOfGrades)
for i := 0; i < amountOfGrades; i++ {
gradesProfile = append(gradesProfile, candidateTally.Grades[i].Amount)
//gradesProfile = append(gradesProfile, uint64(i+1))
}
meritProfile := &PollCandidateMeritProfile{
Poll: poll,
CandidateID: candidateTally.CandidateID,
Position: 0, // see below
Grades: gradesProfile,
JudgmentsAmount: candidateTally.JudgmentsAmount,
//JudgmentsAmount: (6+1)*3,
CreatedUnix: creationTime,
}
candidates = append(candidates, &PollCandidateResult{
Poll: poll,
CandidateID: candidateTally.CandidateID,
Position: 0, // We set it below after the Sort on Score
MedianGrade: medianGrade,
Score: candidateScore,
Tally: candidateTally,
MeritProfile: meritProfile,
CreatedUnix: creationTime,
})
}
sort.Sort(sort.Reverse(candidates))
// Rule: Multiple Candidates may have the same Position in case of perfect equality.
// or (for Randomized Condorcet evangelists)
// Rule: Multiple Candidates at perfect equality are shuffled.
previousScore := ""
for key, candidate := range candidates {
position := uint64(key + 1)
if (previousScore == candidate.Score) && (key > 0) {
position = candidates[key-1].Position
}
candidate.Position = position
candidate.MeritProfile.Position = position
previousScore = candidate.Score
}
result := &PollResult{
Poll: poll,
Tally: pollTally,
Candidates: candidates,
CreatedUnix: timeutil.TimeStampNow(),
}
return result, nil
}
// ____ _
// / ___| ___ ___ _ __(_)_ __ __ _
// \___ \ / __/ _ \| '__| | '_ \ / _` |
// ___) | (_| (_) | | | | | | | (_| |
// |____/ \___\___/|_| |_|_| |_|\__, |
// |___/
// String scoring is not the fastest but it was within reach of a Go newbie.
/*
This method follows the following algorithm:
// Assume that each candidate has the same amount of judgments = MAX_JUDGES.
// (best fill with 0=REJECT to allow posterior candidate addition, cf. <paper>)
for each Candidate
tally = CandidateTally(Candidate) // sums of judgments, per grade, basically
score = "" // score is a string but could be raw bits
// When we append integers to score below,
// consider that we concatenate the string representation including leading zeroes
// up to the amount of digits we need to store 2 * MAX_JUDGES,
// or the raw bits (unsigned and led as well) in case of a byte array.
for i in range(MAX_GRADES)
grade = tally.median()
score.append(grade) // three digits will suffice for int8
// Collect biggest of the two groups of grades outside of the median.
// Group Grade is the group's grade adjacent to the median group
// Group Sign is:
// - +1 if the group promotes higher grades (adhesion)
// - -1 if the group promotes lower grades (contestation)
// - ±0 if there is no spoon
group_size, group_sign, group_grade = tally.get_biggest_group()
// MAX_JUDGES offset to deal with negative values lexicographically
score.append(MAX_JUDGES + groups_sign * group_size)
// Move the median grades into the group grades
tally.regrade_judgments(grade, groups_grade)
// Use it later in a bubble sort or whatever
Candidate.score = score
*/
func (deli *PollNaiveDeliberator) GetScore(pct *PollCandidateTally) (_ string) {
score := ""
ct := pct.Copy() // /!. Poll is not a copy (nor does it have to be)
for _, _ = range pct.Poll.GetGradationList() {
medianGrade := ct.GetMedian()
score += fmt.Sprintf("%03d", medianGrade)
groupSize, groupSign, groupGrade := ct.GetBiggestGroup(medianGrade)
score += fmt.Sprintf("%012d",
int(ct.JudgmentsAmount)+groupSize*groupSign)
ct.RegradeJudgments(medianGrade, groupGrade)
}
return score
}

159
models/poll_deliberator_test.go

@ -0,0 +1,159 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
//"sort"
"testing"
//"time"
"github.com/stretchr/testify/assert"
)
func TestNaiveDeliberator(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
userAli := AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
userBob := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
userCho := AssertExistsAndLoadBean(t, &User{ID: 3}).(*User)
poll, err := CreatePoll(&CreatePollOptions{
Repo: repo,
Author: userAli,
Subject: "Demand",
})
assert.NoError(t, err)
assert.NotNil(t, poll)
pnd := &PollNaiveDeliberator{}
// No judgments yet
result, err := pnd.Deliberate(poll)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.NotNil(t, result.Poll)
assert.Equal(t, poll, result.Poll)
assert.NotNil(t, result.Tally)
assert.NotNil(t, result.Candidates)
assert.Len(t, result.Candidates, 0)
// Add a Judgment from Ali
// Candidate 1 : SOMEWHAT_GOOD
// Candidate 2 :
judgment, err := CreateJudgment(&CreateJudgmentOptions{
Judge: userAli,
Poll: poll,
Grade: 3,
CandidateID: 1,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
result, err = pnd.Deliberate(poll)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.NotNil(t, result.Tally)
assert.NotNil(t, result.Candidates)
assert.Len(t, result.Candidates, 1)
// Add a judgment from Bob
// Candidate 1 : PASSABLE SOMEWHAT_GOOD
// Candidate 2 :
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userBob,
Poll: poll,
Grade: 2,
CandidateID: 1,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
result, err = pnd.Deliberate(poll)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.NotNil(t, result.Tally)
assert.NotNil(t, result.Candidates)
assert.Len(t, result.Candidates, 1)
assert.Equal(t, uint64(1), result.Candidates[0].Position)
// Add another judgment from Bob
// Candidate 1 : PASSABLE SOMEWHAT_GOOD
// Candidate 2 : GOOD
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userBob,
Poll: poll,
Grade: 4,
CandidateID: 2,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
result, err = pnd.Deliberate(poll)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.NotNil(t, result.Candidates)
assert.Len(t, result.Candidates, 2)
assert.Equal(t, uint64(1), result.Candidates[0].Position)
assert.Equal(t, uint64(2), result.Candidates[1].Position)
assert.Equal(t, int64(1), result.Candidates[0].CandidateID)
assert.Equal(t, int64(2), result.Candidates[1].CandidateID)
assert.Equal(t, uint8(2), result.Candidates[0].MedianGrade)
assert.Equal(t, uint8(0), result.Candidates[1].MedianGrade)
// Add another 2 judgments from Cho and one from Ali
// Candidate 1 : PASSABLE SOMEWHAT_GOOD GOOD
// Candidate 2 : SOMEWHAT_GOOD SOMEWHAT_GOOD GOOD
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userCho,
Poll: poll,
Grade: 4,
CandidateID: 1,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userCho,
Poll: poll,
Grade: 3,
CandidateID: 2,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userAli,
Poll: poll,
Grade: 3,
CandidateID: 2,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
result, err = pnd.Deliberate(poll)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.NotNil(t, result.Candidates)
assert.Len(t, result.Candidates, 2)
assert.Equal(t, uint64(1), result.Candidates[0].Position)
assert.Equal(t, uint64(2), result.Candidates[1].Position)
assert.Equal(t, int64(2), result.Candidates[0].CandidateID)
assert.Equal(t, int64(1), result.Candidates[1].CandidateID)
//println("C1", result.Candidates[1].MedianGrade)
assert.Equal(t, uint8(3), result.Candidates[0].MedianGrade)
assert.Equal(t, uint8(3), result.Candidates[1].MedianGrade)
assert.Equal(t, uint64(1), result.Candidates[0].Tally.Grades[4].Amount)
assert.Equal(t, uint64(2), result.Candidates[0].Tally.Grades[3].Amount)
assert.Equal(t, uint64(1), result.Candidates[1].Tally.Grades[2].Amount)
assert.Equal(t, uint64(1), result.Candidates[1].Tally.Grades[3].Amount)
assert.Equal(t, uint64(1), result.Candidates[1].Tally.Grades[4].Amount)
}

187
models/poll_judgment.go

@ -0,0 +1,187 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
//"code.gitea.io/gitea/modules/references"
"code.gitea.io/gitea/modules/timeutil"
"fmt"
//"fmt"
"xorm.io/xorm"
)
// A Judgment on a Poll
type PollJudgment struct {
ID int64 `xorm:"pk autoincr"`
PollID int64 `xorm:"INDEX UNIQUE(poll_judge_candidate)"`
Poll *Poll `xorm:"-"`
JudgeID int64 `xorm:"INDEX UNIQUE(poll_judge_candidate)"`
Judge *User `xorm:"-"`
// Either an Issue ID or an index in the list of Candidates (for inline polls)
CandidateID int64 `xorm:"UNIQUE(poll_judge_candidate)"`
// There may be other graduations
// 0 = to reject
// 1 = poor
// 2 = passable
// 3 = good
// 4 = very good
// 5 = excellent
// Make sure 0 always means *something* in your graduation
// Various graduations are provided <???>.
Grade uint8
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
}
type CreateJudgmentOptions struct {
Poll *Poll
Judge *User
Grade uint8
CandidateID int64
}
type UpdateJudgmentOptions struct {
Poll *Poll
Judge *User
Grade uint8
CandidateID int64
}
type DeleteJudgmentOptions struct {
Poll *Poll
Judge *User
CandidateID int64
}
func CreateJudgment(opts *CreateJudgmentOptions) (judgment *PollJudgment, err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
judgment, err = createJudgment(sess, opts)
if err != nil {
return nil, err
}
if err = sess.Commit(); err != nil {
return nil, err
}
return judgment, nil
}
func createJudgment(e *xorm.Session, opts *CreateJudgmentOptions) (_ *PollJudgment, err error) {
judgment := &PollJudgment{
PollID: opts.Poll.ID,
Poll: opts.Poll,
JudgeID: opts.Judge.ID,
Judge: opts.Judge,
CandidateID: opts.CandidateID,
Grade: opts.Grade,
}
//e.Find()
if _, err = e.Insert(judgment); err != nil {
return nil, err
}
//if err = updatePollInfos(e, opts, poll); err != nil {
// return nil, err
//}
return judgment, nil
}
func getJudgmentByID(e Engine, id int64) (*PollJudgment, error) {
repo := new(PollJudgment)
has, err := e.ID(id).Get(repo)
if err != nil {
return nil, err
} else if !has {
return nil, ErrJudgmentNotFound{}
}
return repo, nil
}
func getJudgmentOfJudgeOnPollCandidate(e Engine, judgeID int64, pollID int64, candidateID int64) (judgment *PollJudgment, err error) {
// We could probably use only one SQL query instead of two here.
// No idea how this ORM works, and sprinting past it with snippet copy-pasting.
judgmentsIds := make([]int64, 0, 1)
if err = e.Table("poll_judgment").
Cols("id").
Where("`poll_judgment`.`judge_id` = ?", judgeID).
And("`poll_judgment`.`poll_id` = ?", pollID).
And("`poll_judgment`.`candidate_id` = ?", candidateID).
Limit(1). // perhaps .Get() is what we need here?
Find(&judgmentsIds); err != nil {
return nil, fmt.Errorf("find judgment: %v", err)
}
if 0 == len(judgmentsIds) {
return nil, ErrJudgmentNotFound{}
}
judgment, errj := getJudgmentByID(e, judgmentsIds[0])
if errj != nil {
return nil, errj
}
return judgment, nil
}
func UpdateJudgment(opts *UpdateJudgmentOptions) (judgment *PollJudgment, err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
judgment, errJ := getJudgmentOfJudgeOnPollCandidate(sess, opts.Judge.ID, opts.Poll.ID, opts.CandidateID)
if nil != errJ {
return nil, errJ
}
judgment.Grade = opts.Grade
_, err = sess.ID(judgment.ID).
Cols("grade", "updated_unix").
Update(judgment)
if err != nil {
return nil, err
}
if err = sess.Commit(); err != nil {
return nil, err
}
return judgment, nil
}
func DeleteJudgment(opts *DeleteJudgmentOptions) (err error) {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
judgment, errJ := getJudgmentOfJudgeOnPollCandidate(sess, opts.Judge.ID, opts.Poll.ID, opts.CandidateID)
if nil != errJ {
return errJ
}
if _, errD := sess.Delete(judgment); nil != errD {
return errD
}
if err = sess.Commit(); nil != err {
return err
}
return nil
}

76
models/poll_judgment_test.go

@ -0,0 +1,76 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
//"sort"
"testing"
//"time"
"github.com/stretchr/testify/assert"
)
func TestPollJudgment_Create(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
//issue := AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue)
//assert.Equal(t, repo, issue.Repo)
poll, errp := CreatePoll(&CreatePollOptions{
Repo: repo,
Author: user,
Subject: "Quality",
})
assert.NoError(t, errp)
assert.NotNil(t, poll)
judgment, err := CreateJudgment(&CreateJudgmentOptions{
Judge: user,
Poll: poll,
Grade: 3,
CandidateID: 1,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
// Emit another Judgment, on another Candidate
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: user,
Poll: poll,
Grade: 1,
CandidateID: 2,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
// Cannot create another judgment on the same poll and candidate
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: user,
Poll: poll,
Grade: 0,
CandidateID: 2,
})
assert.Error(t, err)
assert.Nil(t, judgment)
// … you have to update it
judgment, err = UpdateJudgment(&UpdateJudgmentOptions{
Judge: user,
Poll: poll,
Grade: 0,
CandidateID: 2,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
}

78
models/poll_result.go

@ -0,0 +1,78 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"code.gitea.io/gitea/modules/timeutil"
"strconv"
)
// ____ _ _ _ _ ____ _ _
// / ___|__ _ _ __ __| (_) __| | __ _| |_ ___| _ \ ___ ___ _ _| | |_
// | | / _` | '_ \ / _` | |/ _` |/ _` | __/ _ \ |_) / _ \/ __| | | | | __|
// | |__| (_| | | | | (_| | | (_| | (_| | || __/ _ < __/\__ \ |_| | | |_
// \____\__,_|_| |_|\__,_|_|\__,_|\__,_|\__\___|_| \_\___||___/\__,_|_|\__|
//
type PollCandidateResult struct {
Poll *Poll
CandidateID int64 // Issue Index (or internal candidate index, later on)
Position uint64 // Two Candidates may share the same Position (perfect equality)
MedianGrade uint8
Score string
Tally *PollCandidateTally
MeritProfile *PollCandidateMeritProfile
CreatedUnix timeutil.TimeStamp
}
func (result *PollCandidateResult) GetColorWord() (_ string) {
return result.Poll.GetGradeColorWord(result.MedianGrade)
}
func (result *PollCandidateResult) GetCandidateName() (_ string) { // FIXME
isssue, err := GetIssueByID(result.CandidateID)
if nil != err {
return "Candidate #" + strconv.FormatInt(result.CandidateID, 10)
}
return isssue.Title
}
// ____ _ _ _ _ ____ _ _
// / ___|__ _ _ __ __| (_) __| | __ _| |_ ___| _ \ ___ ___ _ _| | |_ ___
// | | / _` | '_ \ / _` | |/ _` |/ _` | __/ _ \ |_) / _ \/ __| | | | | __/ __|
// | |__| (_| | | | | (_| | | (_| | (_| | || __/ _ < __/\__ \ |_| | | |_\__ \
// \____\__,_|_| |_|\__,_|_|\__,_|\__,_|\__\___|_| \_\___||___/\__,_|_|\__|___/
//
// PollCandidateResults implements sort.Interface based on the Score field.
type PollCandidateResults []*PollCandidateResult
func (a PollCandidateResults) Len() int { return len(a) }
func (a PollCandidateResults) Less(i, j int) bool { return a[i].Score < a[j].Score }
func (a PollCandidateResults) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// ____ _ _
// | _ \ ___ ___ _ _| | |_
// | |_) / _ \/ __| | | | | __|
// | _ < __/\__ \ |_| | | |_
// |_| \_\___||___/\__,_|_|\__|
//
type PollResult struct {
Poll *Poll
Tally *PollTally
Candidates PollCandidateResults
CreatedUnix timeutil.TimeStamp
}
func (result *PollResult) GetCandidate(candidateID int64) (_ *PollCandidateResult) {
// A `for` loop is pretty inefficient, index this somehow?
for _, candidate := range result.Candidates {
if candidate.CandidateID == candidateID {
return candidate
}
}
return nil
}

214
models/poll_tally.go

@ -0,0 +1,214 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"code.gitea.io/gitea/modules/timeutil"
)
// ____ _ _____ _ _
// / ___|_ __ __ _ __| | ___ |_ _|_ _| | |_ _
// | | _| '__/ _` |/ _` |/ _ \ | |/ _` | | | | | |
// | |_| | | | (_| | (_| | __/ | | (_| | | | |_| |
// \____|_| \__,_|\__,_|\___| |_|\__,_|_|_|\__, |
// |___/
type PollCandidateGradeTally struct {
Grade uint8
Amount uint64
CreatedUnix timeutil.TimeStamp
}
// ____ _ _ _ _ _____ _ _
// / ___|__ _ _ __ __| (_) __| | __ _| |_ ___ |_ _|_ _| | |_ _
// | | / _` | '_ \ / _` | |/ _` |/ _` | __/ _ \ | |/ _` | | | | | |
// | |__| (_| | | | | (_| | | (_| | (_| | || __/ | | (_| | | | |_| |
// \____\__,_|_| |_|\__,_|_|\__,_|\__,_|\__\___| |_|\__,_|_|_|\__, |
// |___/
type PollCandidateTally struct {
Poll *Poll
CandidateID int64 // Issue Index (or internal candidate index, later on)
Grades []*PollCandidateGradeTally // Sorted by grade (0 == REJECT)
JudgmentsAmount uint64
CreatedUnix timeutil.TimeStamp
}
func (pct *PollCandidateTally) Copy() (_ *PollCandidateTally) {
grades := make([]*PollCandidateGradeTally, 0, 8)
for _, grade := range pct.Grades {
grades = append(grades, &PollCandidateGradeTally{
Grade: grade.Grade,
Amount: grade.Amount,
CreatedUnix: grade.CreatedUnix,
})
}
return &PollCandidateTally{
Poll: pct.Poll,
CandidateID: pct.CandidateID,
Grades: grades,
JudgmentsAmount: pct.JudgmentsAmount,
CreatedUnix: pct.CreatedUnix,
}
}
func (pct *PollCandidateTally) GetMedian() (_ uint8) {
if 0 == pct.JudgmentsAmount {
return uint8(0)
//return 0 // to test
}
adjustedTotal := pct.JudgmentsAmount - 1
//if opts.UseHighMedian {
// adjustedTotal := pct.JudgmentsAmount + 1
//}
medianIndex := adjustedTotal / 2 // Euclidean div
cursorIndex := uint64(0)
for _, grade := range pct.Grades {
if 0 == grade.Amount {
continue
}
startIndex := cursorIndex
cursorIndex += grade.Amount
endIndex := cursorIndex
if (startIndex <= medianIndex) && (medianIndex < endIndex) {
return grade.Grade
}
}
println("warning: GetMedian defaulting to 0")
return uint8(0)
}
func (pct *PollCandidateTally) GetBiggestGroup(aroundGrade uint8) (groupSize int, groupSign int, groupGrade uint8) {
belowGroupSize := 0
belowGroupSign := -1
belowGroupGrade := uint8(0)
aboveGroupSize := 0
aboveGroupSign := 1
aboveGroupGrade := uint8(0)
for k, _ := range pct.Poll.GetGradationList() {
grade := uint8(k)
//for _, grade := range pct.Poll.GetGrades() {
if grade < aroundGrade {
belowGroupSize += int(pct.Grades[grade].Amount)
belowGroupGrade = grade
}
if grade > aroundGrade {
aboveGroupSize += int(pct.Grades[grade].Amount)
if 0 == aboveGroupGrade {
aboveGroupGrade = grade
}
}
}
if aboveGroupSize > belowGroupSize {
return aboveGroupSize, aboveGroupSign, aboveGroupGrade
}
return belowGroupSize, belowGroupSign, belowGroupGrade
}
func (pct *PollCandidateTally) RegradeJudgments(fromGrade uint8, toGrade uint8) {
if toGrade == fromGrade {
return
}
pct.Grades[toGrade].Amount += pct.Grades[fromGrade].Amount
pct.Grades[fromGrade].Amount = 0
}
// _____ _ _
// |_ _|_ _| | |_ _
// | |/ _` | | | | | |
// | | (_| | | | |_| |
// |_|\__,_|_|_|\__, |
// |___/
type PollTally struct {
Poll *Poll
MaxJudgmentsAmount uint64 // per candidate, will help including default grade 0=TO_REJECT
Candidates []*PollCandidateTally
CreatedUnix timeutil.TimeStamp
}
// _____ _ _ _
// |_ _|_ _| | (_) ___ _ __
// | |/ _` | | | |/ _ \ '__|
// | | (_| | | | | __/ |
// |_|\__,_|_|_|_|\___|_|
//
type PollTallier interface {
Tally(poll *Poll) (tally *PollTally, err error)
}
// _ _ _
// | \ | | __ _(_)_ _____
// | \| |/ _` | \ \ / / _ \
// | |\ | (_| | |\ V / __/
// |_| \_|\__,_|_| \_/ \___|
//
type PollNaiveTallier struct{}
func (tallier *PollNaiveTallier) Tally(poll *Poll) (_ *PollTally, err error) {
gradation := poll.GetGradationList()
candidatesIDs, errG := poll.GetCandidatesIDs()
if nil != errG {
return nil, errG
}
candidates := make([]*PollCandidateTally, 0, 64)
maximumAmount := uint64(0)
for _, candidateID := range candidatesIDs {
grades := make([]*PollCandidateGradeTally, 0, 8)
judgmentsAmount := uint64(0)
for gradeInt, _ := range gradation {
grade := uint8(gradeInt)
amount, errC := poll.CountGrades(candidateID, grade)
if nil != errC {
return nil, errC
}
judgmentsAmount += amount
grades = append(grades, &PollCandidateGradeTally{
Grade: grade,
Amount: amount,
CreatedUnix: timeutil.TimeStampNow(),
})
}
//maximumAmount = util.Max(judgmentsAmount, maximumAmount)
if maximumAmount < judgmentsAmount {
maximumAmount = judgmentsAmount
}
candidates = append(candidates, &PollCandidateTally{
Poll: poll,
CandidateID: candidateID,
Grades: grades,
JudgmentsAmount: judgmentsAmount,
CreatedUnix: timeutil.TimeStampNow(),
})
}
tally := &PollTally{
Poll: poll,
MaxJudgmentsAmount: maximumAmount,
Candidates: candidates,
CreatedUnix: timeutil.TimeStampNow(),
}
return tally, nil
}

139
models/poll_tally_test.go

@ -0,0 +1,139 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"code.gitea.io/gitea/modules/timeutil"
//"sort"
"testing"
//"time"
"github.com/stretchr/testify/assert"
)
func TestTally(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
userAli := AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
userBob := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
poll, err := CreatePoll(&CreatePollOptions{
Repo: repo,
Author: userAli,
Subject: "Demand",
})
assert.NoError(t, err)
assert.NotNil(t, poll)
pnt := &PollNaiveTallier{}
// No judgments yet
tally, err := pnt.Tally(poll)
assert.NoError(t, err)
assert.NotNil(t, tally)
assert.Len(t, tally.Candidates, 0)
assert.Equal(t, uint64(0), tally.MaxJudgmentsAmount)
// Add a Judgment from Ali
judgment, err := CreateJudgment(&CreateJudgmentOptions{
Judge: userAli,
Poll: poll,
Grade: 3,
CandidateID: 1,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
tally, err = pnt.Tally(poll)
assert.NoError(t, err)
assert.NotNil(t, tally)
assert.Len(t, tally.Candidates, 1)
assert.Equal(t, uint64(1), tally.MaxJudgmentsAmount)
// Add a judgment from Bob
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userBob,
Poll: poll,
Grade: 2,
CandidateID: 1,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
tally, err = pnt.Tally(poll)
assert.NoError(t, err)
assert.NotNil(t, tally)
assert.Len(t, tally.Candidates, 1)
assert.Equal(t, uint64(2), tally.MaxJudgmentsAmount)
// Add another judgment from Ali, on another candidate
judgment, err = CreateJudgment(&CreateJudgmentOptions{
Judge: userAli,
Poll: poll,
Grade: 3,
CandidateID: 2,
})
assert.NoError(t, err)
assert.NotNil(t, judgment)
tally, err = pnt.Tally(poll)
assert.NoError(t, err)
assert.NotNil(t, tally)
assert.Len(t, tally.Candidates, 2)
assert.Equal(t, uint64(2), tally.MaxJudgmentsAmount)
}
func TestPollCandidateTally_GetMedian(t *testing.T) {
tally := buildCandidateTally([]int{2, 3, 5, 7, 11, 13})
assert.Equal(t, uint8(4), tally.GetMedian())
tally = buildCandidateTally([]int{0, 0, 0, 0, 0, 0})
assert.Equal(t, uint8(0), tally.GetMedian())
tally = buildCandidateTally([]int{0, 0, 0, 1, 0, 0})
assert.Equal(t, uint8(3), tally.GetMedian())
tally = buildCandidateTally([]int{0, 0, 1, 0, 0, 1})
assert.Equal(t, uint8(2), tally.GetMedian())
tally = buildCandidateTally([]int{1, 0, 1, 0, 0, 1})
assert.Equal(t, uint8(2), tally.GetMedian())
tally = buildCandidateTally([]int{1, 0, 1, 0, 0, 3})
assert.Equal(t, uint8(5), tally.GetMedian())
tally = buildCandidateTally([]int{0, 2, 2})
assert.Equal(t, uint8(1), tally.GetMedian())
}
func buildCandidateTally(grades []int) (_ *PollCandidateTally) {
things := make([]*PollCandidateGradeTally, 0, len(grades))
totalAmount := 0
for grade, amount := range grades {
things = append(things, &PollCandidateGradeTally{
Grade: uint8(grade),
Amount: uint64(amount),
CreatedUnix: timeutil.TimeStampNow(),
})
totalAmount += amount
}
return &PollCandidateTally{
Poll: nil, // mock me
CandidateID: 0,
Grades: things,
JudgmentsAmount: uint64(totalAmount),
CreatedUnix: timeutil.TimeStampNow(),
}
}

30
models/poll_test.go

@ -0,0 +1,30 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
//"sort"
"testing"
//"time"
"github.com/stretchr/testify/assert"
)
func TestPoll_Create(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
var opts = CreatePollOptions{
Repo: repo,
Author: user,
Subject: "Quality",
}
poll, err := CreatePoll(&opts)
assert.NoError(t, err)
assert.NotNil(t, poll)
}

4
models/repo.go

@ -532,6 +532,10 @@ func (repo *Repository) deleteWiki(e Engine) error {
return err
}
func (repo *Repository) GetPolls() (_ PollList, err error) {
return GetPolls(repo.ID, 0)
}
func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
if err = repo.getOwner(e); err != nil {
return nil, err

17
modules/auth/poll_form.go

@ -0,0 +1,17 @@
package auth // not sure why this is in package auth?
import (
"gitea.com/macaron/binding"
"gitea.com/macaron/macaron"
)
// Form for creating a poll
type CreatePollForm struct {
Subject string `binding:"Required;MaxSize(128)"` // 128 is duplicated in the template
Description string
}
// Validate validates the form fields
func (f *CreatePollForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

30
options/locale/locale_en-US.ini

@ -1395,6 +1395,36 @@ milestones.filter_sort.most_complete = Most complete
milestones.filter_sort.most_issues = Most issues
milestones.filter_sort.least_issues = Least issues
polls = Polls
polls.create = Create Poll
polls.create.success = You created the poll '%s'.
polls.cancel = Cancel
polls.delete.success = You deleted the poll. Why would you do such a thing?! I'm hurt.
polls.modify = Update Poll
polls.operate.edit = Edit
polls.operate.delete = Delete
polls.view = View Poll
polls.new = New Poll
polls.new.subheader = This poll will use Majority Judgment on all the Issues
polls.subject.label = Subject (one-word, short name is advised)
polls.subject.placeholder = Urgency, Importance, Demand…
polls.description.label = Description (rationale, constitutive details, consequences…)
polls.gradation.label = Grades
polls.candidates.label = Candidates
polls.candidates.pool.issues_merges = All Issues and Merge Requests
polls.candidates.pool.issues = All Issues only
polls.candidates.pool.merges = All Merge Requests only
polls.candidates.pool.indices = All of these
polls.candidates.pool.indices.help = Comma-separated list of issues
polls.edit = Edit Poll
polls.edit.subheader = Should one be allowed to change the subject after the poll has started?
polls.edit.success = You edited the poll '%s' successfully.
polls.modal.deletion.header = Are you sure you want to delete this poll?
polls.modal.deletion.description = This operation CANNOT be undone! It will also delete all attached judgments.
polls.judgments.create.success = Your judgment was recorded. Thank you ! (+0.618 karma)
polls.judgments.update.success = Your judgment was updated.
polls.judgments.delete.success = Your judgment was discarded, and then burnt, and the ashes were scattered into lava.
signing.will_sign = This commit will be signed with key '%s'
signing.wont_sign.error = There was an error whilst checking if the commit could be signed
signing.wont_sign.nokey = There is no key available to sign this commit