summaryrefslogtreecommitdiff
path: root/forms.go
blob: 503e7e5996e284ed5e53ce89ecd7827caaf286bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

var validDueDurations = map[string]time.Duration{
	"+3 days":  time.Hour * 24 * 3,
	"+7 days":  time.Hour * 24 * 7,
	"+14 days": time.Hour * 24 * 14,
	"+28 days": time.Hour * 24 * 28,
}

type NewDecisionForm struct {
	Title    string
	Content  string
	VoteType string
	Due      string
	Errors   map[string]string
}

func (f *NewDecisionForm) Validate() (bool, *Decision) {
	f.Errors = make(map[string]string)

	data := &Decision{}

	data.Title = strings.TrimSpace(f.Title)
	if len(data.Title) < 3 {
		f.Errors["Title"] = "Please enter at least 3 characters."
	}

	data.Content = strings.TrimSpace(f.Content)
	if len(strings.Fields(data.Content)) < 3 {
		f.Errors["Content"] = "Please enter at least 3 words."
	}

	if voteType, err := strconv.ParseUint(f.VoteType, 10, 8); err != nil || (voteType != 0 && voteType != 1) {
		f.Errors["VoteType"] = fmt.Sprint("Please choose a valid vote type", err)
	} else {
		data.VoteType = VoteType(uint8(voteType))
	}

	if dueDuration, ok := validDueDurations[f.Due]; !ok {
		f.Errors["Due"] = "Please choose a valid due date"
	} else {
		year, month, day := time.Now().UTC().Add(dueDuration).Date()
		data.Due = time.Date(year, month, day, 23, 59, 59, 0, time.UTC)
	}

	data.Proposed = time.Now().UTC()

	return len(f.Errors) == 0, data
}

type EditDecisionForm struct {
	Title    string
	Content  string
	VoteType string
	Due      string
	Decision *Decision
	Errors   map[string]string
}

func (f *EditDecisionForm) Validate() (bool, *Decision) {
	f.Errors = make(map[string]string)

	data := f.Decision

	data.Title = strings.TrimSpace(f.Title)
	if len(data.Title) < 3 {
		f.Errors["Title"] = "Please enter at least 3 characters."
	}

	data.Content = strings.TrimSpace(f.Content)
	if len(strings.Fields(data.Content)) < 3 {
		f.Errors["Content"] = "Please enter at least 3 words."
	}

	if voteType, err := strconv.ParseUint(f.VoteType, 10, 8); err != nil || (voteType != 0 && voteType != 1) {
		f.Errors["VoteType"] = fmt.Sprint("Please choose a valid vote type", err)
	} else {
		data.VoteType = VoteType(uint8(voteType))
	}

	if dueDuration, ok := validDueDurations[f.Due]; !ok {
		f.Errors["Due"] = "Please choose a valid due date"
	} else {
		year, month, day := time.Now().UTC().Add(dueDuration).Date()
		data.Due = time.Date(year, month, day, 23, 59, 59, 0, time.UTC)
	}

	data.Modified = time.Now().UTC()

	return len(f.Errors) == 0, data
}