111 lines
2.3 KiB
Go
111 lines
2.3 KiB
Go
|
package store
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"strings"
|
||
|
"time"
|
||
|
|
||
|
"code.c-base.org/baccenfutter/govote/voting"
|
||
|
"code.c-base.org/baccenfutter/govote/voting/quorum"
|
||
|
"code.c-base.org/baccenfutter/govote/voting/threshold"
|
||
|
"code.c-base.org/baccenfutter/govote/voting/vote"
|
||
|
)
|
||
|
|
||
|
func NewVoting(
|
||
|
id string,
|
||
|
r string,
|
||
|
d time.Time,
|
||
|
q quorum.Quorum,
|
||
|
t threshold.Threshold,
|
||
|
e []string,
|
||
|
a bool,
|
||
|
) error {
|
||
|
electors := strings.Join(e, ";")
|
||
|
if _, err := votingInsert.Exec(id, r, d.String(), q.String(), t.String(), electors, a); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func GetVoting(id string) (*voting.Voting, error) {
|
||
|
result := votingSelect.QueryRow(id)
|
||
|
if result == nil {
|
||
|
return nil, fmt.Errorf("not found: %s", id)
|
||
|
}
|
||
|
var (
|
||
|
err error
|
||
|
r string
|
||
|
d time.Time
|
||
|
q quorum.Quorum
|
||
|
t threshold.Threshold
|
||
|
e []string
|
||
|
a bool
|
||
|
dbDeadline string
|
||
|
dbQuorum string
|
||
|
dbThreshold string
|
||
|
dbElectors string
|
||
|
)
|
||
|
if err := result.Scan(&r, &dbDeadline, &dbQuorum, &dbThreshold, &dbElectors, &a); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if d, err = time.Parse("2006-01-02 15:04:05 -0700 MST", dbDeadline); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if q, err = quorum.FromString(dbQuorum); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
if t, err = threshold.FromString(dbThreshold); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
e = strings.Split(dbElectors, " ")
|
||
|
|
||
|
votes, err := getVotes(id)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
v := voting.NewVotingWithVotes(id, r, d, q, t, e, a, votes)
|
||
|
return v, nil
|
||
|
}
|
||
|
|
||
|
func PlaceVote(id, votingID, elector string, choice vote.Choice) error {
|
||
|
if _, err := voteInsert.Exec(id, votingID, elector, choice.String()); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func getVotes(id string) ([]vote.Vote, error) {
|
||
|
result, err := voteSelect.Query(id)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
var (
|
||
|
e string
|
||
|
c vote.Choice
|
||
|
ts time.Time
|
||
|
dbChoice string
|
||
|
dbTimestamp string
|
||
|
votes = []vote.Vote{}
|
||
|
)
|
||
|
for result.Next() {
|
||
|
if err = result.Scan(&e, &dbChoice, &dbTimestamp); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if c, err = vote.ChoiceFromString(dbChoice); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if ts, err = time.Parse("2006-01-02 15:04:05", dbTimestamp); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
v := vote.NewVoteWithTimestamp(e, c, ts)
|
||
|
votes = append(votes, v)
|
||
|
}
|
||
|
|
||
|
return votes, nil
|
||
|
}
|