You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gitea-fork-majority-judgment/models/poll.go

332 lines
8.1 KiB

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
4 years ago
// 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()
}