/
contact.go
122 lines (87 loc) · 2.47 KB
/
contact.go
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package db
import (
"errors"
"github.com/gosimple/slug"
"github.com/jinzhu/gorm"
"github.com/nyaruka/phonenumbers"
)
// DB is the accessible database.
var DB *gorm.DB
// Contact is the main person.
type Contact struct {
gorm.Model
Name string `json:"name"`
Email string `json:"email"`
Number string `json:"number,omitempty"`
Slug string `json:"slug"`
Notes []Note `json:"notes,omitempty"`
Lead bool `json:"lead,omitempty"`
Advocate bool `json:"advocate,omitempty"`
Customer bool `json:"customer,omitempty"`
Subscriber bool `json:"subscriber,omitempty"`
Other string `json:"other"`
Contacted bool `json:"contacted"`
}
// Create a contact in the database.
func (c *Contact) Create() error {
// Enforce the requirement of a name and email.
if c.Name == "" || c.Email == "" {
return errors.New("missing a name or email")
}
// Format the phone number
if c.Number != "" {
if number, err := phonenumbers.Parse(c.Number, "US"); err == nil {
c.Number = phonenumbers.Format(number, phonenumbers.NATIONAL)
}
}
// All subscribers are customers, but not all customers are subscribers.
if c.Subscriber {
c.Customer = true
}
c.Slug = slug.Make(c.Name)
return DB.Create(&c).Error
}
// Update a contact that is in the database.
func (c *Contact) Update() error {
// All subscribers are customers, but not all customers are subscribers.
if c.Subscriber {
c.Customer = true
}
// Format the phone number
if c.Number != "" {
if number, err := phonenumbers.Parse(c.Number, "US"); err == nil {
c.Number = phonenumbers.Format(number, phonenumbers.NATIONAL)
}
}
// return DB.Model(&c).Updates(&c).Error
return DB.Save(&c).Error
}
// Remove a contact that is in the database.
func (c *Contact) Remove() error {
if c.ID == 0 {
return errors.New("need an ID")
}
return DB.Delete(&c).Error
}
// Query a contact given an ID.
func (c *Contact) Query() error {
if c.ID == 0 {
return errors.New("need an ID")
}
return DB.First(&c).Error
}
// QueryContacts returns all of the contacts in the database.
func QueryContacts() ([]Contact, error) {
contacts := []Contact{}
err := DB.Find(&contacts).Error
return contacts, err
}
// Search returns a single contact that matches c.
func (c *Contact) Search() (err error) {
return DB.Where(&c).First(&c).Error
}
// SearchMultiple returns multiple contacts that match c.
func (c *Contact) SearchMultiple() (result []Contact, err error) {
err = DB.Where(&c).Find(&result).Error
return
}