Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

Merge remote-tracking branch 'weblate/main'

Matthew Kilgore95aaddea0a6d
diff --cc backend/app/api/handlers/v1/v1_ctrl_entities.go
index c6c3c4ed,3b3959b7..b91b13ca
--- a/backend/app/api/handlers/v1/v1_ctrl_entities.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_entities.go
@@@ -48,16 -48,12 +48,16 @@@ func startEntityCtrlSpan(ctx context.Co
// @Summary Query All Entities
// @Tags Entities
// @Produce json
-// @Param q query string false "search string"
-// @Param page query int false "page number"
-// @Param pageSize query int false "items per page"
-// @Param tags query []string false "tags Ids" collectionFormat(multi)
-// @Param parentIds query []string false "parent Ids" collectionFormat(multi)
-// @Success 200 {object} repo.EntityListResult
+// @Param q query string false "search string; matches names, descriptions, serial/model numbers, manufacturers, notes, purchase sources, tag names, and custom field values. Use #<assetId> to look up by asset ID and double quotes for exact phrases"
+// @Param page query int false "page number"
+// @Param pageSize query int false "items per page"
- // @Param tags query []string false "tags Ids" collectionFormat(multi)
++// @Param tags query []string false "tags Ids" collectionFormat(multi)
+// @Param matchAllTags query bool false "require all selected tags to match (AND) instead of any (OR)"
- // @Param parentIds query []string false "parent Ids" collectionFormat(multi)
++// @Param parentIds query []string false "parent Ids" collectionFormat(multi)
+// @Param entityTypeIds query []string false "entity type IDs; when provided this filter takes precedence over isLocation" collectionFormat(multi)
- // @Param orderBy query string false "field to order by; valid values: name, createdAt, updatedAt, assetId"
- // @Param orderDirection query string false "order direction; valid values: asc, desc"
++// @Param orderBy query string false "field to order by; valid values: name, createdAt, updatedAt, assetId"
++// @Param orderDirection query string false "order direction; valid values: asc, desc"
+// @Success 200 {object} repo.EntityListResult
// @Router /v1/entities [GET]
// @Security Bearer
func (ctrl *V1Controller) HandleEntitiesGetAll() errchain.HandlerFunc {
diff --cc backend/internal/data/repo/repo_entities.go
index 60c305f3,efc6c38c..fdc80520
--- a/backend/internal/data/repo/repo_entities.go
+++ b/backend/internal/data/repo/repo_entities.go
@@@ -617,155 -593,6 +617,190 @@@ func entityQuerySpanAttrs(gid uuid.UUID
}
}
+// tagPredicates translates the tag filter portion of q into predicates that
+// QueryByGroup ANDs with the rest of the query. Selected tags also match any
+// of their descendant tags.
+func (r *EntityRepository) tagPredicates(ctx context.Context, q EntityQuery) []predicate.Entity {
+ 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))))
+ defer descSpan.End()
+
+ // expandTags returns the given tags plus all their descendant tags,
+ // falling back to just the given tags when expansion fails.
+ expandTags := func(ids []uuid.UUID) []uuid.UUID {
+ descendants, err := tagRepo.GetDescendantTagIDs(ctxDescendants, ids)
+ if err != nil {
+ recordSpanError(descSpan, err)
+ log.Warn().Err(err).Msg("failed to get descendant tags, using only direct tags")
+ return ids
+ }
+ if len(descendants) == 0 {
+ return ids
+ }
+ return descendants
+ }
+
+ hasTag := func(l uuid.UUID, _ int) predicate.Entity {
+ return entity.HasTagWith(tag.ID(l))
+ }
+
+ switch {
+ case q.NegateTags:
+ descendants := expandTags(q.TagIDs)
+ descSpan.SetAttributes(attribute.Int("query.tag_descendants.count", len(descendants)))
+ notTag := lo.Map(descendants, func(l uuid.UUID, _ int) predicate.Entity {
+ return entity.Not(entity.HasTagWith(tag.ID(l)))
+ })
+ return []predicate.Entity{entity.And(notTag...)}
+ case q.MatchAllTags:
+ // Every selected tag must be present, where each tag also counts as
+ // matched by any of its descendants.
+ preds := make([]predicate.Entity, 0, len(q.TagIDs))
+ for _, id := range q.TagIDs {
+ expanded := expandTags([]uuid.UUID{id})
+ preds = append(preds, entity.Or(lo.Map(expanded, hasTag)...))
+ }
+ return preds
+ default:
+ descendants := expandTags(q.TagIDs)
+ descSpan.SetAttributes(attribute.Int("query.tag_descendants.count", len(descendants)))
+ return []predicate.Entity{entity.Or(lo.Map(descendants, hasTag)...)}
+ }
+}
+
+// orderByLocation orders the entities of a group by their location, matching
+// the Location field computed by nearestLocationAncestor: when the direct
+// parent is a location it is used as-is, otherwise the parent chain is climbed
+// until a location is found. Ent has no support for recursive CTEs, so the
+// chain is walked with the dialect-aware sql builder, which keeps every value
+// bound as a query argument and every identifier quoted for the dialect in
+// use.
+//
+// Locations are compared by name. Entities without a location sort last in
+// both directions, and entities sharing a location fall back to their own name
+// so pages stay stable.
+func orderByLocation(gid uuid.UUID, desc bool) entity.OrderOption {
+ return func(s *sql.Selector) {
+ // Names of the CTEs and of the columns they add.
+ const (
+ ancestorsCTE = "entity_ancestors"
+ nearestLocationCTE = "entity_nearest_location"
+
+ colAncestorID = "ancestor_id"
+ colDepth = "depth"
+ colLocationName = "location_name"
+ )
+
+ d := sql.Dialect(s.Dialect())
+
+ // Seed the walk with every entity in the group that has a parent,
+ // paired with that parent and a depth of zero.
+ child := d.Table(entity.Table)
+ seed := d.Select(child.C(entity.FieldID), child.C(entity.ParentColumn)).
+ AppendSelectExpr(sql.Expr("0")). // literal, so Postgres can type the depth column
+ From(child).
+ Where(sql.And(
+ sql.EQ(child.C(entity.GroupColumn), gid),
+ sql.NotNull(child.C(entity.ParentColumn)),
+ ))
+
+ // Climb one level for as long as the ancestor reached so far is not a
+ // location, bounded by maxAncestorDepth so a cyclic tree terminates.
+ walked := d.Table(ancestorsCTE)
+ parent := d.Table(entity.Table).As("parent")
+ parentType := d.Table(entitytype.Table).As("parent_type")
+ climb := d.Select(walked.C(entity.FieldID), parent.C(entity.ParentColumn)).
+ AppendSelectExpr(sql.ExprFunc(func(b *sql.Builder) {
+ b.Ident(walked.C(colDepth)).WriteOp(sql.OpAdd).WriteString("1")
+ })).
+ From(walked).
+ Join(parent).On(parent.C(entity.FieldID), walked.C(colAncestorID)).
+ Join(parentType).On(parentType.C(entitytype.FieldID), parent.C(entity.EntityTypeColumn)).
+ Where(sql.And(
+ sql.EQ(parentType.C(entitytype.FieldIsLocation), false),
+ sql.NotNull(parent.C(entity.ParentColumn)),
+ sql.LT(walked.C(colDepth), maxAncestorDepth),
+ ))
+
+ // Every chain stops at the first location it reaches, so at most one
+ // row per entity survives this filter.
+ ancestors := d.Table(ancestorsCTE)
+ location := d.Table(entity.Table).As("location")
+ locationType := d.Table(entitytype.Table).As("location_type")
+ nearest := d.Select(
+ ancestors.C(entity.FieldID),
+ sql.Min(sql.Lower(location.C(entity.FieldName))),
+ ).
+ From(ancestors).
+ Join(location).On(location.C(entity.FieldID), ancestors.C(colAncestorID)).
+ Join(locationType).On(locationType.C(entitytype.FieldID), location.C(entity.EntityTypeColumn)).
+ Where(sql.EQ(locationType.C(entitytype.FieldIsLocation), true)).
+ GroupBy(ancestors.C(entity.FieldID))
+
+ ctes := sql.WithRecursive(ancestorsCTE, entity.FieldID, colAncestorID, colDepth).
+ As(seed.UnionAll(climb)).
+ With(nearestLocationCTE, entity.FieldID, colLocationName).
+ As(nearest)
+ ctes.SetDialect(s.Dialect())
+ s.Prefix(ctes)
+
+ nearestTable := d.Table(nearestLocationCTE)
+ s.LeftJoin(nearestTable).On(nearestTable.C(entity.FieldID), s.C(entity.FieldID))
+
+ // Ordering is written the same way ent writes its own order terms, see
+ // (*sql.OrderFieldTerm).ToFunc.
+ s.OrderExprFunc(func(b *sql.Builder) {
+ b.Ident(nearestTable.C(colLocationName))
+ if desc {
+ b.WriteString(" DESC")
+ }
+ // SQLite and Postgres disagree on where NULLs land by default, so
+ // the entities without a location are placed explicitly.
+ b.WriteString(" NULLS LAST")
+ })
+ // Tie-break so entities sharing a location paginate consistently.
+ s.OrderExprFunc(func(b *sql.Builder) {
+ b.Ident(sql.Lower(s.C(entity.FieldName)))
+ })
+ }
+}
+
++// applyEntityOrder applies the ORDER BY for q.OrderBy / q.OrderDirection and
++// returns the resolved order field name for logging.
++func applyEntityOrder(qb *ent.EntityQuery, gid uuid.UUID, q EntityQuery) (*ent.EntityQuery, string) {
++ var orderBy string
++
++ switch q.OrderBy {
++ case "createdAt":
++ orderBy = entity.FieldCreatedAt
++ case "updatedAt":
++ orderBy = entity.FieldUpdatedAt
++ case "assetId":
++ orderBy = entity.FieldAssetID
++ case "quantity":
++ orderBy = entity.FieldQuantity
++ case "insured":
++ orderBy = entity.FieldInsured
++ case "archived":
++ orderBy = entity.FieldArchived
++ case "purchasePrice":
++ orderBy = entity.FieldPurchasePrice
++ case "location":
++ // Sort by the name of the nearest location ancestor.
++ return qb.Order(orderByLocation(gid, q.OrderDirection == "desc")), "location"
++ default: // "name"
++ orderBy = entity.FieldName
++ }
++
++ switch q.OrderDirection {
++ case "desc":
++ return qb.Order(ent.Desc(orderBy)), orderBy
++ default: // "asc"
++ return qb.Order(ent.Asc(orderBy)), orderBy
++ }
++}
++
// 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",
@@@ -893,49 -743,17 +928,14 @@@
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))
- }
+ var orderBy string
- locationSort := false
-
- // Order
- switch q.OrderBy {
- case "createdAt":
- orderBy = entity.FieldCreatedAt
- case "updatedAt":
- orderBy = entity.FieldUpdatedAt
- case "assetId":
- orderBy = entity.FieldAssetID
- case "quantity":
- orderBy = entity.FieldQuantity
- case "insured":
- orderBy = entity.FieldInsured
- case "archived":
- orderBy = entity.FieldArchived
- case "purchasePrice":
- orderBy = entity.FieldPurchasePrice
- case "location":
- // Sort by the name of the nearest location ancestor.
- orderBy = "location"
- locationSort = true
- default: // "name"
- orderBy = entity.FieldName
- }
-
- if locationSort {
- qb = qb.Order(orderByLocation(gid, q.OrderDirection == "desc"))
- } else {
- switch q.OrderDirection {
- case "desc":
- qb = qb.Order(ent.Desc(orderBy))
- default: // "asc"
- qb = qb.Order(ent.Asc(orderBy))
- }
- }
++ qb, orderBy = applyEntityOrder(qb, gid, q)
+
+ // log order direction
+ log.Debug().
+ Str("orderBy", orderBy).
+ Str("orderDirection", q.OrderDirection).
+ Msg("QueryByGroup order")
qb = qb.
WithTag().
diff --cc frontend/locales/en.json
index 8c6edaf8,a54328ec..0b4c387b
--- a/frontend/locales/en.json
+++ b/frontend/locales/en.json
@@@ -455,6 -455,8 +455,9 @@@
"duplicate": "Duplicate",
"edit": "Edit",
"email": "Email",
+ "entity": "Entity",
+ "entity_type": "Entity Type",
++ "entity_types": "Entity Types",
"follow_dev": "Follow the Developer",
"footer": {
"api_link": "'<a href=\"https://homebox.software/en/api/\" target=\"_blank\">'API'</a>'",
@@@ -474,6 -478,6 +479,7 @@@
"preview": "Preview",
"quantity": "Quantity",
"read_docs": "Read the Docs",
++ "results": "Results",
"return_home": "Return Home",
"save": "Save",
"search": "Search",
@@@ -553,6 -551,6 +553,7 @@@
"add": "Add",
"advanced": "Advanced",
"archived": "Archived",
++ "asc": "Ascending",
"asset_id": "Asset ID",
"associated_with_multiple": "This Asset Id is associated with multiple items",
"attachment": "Attachment",
@@@ -562,6 -560,6 +563,7 @@@
"custom_fields": "Custom Fields",
"delete_attachment_confirm": "Are you sure you want to delete this attachment?",
"delete_item_confirm": "Are you sure you want to delete this item?",
++ "desc": "Descending",
"description": "Description",
"details": "Details",
"drag_and_drop": "Drag and drop files here or click to select files",
@@@ -610,6 -607,6 +612,7 @@@
"next_page": "Next Page",
"no_attachments": "No attachments found",
"no_results": "No Items Found",
++ "no_saved_searches": "No saved searches",
"notes": "Notes",
"only_with_photo": "Only items with photo",
"only_without_photo": "Only items without photo",
@@@ -630,6 -627,6 +633,8 @@@
"receipts": "Receipts",
"reset_search": "Reset Search",
"results": "{ total } Results",
++ "saved_search_name": "Save search as...",
++ "saved_searches": "Saved Searches",
"select_field": "Select a field",
"select_value": "Select a value",
"serial_number": "Serial Number",
@@@ -642,8 -639,7 +647,8 @@@
"sync_child_locations": "Sync child items' locations",
"tip_1": "Location and tag filters use the 'OR' operation. If more than one is selected only one will be\n required for a match.",
"tip_2": "Searches prefixed with '#'' will query for a asset ID (example '#000-001')",
- "tip_4": "Search matches names, descriptions, serial and model numbers, manufacturers, notes, purchase sources, tag names, and custom field values. Every word must match somewhere; wrap words in double quotes to match an exact phrase.",
"tip_3": "Field filters use the 'OR' operation. If more than one is selected only one will be required for a\n match.",
++ "tip_4": "Search matches names, descriptions, serial and model numbers, manufacturers, notes, purchase sources, tag names, and custom field values. Every word must match somewhere; wrap words in double quotes to match an exact phrase.",
"tips": "Tips",
"tips_sub": "Search Tips",
"toast": {
@@@ -671,10 -667,7 +676,10 @@@
"item_deleted": "Item deleted",
"item_saved": "Item saved",
"quantity_cannot_negative": "Quantity cannot be negative",
- "sync_child_location": "Selected parent syncs its children's locations to its own. The location has been updated.",
++ "saved_search_deleted": "Saved search deleted",
+ "saved_search_name_required": "Saved search name is required",
+ "saved_search_saved": "Search saved",
- "saved_search_deleted": "Saved search deleted"
+ "sync_child_location": "Selected parent syncs its children's locations to its own. The location has been updated."
},
"updated_at": "Updated At",
"warranty": "Warranty",