b7b72256facdb4ccd3b71b15883abe5876e4c299
[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 return len(f.Errors) == 0, data
54 }
55
56 type EditDecisionForm struct {
57 Title string
58 Content string
59 VoteType string
60 Due string
61 Decision *Decision
62 Errors map[string]string
63 }
64
65 func (f *EditDecisionForm) Validate() (bool, *Decision) {
66 f.Errors = make(map[string]string)
67
68 data := f.Decision
69
70 data.Title = strings.TrimSpace(f.Title)
71 if len(data.Title) < 3 {
72 f.Errors["Title"] = "Please enter at least 3 characters."
73 }
74
75 data.Content = strings.TrimSpace(f.Content)
76 if len(strings.Fields(data.Content)) < 3 {
77 f.Errors["Content"] = "Please enter at least 3 words."
78 }
79
80 if voteType, err := strconv.ParseUint(f.VoteType, 10, 8); err != nil || (voteType != 0 && voteType != 1) {
81 f.Errors["VoteType"] = fmt.Sprint("Please choose a valid vote type", err)
82 } else {
83 data.VoteType = VoteType(uint8(voteType))
84 }
85
86 if dueDuration, ok := validDueDurations[f.Due]; !ok {
87 f.Errors["Due"] = "Please choose a valid due date"
88 } else {
89 year, month, day := time.Now().UTC().Add(dueDuration).Date()
90 data.Due = time.Date(year, month, day, 23, 59, 59, 0, time.UTC)
91 }
92
93 return len(f.Errors) == 0, data
94 }