feat: group statistics endpoint (#123)

* group statistics endpoint

* remove item store

* return possible errors

* add statistics tests
This commit is contained in:
Hayden 2022-11-01 13:58:05 -08:00 committed by GitHub
parent a886fa86ca
commit 7e0f1fac23
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 201 additions and 74 deletions

View file

@ -41,6 +41,12 @@ type (
Uses int `json:"uses"`
Group Group `json:"group"`
}
GroupStatistics struct {
TotalUsers int `json:"totalUsers"`
TotalItems int `json:"totalItems"`
TotalLocations int `json:"totalLocations"`
TotalLabels int `json:"totalLabels"`
}
)
var (
@ -70,6 +76,25 @@ func mapToGroupInvitation(g *ent.GroupInvitationToken) GroupInvitation {
}
}
func (r *GroupRepository) GroupStatistics(ctx context.Context, GID uuid.UUID) (GroupStatistics, error) {
q := `
SELECT
(SELECT COUNT(*) FROM users WHERE group_users = ?) AS total_users,
(SELECT COUNT(*) FROM items WHERE group_items = ? AND items.archived = false) AS total_items,
(SELECT COUNT(*) FROM locations WHERE group_locations = ?) AS total_locations,
(SELECT COUNT(*) FROM labels WHERE group_labels = ?) AS total_labels
`
var stats GroupStatistics
row := r.db.Sql().QueryRowContext(ctx, q, GID, GID, GID, GID)
err := row.Scan(&stats.TotalUsers, &stats.TotalItems, &stats.TotalLocations, &stats.TotalLabels)
if err != nil {
return GroupStatistics{}, err
}
return stats, nil
}
func (r *GroupRepository) GroupCreate(ctx context.Context, name string) (Group, error) {
return mapToGroupErr(r.db.Group.Create().
SetName(name).

View file

@ -31,3 +31,16 @@ func Test_Group_Update(t *testing.T) {
assert.Equal(t, "test2", g.Name)
assert.Equal(t, "EUR", g.Currency)
}
func Test_Group_GroupStatistics(t *testing.T) {
useItems(t, 20)
useLabels(t, 20)
stats, err := tRepos.Groups.GroupStatistics(context.Background(), tGroup.ID)
assert.NoError(t, err)
assert.Equal(t, 20, stats.TotalItems)
assert.Equal(t, 20, stats.TotalLabels)
assert.Equal(t, 1, stats.TotalUsers)
assert.Equal(t, 1, stats.TotalLocations)
}