/
trips.go
80 lines (70 loc) · 2.36 KB
/
trips.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
package trips
import (
"errors"
"github.com/bradpurchase/grocerytime-backend/internal/pkg/db"
"github.com/bradpurchase/grocerytime-backend/internal/pkg/db/models"
uuid "github.com/satori/go.uuid"
)
// RetrieveCurrentStoreTripForUser retrieves the currently active grocery trip in a
// store by storeID if the userID has access to to the store
func RetrieveCurrentStoreTripForUser(storeID uuid.UUID, user models.User) (groceryTrip models.GroceryTrip, err error) {
query := db.Manager.
Where("store_id = ?", storeID).
Where("user_id = ? OR email = ?", user.ID, user.Email).
Find(&models.StoreUser{}).
Error
if err := query; err != nil {
return groceryTrip, errors.New("user is not a member of this store")
}
trip, err := RetrieveCurrentStoreTrip(storeID)
if err != nil {
return groceryTrip, errors.New("could not find trip associated with this store")
}
return trip, nil
}
// RetrieveCurrentStoreTrip retrieves the currently active grocery trip in a store
func RetrieveCurrentStoreTrip(storeID uuid.UUID) (groceryTrip models.GroceryTrip, err error) {
query := db.Manager.
Where("store_id = ? AND completed = ?", storeID, false).
Order("created_at DESC").
Last(&groceryTrip).
Error
if err := query; err != nil {
return groceryTrip, err
}
return groceryTrip, nil
}
// RetrieveTrips retrieves grocery trips within a store
func RetrieveTrips(storeID interface{}, userID uuid.UUID, completed bool) (tripsList []models.GroceryTrip, err error) {
// Verify that this store belongs to the user
var count int64
existsQuery := db.Manager.
Model(&models.StoreUser{}).
Where("store_id = ? AND user_id = ? AND active = ?", storeID, userID, true).
Count(&count).
Error
if err := existsQuery; err != nil {
return tripsList, err
}
if count == 0 {
return tripsList, errors.New("user is not active in this store")
}
var trips []models.GroceryTrip
tripsQuery := db.Manager.
Where("store_id = ? AND completed = ?", storeID, completed).
Order("created_at DESC").
Find(&trips).
Error
if err := tripsQuery; err != nil {
return tripsList, err
}
return trips, nil
}
// RetrieveTrip retrieves a specific grocery trip by ID
func RetrieveTrip(tripID interface{}) (models.GroceryTrip, error) {
trip := models.GroceryTrip{}
if err := db.Manager.Where("id = ?", tripID).First(&trip).Error; err != nil {
return trip, errors.New("trip not found")
}
return trip, nil
}