/
expenses.go
348 lines (295 loc) · 8.18 KB
/
expenses.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package models
import (
"github.com/juju/errors"
"database/sql/driver"
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var (
// ErrNegativePence is returned when a Pence with a negative values is
// given to a function where it must not be negative
ErrNegativePence = errors.New("Pence must not be negative")
// ErrInvalidMoneyStr indicates that a string used to represent money
// could not be parsed and converted to Pence
ErrInvalidMoneyStr = errors.New("Invalid string passed to PenceFromString")
// ErrStructNotSaved is returned when an operation is performed on a struct
// that must first be saved to the database
ErrStructNotSaved = errors.New("Invalid operation: struct must be saved first")
ErrMustAssignToUsers = errors.New("There must be a positive number of users to assign an expense")
)
// Pence is an amount of money used in Payments & Expenses. There are 100 Pence
// in a Pound (Sterling)
type Pence int64
// String formats pence into a human readable string
func (p Pence) String() string {
var negativeString = ""
if p < 0 {
p = -p
negativeString = "-"
}
return fmt.Sprintf("%s£%01d.%02d", negativeString, p/100, p%100)
}
func (p *Pence) Scan(src interface{}) error {
if src == nil {
return errors.New("nil value cannot be assigned to Pence value")
}
n, ok := src.(int64)
if !ok {
return errors.New("cannot convert non-int64 to Pence")
}
*p = Pence(n)
return nil
}
func (p Pence) Value() (driver.Value, error) {
return int64(p), nil
}
// Validate ensures that the pence is positive.
func (p Pence) Validate() error {
if p <= 0 {
return ErrNegativePence
}
return nil
}
// PenceFromString parses a string and returns the amount of pence.
func PenceFromString(s string) (Pence, error) {
//Quick check to see if there are any non-numerical digits
if strings.ToUpper(s) != strings.ToLower(s) {
return Pence(0), ErrInvalidMoneyStr
}
//Ensure there is, at most, 1 decimal point.
nDec := strings.Count(s, ".")
if nDec > 1 {
return Pence(0), ErrInvalidMoneyStr
} else if nDec == 0 {
return poundsStrToPence(s)
}
pIndex := strings.Index(s, ".")
if pIndex == -1 {
//No decimal place
return penceStrToPence(s)
}
if pIndex == 0 {
//decimal point at beginning
return penceStrToPence(strings.TrimLeft(s, "."))
}
strs := strings.Split(s, ".")
pence, err := penceStrToPence(strs[1])
if err != nil {
return Pence(0), err
}
pounds, err := poundsStrToPence(strs[0])
if err != nil {
return Pence(0), err
}
return pence + pounds, nil
}
// penceStrToPence converts a string containing an amount of pence to the value
// in pence.
func penceStrToPence(s string) (Pence, error) {
s = strings.TrimRight(s, "0")
if len(s) > 2 {
return Pence(0), ErrInvalidMoneyStr
}
if len(s) == 0 {
return Pence(0), nil
}
if len(s) == 1 {
s += "0"
}
//Now everything should have correct number of Zeros
s = strings.TrimLeft(s, ".")
ret, err := strconv.Atoi(s)
if err != nil {
return Pence(0), err
}
return Pence(ret), nil
}
// poundsStrToPence returns the number of pence in the pounds passed as an
// argument
func poundsStrToPence(s string) (Pence, error) {
if s == "" {
return Pence(0), nil
}
ret, err := strconv.Atoi(s)
if err != nil {
return Pence(0), err
}
return Pence(ret * 100), nil
}
// Category is used to group expenses
type Category int
const (
// CategoryGroceries indicates an expense spend on groceries
// e.g. Boursin
CategoryGroceries Category = iota
// CategoryAlcohol indicates an expense spend on alcohol e.g. K Cider
CategoryAlcohol
// CategoryDrugs indicates an expense spend on medicine e.g cough
// medicine
CategoryDrugs
// CategoryHouseholdItems indicates an expense spend on household items
// e.g. An iron
CategoryHouseholdItems
// CategoryBills indicates an expense spend to on bill e.g. Netflix
CategoryBills
// CategoryPresents indicates an expense spent on presents e.g. singing
// lessons
CategoryPresents
// CategoryTickets indicates an expense spent on tickets e.g. Balls Deep
CategoryTickets
// CategoryMisc is used for expenses that do not fit into any of the
// other categories
CategoryMisc
// CategoryUnknown is not a category that should be used and indicates
// a logic error.
CategoryUnknown //Should always be last
)
func (c Category) String() string {
switch c {
case CategoryGroceries:
return "Groceries"
case CategoryAlcohol:
return "Alcohol"
case CategoryDrugs:
return "Drugs"
case CategoryHouseholdItems:
return "Household Items"
case CategoryBills:
return "Bills"
case CategoryPresents:
return "Presents"
case CategoryMisc:
return "Misc"
case CategoryTickets:
return "Tickets"
default:
return "Unknown Category"
}
}
func (c Category) Value() (driver.Value, error) {
return strings.ToLower(c.String()), nil
}
func (c *Category) Scan(src interface{}) error {
if src == nil {
return errors.New("nil value cannot be assigned to Category")
}
v := src.([]uint8)
s := ""
for _, n := range v {
s += string(int(n))
}
*c = StringToCategory(s)
return nil
}
// Validate ensures the Category is valid
func (c Category) Validate() error {
if c == CategoryUnknown {
return fmt.Errorf("Invalid category: %s.", c)
}
return nil
}
// AllCategories returns a slice containing all the valid categories
func AllCategories() []Category {
var ret []Category
for c := CategoryGroceries; c < CategoryUnknown; c++ {
ret = append(ret, c)
}
return ret
}
// StringToCategory converts a string to the appropriate category.
// This performs a lower case compare and strips any surrounding double quote
// characters.
func StringToCategory(s string) Category {
// Trim any quotes
ret, ok := strToCategory[strings.ToLower(strings.Trim(s, `"`))]
if !ok {
return CategoryUnknown
}
return ret
}
var strToCategory = make(map[string]Category)
// Expense represents an expense made that is to be shared with the group
type Expense struct {
ID int64 `db:"id" json:"id"`
Amount Pence `db:"amount" json:"amount"`
PayerID int64 `db:"payer_id" json:"payerId"`
GroupID int64 `db:"group_id" json:"groupId"`
Category Category `db:"category" json:"category"`
Description string `db:"description" json:"category"`
CreatedAt time.Time `db:"created_at" json:"category"`
Assignments []*ExpenseAssignment `db:"-" json:"assignments"`
}
// ExpenseAssignment represents the amount of money assigned to each user when
// an expense is made.
type ExpenseAssignment struct {
ID int64 `db:"id" json:"id"`
UserID int64 `db:"user_id" json:"userId"`
Amount Pence `db:"amount" json:"amount"`
ExpenseID int64 `db:"expense_id" json:"expenseId"`
GroupID int64 `db:"group_id" json:"groupId"`
}
type ByExpense []*ExpenseAssignment
func (a ByExpense) Len() int {
return len(a)
}
func (a ByExpense) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByExpense) Less(i, j int) bool {
return a[i].ExpenseID < a[j].ExpenseID
}
func (e Expense) validate() error {
err := e.Amount.Validate()
if err != nil {
return err
}
err = e.Category.Validate()
if err != nil {
return err
}
if e.PayerID <= 0 || e.GroupID <= 0 {
return errors.New("PayerId and GroupId must be positive")
}
return nil
}
// Assign assigns an expense to the users given. If the amount is not equally
// divisable by the number of users the expense applies to, then the
// remaining amount is assigned at random.
func (e *Expense) Assign(userIds []int64) ([]*ExpenseAssignment, error) {
if len(userIds) == 0 {
return nil, ErrMustAssignToUsers
}
err := e.validate()
if err != nil {
return nil, err
}
if e.ID <= 0 {
return nil, errors.Trace(ErrStructNotSaved)
}
numUsers := int64(len(userIds))
average := e.Amount / Pence(numUsers)
remainder := int64(e.Amount) % numUsers
randIndexes := rand.Perm(int(numUsers))
var ret []*ExpenseAssignment
for i := int64(0); i < numUsers; i++ {
amount := average
if i < remainder {
amount++
}
ret = append(ret, &ExpenseAssignment{
UserID: int64(userIds[randIndexes[i]]),
Amount: amount,
ExpenseID: e.ID,
GroupID: e.GroupID,
})
}
return ret, nil
}
func init() {
for _, c := range AllCategories() {
strToCategory[strings.ToLower(c.String())] = c
}
}