/* Copyright 2017-2022 CAcert Inc. SPDX-License-Identifier: Apache-2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package models import ( "context" "database/sql" "errors" "fmt" "log" "time" "github.com/jmoiron/sqlx" ) type VoteType uint8 const unknownVariant = "unknown" const ( VoteTypeMotion VoteType = 0 VoteTypeVeto VoteType = 1 ) var voteTypeLabels = map[VoteType]string{ VoteTypeMotion: "motion", VoteTypeVeto: "veto", } func (v VoteType) String() string { if label, ok := voteTypeLabels[v]; ok { return label } return unknownVariant } func (v VoteType) QuorumAndMajority() (int, float32) { const ( majorityDefault = 0.99 majorityMotion = 0.50 quorumDefault = 1 quorumMotion = 3 ) if v == VoteTypeMotion { return quorumMotion, majorityMotion } return quorumDefault, majorityDefault } type VoteStatus int8 const ( voteStatusDeclined VoteStatus = -1 voteStatusPending VoteStatus = 0 voteStatusApproved VoteStatus = 1 voteStatusWithdrawn VoteStatus = -2 ) var voteStatusLabels = map[VoteStatus]string{ voteStatusDeclined: "declined", voteStatusPending: "pending", voteStatusApproved: "approved", voteStatusWithdrawn: "withdrawn", } func (v VoteStatus) String() string { if label, ok := voteStatusLabels[v]; ok { return label } return unknownVariant } type VoteChoice int const ( voteAye VoteChoice = 1 voteNaye VoteChoice = -1 voteAbstain VoteChoice = 0 ) var voteChoiceLabels = map[VoteChoice]string{ voteAye: "aye", voteNaye: "naye", voteAbstain: "abstain", } func (v VoteChoice) String() string { if label, ok := voteChoiceLabels[v]; ok { return label } return unknownVariant } type VoteSums struct { Ayes, Nayes, Abstains int } func (v *VoteSums) VoteCount() int { return v.Ayes + v.Nayes + v.Abstains } func (v *VoteSums) TotalVotes() int { return v.Ayes + v.Nayes } func (v *VoteSums) CalculateResult(quorum int, majority float32) (VoteStatus, string) { if v.VoteCount() < quorum { return voteStatusDeclined, fmt.Sprintf("Needed quorum of %d has not been reached.", quorum) } if (float32(v.Ayes) / float32(v.TotalVotes())) < majority { return voteStatusDeclined, fmt.Sprintf("Needed majority of %0.2f%% has not been reached.", majority) } return voteStatusApproved, "Quorum and majority have been reached" } type Decision struct { ID int64 `db:"id"` Proposed time.Time Proponent int64 `db:"proponent"` Title string Content string Quorum int Majority int Status VoteStatus Due time.Time Modified time.Time Tag string VoteType VoteType } type ClosedDecision struct { Decision *Decision VoteSums *VoteSums Reasoning string } type DecisionModel struct { DB *sqlx.DB InfoLog *log.Logger } // Create a new decision. func (m *DecisionModel) Create( ctx context.Context, proponent *Voter, voteType VoteType, title, content string, proposed, due time.Time, ) (int64, error) { d := &Decision{ Proposed: proposed.UTC(), Proponent: proponent.ID, Title: title, Content: content, Due: due.UTC(), VoteType: voteType, } result, err := m.DB.NamedExecContext( ctx, `INSERT INTO decisions (proposed, proponent, title, content, votetype, status, due, modified, tag) VALUES (:proposed, :proponent, :title, :content, :votetype, :status, :due, :proposed, 'm' || strftime('%Y%m%d', :proposed) || '.' || ( SELECT COUNT(*)+1 AS num FROM decisions WHERE proposed BETWEEN date(:proposed) AND date(:proposed, '1 day') ))`, d, ) if err != nil { return 0, fmt.Errorf("creating motion failed: %w", err) } id, err := result.LastInsertId() if err != nil { return 0, fmt.Errorf("could not get inserted decision id: %w", err) } return id, nil } func (m *DecisionModel) CloseDecisions(ctx context.Context) ([]*ClosedDecision, error) { tx, err := m.DB.BeginTxx(ctx, nil) if err != nil { return nil, fmt.Errorf("could not start transaction: %w", err) } defer func(tx *sqlx.Tx) { _ = tx.Rollback() }(tx) rows, err := tx.NamedQuery(` SELECT decisions.id, decisions.tag, decisions.proponent, decisions.proposed, decisions.title, decisions.content, decisions.votetype, decisions.status, decisions.due, decisions.modified FROM decisions WHERE decisions.status=0 AND :now > due`, struct{ Now time.Time }{Now: time.Now().UTC()}) if err != nil { return nil, fmt.Errorf("fetching closable decisions failed: %w", err) } defer func(rows *sqlx.Rows) { _ = rows.Close() }(rows) decisions := make([]*Decision, 0) for rows.Next() { decision := &Decision{} if err = rows.StructScan(decision); err != nil { return nil, fmt.Errorf("scanning row failed: %w", err) } if rows.Err() != nil { return nil, fmt.Errorf("row error: %w", err) } decisions = append(decisions, decision) } results := make([]*ClosedDecision, 0, len(decisions)) var decisionResult *ClosedDecision for _, decision := range decisions { m.InfoLog.Printf("found closable decision %s", decision.Tag) if decisionResult, err = m.CloseDecision(ctx, tx, decision); err != nil { return nil, fmt.Errorf("closing decision %s failed: %w", decision.Tag, err) } results = append(results, decisionResult) } if err = tx.Commit(); err != nil { return nil, fmt.Errorf("could not commit transaction: %w", err) } return results, nil } func (m *DecisionModel) CloseDecision(ctx context.Context, tx *sqlx.Tx, d *Decision) (*ClosedDecision, error) { quorum, majority := d.VoteType.QuorumAndMajority() var ( voteSums *VoteSums err error reasoning string ) if voteSums, err = m.SumsForDecision(ctx, tx, d); err != nil { return nil, fmt.Errorf("getting vote sums failed: %w", err) } d.Status, reasoning = voteSums.CalculateResult(quorum, majority) result, err := m.DB.NamedExecContext( ctx, `UPDATE decisions SET status=:status, modified=CURRENT_TIMESTAMP WHERE id=:id`, d, ) if err != nil { return nil, fmt.Errorf("could not execute update query: %w", err) } affectedRows, err := result.RowsAffected() if err != nil { return nil, fmt.Errorf("could not get affected rows count: %w", err) } if affectedRows != 1 { return nil, fmt.Errorf("unexpected number of rows %d instead of 1", affectedRows) } m.InfoLog.Printf("decision %s closed with result %s: reasoning '%s'", d.Tag, d.Status, reasoning) return &ClosedDecision{d, voteSums, reasoning}, nil } func (m *DecisionModel) UnVotedDecisionsForVoter(_ context.Context, _ *Voter) ([]Decision, error) { panic("not implemented") } func (m *DecisionModel) SumsForDecision(ctx context.Context, tx *sqlx.Tx, d *Decision) (*VoteSums, error) { voteRows, err := tx.QueryxContext( ctx, `SELECT vote, COUNT(vote) FROM votes WHERE decision=$1 GROUP BY vote`, d.ID, ) if err != nil { return nil, fmt.Errorf("fetching vote sums for motion %s failed: %w", d.Tag, err) } defer func(voteRows *sqlx.Rows) { _ = voteRows.Close() }(voteRows) sums := &VoteSums{} for voteRows.Next() { var ( vote VoteChoice count int ) if err = voteRows.Err(); err != nil { return nil, fmt.Errorf("could not fetch vote sums for motion %s: %w", d.Tag, err) } if err = voteRows.Scan(&vote, &count); err != nil { return nil, fmt.Errorf("could not parse row for vote sums of motion %s: %w", d.Tag, err) } switch vote { case voteAye: sums.Ayes = count case voteNaye: sums.Nayes = count case voteAbstain: sums.Abstains = count } } return sums, nil } func (m *DecisionModel) NextPendingDecisionDue(ctx context.Context) (*time.Time, error) { row := m.DB.QueryRowContext( ctx, `SELECT due FROM decisions WHERE status=0 ORDER BY due LIMIT 1`, nil, ) if row == nil { return nil, errors.New("no row returned") } if err := row.Err(); err != nil { return nil, fmt.Errorf("could not retrieve row for next pending decision: %w", err) } var due time.Time if err := row.Scan(&due); err != nil { if errors.Is(err, sql.ErrNoRows) { m.InfoLog.Print("no pending decisions") return nil, nil } return nil, fmt.Errorf("parsing result failed: %w", err) } return &due, nil }