-
-
Notifications
You must be signed in to change notification settings - Fork 559
Expand file tree
/
Copy pathrepo_entities.go
More file actions
2828 lines (2505 loc) · 82.4 KB
/
Copy pathrepo_entities.go
File metadata and controls
2828 lines (2505 loc) · 82.4 KB
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package repo
import (
"context"
"fmt"
"math"
"strings"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/samber/lo"
"github.com/samber/lo/mutable"
"github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/entity"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/entityfield"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/entitytype"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/maintenanceentry"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/types"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
func entityTracer() trace.Tracer {
return otel.Tracer("data")
}
func recordSpanError(span trace.Span, err error) {
if err == nil {
return
}
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
type EntityRepository struct {
db *ent.Client
bus *eventbus.EventBus
attachments *AttachmentRepo
}
type (
FieldQuery struct {
Name string
Value string
}
EntityQuery struct {
Page int
PageSize int
Search string `json:"search"`
AssetID AssetID `json:"assetId"`
ParentIDs []uuid.UUID `json:"parentIds"`
TagIDs []uuid.UUID `json:"tagIds"`
NegateTags bool `json:"negateTags"`
MatchAllTags bool `json:"matchAllTags"`
OnlyWithoutPhoto bool `json:"onlyWithoutPhoto"`
OnlyWithPhoto bool `json:"onlyWithPhoto"`
ParentItemIDs []uuid.UUID `json:"parentItemIds"`
SortBy string `json:"sortBy"`
IncludeArchived bool `json:"includeArchived"`
IsLocation *bool `json:"isLocation"` // nil=all, true=locations only, false=items only
FilterChildren bool `json:"filterChildren"` // when true, only return root entities (no parent)
Fields []FieldQuery `json:"fields"`
OrderBy string `json:"orderBy"`
}
DuplicateOptions struct {
CopyMaintenance bool `json:"copyMaintenance"`
CopyAttachments bool `json:"copyAttachments"`
CopyCustomFields bool `json:"copyCustomFields"`
CopyPrefix string `json:"copyPrefix"`
}
EntityFieldData struct {
ID uuid.UUID `json:"id,omitempty"`
Type string `json:"type"`
Name string `json:"name"`
TextValue string `json:"textValue"`
NumberValue int `json:"numberValue"`
BooleanValue bool `json:"booleanValue"`
}
EntityCreate struct {
ImportRef string `json:"-"`
ParentID uuid.UUID `json:"parentId" extensions:"x-nullable"`
Name string `json:"name" validate:"required,min=1,max=255"`
Quantity float64 `json:"quantity"`
Description string `json:"description" validate:"max=1000"`
AssetID AssetID `json:"-"`
EntityTypeID uuid.UUID `json:"entityTypeId"`
// Edges
TagIDs []uuid.UUID `json:"tagIds"`
}
EntityUpdate struct {
ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`
ID uuid.UUID `json:"id"`
AssetID AssetID `json:"assetId" swaggertype:"string"`
Name string `json:"name" validate:"required,min=1,max=255"`
Description string `json:"description" validate:"max=1000"`
Quantity float64 `json:"quantity"`
Insured bool `json:"insured"`
Archived bool `json:"archived"`
SyncChildEntityLocations bool `json:"syncChildEntityLocations"`
EntityTypeID uuid.UUID `json:"entityTypeId"`
// Edges
TagIDs []uuid.UUID `json:"tagIds"`
// Identifications
SerialNumber string `json:"serialNumber"`
ModelNumber string `json:"modelNumber"`
Manufacturer string `json:"manufacturer"`
// Warranty
LifetimeWarranty bool `json:"lifetimeWarranty"`
WarrantyExpires types.Date `json:"warrantyExpires"`
WarrantyDetails string `json:"warrantyDetails"`
// Purchase
PurchaseDate types.Date `json:"purchaseDate"`
PurchaseFrom string `json:"purchaseFrom" validate:"max=255"`
PurchasePrice float64 `json:"purchasePrice" extensions:"x-nullable,x-omitempty"`
// Sold
SoldDate types.Date `json:"soldDate"`
SoldTo string `json:"soldTo" validate:"max=255"`
SoldPrice float64 `json:"soldPrice" extensions:"x-nullable,x-omitempty"`
SoldNotes string `json:"soldNotes"`
// Extras
Notes string `json:"notes"`
Fields []EntityFieldData `json:"fields"`
}
EntityPatch struct {
ID uuid.UUID `json:"id"`
Quantity *float64 `json:"quantity,omitempty" extensions:"x-nullable,x-omitempty"`
ImportRef *string `json:"-" extensions:"x-nullable,x-omitempty"`
ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`
EntityTypeID uuid.UUID `json:"entityTypeId" extensions:"x-nullable,x-omitempty"`
TagIDs []uuid.UUID `json:"tagIds" extensions:"x-nullable,x-omitempty"`
}
EntitySummary struct {
ImportRef string `json:"-"`
ID uuid.UUID `json:"id"`
AssetID AssetID `json:"assetId,string"`
Name string `json:"name"`
Description string `json:"description"`
Quantity float64 `json:"quantity"`
Insured bool `json:"insured"`
Archived bool `json:"archived"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
PurchasePrice float64 `json:"purchasePrice"`
// Edges
Parent *EntitySummary `json:"parent,omitempty" extensions:"x-nullable,x-omitempty"`
EntityType *EntityTypeSummary `json:"entityType,omitempty" extensions:"x-nullable,x-omitempty"`
Tags []TagSummary `json:"tags"`
ImageID *uuid.UUID `json:"imageId,omitempty" extensions:"x-nullable,x-omitempty"`
ThumbnailId *uuid.UUID `json:"thumbnailId,omitempty" extensions:"x-nullable,x-omitempty"`
// Sale details
SoldDate types.Date `json:"soldDate"`
// Container-specific (populated when querying locations)
ItemCount float64 `json:"itemCount,omitempty"`
}
EntityOut struct {
Parent *EntitySummary `json:"parent,omitempty" extensions:"x-nullable,x-omitempty"`
EntitySummary
AssetID AssetID `json:"assetId,string"`
SyncChildEntityLocations bool `json:"syncChildEntityLocations"`
SerialNumber string `json:"serialNumber"`
ModelNumber string `json:"modelNumber"`
Manufacturer string `json:"manufacturer"`
// Warranty
LifetimeWarranty bool `json:"lifetimeWarranty"`
WarrantyExpires types.Date `json:"warrantyExpires"`
WarrantyDetails string `json:"warrantyDetails"`
// Purchase
PurchaseDate types.Date `json:"purchaseDate"`
PurchaseFrom string `json:"purchaseFrom"`
// Sold
SoldDate types.Date `json:"soldDate"`
SoldTo string `json:"soldTo"`
SoldPrice float64 `json:"soldPrice"`
SoldNotes string `json:"soldNotes"`
// Extras
Notes string `json:"notes"`
Attachments []ItemAttachment `json:"attachments"`
Fields []EntityFieldData `json:"fields"`
// Container-specific fields (for entities whose entity_type.is_location = true)
Children []EntitySummary `json:"children,omitempty"`
TotalPrice float64 `json:"totalPrice,omitempty"`
}
// EntityOutCount is used for container listing with child count.
EntityOutCount struct {
EntitySummary
ItemCount float64 `json:"itemCount"`
}
)
var mapEntitiesSummaryErr = mapTEachErrFunc(mapEntitySummary)
func mapEntitySummary(e *ent.Entity) EntitySummary {
var parent *EntitySummary
if e.Edges.Parent != nil {
p := mapEntitySummary(e.Edges.Parent)
parent = &p
}
var et *EntityTypeSummary
if e.Edges.EntityType != nil {
s := mapEntityTypeSummary(e.Edges.EntityType)
et = &s
}
tags := lo.Ternary(e.Edges.Tag != nil, mapEach(e.Edges.Tag, mapTagSummary), []TagSummary{})
var imageID *uuid.UUID
var thumbnailID *uuid.UUID
if e.Edges.Attachments != nil {
if a, ok := lo.Find(e.Edges.Attachments, func(a *ent.Attachment) bool {
return a.Primary && a.Type == attachment.TypePhoto
}); ok {
imageID = &a.ID
if a.Edges.Thumbnail != nil && a.Edges.Thumbnail.ID != uuid.Nil {
thumbnailID = &a.Edges.Thumbnail.ID
}
}
}
return EntitySummary{
ID: e.ID,
AssetID: AssetID(e.AssetID),
Name: e.Name,
Description: e.Description,
ImportRef: e.ImportRef,
Quantity: e.Quantity,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
Archived: e.Archived,
PurchasePrice: e.PurchasePrice,
// Edges
Parent: parent,
EntityType: et,
Tags: tags,
// Warranty
Insured: e.Insured,
ImageID: imageID,
ThumbnailId: thumbnailID,
// Sale
SoldDate: types.DateFromTime(e.SoldDate),
}
}
var (
mapEntityOutErr = mapTErrFunc(mapEntityOut)
mapEntitiesOutErr = mapTEachErrFunc(mapEntityOut)
)
func mapEntityFields(fields []*ent.EntityField) []EntityFieldData {
return lo.Map(fields, func(f *ent.EntityField, _ int) EntityFieldData {
return EntityFieldData{
ID: f.ID,
Type: f.Type.String(),
Name: f.Name,
TextValue: f.TextValue,
NumberValue: f.NumberValue,
BooleanValue: f.BooleanValue,
}
})
}
func mapEntityOut(e *ent.Entity) EntityOut {
var attachments []ItemAttachment
if e.Edges.Attachments != nil {
attachments = mapEach(e.Edges.Attachments, ToItemAttachment)
}
var fields []EntityFieldData
if e.Edges.Fields != nil {
fields = mapEntityFields(e.Edges.Fields)
}
var parent *EntitySummary
if e.Edges.Parent != nil {
p := mapEntitySummary(e.Edges.Parent)
parent = &p
}
var children []EntitySummary
if e.Edges.Children != nil {
// Only include location-type children (sub-containers), not items
children = lo.FilterMap(e.Edges.Children, func(c *ent.Entity, _ int) (EntitySummary, bool) {
if c.Edges.EntityType != nil && c.Edges.EntityType.IsLocation {
return mapEntitySummary(c), true
}
return EntitySummary{}, false
})
}
return EntityOut{
Parent: parent,
AssetID: AssetID(e.AssetID),
EntitySummary: mapEntitySummary(e),
LifetimeWarranty: e.LifetimeWarranty,
WarrantyExpires: types.DateFromTime(e.WarrantyExpires),
WarrantyDetails: e.WarrantyDetails,
SyncChildEntityLocations: e.SyncChildEntityLocations,
// Identification
SerialNumber: e.SerialNumber,
ModelNumber: e.ModelNumber,
Manufacturer: e.Manufacturer,
// Purchase
PurchaseDate: types.DateFromTime(e.PurchaseDate),
PurchaseFrom: e.PurchaseFrom,
// Sold
SoldDate: types.DateFromTime(e.SoldDate),
SoldTo: e.SoldTo,
SoldPrice: e.SoldPrice,
SoldNotes: e.SoldNotes,
// Extras
Notes: e.Notes,
Attachments: attachments,
Fields: fields,
Children: children,
}
}
// resolveDefaultEntityType finds or creates the default entity type for a group.
func (r *EntityRepository) resolveDefaultEntityType(ctx context.Context, gid uuid.UUID, isLocation bool) (uuid.UUID, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.resolveDefaultEntityType",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.Bool("entity_type.is_location", isLocation),
))
defer span.End()
et, err := r.db.EntityType.Query().
Where(
entitytype.HasGroupWith(group.ID(gid)),
entitytype.IsLocation(isLocation),
).
Order(entitytype.ByCreatedAt()).
First(ctx)
if err != nil {
if ent.IsNotFound(err) {
name := "Item"
if isLocation {
name = "Location"
}
createCtx, createSpan := entityTracer().Start(ctx, "repo.EntityRepository.resolveDefaultEntityType.create",
trace.WithAttributes(attribute.String("entity_type.name", name)))
created, err := r.db.EntityType.Create().
SetName(name).
SetDescription("").
SetIsLocation(isLocation).
SetGroupID(gid).
Save(createCtx)
if err != nil {
recordSpanError(createSpan, err)
createSpan.End()
recordSpanError(span, err)
return uuid.Nil, err
}
createSpan.SetAttributes(attribute.String("entity_type.id", created.ID.String()))
createSpan.End()
span.SetAttributes(attribute.String("entity_type.id", created.ID.String()))
return created.ID, nil
}
recordSpanError(span, err)
return uuid.Nil, err
}
span.SetAttributes(attribute.String("entity_type.id", et.ID.String()))
return et.ID, nil
}
func (r *EntityRepository) publishMutationEvent(gid uuid.UUID) {
if r.bus != nil {
r.bus.Publish(eventbus.EventEntityMutation, eventbus.GroupMutationEvent{GID: gid})
}
}
func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...predicate.Entity) (EntityOut, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.getOneTx",
trace.WithAttributes(
attribute.Bool("tx", tx != nil),
attribute.Int("predicate.count", len(where)),
))
defer span.End()
var q *ent.EntityQuery
if tx != nil {
q = tx.Entity.Query().Where(where...)
} else {
q = r.db.Entity.Query().Where(where...)
}
out, err := mapEntityOutErr(q.
WithFields().
WithTag().
WithParent(func(eq *ent.EntityQuery) {
eq.WithEntityType()
}).
WithEntityType().
WithGroup().
WithChildren(func(eq *ent.EntityQuery) {
eq.WithEntityType()
}).
WithAttachments().
Only(ctx),
)
if err != nil {
recordSpanError(span, err)
return out, err
}
span.SetAttributes(
attribute.String("entity.id", out.ID.String()),
attribute.Int("entity.fields.count", len(out.Fields)),
attribute.Int("entity.tags.count", len(out.Tags)),
attribute.Int("entity.attachments.count", len(out.Attachments)),
attribute.Int("entity.children.count", len(out.Children)),
)
return out, nil
}
func (r *EntityRepository) getOne(ctx context.Context, where ...predicate.Entity) (EntityOut, error) {
return r.getOneTx(ctx, nil, where...)
}
// GetOne returns a single entity by ID. If the entity does not exist, an error is returned.
func (r *EntityRepository) GetOne(ctx context.Context, id uuid.UUID) (EntityOut, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetOne",
trace.WithAttributes(attribute.String("entity.id", id.String())))
defer span.End()
out, err := r.getOne(ctx, entity.ID(id))
recordSpanError(span, err)
return out, err
}
func (r *EntityRepository) CheckRef(ctx context.Context, gid uuid.UUID, ref string) (bool, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.CheckRef",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.String("entity.import_ref", ref),
))
defer span.End()
q := r.db.Entity.Query().Where(entity.HasGroupWith(group.ID(gid)))
exists, err := q.Where(entity.ImportRef(ref)).Exist(ctx)
if err != nil {
recordSpanError(span, err)
return exists, err
}
span.SetAttributes(attribute.Bool("entity.exists", exists))
return exists, nil
}
func (r *EntityRepository) GetByRef(ctx context.Context, gid uuid.UUID, ref string) (EntityOut, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetByRef",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.String("entity.import_ref", ref),
))
defer span.End()
out, err := r.getOne(ctx, entity.ImportRef(ref), entity.HasGroupWith(group.ID(gid)))
recordSpanError(span, err)
return out, err
}
// GetOneByGroup returns a single entity by ID, verified to belong to a specific group.
func (r *EntityRepository) GetOneByGroup(ctx context.Context, gid, id uuid.UUID) (EntityOut, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetOneByGroup",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.String("entity.id", id.String()),
))
defer span.End()
out, err := r.getOne(ctx, entity.ID(id), entity.HasGroupWith(group.ID(gid)))
recordSpanError(span, err)
return out, err
}
func entityQuerySpanAttrs(gid uuid.UUID, q EntityQuery) []attribute.KeyValue {
isLocSet := q.IsLocation != nil
isLocValue := false
if isLocSet {
isLocValue = *q.IsLocation
}
return []attribute.KeyValue{
attribute.String("group.id", gid.String()),
attribute.Int("query.page", q.Page),
attribute.Int("query.page_size", q.PageSize),
attribute.String("query.search", q.Search),
attribute.Int("query.tag_ids.count", len(q.TagIDs)),
attribute.Bool("query.negate_tags", q.NegateTags),
attribute.Int("query.parent_ids.count", len(q.ParentIDs)),
attribute.Int("query.parent_item_ids.count", len(q.ParentItemIDs)),
attribute.Int("query.fields.count", len(q.Fields)),
attribute.Bool("query.only_with_photo", q.OnlyWithPhoto),
attribute.Bool("query.only_without_photo", q.OnlyWithoutPhoto),
attribute.Bool("query.include_archived", q.IncludeArchived),
attribute.Bool("query.filter_children", q.FilterChildren),
attribute.String("query.order_by", q.OrderBy),
attribute.Bool("query.is_location.set", isLocSet),
attribute.Bool("query.is_location.value", isLocValue),
attribute.Bool("query.asset_id.set", !q.AssetID.Nil()),
}
}
// QueryByGroup returns a list of entities that belong to a specific group based on the provided query.
func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q EntityQuery) (PaginationResult[EntitySummary], error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup",
trace.WithAttributes(entityQuerySpanAttrs(gid, q)...))
defer span.End()
qb := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
)
// Filter by entity type (location vs item) when specified.
// Default (nil) = items only (excludes locations for backward compat)
switch {
case q.IsLocation != nil && *q.IsLocation:
qb = qb.Where(entity.HasEntityTypeWith(entitytype.IsLocation(true)))
default:
// nil or false: exclude locations
qb = qb.Where(
entity.Or(
entity.Not(entity.HasEntityType()),
entity.HasEntityTypeWith(entitytype.IsLocation(false)),
),
)
}
if q.FilterChildren {
qb = qb.Where(entity.Not(entity.HasParent()))
}
if q.IncludeArchived {
qb = qb.Where(
entity.Or(
entity.Archived(true),
entity.Archived(false),
),
)
} else {
qb = qb.Where(entity.Archived(false))
}
if q.Search != "" {
qb.Where(
entity.Or(
entity.NameContainsFold(q.Search),
entity.DescriptionContainsFold(q.Search),
entity.SerialNumberContainsFold(q.Search),
entity.ModelNumberContainsFold(q.Search),
entity.ManufacturerContainsFold(q.Search),
entity.NotesContainsFold(q.Search),
),
)
}
if !q.AssetID.Nil() {
qb = qb.Where(entity.AssetID(int64(q.AssetID)))
}
var andPredicates []predicate.Entity
{
if len(q.TagIDs) > 0 {
tagRepo := &TagRepository{r.db, r.bus}
ctxDescendants, descSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.tagDescendants",
trace.WithAttributes(attribute.Int("query.tag_ids.count", len(q.TagIDs))))
descendantGroups := make([][]uuid.UUID, 0, len(q.TagIDs))
descendantCount := 0
if q.MatchAllTags && !q.NegateTags {
for _, tagID := range q.TagIDs {
descendants, err := tagRepo.GetDescendantTagIDs(ctxDescendants, []uuid.UUID{tagID})
if err != nil {
recordSpanError(descSpan, err)
log.Warn().Err(err).Msg("failed to get descendant tags, using only direct tag")
descendants = []uuid.UUID{tagID}
} else if len(descendants) == 0 {
descendants = []uuid.UUID{tagID}
}
descendantGroups = append(descendantGroups, descendants)
descendantCount += len(descendants)
}
} else {
descendants, err := tagRepo.GetDescendantTagIDs(ctxDescendants, q.TagIDs)
if err != nil {
recordSpanError(descSpan, err)
log.Warn().Err(err).Msg("failed to get descendant tags, using only direct tags")
descendants = q.TagIDs
} else if len(descendants) == 0 {
descendants = q.TagIDs
}
descendantGroups = append(descendantGroups, descendants)
descendantCount = len(descendants)
}
descSpan.SetAttributes(attribute.Int("query.tag_descendants.count", descendantCount))
descSpan.End()
if !q.NegateTags {
if q.MatchAllTags {
for _, descendants := range descendantGroups {
tagPredicates := lo.Map(descendants, func(l uuid.UUID, _ int) predicate.Entity {
return entity.HasTagWith(tag.ID(l))
})
andPredicates = append(andPredicates, entity.Or(tagPredicates...))
}
} else {
tagPredicates := lo.Map(descendantGroups[0], func(l uuid.UUID, _ int) predicate.Entity {
return entity.HasTagWith(tag.ID(l))
})
andPredicates = append(andPredicates, entity.Or(tagPredicates...))
}
} else {
tagPredicates := lo.Map(descendantGroups[0], func(l uuid.UUID, _ int) predicate.Entity {
return entity.Not(entity.HasTagWith(tag.ID(l)))
})
andPredicates = append(andPredicates, entity.And(tagPredicates...))
}
}
if q.OnlyWithoutPhoto {
andPredicates = append(andPredicates, entity.Not(
entity.HasAttachmentsWith(
attachment.And(
attachment.Primary(true),
attachment.TypeEQ(attachment.TypePhoto),
),
)),
)
}
if q.OnlyWithPhoto {
andPredicates = append(andPredicates, entity.HasAttachmentsWith(
attachment.And(
attachment.Primary(true),
attachment.TypeEQ(attachment.TypePhoto),
),
),
)
}
if len(q.ParentIDs) > 0 {
parentPredicates := lo.Map(q.ParentIDs, func(l uuid.UUID, _ int) predicate.Entity {
return entity.HasParentWith(entity.ID(l))
})
andPredicates = append(andPredicates, entity.Or(parentPredicates...))
}
if len(q.Fields) > 0 {
fieldPredicates := lo.Map(q.Fields, func(f FieldQuery, _ int) predicate.Entity {
return entity.HasFieldsWith(
entityfield.And(
entityfield.Name(f.Name),
entityfield.TextValue(f.Value),
),
)
})
andPredicates = append(andPredicates, entity.Or(fieldPredicates...))
}
if len(q.ParentItemIDs) > 0 {
andPredicates = append(andPredicates, entity.HasParentWith(entity.IDIn(q.ParentItemIDs...)))
}
}
if len(andPredicates) > 0 {
qb = qb.Where(entity.And(andPredicates...))
}
span.SetAttributes(attribute.Int("query.predicates.and.count", len(andPredicates)))
countCtx, countSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.count")
count, err := qb.Count(countCtx)
if err != nil {
recordSpanError(countSpan, err)
countSpan.End()
recordSpanError(span, err)
return PaginationResult[EntitySummary]{}, err
}
countSpan.SetAttributes(attribute.Int("query.total.count", count))
countSpan.End()
// Order
switch q.OrderBy {
case "createdAt":
qb = qb.Order(ent.Desc(entity.FieldCreatedAt))
case "updatedAt":
qb = qb.Order(ent.Desc(entity.FieldUpdatedAt))
case "assetId":
qb = qb.Order(ent.Asc(entity.FieldAssetID))
default: // "name"
qb = qb.Order(ent.Asc(entity.FieldName))
}
qb = qb.
WithTag().
WithParent().
WithEntityType().
WithAttachments(func(aq *ent.AttachmentQuery) {
aq.Where(
attachment.Primary(true),
)
aq.WithThumbnail()
})
if q.Page != -1 || q.PageSize != -1 {
qb = qb.
Offset(calculateOffset(q.Page, q.PageSize)).
Limit(q.PageSize)
}
fetchCtx, fetchSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.fetch")
entities, err := mapEntitiesSummaryErr(qb.All(fetchCtx))
if err != nil {
recordSpanError(fetchSpan, err)
fetchSpan.End()
recordSpanError(span, err)
return PaginationResult[EntitySummary]{}, err
}
fetchSpan.SetAttributes(attribute.Int("query.results.count", len(entities)))
fetchSpan.End()
// Populate ItemCount for location-type entities
if q.IsLocation != nil && *q.IsLocation && len(entities) > 0 {
childCtx, childSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.childItemCounts",
trace.WithAttributes(attribute.Int("locations.count", len(entities))))
ids := lo.Map(entities, func(e EntitySummary, _ int) uuid.UUID { return e.ID })
counts, cErr := r.getChildItemCounts(childCtx, gid, ids)
if cErr != nil {
recordSpanError(childSpan, cErr)
} else {
for i := range entities {
if c, ok := counts[entities[i].ID]; ok {
entities[i].ItemCount = c
}
}
}
childSpan.End()
}
span.SetAttributes(
attribute.Int("query.results.count", len(entities)),
attribute.Int("query.total.count", count),
)
return PaginationResult[EntitySummary]{
Page: q.Page,
PageSize: q.PageSize,
Total: count,
Items: entities,
}, nil
}
// getChildItemCounts returns a map of entity ID → sum of child item quantities for the given location IDs.
func (r *EntityRepository) getChildItemCounts(ctx context.Context, gid uuid.UUID, locationIDs []uuid.UUID) (map[uuid.UUID]float64, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.getChildItemCounts",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.Int("locations.count", len(locationIDs)),
))
defer span.End()
if len(locationIDs) == 0 {
return nil, nil
}
// Build placeholders for the IN clause
placeholders := make([]string, len(locationIDs))
args := make([]any, 0, len(locationIDs)+1)
args = append(args, gid)
for i, id := range locationIDs {
placeholders[i] = fmt.Sprintf("$%d", i+2)
args = append(args, id)
}
query := fmt.Sprintf(`
SELECT e.entity_children, COALESCE(SUM(e.quantity), 0)
FROM entities e
JOIN entity_types et ON et.id = e.entity_type_entities
WHERE e.group_entities = $1
AND et.is_location = false
AND e.archived = false
AND e.entity_children IN (%s)
GROUP BY e.entity_children
`, strings.Join(placeholders, ","))
rows, err := r.db.Sql().QueryContext(ctx, query, args...)
if err != nil {
recordSpanError(span, err)
return nil, err
}
defer func() { _ = rows.Close() }()
result := make(map[uuid.UUID]float64)
for rows.Next() {
var parentID uuid.UUID
var count float64
if err := rows.Scan(&parentID, &count); err != nil {
recordSpanError(span, err)
return nil, err
}
result[parentID] = count
}
if err := rows.Err(); err != nil {
recordSpanError(span, err)
return result, err
}
span.SetAttributes(attribute.Int("results.count", len(result)))
return result, nil
}
// QueryByAssetID returns entities by asset ID.
func (r *EntityRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, assetID AssetID, page int, pageSize int) (PaginationResult[EntitySummary], error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.QueryByAssetID",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.Int64("entity.asset_id", int64(assetID)),
attribute.Int("query.page", page),
attribute.Int("query.page_size", pageSize),
))
defer span.End()
qb := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
entity.AssetID(int64(assetID)),
)
if page != -1 || pageSize != -1 {
qb.Offset(calculateOffset(page, pageSize)).
Limit(pageSize)
} else {
page = -1
pageSize = -1
}
entities, err := mapEntitiesSummaryErr(
qb.Order(ent.Asc(entity.FieldName)).
WithTag().
WithParent().
WithEntityType().
All(ctx),
)
if err != nil {
recordSpanError(span, err)
return PaginationResult[EntitySummary]{}, err
}
span.SetAttributes(attribute.Int("query.results.count", len(entities)))
return PaginationResult[EntitySummary]{
Page: page,
PageSize: pageSize,
Total: len(entities),
Items: entities,
}, nil
}
// GetAll returns all the entities in the database with the Tags, Parent, and EntityType eager loaded.
func (r *EntityRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]EntityOut, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAll",
trace.WithAttributes(attribute.String("group.id", gid.String())))
defer span.End()
out, err := mapEntitiesOutErr(r.db.Entity.Query().
Where(entity.HasGroupWith(group.ID(gid))).
WithTag().
WithParent().
WithEntityType().
WithFields().
All(ctx))
if err != nil {
recordSpanError(span, err)
return out, err
}
span.SetAttributes(attribute.Int("entities.count", len(out)))
return out, nil
}
func (r *EntityRepository) GetAllZeroAssetID(ctx context.Context, gid uuid.UUID) ([]EntitySummary, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAllZeroAssetID",
trace.WithAttributes(attribute.String("group.id", gid.String())))
defer span.End()
q := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
entity.AssetID(0),
).Order(
ent.Asc(entity.FieldCreatedAt),
)
out, err := mapEntitiesSummaryErr(q.All(ctx))
if err != nil {
recordSpanError(span, err)
return out, err
}
span.SetAttributes(attribute.Int("entities.count", len(out)))
return out, nil
}
func (r *EntityRepository) GetHighestAssetIDTx(ctx context.Context, tx *ent.Tx, gid uuid.UUID) (AssetID, error) {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetHighestAssetIDTx",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.Bool("tx", tx != nil),
))
defer span.End()
var q *ent.EntityQuery
if tx != nil {
q = tx.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
).Order(
ent.Desc(entity.FieldAssetID),
).Limit(1)
} else {
q = r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
).Order(
ent.Desc(entity.FieldAssetID),
).Limit(1)
}
result, err := q.First(ctx)
if err != nil {
if ent.IsNotFound(err) {
return 0, nil
}
recordSpanError(span, err)
return 0, err
}
span.SetAttributes(attribute.Int64("entity.asset_id.highest", result.AssetID))
return AssetID(result.AssetID), nil
}
func (r *EntityRepository) GetHighestAssetID(ctx context.Context, gid uuid.UUID) (AssetID, error) {
return r.GetHighestAssetIDTx(ctx, nil, gid)
}
func (r *EntityRepository) SetAssetID(ctx context.Context, gid uuid.UUID, id uuid.UUID, assetID AssetID) error {
ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.SetAssetID",
trace.WithAttributes(
attribute.String("group.id", gid.String()),
attribute.String("entity.id", id.String()),
attribute.Int64("entity.asset_id", int64(assetID)),
))
defer span.End()
q := r.db.Entity.Update().Where(
entity.HasGroupWith(group.ID(gid)),
entity.ID(id),
)
_, err := q.SetAssetID(int64(assetID)).Save(ctx)
recordSpanError(span, err)
return err
}
func validateQuantity(op string, quantity float64) error {
if math.IsNaN(quantity) || math.IsInf(quantity, 0) {
return fmt.Errorf("%s: invalid quantity: must be a finite number", op)