This repository was archived by the owner on Jun 12, 2024. It is now read-only.
generated from hay-kot/go-web-template
-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathrepo_locations.go
458 lines (380 loc) · 10.9 KB
/
repo_locations.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package repo
import (
"context"
"strings"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/core/services/reporting/eventbus"
"github.com/hay-kot/homebox/backend/internal/data/ent"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
type LocationRepository struct {
db *ent.Client
bus *eventbus.EventBus
}
type (
LocationCreate struct {
Name string `json:"name"`
ParentID uuid.UUID `json:"parentId" extensions:"x-nullable"`
Description string `json:"description"`
}
LocationUpdate struct {
ParentID uuid.UUID `json:"parentId" extensions:"x-nullable"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
}
LocationSummary struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
LocationOutCount struct {
LocationSummary
ItemCount int `json:"itemCount"`
}
LocationOut struct {
Parent *LocationSummary `json:"parent,omitempty"`
LocationSummary
Children []LocationSummary `json:"children"`
TotalPrice float64 `json:"totalPrice"`
}
)
func mapLocationSummary(location *ent.Location) LocationSummary {
return LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
}
}
var mapLocationOutErr = mapTErrFunc(mapLocationOut)
func mapLocationOut(location *ent.Location) LocationOut {
var parent *LocationSummary
if location.Edges.Parent != nil {
p := mapLocationSummary(location.Edges.Parent)
parent = &p
}
children := make([]LocationSummary, 0, len(location.Edges.Children))
for _, c := range location.Edges.Children {
children = append(children, mapLocationSummary(c))
}
return LocationOut{
Parent: parent,
Children: children,
LocationSummary: LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
},
}
}
func (r *LocationRepository) publishMutationEvent(GID uuid.UUID) {
if r.bus != nil {
r.bus.Publish(eventbus.EventLocationMutation, eventbus.GroupMutationEvent{GID: GID})
}
}
type LocationQuery struct {
FilterChildren bool `json:"filterChildren" schema:"filterChildren"`
}
// GetAll returns all locations with item count field populated
func (r *LocationRepository) GetAll(ctx context.Context, GID uuid.UUID, filter LocationQuery) ([]LocationOutCount, error) {
query := `--sql
SELECT
id,
name,
description,
created_at,
updated_at,
(
SELECT
SUM(items.quantity)
FROM
items
WHERE
items.location_items = locations.id
AND items.archived = false
) as item_count
FROM
locations
WHERE
locations.group_locations = ? {{ FILTER_CHILDREN }}
ORDER BY
locations.name ASC
`
if filter.FilterChildren {
query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "AND locations.location_children IS NULL", 1)
} else {
query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "", 1)
}
rows, err := r.db.Sql().QueryContext(ctx, query, GID)
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
list := []LocationOutCount{}
for rows.Next() {
var ct LocationOutCount
var maybeCount *int
err := rows.Scan(&ct.ID, &ct.Name, &ct.Description, &ct.CreatedAt, &ct.UpdatedAt, &maybeCount)
if err != nil {
return nil, err
}
if maybeCount != nil {
ct.ItemCount = *maybeCount
}
list = append(list, ct)
}
return list, err
}
func (r *LocationRepository) getOne(ctx context.Context, where ...predicate.Location) (LocationOut, error) {
return mapLocationOutErr(r.db.Location.Query().
Where(where...).
WithGroup().
WithParent().
WithChildren().
Only(ctx))
}
func (r *LocationRepository) Get(ctx context.Context, ID uuid.UUID) (LocationOut, error) {
return r.getOne(ctx, location.ID(ID))
}
func (r *LocationRepository) GetOneByGroup(ctx context.Context, GID, ID uuid.UUID) (LocationOut, error) {
return r.getOne(ctx, location.ID(ID), location.HasGroupWith(group.ID(GID)))
}
func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data LocationCreate) (LocationOut, error) {
q := r.db.Location.Create().
SetName(data.Name).
SetDescription(data.Description).
SetGroupID(GID)
if data.ParentID != uuid.Nil {
q.SetParentID(data.ParentID)
}
location, err := q.Save(ctx)
if err != nil {
return LocationOut{}, err
}
location.Edges.Group = &ent.Group{ID: GID} // bootstrap group ID
r.publishMutationEvent(GID)
return mapLocationOut(location), nil
}
func (r *LocationRepository) update(ctx context.Context, data LocationUpdate, where ...predicate.Location) (LocationOut, error) {
q := r.db.Location.Update().
Where(where...).
SetName(data.Name).
SetDescription(data.Description)
if data.ParentID != uuid.Nil {
q.SetParentID(data.ParentID)
} else {
q.ClearParent()
}
_, err := q.Save(ctx)
if err != nil {
return LocationOut{}, err
}
return r.Get(ctx, data.ID)
}
func (r *LocationRepository) UpdateByGroup(ctx context.Context, GID, ID uuid.UUID, data LocationUpdate) (LocationOut, error) {
v, err := r.update(ctx, data, location.ID(ID), location.HasGroupWith(group.ID(GID)))
if err != nil {
return LocationOut{}, err
}
r.publishMutationEvent(GID)
return v, err
}
// delete should only be used after checking that the location is owned by the
// group. Otherwise, use DeleteByGroup
func (r *LocationRepository) delete(ctx context.Context, ID uuid.UUID) error {
return r.db.Location.DeleteOneID(ID).Exec(ctx)
}
func (r *LocationRepository) DeleteByGroup(ctx context.Context, GID, ID uuid.UUID) error {
_, err := r.db.Location.Delete().Where(location.ID(ID), location.HasGroupWith(group.ID(GID))).Exec(ctx)
if err != nil {
return err
}
r.publishMutationEvent(GID)
return err
}
type TreeItem struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Children []*TreeItem `json:"children"`
}
type FlatTreeItem struct {
ID uuid.UUID
Name string
Type string
ParentID uuid.UUID
Level int
}
type TreeQuery struct {
WithItems bool `json:"withItems" schema:"withItems"`
}
type ItemType string
const (
ItemTypeLocation ItemType = "location"
ItemTypeItem ItemType = "item"
)
type ItemPath struct {
Type ItemType `json:"type"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
}
func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUID) ([]ItemPath, error) {
query := `WITH RECURSIVE location_path AS (
SELECT id, name, location_children
FROM locations
WHERE id = ? -- Replace ? with the ID of the item's location
AND group_locations = ? -- Replace ? with the ID of the group
UNION ALL
SELECT loc.id, loc.name, loc.location_children
FROM locations loc
JOIN location_path lp ON loc.id = lp.location_children
)
SELECT id, name
FROM location_path`
rows, err := r.db.Sql().QueryContext(ctx, query, locID, GID)
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
var locations []ItemPath
for rows.Next() {
var location ItemPath
location.Type = ItemTypeLocation
if err := rows.Scan(&location.ID, &location.Name); err != nil {
return nil, err
}
locations = append(locations, location)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse the order of the locations so that the root is last
for i := len(locations)/2 - 1; i >= 0; i-- {
opp := len(locations) - 1 - i
locations[i], locations[opp] = locations[opp], locations[i]
}
return locations, nil
}
func (r *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQuery) ([]TreeItem, error) {
query := `
WITH recursive location_tree(id, NAME, parent_id, level, node_type) AS
(
SELECT id,
NAME,
location_children AS parent_id,
0 AS level,
'location' AS node_type
FROM locations
WHERE location_children IS NULL
AND group_locations = ?
UNION ALL
SELECT c.id,
c.NAME,
c.location_children AS parent_id,
level + 1,
'location' AS node_type
FROM locations c
JOIN location_tree p
ON c.location_children = p.id
WHERE level < 10 -- prevent infinite loop & excessive recursion
){{ WITH_ITEMS }}
SELECT id,
NAME,
level,
parent_id,
node_type
FROM (
SELECT *
FROM location_tree
{{ WITH_ITEMS_FROM }}
) tree
ORDER BY node_type DESC, -- sort locations before items
level,
lower(NAME)`
if tq.WithItems {
itemQuery := `, item_tree(id, NAME, parent_id, level, node_type) AS
(
SELECT id,
NAME,
location_items as parent_id,
0 AS level,
'item' AS node_type
FROM items
WHERE item_children IS NULL
AND location_items IN (SELECT id FROM location_tree)
UNION ALL
SELECT c.id,
c.NAME,
c.item_children AS parent_id,
level + 1,
'item' AS node_type
FROM items c
JOIN item_tree p
ON c.item_children = p.id
WHERE c.item_children IS NOT NULL
AND level < 10 -- prevent infinite loop & excessive recursion
)`
// Conditional table joined to main query
itemsFrom := `
UNION ALL
SELECT *
FROM item_tree`
query = strings.ReplaceAll(query, "{{ WITH_ITEMS }}", itemQuery)
query = strings.ReplaceAll(query, "{{ WITH_ITEMS_FROM }}", itemsFrom)
} else {
query = strings.ReplaceAll(query, "{{ WITH_ITEMS }}", "")
query = strings.ReplaceAll(query, "{{ WITH_ITEMS_FROM }}", "")
}
rows, err := r.db.Sql().QueryContext(ctx, query, GID)
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
var locations []FlatTreeItem
for rows.Next() {
var location FlatTreeItem
if err := rows.Scan(&location.ID, &location.Name, &location.Level, &location.ParentID, &location.Type); err != nil {
return nil, err
}
locations = append(locations, location)
}
if err := rows.Err(); err != nil {
return nil, err
}
return ConvertLocationsToTree(locations), nil
}
func ConvertLocationsToTree(locations []FlatTreeItem) []TreeItem {
locationMap := make(map[uuid.UUID]*TreeItem, len(locations))
var rootIds []uuid.UUID
for _, location := range locations {
loc := &TreeItem{
ID: location.ID,
Name: location.Name,
Type: location.Type,
Children: []*TreeItem{},
}
locationMap[location.ID] = loc
if location.ParentID != uuid.Nil {
parent, ok := locationMap[location.ParentID]
if ok {
parent.Children = append(parent.Children, loc)
}
} else {
rootIds = append(rootIds, location.ID)
}
}
roots := make([]TreeItem, 0, len(rootIds))
for _, id := range rootIds {
roots = append(roots, *locationMap[id])
}
return roots
}