503e7e5996e284ed5e53ce89ecd7827caaf286bd
[cacert-boardvoting.git] / forms.go
1 package main
2
3 import (
4 "fmt"
5 "strconv"
6 "strings"
7 "time"
8 )
9
10 var validDueDurations = map[string]time.Duration{
11 "+3 days": time.Hour * 24 * 3,
12 "+7 days": time.Hour * 24 * 7,
13 "+14 days": time.Hour * 24 * 14,
14 "+28 days": time.Hour * 24 * 28,
15 }
16
17 type NewDecisionForm struct {
18 Title string
19 Content string
20 VoteType string
21 Due string
22 Errors map[string]string
23 }
24
25 func (f *NewDecisionForm) Validate() (bool, *Decision) {
26 f.Errors = make(map[string]string)
27
28 data := &Decision{}
29
30 data.Title = strings.TrimSpace(f.Title)
31 if len(data.Title) < 3 {
32 f.Errors["Title"] = "Please enter at least 3 characters."
33 }
34
35 data.Content = strings.TrimSpace(f.Content)
36 if len(strings.Fields(data.Content)) < 3 {
37 f.Errors["Content"] = "Please enter at least 3 words."
38 }
39
40 if voteType, err := strconv.ParseUint(f.VoteType, 10, 8); err != nil || (voteType != 0 && voteType != 1) {
41 f.Errors["VoteType"] = fmt.Sprint("Please choose a valid vote type", err)
42 } else {
43 data.VoteType = VoteType(uint8(voteType))
44 }
45
46 if dueDuration, ok := validDueDurations[f.Due]; !ok {
47 f.Errors["Due"] = "Please choose a valid due date"
48 } else {
49 year, month, day := time.Now().UTC().Add(dueDuration).Date()
50 data.Due = time.Date(year, month, day, 23, 59, 59, 0, time.UTC)
51 }
52
53 data.Proposed = time.Now().UTC()
54
55 return len(f.Errors) == 0, data
56 }
57
58 type EditDecisionForm struct {
59 Title string
60 Content string
61 VoteType string
62 Due string
63 Decision *Decision
64 Errors map[string]string
65 }
66
67 func (f *EditDecisionForm) Validate() (bool, *Decision) {
68 f.Errors = make(map[string]string)
69
70 data := f.Decision
71
72 data.Title = strings.TrimSpace(f.Title)
73 if len(data.Title) < 3 {
74 f.Errors["Title"] = "Please enter at least 3 characters."
75 }
76
77 data.Content = strings.TrimSpace(f.Content)
78 if len(strings.Fields(data.Content)) < 3 {
79 f.Errors["Content"] = "Please enter at least 3 words."
80 }
81
82 if voteType, err := strconv.ParseUint(f.VoteType, 10, 8); err != nil || (voteType != 0 && voteType != 1) {
83 f.Errors["VoteType"] = fmt.Sprint("Please choose a valid vote type", err)
84 } else {
85 data.VoteType = VoteType(uint8(voteType))
86 }
87
88 if dueDuration, ok := validDueDurations[f.Due]; !ok {
89 f.Errors["Due"] = "Please choose a valid due date"
90 } else {
91 year, month, day := time.Now().UTC().Add(dueDuration).Date()
92 data.Due = time.Date(year, month, day, 23, 59, 59, 0, time.UTC)
93 }
94
95 data.Modified = time.Now().UTC()
96
97 return len(f.Errors) == 0, data
98 }