A continuation of HomeBox the inventory and organization system built for the Home User
fix: child item seperate location (#1696)
Matt3d84c421a225
diff --git a/backend/app/api/handlers/v1/v1_ctrl_entity_templates.go b/backend/app/api/handlers/v1/v1_ctrl_entity_templates.goindex 17a82300..f1317f3e 100644--- a/backend/app/api/handlers/v1/v1_ctrl_entity_templates.go+++ b/backend/app/api/handlers/v1/v1_ctrl_entity_templates.go@@ -107,6 +107,7 @@ type EntityTemplateCreateItemRequest struct {Name string `json:"name" validate:"required,min=1,max=255"`Description string `json:"description" validate:"max=1000"`ParentID uuid.UUID `json:"parentId" validate:"required"`+ LocationID uuid.UUID `json:"locationId" extensions:"x-nullable,x-omitempty"`// EntityTypeID is the entity type selected by the user. When set it takes// precedence; when empty the repository falls back to the group's default.EntityTypeID uuid.UUID `json:"entityTypeId"`@@ -155,6 +156,7 @@ func (ctrl *V1Controller) HandleEntityTemplatesCreateItem() errchain.HandlerFuncDescription: body.Description,Quantity: quantity,ParentID: body.ParentID,+ LocationID: body.LocationID,EntityTypeID: body.EntityTypeID,TagIDs: body.TagIDs,Insured: template.DefaultInsured,diff --git a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go b/backend/app/api/handlers/v1/v1_ctrl_notifiers.goindex a1db18bb..24be09b4 100644--- a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go+++ b/backend/app/api/handlers/v1/v1_ctrl_notifiers.go@@ -1,10 +1,13 @@package v1import (+ "errors""net/http"+ "net/url""github.com/google/uuid""github.com/hay-kot/httpkit/errchain"+ "github.com/rs/zerolog/log""github.com/sysadminsmedia/homebox/backend/internal/core/services""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/internal/sys/validate"@@ -118,13 +121,29 @@ func (ctrl *V1Controller) HandlerNotifierTest() errchain.HandlerFunc {// Deliver through the guarded client so redirect hops and the resolved// address are re-checked against the same policy.- err := validate.SendNotifierMessage(q.URL, "Test message from Homebox", &ctrl.config.Notifier)- return nil, err+ if err := validate.SendNotifierMessage(q.URL, "Test message from Homebox", &ctrl.config.Notifier); err != nil {+ // The delivery error can quote the URL, which carries the notifier's+ // credentials; keep it to the log and hand the caller a bare failure.+ log.Err(err).Str("notifier_url", redactNotifierURL(q.URL)).Msg("notifier test failed")+ return nil, validate.NewRequestError(errTestNotifierFailed, http.StatusBadRequest)+ }++ return nil, nil}return adapters.Action(fn, http.StatusOK)}+var errTestNotifierFailed = errors.New("failed to send test notification")++func redactNotifierURL(raw string) string {+ u, err := url.Parse(raw)+ if err != nil {+ return "<unparsable url>"+ }+ return u.Redacted()+}+// validateNotifierURL validates a notifier URL against the configured block/allow listsfunc (ctrl *V1Controller) validateNotifierURL(url string) error {return validate.ValidateNotifierURL(url, &ctrl.config.Notifier)diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.goindex 7b1eac1f..040b018b 100644--- a/backend/app/api/static/docs/docs.go+++ b/backend/app/api/static/docs/docs.go@@ -3631,6 +3631,21 @@ const docTemplate = `{}]},+ "location": {+ "description": "Location holds the value of the location edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.Entity"+ }+ ]+ },+ "location_entities": {+ "description": "LocationEntities holds the value of the location_entities edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.Entity"+ }+ },"maintenance_entries": {"description": "MaintenanceEntries holds the value of the maintenance_entries edge.","type": "array",@@ -4800,6 +4815,12 @@ const docTemplate = `{"entityTypeId": {"type": "string"},+ "locationId": {+ "description": "LocationID is only needed when ParentID refers to another item and\nthe new entity is stored somewhere other than that item's location.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string","maxLength": 255,@@ -4944,7 +4965,7 @@ const docTemplate = `{"type": "boolean"},"location": {- "description": "Location is the nearest ancestor whose entity type is a location.\nWhen the direct parent is already a location it equals Parent; when\nthe entity is nested inside other items it is the location those\nitems ultimately live in. Nil for top-level entities.",+ "description": "Location is where this entity resolves to: its own location when one\nis set, otherwise the nearest ancestor whose entity type is a\nlocation. Nil for top-level entities. This is a *resolved* value —\nwrite it back through LocationID, not through this field.","allOf": [{"$ref": "#/definitions/repo.EntitySummary"@@ -4953,6 +4974,12 @@ const docTemplate = `{"x-nullable": true,"x-omitempty": true},+ "locationId": {+ "description": "LocationID is this entity's own location, and is nil when Location was\ninherited from an ancestor. It is named to match the locationId field\non EntityUpdate on purpose: a GET body PUT back verbatim keeps the\nentity exactly where it was, rather than silently pinning an\ninherited location or dropping an explicit one.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},@@ -5044,6 +5071,11 @@ const docTemplate = `{"id": {"type": "string"},+ "locationId": {+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"parentId": {"type": "string","x-nullable": true,@@ -5546,6 +5578,12 @@ const docTemplate = `{"description": "Warranty","type": "boolean"},+ "locationId": {+ "description": "LocationID names the location this entity is stored in. It only\nneeds to be sent when ParentID refers to another item and the entity\nlives somewhere other than that item's location (#1688); otherwise\nParentID alone carries the location. See resolveLocationOverride.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},@@ -6439,6 +6477,11 @@ const docTemplate = `{"description": "EntityTypeID is the entity type selected by the user. When set it takes\nprecedence; when empty the repository falls back to the group's default.","type": "string"},+ "locationId": {+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"name": {"type": "string","maxLength": 255,diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.jsonindex 87227ba7..82963259 100644--- a/backend/app/api/static/docs/openapi-3.json+++ b/backend/app/api/static/docs/openapi-3.json@@ -3872,6 +3872,21 @@}]},+ "location": {+ "description": "Location holds the value of the location edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.Entity"+ }+ ]+ },+ "location_entities": {+ "description": "LocationEntities holds the value of the location_entities edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.Entity"+ }+ },"maintenance_entries": {"description": "MaintenanceEntries holds the value of the maintenance_entries edge.","type": "array",@@ -5041,6 +5056,12 @@"entityTypeId": {"type": "string"},+ "locationId": {+ "description": "LocationID is only needed when ParentID refers to another item and\nthe new entity is stored somewhere other than that item's location.",+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string","maxLength": 255,@@ -5185,7 +5206,7 @@"type": "boolean"},"location": {- "description": "Location is the nearest ancestor whose entity type is a location.\nWhen the direct parent is already a location it equals Parent; when\nthe entity is nested inside other items it is the location those\nitems ultimately live in. Nil for top-level entities.",+ "description": "Location is where this entity resolves to: its own location when one\nis set, otherwise the nearest ancestor whose entity type is a\nlocation. Nil for top-level entities. This is a *resolved* value —\nwrite it back through LocationID, not through this field.","allOf": [{"$ref": "#/components/schemas/repo.EntitySummary"@@ -5194,6 +5215,12 @@"x-omitempty": true,"nullable": true},+ "locationId": {+ "description": "LocationID is this entity's own location, and is nil when Location was\ninherited from an ancestor. It is named to match the locationId field\non EntityUpdate on purpose: a GET body PUT back verbatim keeps the\nentity exactly where it was, rather than silently pinning an\ninherited location or dropping an explicit one.",+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string"},@@ -5285,6 +5312,11 @@"id": {"type": "string"},+ "locationId": {+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"parentId": {"type": "string","x-omitempty": true,@@ -5787,6 +5819,12 @@"description": "Warranty","type": "boolean"},+ "locationId": {+ "description": "LocationID names the location this entity is stored in. It only\nneeds to be sent when ParentID refers to another item and the entity\nlives somewhere other than that item's location (#1688); otherwise\nParentID alone carries the location. See resolveLocationOverride.",+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string"},@@ -6680,6 +6718,11 @@"description": "EntityTypeID is the entity type selected by the user. When set it takes\nprecedence; when empty the repository falls back to the group's default.","type": "string"},+ "locationId": {+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"name": {"type": "string","maxLength": 255,diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yamlindex fa8d89db..a00c2bbc 100644--- a/backend/app/api/static/docs/openapi-3.yaml+++ b/backend/app/api/static/docs/openapi-3.yaml@@ -2357,6 +2357,15 @@ components:description: Group holds the value of the group edge.allOf:- $ref: "#/components/schemas/ent.Group"+ location:+ description: Location holds the value of the location edge.+ allOf:+ - $ref: "#/components/schemas/ent.Entity"+ location_entities:+ description: LocationEntities holds the value of the location_entities edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.Entity"maintenance_entries:description: MaintenanceEntries holds the value of the maintenance_entries edge.type: array@@ -3176,6 +3185,13 @@ components:maxLength: 1000entityTypeId:type: string+ locationId:+ description: |-+ LocationID is only needed when ParentID refers to another item and+ the new entity is stored somewhere other than that item's location.+ type: string+ x-omitempty: true+ nullable: truemanufacturer:type: stringmaxLength: 255@@ -3280,14 +3296,29 @@ components:type: booleanlocation:description: |-- Location is the nearest ancestor whose entity type is a location.- When the direct parent is already a location it equals Parent; when- the entity is nested inside other items it is the location those- items ultimately live in. Nil for top-level entities.+ Location is where this entity resolves to: its own location when one+ is set, otherwise the nearest ancestor whose entity type is a+ location. Nil for top-level entities. This is a *resolved* value —+ write it back through LocationID, not through this field.allOf:- $ref: "#/components/schemas/repo.EntitySummary"x-omitempty: truenullable: true+ locationId:+ description: >-+ LocationID is this entity's own location, and is nil when Location+ was++ inherited from an ancestor. It is named to match the locationId field++ on EntityUpdate on purpose: a GET body PUT back verbatim keeps the++ entity exactly where it was, rather than silently pinning an++ inherited location or dropping an explicit one.+ type: string+ x-omitempty: true+ nullable: truemanufacturer:type: stringmodelNumber:@@ -3350,6 +3381,10 @@ components:nullable: trueid:type: string+ locationId:+ type: string+ x-omitempty: true+ nullable: trueparentId:type: stringx-omitempty: true@@ -3699,6 +3734,15 @@ components:lifetimeWarranty:description: Warrantytype: boolean+ locationId:+ description: |-+ LocationID names the location this entity is stored in. It only+ needs to be sent when ParentID refers to another item and the entity+ lives somewhere other than that item's location (#1688); otherwise+ ParentID alone carries the location. See resolveLocationOverride.+ type: string+ x-omitempty: true+ nullable: truemanufacturer:type: stringmodelNumber:@@ -4306,6 +4350,10 @@ components:precedence; when empty the repository falls back to the group's default.type: string+ locationId:+ type: string+ x-omitempty: true+ nullable: truename:type: stringmaxLength: 255diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.jsonindex 8443d2ef..8ec23bee 100644--- a/backend/app/api/static/docs/swagger.json+++ b/backend/app/api/static/docs/swagger.json@@ -3628,6 +3628,21 @@}]},+ "location": {+ "description": "Location holds the value of the location edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.Entity"+ }+ ]+ },+ "location_entities": {+ "description": "LocationEntities holds the value of the location_entities edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.Entity"+ }+ },"maintenance_entries": {"description": "MaintenanceEntries holds the value of the maintenance_entries edge.","type": "array",@@ -4797,6 +4812,12 @@"entityTypeId": {"type": "string"},+ "locationId": {+ "description": "LocationID is only needed when ParentID refers to another item and\nthe new entity is stored somewhere other than that item's location.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string","maxLength": 255,@@ -4941,7 +4962,7 @@"type": "boolean"},"location": {- "description": "Location is the nearest ancestor whose entity type is a location.\nWhen the direct parent is already a location it equals Parent; when\nthe entity is nested inside other items it is the location those\nitems ultimately live in. Nil for top-level entities.",+ "description": "Location is where this entity resolves to: its own location when one\nis set, otherwise the nearest ancestor whose entity type is a\nlocation. Nil for top-level entities. This is a *resolved* value —\nwrite it back through LocationID, not through this field.","allOf": [{"$ref": "#/definitions/repo.EntitySummary"@@ -4950,6 +4971,12 @@"x-nullable": true,"x-omitempty": true},+ "locationId": {+ "description": "LocationID is this entity's own location, and is nil when Location was\ninherited from an ancestor. It is named to match the locationId field\non EntityUpdate on purpose: a GET body PUT back verbatim keeps the\nentity exactly where it was, rather than silently pinning an\ninherited location or dropping an explicit one.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},@@ -5041,6 +5068,11 @@"id": {"type": "string"},+ "locationId": {+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"parentId": {"type": "string","x-nullable": true,@@ -5543,6 +5575,12 @@"description": "Warranty","type": "boolean"},+ "locationId": {+ "description": "LocationID names the location this entity is stored in. It only\nneeds to be sent when ParentID refers to another item and the entity\nlives somewhere other than that item's location (#1688); otherwise\nParentID alone carries the location. See resolveLocationOverride.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},@@ -6436,6 +6474,11 @@"description": "EntityTypeID is the entity type selected by the user. When set it takes\nprecedence; when empty the repository falls back to the group's default.","type": "string"},+ "locationId": {+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"name": {"type": "string","maxLength": 255,diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yamlindex af0a77c9..f4f1fb2a 100644--- a/backend/app/api/static/docs/swagger.yaml+++ b/backend/app/api/static/docs/swagger.yaml@@ -295,6 +295,15 @@ definitions:allOf:- $ref: '#/definitions/ent.Group'description: Group holds the value of the group edge.+ location:+ allOf:+ - $ref: '#/definitions/ent.Entity'+ description: Location holds the value of the location edge.+ location_entities:+ description: LocationEntities holds the value of the location_entities edge.+ items:+ $ref: '#/definitions/ent.Entity'+ type: arraymaintenance_entries:description: MaintenanceEntries holds the value of the maintenance_entriesedge.@@ -1100,6 +1109,13 @@ definitions:type: stringentityTypeId:type: string+ locationId:+ description: |-+ LocationID is only needed when ParentID refers to another item and+ the new entity is stored somewhere other than that item's location.+ type: string+ x-nullable: true+ x-omitempty: truemanufacturer:maxLength: 255type: string@@ -1208,10 +1224,20 @@ definitions:allOf:- $ref: '#/definitions/repo.EntitySummary'description: |-- Location is the nearest ancestor whose entity type is a location.- When the direct parent is already a location it equals Parent; when- the entity is nested inside other items it is the location those- items ultimately live in. Nil for top-level entities.+ Location is where this entity resolves to: its own location when one+ is set, otherwise the nearest ancestor whose entity type is a+ location. Nil for top-level entities. This is a *resolved* value —+ write it back through LocationID, not through this field.+ x-nullable: true+ x-omitempty: true+ locationId:+ description: |-+ LocationID is this entity's own location, and is nil when Location was+ inherited from an ancestor. It is named to match the locationId field+ on EntityUpdate on purpose: a GET body PUT back verbatim keeps the+ entity exactly where it was, rather than silently pinning an+ inherited location or dropping an explicit one.+ type: stringx-nullable: truex-omitempty: truemanufacturer:@@ -1276,6 +1302,10 @@ definitions:x-omitempty: trueid:type: string+ locationId:+ type: string+ x-nullable: true+ x-omitempty: trueparentId:type: stringx-nullable: true@@ -1623,6 +1653,15 @@ definitions:lifetimeWarranty:description: Warrantytype: boolean+ locationId:+ description: |-+ LocationID names the location this entity is stored in. It only+ needs to be sent when ParentID refers to another item and the entity+ lives somewhere other than that item's location (#1688); otherwise+ ParentID alone carries the location. See resolveLocationOverride.+ type: string+ x-nullable: true+ x-omitempty: truemanufacturer:type: stringmodelNumber:@@ -2227,6 +2266,10 @@ definitions:EntityTypeID is the entity type selected by the user. When set it takesprecedence; when empty the repository falls back to the group's default.type: string+ locationId:+ type: string+ x-nullable: true+ x-omitempty: truename:maxLength: 255minLength: 1diff --git a/backend/internal/data/ent/client.go b/backend/internal/data/ent/client.goindex 8d7d57c0..12d22612 100644--- a/backend/internal/data/ent/client.go+++ b/backend/internal/data/ent/client.go@@ -1132,6 +1132,38 @@ func (c *EntityClient) QueryChildren(_m *Entity) *EntityQuery {return query}+// QueryLocation queries the location edge of a Entity.+func (c *EntityClient) QueryLocation(_m *Entity) *EntityQuery {+ query := (&EntityClient{config: c.config}).Query()+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {+ id := _m.ID+ step := sqlgraph.NewStep(+ sqlgraph.From(entity.Table, entity.FieldID, id),+ sqlgraph.To(entity.Table, entity.FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, entity.LocationTable, entity.LocationColumn),+ )+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)+ return fromV, nil+ }+ return query+}++// QueryLocationEntities queries the location_entities edge of a Entity.+func (c *EntityClient) QueryLocationEntities(_m *Entity) *EntityQuery {+ query := (&EntityClient{config: c.config}).Query()+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {+ id := _m.ID+ step := sqlgraph.NewStep(+ sqlgraph.From(entity.Table, entity.FieldID, id),+ sqlgraph.To(entity.Table, entity.FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, entity.LocationEntitiesTable, entity.LocationEntitiesColumn),+ )+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)+ return fromV, nil+ }+ return query+}+// QueryTag queries the tag edge of a Entity.func (c *EntityClient) QueryTag(_m *Entity) *TagQuery {query := (&TagClient{config: c.config}).Query()diff --git a/backend/internal/data/ent/entity.go b/backend/internal/data/ent/entity.goindex 7de03133..a90872dd 100644--- a/backend/internal/data/ent/entity.go+++ b/backend/internal/data/ent/entity.go@@ -70,11 +70,12 @@ type Entity struct {SoldNotes string `json:"sold_notes,omitempty"`// Edges holds the relations/edges for other nodes in the graph.// The values are being populated by the EntityQuery when eager-loading is set.- Edges EntityEdges `json:"edges"`- entity_children *uuid.UUID- entity_type_entities *uuid.UUID- group_entities *uuid.UUID- selectValues sql.SelectValues+ Edges EntityEdges `json:"edges"`+ entity_children *uuid.UUID+ entity_location_entities *uuid.UUID+ entity_type_entities *uuid.UUID+ group_entities *uuid.UUID+ selectValues sql.SelectValues}// EntityEdges holds the relations/edges for other nodes in the graph.@@ -85,6 +86,10 @@ type EntityEdges struct {Parent *Entity `json:"parent,omitempty"`// Children holds the value of the children edge.Children []*Entity `json:"children,omitempty"`+ // Location holds the value of the location edge.+ Location *Entity `json:"location,omitempty"`+ // LocationEntities holds the value of the location_entities edge.+ LocationEntities []*Entity `json:"location_entities,omitempty"`// Tag holds the value of the tag edge.Tag []*Tag `json:"tag,omitempty"`// EntityType holds the value of the entity_type edge.@@ -97,7 +102,7 @@ type EntityEdges struct {Attachments []*Attachment `json:"attachments,omitempty"`// loadedTypes holds the information for reporting if a// type was loaded (or requested) in eager-loading or not.- loadedTypes [8]bool+ loadedTypes [10]bool}// GroupOrErr returns the Group value or an error if the edge@@ -131,10 +136,30 @@ func (e EntityEdges) ChildrenOrErr() ([]*Entity, error) {return nil, &NotLoadedError{edge: "children"}}+// LocationOrErr returns the Location value or an error if the edge+// was not loaded in eager-loading, or loaded but was not found.+func (e EntityEdges) LocationOrErr() (*Entity, error) {+ if e.Location != nil {+ return e.Location, nil+ } else if e.loadedTypes[3] {+ return nil, &NotFoundError{label: entity.Label}+ }+ return nil, &NotLoadedError{edge: "location"}+}++// LocationEntitiesOrErr returns the LocationEntities value or an error if the edge+// was not loaded in eager-loading.+func (e EntityEdges) LocationEntitiesOrErr() ([]*Entity, error) {+ if e.loadedTypes[4] {+ return e.LocationEntities, nil+ }+ return nil, &NotLoadedError{edge: "location_entities"}+}+// TagOrErr returns the Tag value or an error if the edge// was not loaded in eager-loading.func (e EntityEdges) TagOrErr() ([]*Tag, error) {- if e.loadedTypes[3] {+ if e.loadedTypes[5] {return e.Tag, nil}return nil, &NotLoadedError{edge: "tag"}@@ -145,7 +170,7 @@ func (e EntityEdges) TagOrErr() ([]*Tag, error) {func (e EntityEdges) EntityTypeOrErr() (*EntityType, error) {if e.EntityType != nil {return e.EntityType, nil- } else if e.loadedTypes[4] {+ } else if e.loadedTypes[6] {return nil, &NotFoundError{label: entitytype.Label}}return nil, &NotLoadedError{edge: "entity_type"}@@ -154,7 +179,7 @@ func (e EntityEdges) EntityTypeOrErr() (*EntityType, error) {// FieldsOrErr returns the Fields value or an error if the edge// was not loaded in eager-loading.func (e EntityEdges) FieldsOrErr() ([]*EntityField, error) {- if e.loadedTypes[5] {+ if e.loadedTypes[7] {return e.Fields, nil}return nil, &NotLoadedError{edge: "fields"}@@ -163,7 +188,7 @@ func (e EntityEdges) FieldsOrErr() ([]*EntityField, error) {// MaintenanceEntriesOrErr returns the MaintenanceEntries value or an error if the edge// was not loaded in eager-loading.func (e EntityEdges) MaintenanceEntriesOrErr() ([]*MaintenanceEntry, error) {- if e.loadedTypes[6] {+ if e.loadedTypes[8] {return e.MaintenanceEntries, nil}return nil, &NotLoadedError{edge: "maintenance_entries"}@@ -172,7 +197,7 @@ func (e EntityEdges) MaintenanceEntriesOrErr() ([]*MaintenanceEntry, error) {// AttachmentsOrErr returns the Attachments value or an error if the edge// was not loaded in eager-loading.func (e EntityEdges) AttachmentsOrErr() ([]*Attachment, error) {- if e.loadedTypes[7] {+ if e.loadedTypes[9] {return e.Attachments, nil}return nil, &NotLoadedError{edge: "attachments"}@@ -197,9 +222,11 @@ func (*Entity) scanValues(columns []string) ([]any, error) {values[i] = new(uuid.UUID)case entity.ForeignKeys[0]: // entity_childrenvalues[i] = &sql.NullScanner{S: new(uuid.UUID)}- case entity.ForeignKeys[1]: // entity_type_entities+ case entity.ForeignKeys[1]: // entity_location_entities+ values[i] = &sql.NullScanner{S: new(uuid.UUID)}+ case entity.ForeignKeys[2]: // entity_type_entitiesvalues[i] = &sql.NullScanner{S: new(uuid.UUID)}- case entity.ForeignKeys[2]: // group_entities+ case entity.ForeignKeys[3]: // group_entitiesvalues[i] = &sql.NullScanner{S: new(uuid.UUID)}default:values[i] = new(sql.UnknownType)@@ -374,13 +401,20 @@ func (_m *Entity) assignValues(columns []string, values []any) error {*_m.entity_children = *value.S.(*uuid.UUID)}case entity.ForeignKeys[1]:+ if value, ok := values[i].(*sql.NullScanner); !ok {+ return fmt.Errorf("unexpected type %T for field entity_location_entities", values[i])+ } else if value.Valid {+ _m.entity_location_entities = new(uuid.UUID)+ *_m.entity_location_entities = *value.S.(*uuid.UUID)+ }+ case entity.ForeignKeys[2]:if value, ok := values[i].(*sql.NullScanner); !ok {return fmt.Errorf("unexpected type %T for field entity_type_entities", values[i])} else if value.Valid {_m.entity_type_entities = new(uuid.UUID)*_m.entity_type_entities = *value.S.(*uuid.UUID)}- case entity.ForeignKeys[2]:+ case entity.ForeignKeys[3]:if value, ok := values[i].(*sql.NullScanner); !ok {return fmt.Errorf("unexpected type %T for field group_entities", values[i])} else if value.Valid {@@ -415,6 +449,16 @@ func (_m *Entity) QueryChildren() *EntityQuery {return NewEntityClient(_m.config).QueryChildren(_m)}+// QueryLocation queries the "location" edge of the Entity entity.+func (_m *Entity) QueryLocation() *EntityQuery {+ return NewEntityClient(_m.config).QueryLocation(_m)+}++// QueryLocationEntities queries the "location_entities" edge of the Entity entity.+func (_m *Entity) QueryLocationEntities() *EntityQuery {+ return NewEntityClient(_m.config).QueryLocationEntities(_m)+}+// QueryTag queries the "tag" edge of the Entity entity.func (_m *Entity) QueryTag() *TagQuery {return NewEntityClient(_m.config).QueryTag(_m)diff --git a/backend/internal/data/ent/entity/entity.go b/backend/internal/data/ent/entity/entity.goindex 86695dcb..355d2417 100644--- a/backend/internal/data/ent/entity/entity.go+++ b/backend/internal/data/ent/entity/entity.go@@ -69,6 +69,10 @@ const (EdgeParent = "parent"// EdgeChildren holds the string denoting the children edge name in mutations.EdgeChildren = "children"+ // EdgeLocation holds the string denoting the location edge name in mutations.+ EdgeLocation = "location"+ // EdgeLocationEntities holds the string denoting the location_entities edge name in mutations.+ EdgeLocationEntities = "location_entities"// EdgeTag holds the string denoting the tag edge name in mutations.EdgeTag = "tag"// EdgeEntityType holds the string denoting the entity_type edge name in mutations.@@ -96,6 +100,14 @@ const (ChildrenTable = "entities"// ChildrenColumn is the table column denoting the children relation/edge.ChildrenColumn = "entity_children"+ // LocationTable is the table that holds the location relation/edge.+ LocationTable = "entities"+ // LocationColumn is the table column denoting the location relation/edge.+ LocationColumn = "entity_location_entities"+ // LocationEntitiesTable is the table that holds the location_entities relation/edge.+ LocationEntitiesTable = "entities"+ // LocationEntitiesColumn is the table column denoting the location_entities relation/edge.+ LocationEntitiesColumn = "entity_location_entities"// TagTable is the table that holds the tag relation/edge. The primary key declared below.TagTable = "tag_entities"// TagInverseTable is the table name for the Tag entity.@@ -164,6 +176,7 @@ var Columns = []string{// table and are not defined as standalone fields in the schema.var ForeignKeys = []string{"entity_children",+ "entity_location_entities","entity_type_entities","group_entities",}@@ -390,6 +403,27 @@ func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {}}+// ByLocationField orders the results by location field.+func ByLocationField(field string, opts ...sql.OrderTermOption) OrderOption {+ return func(s *sql.Selector) {+ sqlgraph.OrderByNeighborTerms(s, newLocationStep(), sql.OrderByField(field, opts...))+ }+}++// ByLocationEntitiesCount orders the results by location_entities count.+func ByLocationEntitiesCount(opts ...sql.OrderTermOption) OrderOption {+ return func(s *sql.Selector) {+ sqlgraph.OrderByNeighborsCount(s, newLocationEntitiesStep(), opts...)+ }+}++// ByLocationEntities orders the results by location_entities terms.+func ByLocationEntities(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {+ return func(s *sql.Selector) {+ sqlgraph.OrderByNeighborTerms(s, newLocationEntitiesStep(), append([]sql.OrderTerm{term}, terms...)...)+ }+}+// ByTagCount orders the results by tag count.func ByTagCount(opts ...sql.OrderTermOption) OrderOption {return func(s *sql.Selector) {@@ -473,6 +507,20 @@ func newChildrenStep() *sqlgraph.Step {sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),)}+func newLocationStep() *sqlgraph.Step {+ return sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.To(Table, FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, LocationTable, LocationColumn),+ )+}+func newLocationEntitiesStep() *sqlgraph.Step {+ return sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.To(Table, FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, LocationEntitiesTable, LocationEntitiesColumn),+ )+}func newTagStep() *sqlgraph.Step {return sqlgraph.NewStep(sqlgraph.From(Table, FieldID),diff --git a/backend/internal/data/ent/entity/where.go b/backend/internal/data/ent/entity/where.goindex 2115f63f..9ac7779a 100644--- a/backend/internal/data/ent/entity/where.go+++ b/backend/internal/data/ent/entity/where.go@@ -1490,6 +1490,52 @@ func HasChildrenWith(preds ...predicate.Entity) predicate.Entity {})}+// HasLocation applies the HasEdge predicate on the "location" edge.+func HasLocation() predicate.Entity {+ return predicate.Entity(func(s *sql.Selector) {+ step := sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, LocationTable, LocationColumn),+ )+ sqlgraph.HasNeighbors(s, step)+ })+}++// HasLocationWith applies the HasEdge predicate on the "location" edge with a given conditions (other predicates).+func HasLocationWith(preds ...predicate.Entity) predicate.Entity {+ return predicate.Entity(func(s *sql.Selector) {+ step := newLocationStep()+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {+ for _, p := range preds {+ p(s)+ }+ })+ })+}++// HasLocationEntities applies the HasEdge predicate on the "location_entities" edge.+func HasLocationEntities() predicate.Entity {+ return predicate.Entity(func(s *sql.Selector) {+ step := sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, LocationEntitiesTable, LocationEntitiesColumn),+ )+ sqlgraph.HasNeighbors(s, step)+ })+}++// HasLocationEntitiesWith applies the HasEdge predicate on the "location_entities" edge with a given conditions (other predicates).+func HasLocationEntitiesWith(preds ...predicate.Entity) predicate.Entity {+ return predicate.Entity(func(s *sql.Selector) {+ step := newLocationEntitiesStep()+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {+ for _, p := range preds {+ p(s)+ }+ })+ })+}+// HasTag applies the HasEdge predicate on the "tag" edge.func HasTag() predicate.Entity {return predicate.Entity(func(s *sql.Selector) {diff --git a/backend/internal/data/ent/entity_create.go b/backend/internal/data/ent/entity_create.goindex fdf2917b..3a1c7988 100644--- a/backend/internal/data/ent/entity_create.go+++ b/backend/internal/data/ent/entity_create.go@@ -414,6 +414,40 @@ func (_c *EntityCreate) AddChildren(v ...*Entity) *EntityCreate {return _c.AddChildIDs(ids...)}+// SetLocationID sets the "location" edge to the Entity entity by ID.+func (_c *EntityCreate) SetLocationID(id uuid.UUID) *EntityCreate {+ _c.mutation.SetLocationID(id)+ return _c+}++// SetNillableLocationID sets the "location" edge to the Entity entity by ID if the given value is not nil.+func (_c *EntityCreate) SetNillableLocationID(id *uuid.UUID) *EntityCreate {+ if id != nil {+ _c = _c.SetLocationID(*id)+ }+ return _c+}++// SetLocation sets the "location" edge to the Entity entity.+func (_c *EntityCreate) SetLocation(v *Entity) *EntityCreate {+ return _c.SetLocationID(v.ID)+}++// AddLocationEntityIDs adds the "location_entities" edge to the Entity entity by IDs.+func (_c *EntityCreate) AddLocationEntityIDs(ids ...uuid.UUID) *EntityCreate {+ _c.mutation.AddLocationEntityIDs(ids...)+ return _c+}++// AddLocationEntities adds the "location_entities" edges to the Entity entity.+func (_c *EntityCreate) AddLocationEntities(v ...*Entity) *EntityCreate {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _c.AddLocationEntityIDs(ids...)+}+// AddTagIDs adds the "tag" edge to the Tag entity by IDs.func (_c *EntityCreate) AddTagIDs(ids ...uuid.UUID) *EntityCreate {_c.mutation.AddTagIDs(ids...)@@ -833,6 +867,39 @@ func (_c *EntityCreate) createSpec() (*Entity, *sqlgraph.CreateSpec) {}_spec.Edges = append(_spec.Edges, edge)}+ if nodes := _c.mutation.LocationIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: entity.LocationTable,+ Columns: []string{entity.LocationColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _node.entity_location_entities = &nodes[0]+ _spec.Edges = append(_spec.Edges, edge)+ }+ if nodes := _c.mutation.LocationEntitiesIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges = append(_spec.Edges, edge)+ }if nodes := _c.mutation.TagIDs(); len(nodes) > 0 {edge := &sqlgraph.EdgeSpec{Rel: sqlgraph.M2M,diff --git a/backend/internal/data/ent/entity_query.go b/backend/internal/data/ent/entity_query.goindex 775a6401..885c205d 100644--- a/backend/internal/data/ent/entity_query.go+++ b/backend/internal/data/ent/entity_query.go@@ -33,6 +33,8 @@ type EntityQuery struct {withGroup *GroupQuerywithParent *EntityQuerywithChildren *EntityQuery+ withLocation *EntityQuery+ withLocationEntities *EntityQuerywithTag *TagQuerywithEntityType *EntityTypeQuerywithFields *EntityFieldQuery@@ -141,6 +143,50 @@ func (_q *EntityQuery) QueryChildren() *EntityQuery {return query}+// QueryLocation chains the current query on the "location" edge.+func (_q *EntityQuery) QueryLocation() *EntityQuery {+ query := (&EntityClient{config: _q.config}).Query()+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {+ if err := _q.prepareQuery(ctx); err != nil {+ return nil, err+ }+ selector := _q.sqlQuery(ctx)+ if err := selector.Err(); err != nil {+ return nil, err+ }+ step := sqlgraph.NewStep(+ sqlgraph.From(entity.Table, entity.FieldID, selector),+ sqlgraph.To(entity.Table, entity.FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, entity.LocationTable, entity.LocationColumn),+ )+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)+ return fromU, nil+ }+ return query+}++// QueryLocationEntities chains the current query on the "location_entities" edge.+func (_q *EntityQuery) QueryLocationEntities() *EntityQuery {+ query := (&EntityClient{config: _q.config}).Query()+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {+ if err := _q.prepareQuery(ctx); err != nil {+ return nil, err+ }+ selector := _q.sqlQuery(ctx)+ if err := selector.Err(); err != nil {+ return nil, err+ }+ step := sqlgraph.NewStep(+ sqlgraph.From(entity.Table, entity.FieldID, selector),+ sqlgraph.To(entity.Table, entity.FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, entity.LocationEntitiesTable, entity.LocationEntitiesColumn),+ )+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)+ return fromU, nil+ }+ return query+}+// QueryTag chains the current query on the "tag" edge.func (_q *EntityQuery) QueryTag() *TagQuery {query := (&TagClient{config: _q.config}).Query()@@ -446,6 +492,8 @@ func (_q *EntityQuery) Clone() *EntityQuery {withGroup: _q.withGroup.Clone(),withParent: _q.withParent.Clone(),withChildren: _q.withChildren.Clone(),+ withLocation: _q.withLocation.Clone(),+ withLocationEntities: _q.withLocationEntities.Clone(),withTag: _q.withTag.Clone(),withEntityType: _q.withEntityType.Clone(),withFields: _q.withFields.Clone(),@@ -490,6 +538,28 @@ func (_q *EntityQuery) WithChildren(opts ...func(*EntityQuery)) *EntityQuery {return _q}+// WithLocation tells the query-builder to eager-load the nodes that are connected to+// the "location" edge. The optional arguments are used to configure the query builder of the edge.+func (_q *EntityQuery) WithLocation(opts ...func(*EntityQuery)) *EntityQuery {+ query := (&EntityClient{config: _q.config}).Query()+ for _, opt := range opts {+ opt(query)+ }+ _q.withLocation = query+ return _q+}++// WithLocationEntities tells the query-builder to eager-load the nodes that are connected to+// the "location_entities" edge. The optional arguments are used to configure the query builder of the edge.+func (_q *EntityQuery) WithLocationEntities(opts ...func(*EntityQuery)) *EntityQuery {+ query := (&EntityClient{config: _q.config}).Query()+ for _, opt := range opts {+ opt(query)+ }+ _q.withLocationEntities = query+ return _q+}+// WithTag tells the query-builder to eager-load the nodes that are connected to// the "tag" edge. The optional arguments are used to configure the query builder of the edge.func (_q *EntityQuery) WithTag(opts ...func(*TagQuery)) *EntityQuery {@@ -624,10 +694,12 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entitnodes = []*Entity{}withFKs = _q.withFKs_spec = _q.querySpec()- loadedTypes = [8]bool{+ loadedTypes = [10]bool{_q.withGroup != nil,_q.withParent != nil,_q.withChildren != nil,+ _q.withLocation != nil,+ _q.withLocationEntities != nil,_q.withTag != nil,_q.withEntityType != nil,_q.withFields != nil,@@ -635,7 +707,7 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entit_q.withAttachments != nil,})- if _q.withGroup != nil || _q.withParent != nil || _q.withEntityType != nil {+ if _q.withGroup != nil || _q.withParent != nil || _q.withLocation != nil || _q.withEntityType != nil {withFKs = true}if withFKs {@@ -678,6 +750,19 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entitreturn nil, err}}+ if query := _q.withLocation; query != nil {+ if err := _q.loadLocation(ctx, query, nodes, nil,+ func(n *Entity, e *Entity) { n.Edges.Location = e }); err != nil {+ return nil, err+ }+ }+ if query := _q.withLocationEntities; query != nil {+ if err := _q.loadLocationEntities(ctx, query, nodes,+ func(n *Entity) { n.Edges.LocationEntities = []*Entity{} },+ func(n *Entity, e *Entity) { n.Edges.LocationEntities = append(n.Edges.LocationEntities, e) }); err != nil {+ return nil, err+ }+ }if query := _q.withTag; query != nil {if err := _q.loadTag(ctx, query, nodes,func(n *Entity) { n.Edges.Tag = []*Tag{} },@@ -812,6 +897,69 @@ func (_q *EntityQuery) loadChildren(ctx context.Context, query *EntityQuery, nod}return nil}+func (_q *EntityQuery) loadLocation(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {+ ids := make([]uuid.UUID, 0, len(nodes))+ nodeids := make(map[uuid.UUID][]*Entity)+ for i := range nodes {+ if nodes[i].entity_location_entities == nil {+ continue+ }+ fk := *nodes[i].entity_location_entities+ if _, ok := nodeids[fk]; !ok {+ ids = append(ids, fk)+ }+ nodeids[fk] = append(nodeids[fk], nodes[i])+ }+ if len(ids) == 0 {+ return nil+ }+ query.Where(entity.IDIn(ids...))+ neighbors, err := query.All(ctx)+ if err != nil {+ return err+ }+ for _, n := range neighbors {+ nodes, ok := nodeids[n.ID]+ if !ok {+ return fmt.Errorf(`unexpected foreign-key "entity_location_entities" returned %v`, n.ID)+ }+ for i := range nodes {+ assign(nodes[i], n)+ }+ }+ return nil+}+func (_q *EntityQuery) loadLocationEntities(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {+ fks := make([]driver.Value, 0, len(nodes))+ nodeids := make(map[uuid.UUID]*Entity)+ for i := range nodes {+ fks = append(fks, nodes[i].ID)+ nodeids[nodes[i].ID] = nodes[i]+ if init != nil {+ init(nodes[i])+ }+ }+ query.withFKs = true+ query.Where(predicate.Entity(func(s *sql.Selector) {+ s.Where(sql.InValues(s.C(entity.LocationEntitiesColumn), fks...))+ }))+ neighbors, err := query.All(ctx)+ if err != nil {+ return err+ }+ for _, n := range neighbors {+ fk := n.entity_location_entities+ if fk == nil {+ return fmt.Errorf(`foreign-key "entity_location_entities" is nil for node %v`, n.ID)+ }+ node, ok := nodeids[*fk]+ if !ok {+ return fmt.Errorf(`unexpected referenced foreign-key "entity_location_entities" returned %v for node %v`, *fk, n.ID)+ }+ assign(node, n)+ }+ return nil+}func (_q *EntityQuery) loadTag(ctx context.Context, query *TagQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Tag)) error {edgeIDs := make([]driver.Value, len(nodes))byID := make(map[uuid.UUID]*Entity)diff --git a/backend/internal/data/ent/entity_update.go b/backend/internal/data/ent/entity_update.goindex f3dbf1f4..d84ae147 100644--- a/backend/internal/data/ent/entity_update.go+++ b/backend/internal/data/ent/entity_update.go@@ -500,6 +500,40 @@ func (_u *EntityUpdate) AddChildren(v ...*Entity) *EntityUpdate {return _u.AddChildIDs(ids...)}+// SetLocationID sets the "location" edge to the Entity entity by ID.+func (_u *EntityUpdate) SetLocationID(id uuid.UUID) *EntityUpdate {+ _u.mutation.SetLocationID(id)+ return _u+}++// SetNillableLocationID sets the "location" edge to the Entity entity by ID if the given value is not nil.+func (_u *EntityUpdate) SetNillableLocationID(id *uuid.UUID) *EntityUpdate {+ if id != nil {+ _u = _u.SetLocationID(*id)+ }+ return _u+}++// SetLocation sets the "location" edge to the Entity entity.+func (_u *EntityUpdate) SetLocation(v *Entity) *EntityUpdate {+ return _u.SetLocationID(v.ID)+}++// AddLocationEntityIDs adds the "location_entities" edge to the Entity entity by IDs.+func (_u *EntityUpdate) AddLocationEntityIDs(ids ...uuid.UUID) *EntityUpdate {+ _u.mutation.AddLocationEntityIDs(ids...)+ return _u+}++// AddLocationEntities adds the "location_entities" edges to the Entity entity.+func (_u *EntityUpdate) AddLocationEntities(v ...*Entity) *EntityUpdate {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.AddLocationEntityIDs(ids...)+}+// AddTagIDs adds the "tag" edge to the Tag entity by IDs.func (_u *EntityUpdate) AddTagIDs(ids ...uuid.UUID) *EntityUpdate {_u.mutation.AddTagIDs(ids...)@@ -609,6 +643,33 @@ func (_u *EntityUpdate) RemoveChildren(v ...*Entity) *EntityUpdate {return _u.RemoveChildIDs(ids...)}+// ClearLocation clears the "location" edge to the Entity entity.+func (_u *EntityUpdate) ClearLocation() *EntityUpdate {+ _u.mutation.ClearLocation()+ return _u+}++// ClearLocationEntities clears all "location_entities" edges to the Entity entity.+func (_u *EntityUpdate) ClearLocationEntities() *EntityUpdate {+ _u.mutation.ClearLocationEntities()+ return _u+}++// RemoveLocationEntityIDs removes the "location_entities" edge to Entity entities by IDs.+func (_u *EntityUpdate) RemoveLocationEntityIDs(ids ...uuid.UUID) *EntityUpdate {+ _u.mutation.RemoveLocationEntityIDs(ids...)+ return _u+}++// RemoveLocationEntities removes "location_entities" edges to Entity entities.+func (_u *EntityUpdate) RemoveLocationEntities(v ...*Entity) *EntityUpdate {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.RemoveLocationEntityIDs(ids...)+}+// ClearTag clears all "tag" edges to the Tag entity.func (_u *EntityUpdate) ClearTag() *EntityUpdate {_u.mutation.ClearTag()@@ -1026,6 +1087,80 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {}_spec.Edges.Add = append(_spec.Edges.Add, edge)}+ if _u.mutation.LocationCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: entity.LocationTable,+ Columns: []string{entity.LocationColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.LocationIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: entity.LocationTable,+ Columns: []string{entity.LocationColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }+ if _u.mutation.LocationEntitiesCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.RemovedLocationEntitiesIDs(); len(nodes) > 0 && !_u.mutation.LocationEntitiesCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.LocationEntitiesIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }if _u.mutation.TagCleared() {edge := &sqlgraph.EdgeSpec{Rel: sqlgraph.M2M,@@ -1720,6 +1855,40 @@ func (_u *EntityUpdateOne) AddChildren(v ...*Entity) *EntityUpdateOne {return _u.AddChildIDs(ids...)}+// SetLocationID sets the "location" edge to the Entity entity by ID.+func (_u *EntityUpdateOne) SetLocationID(id uuid.UUID) *EntityUpdateOne {+ _u.mutation.SetLocationID(id)+ return _u+}++// SetNillableLocationID sets the "location" edge to the Entity entity by ID if the given value is not nil.+func (_u *EntityUpdateOne) SetNillableLocationID(id *uuid.UUID) *EntityUpdateOne {+ if id != nil {+ _u = _u.SetLocationID(*id)+ }+ return _u+}++// SetLocation sets the "location" edge to the Entity entity.+func (_u *EntityUpdateOne) SetLocation(v *Entity) *EntityUpdateOne {+ return _u.SetLocationID(v.ID)+}++// AddLocationEntityIDs adds the "location_entities" edge to the Entity entity by IDs.+func (_u *EntityUpdateOne) AddLocationEntityIDs(ids ...uuid.UUID) *EntityUpdateOne {+ _u.mutation.AddLocationEntityIDs(ids...)+ return _u+}++// AddLocationEntities adds the "location_entities" edges to the Entity entity.+func (_u *EntityUpdateOne) AddLocationEntities(v ...*Entity) *EntityUpdateOne {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.AddLocationEntityIDs(ids...)+}+// AddTagIDs adds the "tag" edge to the Tag entity by IDs.func (_u *EntityUpdateOne) AddTagIDs(ids ...uuid.UUID) *EntityUpdateOne {_u.mutation.AddTagIDs(ids...)@@ -1829,6 +1998,33 @@ func (_u *EntityUpdateOne) RemoveChildren(v ...*Entity) *EntityUpdateOne {return _u.RemoveChildIDs(ids...)}+// ClearLocation clears the "location" edge to the Entity entity.+func (_u *EntityUpdateOne) ClearLocation() *EntityUpdateOne {+ _u.mutation.ClearLocation()+ return _u+}++// ClearLocationEntities clears all "location_entities" edges to the Entity entity.+func (_u *EntityUpdateOne) ClearLocationEntities() *EntityUpdateOne {+ _u.mutation.ClearLocationEntities()+ return _u+}++// RemoveLocationEntityIDs removes the "location_entities" edge to Entity entities by IDs.+func (_u *EntityUpdateOne) RemoveLocationEntityIDs(ids ...uuid.UUID) *EntityUpdateOne {+ _u.mutation.RemoveLocationEntityIDs(ids...)+ return _u+}++// RemoveLocationEntities removes "location_entities" edges to Entity entities.+func (_u *EntityUpdateOne) RemoveLocationEntities(v ...*Entity) *EntityUpdateOne {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.RemoveLocationEntityIDs(ids...)+}+// ClearTag clears all "tag" edges to the Tag entity.func (_u *EntityUpdateOne) ClearTag() *EntityUpdateOne {_u.mutation.ClearTag()@@ -2276,6 +2472,80 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro}_spec.Edges.Add = append(_spec.Edges.Add, edge)}+ if _u.mutation.LocationCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: entity.LocationTable,+ Columns: []string{entity.LocationColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.LocationIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: entity.LocationTable,+ Columns: []string{entity.LocationColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }+ if _u.mutation.LocationEntitiesCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.RemovedLocationEntitiesIDs(); len(nodes) > 0 && !_u.mutation.LocationEntitiesCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.LocationEntitiesIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: entity.LocationEntitiesTable,+ Columns: []string{entity.LocationEntitiesColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }if _u.mutation.TagCleared() {edge := &sqlgraph.EdgeSpec{Rel: sqlgraph.M2M,diff --git a/backend/internal/data/ent/migrate/schema.go b/backend/internal/data/ent/migrate/schema.goindex b214fbc8..42bb2c95 100644--- a/backend/internal/data/ent/migrate/schema.go+++ b/backend/internal/data/ent/migrate/schema.go@@ -157,6 +157,7 @@ var ({Name: "sold_price", Type: field.TypeFloat64, Default: 0},{Name: "sold_notes", Type: field.TypeString, Nullable: true, Size: 1000},{Name: "entity_children", Type: field.TypeUUID, Nullable: true},+ {Name: "entity_location_entities", Type: field.TypeUUID, Nullable: true},{Name: "entity_type_entities", Type: field.TypeUUID},{Name: "group_entities", Type: field.TypeUUID},}@@ -173,14 +174,20 @@ var (OnDelete: schema.SetNull,},{- Symbol: "entities_entity_types_entities",+ Symbol: "entities_entities_location_entities",Columns: []*schema.Column{EntitiesColumns[26]},+ RefColumns: []*schema.Column{EntitiesColumns[0]},+ OnDelete: schema.SetNull,+ },+ {+ Symbol: "entities_entity_types_entities",+ Columns: []*schema.Column{EntitiesColumns[27]},RefColumns: []*schema.Column{EntityTypesColumns[0]},OnDelete: schema.Restrict,},{Symbol: "entities_groups_entities",- Columns: []*schema.Column{EntitiesColumns[27]},+ Columns: []*schema.Column{EntitiesColumns[28]},RefColumns: []*schema.Column{GroupsColumns[0]},OnDelete: schema.Cascade,},@@ -686,8 +693,9 @@ func init() {AuthRolesTable.ForeignKeys[0].RefTable = AuthTokensTableAuthTokensTable.ForeignKeys[0].RefTable = UsersTableEntitiesTable.ForeignKeys[0].RefTable = EntitiesTable- EntitiesTable.ForeignKeys[1].RefTable = EntityTypesTable- EntitiesTable.ForeignKeys[2].RefTable = GroupsTable+ EntitiesTable.ForeignKeys[1].RefTable = EntitiesTable+ EntitiesTable.ForeignKeys[2].RefTable = EntityTypesTable+ EntitiesTable.ForeignKeys[3].RefTable = GroupsTableEntityFieldsTable.ForeignKeys[0].RefTable = EntitiesTableEntityTemplatesTable.ForeignKeys[0].RefTable = EntitiesTableEntityTemplatesTable.ForeignKeys[1].RefTable = GroupsTablediff --git a/backend/internal/data/ent/mutation.go b/backend/internal/data/ent/mutation.goindex 70dbae1d..5b18309f 100644--- a/backend/internal/data/ent/mutation.go+++ b/backend/internal/data/ent/mutation.go@@ -2650,6 +2650,11 @@ type EntityMutation struct {children map[uuid.UUID]struct{}removedchildren map[uuid.UUID]struct{}clearedchildren bool+ location *uuid.UUID+ clearedlocation bool+ location_entities map[uuid.UUID]struct{}+ removedlocation_entities map[uuid.UUID]struct{}+ clearedlocation_entities booltag map[uuid.UUID]struct{}removedtag map[uuid.UUID]struct{}clearedtag bool@@ -4018,6 +4023,99 @@ func (m *EntityMutation) ResetChildren() {m.removedchildren = nil}+// SetLocationID sets the "location" edge to the Entity entity by id.+func (m *EntityMutation) SetLocationID(id uuid.UUID) {+ m.location = &id+}++// ClearLocation clears the "location" edge to the Entity entity.+func (m *EntityMutation) ClearLocation() {+ m.clearedlocation = true+}++// LocationCleared reports if the "location" edge to the Entity entity was cleared.+func (m *EntityMutation) LocationCleared() bool {+ return m.clearedlocation+}++// LocationID returns the "location" edge ID in the mutation.+func (m *EntityMutation) LocationID() (id uuid.UUID, exists bool) {+ if m.location != nil {+ return *m.location, true+ }+ return+}++// LocationIDs returns the "location" edge IDs in the mutation.+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use+// LocationID instead. It exists only for internal usage by the builders.+func (m *EntityMutation) LocationIDs() (ids []uuid.UUID) {+ if id := m.location; id != nil {+ ids = append(ids, *id)+ }+ return+}++// ResetLocation resets all changes to the "location" edge.+func (m *EntityMutation) ResetLocation() {+ m.location = nil+ m.clearedlocation = false+}++// AddLocationEntityIDs adds the "location_entities" edge to the Entity entity by ids.+func (m *EntityMutation) AddLocationEntityIDs(ids ...uuid.UUID) {+ if m.location_entities == nil {+ m.location_entities = make(map[uuid.UUID]struct{})+ }+ for i := range ids {+ m.location_entities[ids[i]] = struct{}{}+ }+}++// ClearLocationEntities clears the "location_entities" edge to the Entity entity.+func (m *EntityMutation) ClearLocationEntities() {+ m.clearedlocation_entities = true+}++// LocationEntitiesCleared reports if the "location_entities" edge to the Entity entity was cleared.+func (m *EntityMutation) LocationEntitiesCleared() bool {+ return m.clearedlocation_entities+}++// RemoveLocationEntityIDs removes the "location_entities" edge to the Entity entity by IDs.+func (m *EntityMutation) RemoveLocationEntityIDs(ids ...uuid.UUID) {+ if m.removedlocation_entities == nil {+ m.removedlocation_entities = make(map[uuid.UUID]struct{})+ }+ for i := range ids {+ delete(m.location_entities, ids[i])+ m.removedlocation_entities[ids[i]] = struct{}{}+ }+}++// RemovedLocationEntities returns the removed IDs of the "location_entities" edge to the Entity entity.+func (m *EntityMutation) RemovedLocationEntitiesIDs() (ids []uuid.UUID) {+ for id := range m.removedlocation_entities {+ ids = append(ids, id)+ }+ return+}++// LocationEntitiesIDs returns the "location_entities" edge IDs in the mutation.+func (m *EntityMutation) LocationEntitiesIDs() (ids []uuid.UUID) {+ for id := range m.location_entities {+ ids = append(ids, id)+ }+ return+}++// ResetLocationEntities resets all changes to the "location_entities" edge.+func (m *EntityMutation) ResetLocationEntities() {+ m.location_entities = nil+ m.clearedlocation_entities = false+ m.removedlocation_entities = nil+}+// AddTagIDs adds the "tag" edge to the Tag entity by ids.func (m *EntityMutation) AddTagIDs(ids ...uuid.UUID) {if m.tag == nil {@@ -4929,7 +5027,7 @@ func (m *EntityMutation) ResetField(name string) error {// AddedEdges returns all edge names that were set/added in this mutation.func (m *EntityMutation) AddedEdges() []string {- edges := make([]string, 0, 8)+ edges := make([]string, 0, 10)if m.group != nil {edges = append(edges, entity.EdgeGroup)}@@ -4939,6 +5037,12 @@ func (m *EntityMutation) AddedEdges() []string {if m.children != nil {edges = append(edges, entity.EdgeChildren)}+ if m.location != nil {+ edges = append(edges, entity.EdgeLocation)+ }+ if m.location_entities != nil {+ edges = append(edges, entity.EdgeLocationEntities)+ }if m.tag != nil {edges = append(edges, entity.EdgeTag)}@@ -4975,6 +5079,16 @@ func (m *EntityMutation) AddedIDs(name string) []ent.Value {ids = append(ids, id)}return ids+ case entity.EdgeLocation:+ if id := m.location; id != nil {+ return []ent.Value{*id}+ }+ case entity.EdgeLocationEntities:+ ids := make([]ent.Value, 0, len(m.location_entities))+ for id := range m.location_entities {+ ids = append(ids, id)+ }+ return idscase entity.EdgeTag:ids := make([]ent.Value, 0, len(m.tag))for id := range m.tag {@@ -5009,10 +5123,13 @@ func (m *EntityMutation) AddedIDs(name string) []ent.Value {// RemovedEdges returns all edge names that were removed in this mutation.func (m *EntityMutation) RemovedEdges() []string {- edges := make([]string, 0, 8)+ edges := make([]string, 0, 10)if m.removedchildren != nil {edges = append(edges, entity.EdgeChildren)}+ if m.removedlocation_entities != nil {+ edges = append(edges, entity.EdgeLocationEntities)+ }if m.removedtag != nil {edges = append(edges, entity.EdgeTag)}@@ -5038,6 +5155,12 @@ func (m *EntityMutation) RemovedIDs(name string) []ent.Value {ids = append(ids, id)}return ids+ case entity.EdgeLocationEntities:+ ids := make([]ent.Value, 0, len(m.removedlocation_entities))+ for id := range m.removedlocation_entities {+ ids = append(ids, id)+ }+ return idscase entity.EdgeTag:ids := make([]ent.Value, 0, len(m.removedtag))for id := range m.removedtag {@@ -5068,7 +5191,7 @@ func (m *EntityMutation) RemovedIDs(name string) []ent.Value {// ClearedEdges returns all edge names that were cleared in this mutation.func (m *EntityMutation) ClearedEdges() []string {- edges := make([]string, 0, 8)+ edges := make([]string, 0, 10)if m.clearedgroup {edges = append(edges, entity.EdgeGroup)}@@ -5078,6 +5201,12 @@ func (m *EntityMutation) ClearedEdges() []string {if m.clearedchildren {edges = append(edges, entity.EdgeChildren)}+ if m.clearedlocation {+ edges = append(edges, entity.EdgeLocation)+ }+ if m.clearedlocation_entities {+ edges = append(edges, entity.EdgeLocationEntities)+ }if m.clearedtag {edges = append(edges, entity.EdgeTag)}@@ -5106,6 +5235,10 @@ func (m *EntityMutation) EdgeCleared(name string) bool {return m.clearedparentcase entity.EdgeChildren:return m.clearedchildren+ case entity.EdgeLocation:+ return m.clearedlocation+ case entity.EdgeLocationEntities:+ return m.clearedlocation_entitiescase entity.EdgeTag:return m.clearedtagcase entity.EdgeEntityType:@@ -5130,6 +5263,9 @@ func (m *EntityMutation) ClearEdge(name string) error {case entity.EdgeParent:m.ClearParent()return nil+ case entity.EdgeLocation:+ m.ClearLocation()+ return nilcase entity.EdgeEntityType:m.ClearEntityType()return nil@@ -5150,6 +5286,12 @@ func (m *EntityMutation) ResetEdge(name string) error {case entity.EdgeChildren:m.ResetChildren()return nil+ case entity.EdgeLocation:+ m.ResetLocation()+ return nil+ case entity.EdgeLocationEntities:+ m.ResetLocationEntities()+ return nilcase entity.EdgeTag:m.ResetTag()return nildiff --git a/backend/internal/data/ent/schema/entity.go b/backend/internal/data/ent/schema/entity.goindex c5cf5c87..01ce77c7 100644--- a/backend/internal/data/ent/schema/entity.go+++ b/backend/internal/data/ent/schema/entity.go@@ -111,6 +111,12 @@ func (Entity) Edges() []ent.Edge {edge.To("children", Entity.Type).From("parent").Unique(),+ // Location override, only set when "parent" is a non-location entity.+ // Otherwise NULL and the location comes from walking the parent chain.+ // See repo.resolveLocationOverride (#1688).+ edge.To("location_entities", Entity.Type).+ From("location").+ Unique(),edge.From("tag", Tag.Type).Ref("entities"),edge.From("entity_type", EntityType.Type).diff --git a/backend/internal/data/migrations/postgres/20260821000000_entity_location_override.sql b/backend/internal/data/migrations/postgres/20260821000000_entity_location_override.sqlnew file mode 100644index 00000000..07c595eb--- /dev/null+++ b/backend/internal/data/migrations/postgres/20260821000000_entity_location_override.sql@@ -0,0 +1,38 @@+-- +goose Up+-- Give location its own column again (#1688).+--+-- 0.26.0 merged items and locations into one table with a single self-FK, which+-- made location a derived property: the nearest ancestor that is a location.+-- That can't express "child of item X, stored in Y" — setting a parent drags the+-- child's location along with it.+--+-- entity_location_entities is a sparse override, only set when the parent is a+-- non-location entity; otherwise it stays NULL and the ancestor walk still wins.+-- See repo.resolveLocationOverride.+--+-- No backfill on purpose: existing rows keep NULL and resolve exactly as before,+-- so upgrading changes nothing on screen.+ALTER TABLE "entities"+ ADD COLUMN IF NOT EXISTS "entity_location_entities" uuid NULL;++-- Separate and guarded so a database that already has the column (re-run, or a+-- partially migrated dump) doesn't fail here. The StatementBegin/End fence is+-- required — goose splits on ";" and would cut the block at the first one.+-- +goose StatementBegin+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.table_constraints+ WHERE constraint_schema = current_schema()+ AND table_name = 'entities'+ AND constraint_name = 'entities_entities_location_entities'+ ) THEN+ ALTER TABLE "entities"+ ADD CONSTRAINT "entities_entities_location_entities"+ FOREIGN KEY ("entity_location_entities") REFERENCES "entities" ("id")+ ON UPDATE NO ACTION ON DELETE SET NULL;+ END IF;+END $$;+-- +goose StatementEnd++CREATE INDEX IF NOT EXISTS "idx_entities_location" ON "entities" ("entity_location_entities");diff --git a/backend/internal/data/migrations/sqlite3/20260821000000_entity_location_override.sql b/backend/internal/data/migrations/sqlite3/20260821000000_entity_location_override.sqlnew file mode 100644index 00000000..30a045f1--- /dev/null+++ b/backend/internal/data/migrations/sqlite3/20260821000000_entity_location_override.sql@@ -0,0 +1,22 @@+-- +goose Up+-- Give location its own column again (#1688).+--+-- 0.26.0 merged items and locations into one table with a single self-FK, which+-- made location a derived property: the nearest ancestor that is a location.+-- That can't express "child of item X, stored in Y" — setting a parent drags the+-- child's location along with it.+--+-- entity_location_entities is a sparse override, only set when the parent is a+-- non-location entity; otherwise it stays NULL and the ancestor walk still wins.+-- See repo.resolveLocationOverride.+--+-- No backfill on purpose: existing rows keep NULL and resolve exactly as before,+-- so upgrading changes nothing on screen.+alter table entities+ add column entity_location_entities uuid+ constraint entities_entities_location_entities+ references entities+ on delete set null;++create index if not exists idx_entities_location+ on entities (entity_location_entities);diff --git a/backend/internal/data/repo/repo_entities.go b/backend/internal/data/repo/repo_entities.goindex 7792d062..60c305f3 100644--- a/backend/internal/data/repo/repo_entities.go+++ b/backend/internal/data/repo/repo_entities.go@@ -101,6 +101,8 @@ type (Description string `json:"description" validate:"max=1000"`AssetID AssetID `json:"-"`EntityTypeID uuid.UUID `json:"entityTypeId"`+ // Only needed when ParentID is another item and this lives elsewhere (#1688).+ LocationID uuid.UUID `json:"locationId" extensions:"x-nullable,x-omitempty"`// Identifications — optional at create time; populated e.g. by the// barcode product-search import flow (#1578).@@ -130,18 +132,21 @@ type (// ExtrasNotes string `json:"notes"`// Edges- TagIDs []uuid.UUID `json:"tagIds"`- Fields []EntityFieldData `json:"fields"`- AssetID AssetID `json:"assetId" swaggertype:"string"`- Quantity float64 `json:"quantity"`- PurchasePrice float64 `json:"purchasePrice" extensions:"x-nullable,x-omitempty"`- SoldPrice float64 `json:"soldPrice" extensions:"x-nullable,x-omitempty"`- ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`- ID uuid.UUID `json:"id"`- EntityTypeID uuid.UUID `json:"entityTypeId"`- Insured bool `json:"insured"`- Archived bool `json:"archived"`- SyncChildEntityLocations bool `json:"syncChildEntityLocations"`+ TagIDs []uuid.UUID `json:"tagIds"`+ Fields []EntityFieldData `json:"fields"`+ AssetID AssetID `json:"assetId" swaggertype:"string"`+ Quantity float64 `json:"quantity"`+ PurchasePrice float64 `json:"purchasePrice" extensions:"x-nullable,x-omitempty"`+ SoldPrice float64 `json:"soldPrice" extensions:"x-nullable,x-omitempty"`+ ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`+ // Only needed when ParentID is another item and this lives elsewhere (#1688).+ // Otherwise ParentID carries the location. See resolveLocationOverride.+ LocationID uuid.UUID `json:"locationId" extensions:"x-nullable,x-omitempty"`+ ID uuid.UUID `json:"id"`+ EntityTypeID uuid.UUID `json:"entityTypeId"`+ Insured bool `json:"insured"`+ Archived bool `json:"archived"`+ SyncChildEntityLocations bool `json:"syncChildEntityLocations"`// WarrantyLifetimeWarranty bool `json:"lifetimeWarranty"`}@@ -151,6 +156,7 @@ type (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"`+ LocationID uuid.UUID `json:"locationId" 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"`}@@ -186,11 +192,13 @@ type (EntityOut struct {Parent *EntitySummary `json:"parent,omitempty" extensions:"x-nullable,x-omitempty"`- // Location is the nearest ancestor whose entity type is a location.- // When the direct parent is already a location it equals Parent; when- // the entity is nested inside other items it is the location those- // items ultimately live in. Nil for top-level entities.+ // Location is resolved: this entity's own location, else the nearest+ // location ancestor. Read-only — write via LocationID.Location *EntitySummary `json:"location,omitempty" extensions:"x-nullable,x-omitempty"`+ // LocationID is set only when this entity has its own location, nil when+ // inherited. Same name as the EntityUpdate field so a GET/PUT round trip+ // doesn't pin an inherited location or drop an explicit one.+ LocationID *uuid.UUID `json:"locationId,omitempty" extensions:"x-nullable,x-omitempty"`EntitySummaryAssetID AssetID `json:"assetId,string"`@@ -443,6 +451,9 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...prWithParent(func(eq *ent.EntityQuery) {eq.WithEntityType()}).+ WithLocation(func(eq *ent.EntityQuery) {+ eq.WithEntityType()+ }).WithEntityType().WithGroup().WithChildren(func(eq *ent.EntityQuery) {@@ -463,12 +474,16 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...pr} else {client = r.db.Entity}- loc, err := nearestLocationAncestor(ctx, client, e.Edges.Parent)+ loc, err := resolveEntityLocation(ctx, client, e)if err != nil {recordSpanError(span, err)return EntityOut{}, err}out.Location = loc+ if e.Edges.Location != nil {+ id := e.Edges.Location.ID+ out.LocationID = &id+ }span.SetAttributes(attribute.String("entity.id", out.ID.String()),@@ -838,10 +853,10 @@ func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q En}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...))+ // The UI's location filter. Matches the effective location so an+ // item nested under another item but stored elsewhere lands in the+ // right list (#1688).+ andPredicates = append(andPredicates, effectiveLocationIn(q.ParentIDs))}if len(q.Fields) > 0 {@@ -1003,16 +1018,18 @@ func (r *EntityRepository) getChildItemCounts(ctx context.Context, gid uuid.UUIDargs = append(args, id)}+ // Count by effective location, not by parent (#1688).+ eff := locationOrParentColumn("e")query := fmt.Sprintf(`- SELECT e.entity_children, COALESCE(SUM(e.quantity), 0)+ SELECT %s, COALESCE(SUM(e.quantity), 0)FROM entities eJOIN entity_types et ON et.id = e.entity_type_entitiesWHERE e.group_entities = $1AND et.is_location = falseAND e.archived = false- AND e.entity_children IN (%s)- GROUP BY e.entity_children- `, strings.Join(placeholders, ","))+ AND %s IN (%s)+ GROUP BY %s+ `, eff, eff, strings.Join(placeholders, ","), eff)rows, err := r.db.Sql().QueryContext(ctx, query, args...)if err != nil {@@ -1231,6 +1248,12 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data Entitreturn EntityOut{}, err}+ parentID, locationOverride, err := resolveLocationOverride(ctx, r.db.Entity, gid, uuid.Nil, data.ParentID, data.LocationID)+ if err != nil {+ recordSpanError(span, err)+ return EntityOut{}, err+ }+q := r.db.Entity.Create().SetImportRef(data.ImportRef).SetName(data.Name).@@ -1241,8 +1264,12 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data EntitSetGroupID(gid).SetAssetID(int64(data.AssetID))- if data.ParentID != uuid.Nil {- q.SetParentID(data.ParentID)+ if parentID != uuid.Nil {+ q.SetParentID(parentID)+ }++ if locationOverride != uuid.Nil {+ q.SetLocationID(locationOverride)}if data.EntityTypeID != uuid.Nil {@@ -1267,7 +1294,10 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data Entitreturn EntityOut{}, err}- span.SetAttributes(attribute.String("entity.id", result.ID.String()))+ span.SetAttributes(+ attribute.String("entity.id", result.ID.String()),+ attribute.Bool("entity.location_override.set", locationOverride != uuid.Nil),+ )r.publishMutationEvent(gid)out, err := r.GetOne(ctx, result.ID)recordSpanError(span, err)@@ -1285,6 +1315,7 @@ type EntityCreateFromTemplate struct {Fields []EntityFieldDataQuantity float64ParentID uuid.UUID+ LocationID uuid.UUIDEntityTypeID uuid.UUIDInsured boolLifetimeWarranty bool@@ -1336,6 +1367,12 @@ func (r *EntityRepository) CreateFromTemplate(ctx context.Context, gid uuid.UUIDdata.EntityTypeID = etID}+ templateParentID, templateLocationOverride, err := resolveLocationOverride(ctx, r.db.Entity, gid, uuid.Nil, data.ParentID, data.LocationID)+ if err != nil {+ recordSpanError(span, err)+ return EntityOut{}, err+ }+tx, err := r.db.Tx(ctx)if err != nil {recordSpanError(span, err)@@ -1377,8 +1414,12 @@ func (r *EntityRepository) CreateFromTemplate(ctx context.Context, gid uuid.UUIDSetLifetimeWarranty(data.LifetimeWarranty).SetWarrantyDetails(data.WarrantyDetails)- if data.ParentID != uuid.Nil {- entityBuilder.SetParentID(data.ParentID)+ if templateParentID != uuid.Nil {+ entityBuilder.SetParentID(templateParentID)+ }++ if templateLocationOverride != uuid.Nil {+ entityBuilder.SetLocationID(templateLocationOverride)}entityBuilder.SetEntityTypeID(data.EntityTypeID)@@ -1720,6 +1761,14 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, datreturn EntityOut{}, err}+ // parentID may come back rewritten; see repo_entity_location.go.+ parentID, locationOverride, err := resolveLocationOverride(ctx, r.db.Entity, gid, data.ID, data.ParentID, data.LocationID)+ if err != nil {+ recordSpanError(span, err)+ return EntityOut{}, err+ }+ span.SetAttributes(attribute.Bool("entity.location_override.set", locationOverride != uuid.Nil))+q := r.db.Entity.Update().Where(entity.ID(data.ID), entity.HasGroupWith(group.ID(gid))).SetName(data.Name).SetDescription(data.Description).@@ -1796,17 +1845,17 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat)tagsSpan.End()- if data.ParentID != uuid.Nil {- q.SetParentID(data.ParentID)+ if parentID != uuid.Nil {+ q.SetParentID(parentID)} else {q.ClearParent()}- // Note: SyncChildEntityLocations intentionally triggers no child updates- // here. In the single-parent entity model a child's location is derived- // from its ancestor chain, so children follow a moved parent- // automatically. The old behavior reparented this entity's children onto- // its *new parent* — flattening the hierarchy on every save (#1591).+ if locationOverride != uuid.Nil {+ q.SetLocationID(locationOverride)+ } else {+ q.ClearLocation()+ }_, execSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.exec")err = q.Exec(ctx)@@ -1818,6 +1867,22 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat}execSpan.End()+ // Sync means "children have no location of their own", so drop theirs.+ // Only the location column: touching parent here is what flattened the+ // hierarchy on every save before #1591.+ if data.SyncChildEntityLocations {+ syncCtx, syncSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.syncChildLocations")+ cleared, err := clearChildLocationOverrides(syncCtx, r.db.Entity, gid, data.ID)+ if err != nil {+ recordSpanError(syncSpan, err)+ syncSpan.End()+ recordSpanError(span, err)+ return EntityOut{}, err+ }+ syncSpan.SetAttributes(attribute.Int("children.location_overrides.cleared", cleared))+ syncSpan.End()+ }+fieldsCtx, fieldsSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.fields",trace.WithAttributes(attribute.Int("fields.input.count", len(data.Fields))))fields, err := r.db.EntityField.Query().@@ -2051,8 +2116,58 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data Enq.SetQuantity(*data.Quantity)}- if data.ParentID != uuid.Nil {+ switch {+ case data.LocationID != uuid.Nil:+ // Validate against the parent we'll end up with, not the one we were+ // handed — a location-only patch doesn't carry a parent.+ parentID := data.ParentID+ if parentID == uuid.Nil {+ current, err := tx.Entity.Query().+ Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).+ QueryParent().+ OnlyID(ctx)+ if err != nil && !ent.IsNotFound(err) {+ recordSpanError(span, err)+ return err+ }+ if err == nil {+ parentID = current+ }+ }++ resolvedParent, override, err := resolveLocationOverride(ctx, tx.Entity, gid, id, parentID, data.LocationID)+ if err != nil {+ recordSpanError(span, err)+ return err+ }+ if resolvedParent != uuid.Nil {+ q.SetParentID(resolvedParent)+ }+ if override != uuid.Nil {+ q.SetLocationID(override)+ } else {+ q.ClearLocation()+ }++ case data.ParentID != uuid.Nil:q.SetParentID(data.ParentID)++ // Moving under a location makes any override redundant, and leaving it+ // breaks the invariant the read paths rely on.+ parentIsLocation, err := tx.Entity.Query().+ Where(+ entity.ID(data.ParentID),+ entity.HasGroupWith(group.ID(gid)),+ entity.HasEntityTypeWith(entitytype.IsLocation(true)),+ ).+ Exist(ctx)+ if err != nil {+ recordSpanError(span, err)+ return err+ }+ if parentIsLocation {+ q.ClearLocation()+ }}if data.EntityTypeID != uuid.Nil {@@ -2418,6 +2533,17 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, optentityBuilder.SetParentID(originalEntity.Parent.ID)}+ // Read the raw edge, not originalEntity.Location — that one is resolved, so+ // copying it would pin a duplicate that should have kept inheriting.+ srcLocationID, err := tx.Entity.Query().Where(entity.ID(id)).QueryLocation().OnlyID(ctx)+ switch {+ case err == nil:+ entityBuilder.SetLocationID(srcLocationID)+ case !ent.IsNotFound(err):+ recordSpanError(span, err)+ return EntityOut{}, err+ }+if originalEntity.EntityType != nil {entityBuilder.SetEntityTypeID(originalEntity.EntityType.ID)}@@ -2973,29 +3099,35 @@ func (r *EntityRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQuerylower(NAME)`if tq.WithItems {+ // Items hang off their effective location. The same expression has to be+ // used in both arms: an overridden child's effective parent is a+ // location, so the recursive arm (items only) can't also pick it up and+ // list it twice.+ eff := locationOrParentColumn("e")+ effChild := locationOrParentColumn("c")itemQuery := `, item_tree(id, NAME, parent_id, level, node_type) AS(SELECT e.id,e.NAME,- e.entity_children as parent_id,+ ` + eff + ` as parent_id,0 AS level,'item' AS node_typeFROM entities eJOIN entity_types et ON et.id = e.entity_type_entitiesWHERE et.is_location = false- AND e.entity_children IN (SELECT id FROM entity_tree)+ AND ` + eff + ` IN (SELECT id FROM entity_tree)UNION ALLSELECT c.id,c.NAME,- c.entity_children AS parent_id,+ ` + effChild + ` AS parent_id,level + 1,'item' AS node_typeFROM entities cJOIN entity_types ct ON ct.id = c.entity_type_entitiesJOIN item_tree p- ON c.entity_children = p.id+ ON ` + effChild + ` = p.idWHERE ct.is_location = falseAND level < 10 -- prevent infinite loop & excessive recursion)`diff --git a/backend/internal/data/repo/repo_entity_location.go b/backend/internal/data/repo/repo_entity_location.gonew file mode 100644index 00000000..32396e81--- /dev/null+++ b/backend/internal/data/repo/repo_entity_location.go@@ -0,0 +1,131 @@+package repo++import (+ "context"++ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/entity"+ "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/predicate"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"+)++// Two columns say where an entity lives. entity_children is containment; since+// 0.26 it was also the only source of location, which is why an item couldn't be+// a child of one item and stored somewhere else (#1688).+//+// entity_location_entities is a sparse override, only valid when the parent is a+// non-location entity. NULL means inherit from the parent chain, so an item in a+// location is still just parent=<location>, and the two never both claim one.++const locationField = "locationId"++// resolveLocationOverride normalizes a (parent, location) pair. Returns what to+// persist; a uuid.Nil override means clear it. subjectID is Nil on create.+//+// - no location: parent as given, override cleared (the old behavior)+// - location, no parent or same-location parent: location becomes the parent+// - location + parent item: override stored, the #1688 case+// - location + a different location as parent: rejected, since both claim to+// say where this lives and picking one silently loses data+func resolveLocationOverride(+ ctx context.Context,+ c *ent.EntityClient,+ gid, subjectID, parentID, locationID uuid.UUID,+) (parent, override uuid.UUID, err error) {+ if locationID == uuid.Nil {+ return parentID, uuid.Nil, nil+ }++ if locationID == subjectID {+ return uuid.Nil, uuid.Nil, validate.NewFieldErrors(+ validate.NewFieldError(locationField, "an entity cannot be its own location"),+ )+ }++ // One query, so a cross-group UUID can't be probed by the difference between+ // "not a location" and "not found".+ isLocation, err := c.Query().+ Where(+ entity.ID(locationID),+ entity.HasGroupWith(group.ID(gid)),+ entity.HasEntityTypeWith(entitytype.IsLocation(true)),+ ).+ Exist(ctx)+ if err != nil {+ return uuid.Nil, uuid.Nil, err+ }+ if !isLocation {+ return uuid.Nil, uuid.Nil, validate.NewFieldErrors(+ validate.NewFieldError(locationField, "location must reference an existing location in this group"),+ )+ }++ if parentID == uuid.Nil || parentID == locationID {+ return locationID, uuid.Nil, nil+ }++ parentIsLocation, err := c.Query().+ Where(+ entity.ID(parentID),+ entity.HasGroupWith(group.ID(gid)),+ entity.HasEntityTypeWith(entitytype.IsLocation(true)),+ ).+ Exist(ctx)+ if err != nil {+ return uuid.Nil, uuid.Nil, err+ }+ if parentIsLocation {+ return uuid.Nil, uuid.Nil, validate.NewFieldErrors(+ validate.NewFieldError(locationField,+ "cannot set a location while the parent is a different location; move the entity by changing its parent instead"),+ )+ }++ return parentID, locationID, nil+}++// resolveEntityLocation returns e's override if set, else the nearest location+// ancestor. Needs the Location and Parent edges loaded.+func resolveEntityLocation(ctx context.Context, c *ent.EntityClient, e *ent.Entity) (*EntitySummary, error) {+ if e.Edges.Location != nil {+ s := mapEntitySummary(e.Edges.Location)+ return &s, nil+ }+ return nearestLocationAncestor(ctx, c, e.Edges.Parent)+}++// effectiveLocationIn is the query-side twin of resolveEntityLocation:+// entities parented directly to one of ids, plus entities elsewhere in the+// tree that name it explicitly.+func effectiveLocationIn(ids []uuid.UUID) predicate.Entity {+ return entity.Or(+ entity.And(+ entity.HasParentWith(entity.IDIn(ids...)),+ entity.Not(entity.HasLocation()),+ ),+ entity.HasLocationWith(entity.IDIn(ids...)),+ )+}++// clearChildLocationOverrides drops direct children's overrides so they go back+// to inheriting. Grandchildren are left alone — their override is their own+// parent's toggle to manage.+func clearChildLocationOverrides(ctx context.Context, c *ent.EntityClient, gid, parentID uuid.UUID) (int, error) {+ return c.Update().+ Where(+ entity.HasParentWith(entity.ID(parentID)),+ entity.HasGroupWith(group.ID(gid)),+ entity.HasLocation(),+ ).+ ClearLocation().+ Save(ctx)+}++// locationOrParentColumn is the effective-location expression for the raw SQL+// queries, where ent's predicate builder isn't available.+func locationOrParentColumn(table string) string {+ return "COALESCE(" + table + ".entity_location_entities, " + table + ".entity_children)"+}diff --git a/backend/internal/data/repo/repo_entity_location_test.go b/backend/internal/data/repo/repo_entity_location_test.gonew file mode 100644index 00000000..03e8c61a--- /dev/null+++ b/backend/internal/data/repo/repo_entity_location_test.go@@ -0,0 +1,449 @@+package repo++import (+ "context"+ "testing"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/entity"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"+)++// locationFixture gives each test its own group with two locations, so tests+// don't see each other's tree.+type locationFixture struct {+ gid uuid.UUID+ itemType uuid.UUID+ attic EntityOut+ basement EntityOut+}++func newLocationFixture(t *testing.T, name string) locationFixture {+ t.Helper()+ ctx := context.Background()++ g, err := tRepos.Groups.GroupCreate(ctx, name, uuid.Nil)+ require.NoError(t, err)++ itemType, err := tRepos.EntityTypes.GetDefault(ctx, g.ID, false)+ require.NoError(t, err)+ locType, err := tRepos.EntityTypes.GetDefault(ctx, g.ID, true)+ require.NoError(t, err)++ attic, err := tRepos.Entities.Create(ctx, g.ID, EntityCreate{+ Name: "Attic",+ EntityTypeID: locType.ID,+ })+ require.NoError(t, err)++ basement, err := tRepos.Entities.Create(ctx, g.ID, EntityCreate{+ Name: "Basement",+ EntityTypeID: locType.ID,+ })+ require.NoError(t, err)++ return locationFixture{gid: g.ID, itemType: itemType.ID, attic: attic, basement: basement}+}++// #1688 verbatim: a spare part belonging to a product but stored on a different+// shelf. Step 4 used to drag the child into the parent's location, and step 5+// couldn't put it back.+func TestEntityLocation_ChildKeepsOwnLocation(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-child-own-location")++ // 1. Parent in the Attic.+ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent",+ EntityTypeID: f.itemType,+ ParentID: f.attic.ID,+ })+ require.NoError(t, err)+ require.NotNil(t, parent.Location)+ assert.Equal(t, f.attic.ID, parent.Location.ID)++ // 2. Child in the Basement.+ child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Child",+ EntityTypeID: f.itemType,+ ParentID: f.basement.ID,+ })+ require.NoError(t, err)++ // 4. Make Parent the parent of Child, while keeping Child in the Basement.+ updated, err := tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{+ ID: child.ID,+ Name: "Child",+ Quantity: 1,+ ParentID: parent.ID,+ LocationID: f.basement.ID,+ })+ require.NoError(t, err)++ // 5. Both relationships hold at once.+ require.NotNil(t, updated.Parent)+ assert.Equal(t, parent.ID, updated.Parent.ID, "child should be parented to the parent item")+ require.NotNil(t, updated.Location)+ assert.Equal(t, f.basement.ID, updated.Location.ID, "child should still be stored in the Basement")++ // And it survives a re-read rather than only looking right in the response.+ reread, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, child.ID)+ require.NoError(t, err)+ require.NotNil(t, reread.Location)+ assert.Equal(t, f.basement.ID, reread.Location.ID)++ // The parent is unaffected.+ parentAfter, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, parent.ID)+ require.NoError(t, err)+ require.NotNil(t, parentAfter.Location)+ assert.Equal(t, f.attic.ID, parentAfter.Location.ID)+}++// The default is unchanged: no locationId means the child still follows its+// parent. This is what makes the upgrade a no-op for existing rows.+func TestEntityLocation_InheritsWhenNoOverride(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-inherit-default")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Child", EntityTypeID: f.itemType, ParentID: parent.ID,+ })+ require.NoError(t, err)++ require.NotNil(t, child.Location)+ assert.Equal(t, f.attic.ID, child.Location.ID, "child with no override inherits the parent's location")++ // Moving the parent moves the inheriting child with it.+ _, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{+ ID: parent.ID, Name: "Parent", Quantity: 1, ParentID: f.basement.ID,+ })+ require.NoError(t, err)++ childAfter, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, child.ID)+ require.NoError(t, err)+ require.NotNil(t, childAfter.Location)+ assert.Equal(t, f.basement.ID, childAfter.Location.ID, "inheriting child follows the parent")+}++// Naming a location with no parent item is just a parent change, so no override+// is written and there stays one way to express it.+func TestEntityLocation_DirectLocationStoresNoOverride(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-normalizes-direct")++ item, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Item", EntityTypeID: f.itemType, LocationID: f.attic.ID,+ })+ require.NoError(t, err)++ require.NotNil(t, item.Parent)+ assert.Equal(t, f.attic.ID, item.Parent.ID, "location with no parent item becomes the parent")+ require.NotNil(t, item.Location)+ assert.Equal(t, f.attic.ID, item.Location.ID)++ // No override row was written, so the entity still resolves by ancestry.+ overrideID, err := tClient.Entity.Query().+ Where(entity.ID(item.ID)).+ QueryLocation().+ OnlyID(ctx)+ require.Error(t, err, "no override should be stored for a direct location")+ assert.Equal(t, uuid.Nil, overrideID)+}++// Parent is one location, locationId is another. Both claim to say where this+// lives; silently honoring one is how #1691-class data loss happens.+func TestEntityLocation_RejectsConflictingLocation(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-conflict")++ item, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Item", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ _, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{+ ID: item.ID, Name: "Item", Quantity: 1,+ ParentID: f.attic.ID,+ LocationID: f.basement.ID,+ })+ require.Error(t, err)+ assert.True(t, validate.IsFieldError(err), "should surface as a 422 field error, not a 500")++ // The entity is untouched.+ after, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, item.ID)+ require.NoError(t, err)+ require.NotNil(t, after.Location)+ assert.Equal(t, f.attic.ID, after.Location.ID)+}++// An item can't be used as a location — that would build a second, competing+// containment hierarchy.+func TestEntityLocation_RejectsNonLocationTarget(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-non-location-target")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)+ other, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Other", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ _, err = tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Child", EntityTypeID: f.itemType,+ ParentID: parent.ID,+ LocationID: other.ID,+ })+ require.Error(t, err)+ assert.True(t, validate.IsFieldError(err))+}++// The override must not reach another tenant's location: that corrupts their+// tree and confirms a guessed UUID.+func TestEntityLocation_RejectsCrossGroupLocation(t *testing.T) {+ ctx := context.Background()+ a := newLocationFixture(t, "loc-tenant-a")+ b := newLocationFixture(t, "loc-tenant-b")++ parent, err := tRepos.Entities.Create(ctx, a.gid, EntityCreate{+ Name: "Parent", EntityTypeID: a.itemType, ParentID: a.attic.ID,+ })+ require.NoError(t, err)++ _, err = tRepos.Entities.Create(ctx, a.gid, EntityCreate{+ Name: "Child", EntityTypeID: a.itemType,+ ParentID: parent.ID,+ LocationID: b.basement.ID,+ })+ require.Error(t, err, "must not accept another group's location")+ assert.True(t, validate.IsFieldError(err))+ assert.Contains(t, err.Error(), "must reference an existing location in this group")+}++// The "Sync child items' locations" toggle had nothing to act on between 0.26+// and this change. Turning it on drops the children's own locations — and must+// leave their parent edge alone, which is what flattened the tree before #1591.+func TestEntityLocation_SyncChildLocationsClearsOverrides(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-sync-toggle")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Child", EntityTypeID: f.itemType,+ ParentID: parent.ID,+ LocationID: f.basement.ID,+ })+ require.NoError(t, err)+ require.NotNil(t, child.Location)+ require.Equal(t, f.basement.ID, child.Location.ID)++ // Turn the toggle on for the parent.+ _, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{+ ID: parent.ID, Name: "Parent", Quantity: 1, ParentID: f.attic.ID,+ SyncChildEntityLocations: true,+ })+ require.NoError(t, err)++ childAfter, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, child.ID)+ require.NoError(t, err)+ require.NotNil(t, childAfter.Location)+ assert.Equal(t, f.attic.ID, childAfter.Location.ID, "child should follow the parent once sync is on")+ require.NotNil(t, childAfter.Parent)+ assert.Equal(t, parent.ID, childAfter.Parent.ID, "sync must not reparent the child (#1591)")+}++// The location page must list the spare part stored in the Basement even though+// it hangs off a product in the Attic.+func TestEntityLocation_QueryByLocationFindsOverriddenChild(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-query-filter")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Spare Part", EntityTypeID: f.itemType,+ ParentID: parent.ID,+ LocationID: f.basement.ID,+ })+ require.NoError(t, err)++ inBasement, err := tRepos.Entities.QueryByGroup(ctx, f.gid, EntityQuery{+ ParentIDs: []uuid.UUID{f.basement.ID},+ Page: -1,+ })+ require.NoError(t, err)+ ids := make([]uuid.UUID, 0, len(inBasement.Items))+ for _, e := range inBasement.Items {+ ids = append(ids, e.ID)+ }+ assert.Contains(t, ids, child.ID, "Basement should list the item stored there")++ inAttic, err := tRepos.Entities.QueryByGroup(ctx, f.gid, EntityQuery{+ ParentIDs: []uuid.UUID{f.attic.ID},+ Page: -1,+ })+ require.NoError(t, err)+ atticIDs := make([]uuid.UUID, 0, len(inAttic.Items))+ for _, e := range inAttic.Items {+ atticIDs = append(atticIDs, e.ID)+ }+ assert.Contains(t, atticIDs, parent.ID)+ assert.NotContains(t, atticIDs, child.ID, "Attic must not list an item stored in the Basement")+}++// The recursive tree SQL has to honor the override in both arms. The spare part+// belongs under the Basement, exactly once — handling only one arm lists it+// twice, which is worse than the bug we're fixing.+func TestEntityLocation_TreePlacesOverriddenChildUnderItsLocation(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-tree-placement")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Product", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ // Stored in the Basement despite belonging to the product in the Attic.+ spare, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Spare Part", EntityTypeID: f.itemType,+ ParentID: parent.ID,+ LocationID: f.basement.ID,+ })+ require.NoError(t, err)++ // A sibling with no override still nests under the product.+ bundled, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Bundled Part", EntityTypeID: f.itemType, ParentID: parent.ID,+ })+ require.NoError(t, err)++ tree, err := tRepos.Entities.Tree(ctx, f.gid, TreeQuery{WithItems: true})+ require.NoError(t, err)++ // Flatten to id -> parent name, counting appearances.+ parentOf := map[uuid.UUID]string{}+ seen := map[uuid.UUID]int{}+ var walk func(nodes []*TreeItem, parentName string)+ walk = func(nodes []*TreeItem, parentName string) {+ for _, n := range nodes {+ seen[n.ID]+++ parentOf[n.ID] = parentName+ walk(n.Children, n.Name)+ }+ }+ roots := make([]*TreeItem, 0, len(tree))+ for i := range tree {+ roots = append(roots, &tree[i])+ }+ walk(roots, "")++ assert.Equal(t, 1, seen[spare.ID], "overridden item must appear exactly once")+ assert.Equal(t, "Basement", parentOf[spare.ID], "overridden item belongs under the location it is stored in")+ assert.Equal(t, "Product", parentOf[bundled.ID], "an inheriting sibling still nests under the parent item")+ assert.Equal(t, "Attic", parentOf[parent.ID])+}++// #1691's hazard applied to the new field: GET a body, PUT it straight back, and+// the entity must not move. An inherited location must not become a pinned+// override, and an override must not be dropped.+func TestEntityLocation_RoundTripPreservesPlacement(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-roundtrip")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ inheriting, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Inheriting", EntityTypeID: f.itemType, ParentID: parent.ID,+ })+ require.NoError(t, err)+ assert.Nil(t, inheriting.LocationID, "an inherited location exposes no locationId")++ overridden, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Overridden", EntityTypeID: f.itemType,+ ParentID: parent.ID, LocationID: f.basement.ID,+ })+ require.NoError(t, err)+ require.NotNil(t, overridden.LocationID)+ assert.Equal(t, f.basement.ID, *overridden.LocationID)++ // Echo each record back the way a client would.+ roundTrip := func(e EntityOut) EntityOut {+ t.Helper()+ u := EntityUpdate{ID: e.ID, Name: e.Name, Quantity: e.Quantity}+ if e.Parent != nil {+ u.ParentID = e.Parent.ID+ }+ if e.LocationID != nil {+ u.LocationID = *e.LocationID+ }+ out, err := tRepos.Entities.UpdateByGroup(ctx, f.gid, u)+ require.NoError(t, err)+ return out+ }++ afterInherit := roundTrip(inheriting)+ assert.Nil(t, afterInherit.LocationID, "round trip must not pin an inherited location")+ require.NotNil(t, afterInherit.Location)+ assert.Equal(t, f.attic.ID, afterInherit.Location.ID)++ afterOverride := roundTrip(overridden)+ require.NotNil(t, afterOverride.LocationID, "round trip must not drop an override")+ assert.Equal(t, f.basement.ID, *afterOverride.LocationID)++ // The inheriting one still tracks the parent after its round trip.+ _, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{+ ID: parent.ID, Name: "Parent", Quantity: 1, ParentID: f.basement.ID,+ })+ require.NoError(t, err)+ reread, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, inheriting.ID)+ require.NoError(t, err)+ require.NotNil(t, reread.Location)+ assert.Equal(t, f.basement.ID, reread.Location.ID)+}++// ON DELETE SET NULL: deleting a location that items only point at must not take+// them with it. They fall back to inheriting through their parent.+func TestEntityLocation_DeletingLocationFallsBackToInheritance(t *testing.T) {+ ctx := context.Background()+ f := newLocationFixture(t, "loc-delete-target")++ parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ })+ require.NoError(t, err)++ child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{+ Name: "Child", EntityTypeID: f.itemType,+ ParentID: parent.ID, LocationID: f.basement.ID,+ })+ require.NoError(t, err)++ require.NoError(t, tRepos.Entities.DeleteByGroup(ctx, f.gid, f.basement.ID))++ survived, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, child.ID)+ require.NoError(t, err, "the item must survive deletion of the location it pointed at")+ assert.Nil(t, survived.LocationID, "the dangling override must be cleared")+ require.NotNil(t, survived.Location)+ assert.Equal(t, f.attic.ID, survived.Location.ID, "it falls back to the parent's location")+ require.NotNil(t, survived.Parent)+ assert.Equal(t, parent.ID, survived.Parent.ID)+}diff --git a/docs/public/api/openapi-3.0.json b/docs/public/api/openapi-3.0.jsonindex 87227ba7..82963259 100644--- a/docs/public/api/openapi-3.0.json+++ b/docs/public/api/openapi-3.0.json@@ -3872,6 +3872,21 @@}]},+ "location": {+ "description": "Location holds the value of the location edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.Entity"+ }+ ]+ },+ "location_entities": {+ "description": "LocationEntities holds the value of the location_entities edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.Entity"+ }+ },"maintenance_entries": {"description": "MaintenanceEntries holds the value of the maintenance_entries edge.","type": "array",@@ -5041,6 +5056,12 @@"entityTypeId": {"type": "string"},+ "locationId": {+ "description": "LocationID is only needed when ParentID refers to another item and\nthe new entity is stored somewhere other than that item's location.",+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string","maxLength": 255,@@ -5185,7 +5206,7 @@"type": "boolean"},"location": {- "description": "Location is the nearest ancestor whose entity type is a location.\nWhen the direct parent is already a location it equals Parent; when\nthe entity is nested inside other items it is the location those\nitems ultimately live in. Nil for top-level entities.",+ "description": "Location is where this entity resolves to: its own location when one\nis set, otherwise the nearest ancestor whose entity type is a\nlocation. Nil for top-level entities. This is a *resolved* value —\nwrite it back through LocationID, not through this field.","allOf": [{"$ref": "#/components/schemas/repo.EntitySummary"@@ -5194,6 +5215,12 @@"x-omitempty": true,"nullable": true},+ "locationId": {+ "description": "LocationID is this entity's own location, and is nil when Location was\ninherited from an ancestor. It is named to match the locationId field\non EntityUpdate on purpose: a GET body PUT back verbatim keeps the\nentity exactly where it was, rather than silently pinning an\ninherited location or dropping an explicit one.",+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string"},@@ -5285,6 +5312,11 @@"id": {"type": "string"},+ "locationId": {+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"parentId": {"type": "string","x-omitempty": true,@@ -5787,6 +5819,12 @@"description": "Warranty","type": "boolean"},+ "locationId": {+ "description": "LocationID names the location this entity is stored in. It only\nneeds to be sent when ParentID refers to another item and the entity\nlives somewhere other than that item's location (#1688); otherwise\nParentID alone carries the location. See resolveLocationOverride.",+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string"},@@ -6680,6 +6718,11 @@"description": "EntityTypeID is the entity type selected by the user. When set it takes\nprecedence; when empty the repository falls back to the group's default.","type": "string"},+ "locationId": {+ "type": "string",+ "x-omitempty": true,+ "nullable": true+ },"name": {"type": "string","maxLength": 255,diff --git a/docs/public/api/openapi-3.0.yaml b/docs/public/api/openapi-3.0.yamlindex fa8d89db..a00c2bbc 100644--- a/docs/public/api/openapi-3.0.yaml+++ b/docs/public/api/openapi-3.0.yaml@@ -2357,6 +2357,15 @@ components:description: Group holds the value of the group edge.allOf:- $ref: "#/components/schemas/ent.Group"+ location:+ description: Location holds the value of the location edge.+ allOf:+ - $ref: "#/components/schemas/ent.Entity"+ location_entities:+ description: LocationEntities holds the value of the location_entities edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.Entity"maintenance_entries:description: MaintenanceEntries holds the value of the maintenance_entries edge.type: array@@ -3176,6 +3185,13 @@ components:maxLength: 1000entityTypeId:type: string+ locationId:+ description: |-+ LocationID is only needed when ParentID refers to another item and+ the new entity is stored somewhere other than that item's location.+ type: string+ x-omitempty: true+ nullable: truemanufacturer:type: stringmaxLength: 255@@ -3280,14 +3296,29 @@ components:type: booleanlocation:description: |-- Location is the nearest ancestor whose entity type is a location.- When the direct parent is already a location it equals Parent; when- the entity is nested inside other items it is the location those- items ultimately live in. Nil for top-level entities.+ Location is where this entity resolves to: its own location when one+ is set, otherwise the nearest ancestor whose entity type is a+ location. Nil for top-level entities. This is a *resolved* value —+ write it back through LocationID, not through this field.allOf:- $ref: "#/components/schemas/repo.EntitySummary"x-omitempty: truenullable: true+ locationId:+ description: >-+ LocationID is this entity's own location, and is nil when Location+ was++ inherited from an ancestor. It is named to match the locationId field++ on EntityUpdate on purpose: a GET body PUT back verbatim keeps the++ entity exactly where it was, rather than silently pinning an++ inherited location or dropping an explicit one.+ type: string+ x-omitempty: true+ nullable: truemanufacturer:type: stringmodelNumber:@@ -3350,6 +3381,10 @@ components:nullable: trueid:type: string+ locationId:+ type: string+ x-omitempty: true+ nullable: trueparentId:type: stringx-omitempty: true@@ -3699,6 +3734,15 @@ components:lifetimeWarranty:description: Warrantytype: boolean+ locationId:+ description: |-+ LocationID names the location this entity is stored in. It only+ needs to be sent when ParentID refers to another item and the entity+ lives somewhere other than that item's location (#1688); otherwise+ ParentID alone carries the location. See resolveLocationOverride.+ type: string+ x-omitempty: true+ nullable: truemanufacturer:type: stringmodelNumber:@@ -4306,6 +4350,10 @@ components:precedence; when empty the repository falls back to the group's default.type: string+ locationId:+ type: string+ x-omitempty: true+ nullable: truename:type: stringmaxLength: 255diff --git a/docs/public/api/swagger-2.0.json b/docs/public/api/swagger-2.0.jsonindex 8443d2ef..8ec23bee 100644--- a/docs/public/api/swagger-2.0.json+++ b/docs/public/api/swagger-2.0.json@@ -3628,6 +3628,21 @@}]},+ "location": {+ "description": "Location holds the value of the location edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.Entity"+ }+ ]+ },+ "location_entities": {+ "description": "LocationEntities holds the value of the location_entities edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.Entity"+ }+ },"maintenance_entries": {"description": "MaintenanceEntries holds the value of the maintenance_entries edge.","type": "array",@@ -4797,6 +4812,12 @@"entityTypeId": {"type": "string"},+ "locationId": {+ "description": "LocationID is only needed when ParentID refers to another item and\nthe new entity is stored somewhere other than that item's location.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string","maxLength": 255,@@ -4941,7 +4962,7 @@"type": "boolean"},"location": {- "description": "Location is the nearest ancestor whose entity type is a location.\nWhen the direct parent is already a location it equals Parent; when\nthe entity is nested inside other items it is the location those\nitems ultimately live in. Nil for top-level entities.",+ "description": "Location is where this entity resolves to: its own location when one\nis set, otherwise the nearest ancestor whose entity type is a\nlocation. Nil for top-level entities. This is a *resolved* value —\nwrite it back through LocationID, not through this field.","allOf": [{"$ref": "#/definitions/repo.EntitySummary"@@ -4950,6 +4971,12 @@"x-nullable": true,"x-omitempty": true},+ "locationId": {+ "description": "LocationID is this entity's own location, and is nil when Location was\ninherited from an ancestor. It is named to match the locationId field\non EntityUpdate on purpose: a GET body PUT back verbatim keeps the\nentity exactly where it was, rather than silently pinning an\ninherited location or dropping an explicit one.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},@@ -5041,6 +5068,11 @@"id": {"type": "string"},+ "locationId": {+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"parentId": {"type": "string","x-nullable": true,@@ -5543,6 +5575,12 @@"description": "Warranty","type": "boolean"},+ "locationId": {+ "description": "LocationID names the location this entity is stored in. It only\nneeds to be sent when ParentID refers to another item and the entity\nlives somewhere other than that item's location (#1688); otherwise\nParentID alone carries the location. See resolveLocationOverride.",+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},@@ -6436,6 +6474,11 @@"description": "EntityTypeID is the entity type selected by the user. When set it takes\nprecedence; when empty the repository falls back to the group's default.","type": "string"},+ "locationId": {+ "type": "string",+ "x-nullable": true,+ "x-omitempty": true+ },"name": {"type": "string","maxLength": 255,diff --git a/docs/public/api/swagger-2.0.yaml b/docs/public/api/swagger-2.0.yamlindex af0a77c9..f4f1fb2a 100644--- a/docs/public/api/swagger-2.0.yaml+++ b/docs/public/api/swagger-2.0.yaml@@ -295,6 +295,15 @@ definitions:allOf:- $ref: '#/definitions/ent.Group'description: Group holds the value of the group edge.+ location:+ allOf:+ - $ref: '#/definitions/ent.Entity'+ description: Location holds the value of the location edge.+ location_entities:+ description: LocationEntities holds the value of the location_entities edge.+ items:+ $ref: '#/definitions/ent.Entity'+ type: arraymaintenance_entries:description: MaintenanceEntries holds the value of the maintenance_entriesedge.@@ -1100,6 +1109,13 @@ definitions:type: stringentityTypeId:type: string+ locationId:+ description: |-+ LocationID is only needed when ParentID refers to another item and+ the new entity is stored somewhere other than that item's location.+ type: string+ x-nullable: true+ x-omitempty: truemanufacturer:maxLength: 255type: string@@ -1208,10 +1224,20 @@ definitions:allOf:- $ref: '#/definitions/repo.EntitySummary'description: |-- Location is the nearest ancestor whose entity type is a location.- When the direct parent is already a location it equals Parent; when- the entity is nested inside other items it is the location those- items ultimately live in. Nil for top-level entities.+ Location is where this entity resolves to: its own location when one+ is set, otherwise the nearest ancestor whose entity type is a+ location. Nil for top-level entities. This is a *resolved* value —+ write it back through LocationID, not through this field.+ x-nullable: true+ x-omitempty: true+ locationId:+ description: |-+ LocationID is this entity's own location, and is nil when Location was+ inherited from an ancestor. It is named to match the locationId field+ on EntityUpdate on purpose: a GET body PUT back verbatim keeps the+ entity exactly where it was, rather than silently pinning an+ inherited location or dropping an explicit one.+ type: stringx-nullable: truex-omitempty: truemanufacturer:@@ -1276,6 +1302,10 @@ definitions:x-omitempty: trueid:type: string+ locationId:+ type: string+ x-nullable: true+ x-omitempty: trueparentId:type: stringx-nullable: true@@ -1623,6 +1653,15 @@ definitions:lifetimeWarranty:description: Warrantytype: boolean+ locationId:+ description: |-+ LocationID names the location this entity is stored in. It only+ needs to be sent when ParentID refers to another item and the entity+ lives somewhere other than that item's location (#1688); otherwise+ ParentID alone carries the location. See resolveLocationOverride.+ type: string+ x-nullable: true+ x-omitempty: truemanufacturer:type: stringmodelNumber:@@ -2227,6 +2266,10 @@ definitions:EntityTypeID is the entity type selected by the user. When set it takesprecedence; when empty the repository falls back to the group's default.type: string+ locationId:+ type: string+ x-nullable: true+ x-omitempty: truename:maxLength: 255minLength: 1diff --git a/frontend/components/Entity/CreateModal.vue b/frontend/components/Entity/CreateModal.vueindex 52d537b9..76da9a98 100644--- a/frontend/components/Entity/CreateModal.vue+++ b/frontend/components/Entity/CreateModal.vue@@ -234,6 +234,7 @@EntityTemplateOut,EntityTemplateSummary,EntityOut,+ EntitySummary,EntityTypeSummary,} from "~~/lib/api/types/data-contracts";import { useTagStore } from "~/stores/tags";@@ -475,14 +476,51 @@localStorage.removeItem(LAST_TEMPLATE_KEY);}+ // Used at submit to tell "left at the default" from "stored elsewhere".+ const inheritedLocationId = ref<string | null>(null);++ function resolveInheritedLocation(entity: EntityOut | EntitySummary | null | undefined): string | null {+ if (!entity) return null;+ const resolved = (entity as EntityOut).location?.id;+ if (resolved) return resolved;+ return entity.parent?.entityType?.isLocation ? entity.parent.id : null;+ }++ const resolvedParent = ref<EntityOut | null>(null);+ let parentLookup = 0;+watch(parent,- newParent => {+ async newParent => {if (newParent && newParent.id && subItemCreate.value) {form.parentId = newParent.id;} else {form.parentId = null;}++ const lookup = ++parentLookup;++ if (!newParent?.id) {+ inheritedLocationId.value = null;+ return;+ }++ if (resolvedParent.value?.id === newParent.id) {+ inheritedLocationId.value = resolveInheritedLocation(resolvedParent.value);+ return;+ }++ const { data, error } = await api.items.get(newParent.id);+ if (lookup !== parentLookup) return;++ if (error || !data) {+ console.error("Parent item fetch error:", error);+ inheritedLocationId.value = resolveInheritedLocation(newParent);+ return;+ }++ resolvedParent.value = data;+ inheritedLocationId.value = resolveInheritedLocation(data);},{ immediate: true });@@ -517,6 +555,7 @@subItemCreate.value = false;let parentItemLocationId = null;parent.value = {};+ resolvedParent.value = null;form.parentId = null;if (params.baseType === "item") {@@ -530,16 +569,15 @@if (error || !data) {toast.error(t("components.entity.create_modal.toast.failed_load_parent"));console.error("Parent item fetch error:", error);+ return;}- if (data) {- parent.value = data;- }+ resolvedParent.value = data;+ parent.value = data;- if (data.parent) {- const loc = data.parent;- parentItemLocationId = loc.id;- }+ // What the sub-item inherits if left alone. Resolved location, not the+ // direct parent — those only match when the parent sits in one.+ parentItemLocationId = resolveInheritedLocation(data);}if (params.product) {@@ -646,8 +684,13 @@data = result.data;} else {// Normal item creation without template+ // Only pin a location when it differs from what the item would inherit,+ // so it otherwise still follows the parent (#1688).+ const chosenLocationId = (form.location?.id as string) || null;const out: EntityCreate = {parentId: form.parentId || (form.location.id as string),+ locationId:+ form.parentId && chosenLocationId && chosenLocationId !== inheritedLocationId.value ? chosenLocationId : null,name: form.name,quantity: form.quantity,description: form.description,diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.tsindex 3525f642..e3dc66d1 100644--- a/frontend/lib/api/types/data-contracts.ts+++ b/frontend/lib/api/types/data-contracts.ts@@ -250,6 +250,10 @@ export interface EntEntityEdges {fields: EntEntityField[];/** Group holds the value of the group edge. */group: EntGroup;+ /** Location holds the value of the location edge. */+ location: EntEntity;+ /** LocationEntities holds the value of the location_entities edge. */+ location_entities: EntEntity[];/** MaintenanceEntries holds the value of the maintenance_entries edge. */maintenance_entries: EntMaintenanceEntry[];/** Parent holds the value of the parent edge. */@@ -745,6 +749,11 @@ export interface EntityCreate {/** @maxLength 1000 */description: string;entityTypeId: string;+ /**+ * LocationID is only needed when ParentID refers to another item and+ * the new entity is stored somewhere other than that item's location.+ */+ locationId?: string | null;/** @maxLength 255 */manufacturer?: string | null;/**@@ -800,12 +809,20 @@ export interface EntityOut {/** Warranty */lifetimeWarranty: boolean;/**- * Location is the nearest ancestor whose entity type is a location.- * When the direct parent is already a location it equals Parent; when- * the entity is nested inside other items it is the location those- * items ultimately live in. Nil for top-level entities.+ * Location is where this entity resolves to: its own location when one+ * is set, otherwise the nearest ancestor whose entity type is a+ * location. Nil for top-level entities. This is a *resolved* value —+ * write it back through LocationID, not through this field.*/location?: EntitySummary | null;+ /**+ * LocationID is this entity's own location, and is nil when Location was+ * inherited from an ancestor. It is named to match the locationId field+ * on EntityUpdate on purpose: a GET body PUT back verbatim keeps the+ * entity exactly where it was, rather than silently pinning an+ * inherited location or dropping an explicit one.+ */+ locationId?: string | null;manufacturer: string;modelNumber: string;name: string;@@ -836,6 +853,7 @@ export interface EntityOut {export interface EntityPatch {entityTypeId?: string | null;id: string;+ locationId?: string | null;parentId?: string | null;quantity?: number | null;tagIds?: string[] | null;@@ -1015,6 +1033,13 @@ export interface EntityUpdate {insured: boolean;/** Warranty */lifetimeWarranty: boolean;+ /**+ * LocationID names the location this entity is stored in. It only+ * needs to be sent when ParentID refers to another item and the entity+ * lives somewhere other than that item's location (#1688); otherwise+ * ParentID alone carries the location. See resolveLocationOverride.+ */+ locationId?: string | null;manufacturer: string;modelNumber: string;/**@@ -1364,6 +1389,7 @@ export interface EntityTemplateCreateItemRequest {* precedence; when empty the repository falls back to the group's default.*/entityTypeId: string;+ locationId?: string | null;/*** @minLength 1* @maxLength 255diff --git a/frontend/pages/item/[id]/index/edit.vue b/frontend/pages/item/[id]/index/edit.vueindex 50396280..5362bcd8 100644--- a/frontend/pages/item/[id]/index/edit.vue+++ b/frontend/pages/item/[id]/index/edit.vue@@ -69,11 +69,14 @@parent.value = data.parent;}- // The "Location" selector shows the derived location (nearest ancestor+ // The "Location" selector shows the resolved location (nearest ancestor// that is a location-type entity), not the direct parent — when the item// sits inside another item, the parent is shown in "Parent Item" and the// location stays e.g. "Attic" (#1589).location.value = data.location ?? (data.parent?.entityType?.isLocation ? data.parent : null);+ // locationId is only set when the item has its own location, so it tells us+ // whether to keep sending it back or let the item follow its parent (#1688).+ locationExplicit.value = !!data.locationId;return data;});@@ -128,6 +131,9 @@// A selected parent item is the entity's real parent; otherwise the// item hangs directly off the chosen location.parentId: parent.value?.id || location.value?.id || null,+ // Only when it's inside another item and the user picked a location —+ // echoing back an inherited one would pin it (#1688).+ locationId: parent.value?.id && locationExplicit.value ? location.value?.id || null : null,tagIds: item.value.tagIds,assetId: item.value.assetId,purchasePrice,@@ -516,11 +522,14 @@const { query, results, isLoading, triggerSearch } = useItemSearch(api, { immediate: false });const parent = ref();- // Derived location shown in the "Location" selector. Kept separate from+ // Resolved location shown in the "Location" selector. Kept separate from// `parent` (the "Parent Item" selector): when a parent item is chosen it// becomes the entity's real parent, while this stays the location the item// ultimately lives in (#1589).const location = ref();+ // True when `location` is the user's own choice, not inherited. Only explicit+ // choices are written back, so nested items follow their parent by default.+ const locationExplicit = ref(false);async function keyboardSave(e: KeyboardEvent) {// Cmd + S@@ -545,10 +554,12 @@return;}- // The item now lives inside the parent item, so its location follows- // the parent's derived location — reflect that in the selector instead- // of showing the parent item itself as the "location" (#1589).- location.value = data.location ?? (data.parent?.entityType?.isLocation ? data.parent : null);+ // Show where it lands by default, i.e. the parent's location (#1589).+ // Leave a location the user picked alone — overwriting it here is what+ // made "child of X, stored in Y" impossible (#1688).+ if (!locationExplicit.value) {+ location.value = data.location ?? (data.parent?.entityType?.isLocation ? data.parent : null);+ }if (data.syncChildEntityLocations) {toast.info(t("items.toast.sync_child_location"));}@@ -556,12 +567,9 @@}function onLocationChanged() {- // Picking a location explicitly moves the item there: clear any selected- // parent item so the chosen location actually takes effect on save.- if (parent.value && parent.value.id) {- parent.value = null;- toast.info(t("items.toast.child_location_desync"));- }+ // Location says where the item is stored, not what it belongs to, so the+ // parent stays selected (#1688).+ locationExplicit.value = !!location.value?.id;}async function syncChildEntityLocations() {@@ -573,6 +581,7 @@const payload: EntityUpdate = {...item.value,parentId: parent.value?.id || location.value?.id || null,+ locationId: parent.value?.id && locationExplicit.value ? location.value?.id || null : null,tagIds: item.value.tagIds,assetId: item.value.assetId,syncChildEntityLocations: item.value.syncChildEntityLocations,