A continuation of HomeBox the inventory and organization system built for the Home User
fix: various bugs (#1596)
Matt98568a3342cc
diff --git a/backend/app/api/handlers/v1/controller.go b/backend/app/api/handlers/v1/controller.goindex 5e9ce30f..33d0dc39 100644--- a/backend/app/api/handlers/v1/controller.go+++ b/backend/app/api/handlers/v1/controller.go@@ -3,6 +3,8 @@ package v1import ("encoding/json"+ "errors"+ "fmt""net/http""time"@@ -15,10 +17,25 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/internal/sys/config"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate""github.com/olahol/melody")+// multipartFormError translates a ParseMultipartForm failure into a+// RequestError. A body that tripped the MaxBytesReader cap installed by the+// body-size middleware surfaces as 413 with an explicit message instead of a+// misleading 400 "failed to parse multipart form" (#1538).+func multipartFormError(err error) error {+ var maxBytesErr *http.MaxBytesError+ if errors.As(err, &maxBytesErr) {+ return validate.NewRequestError(+ fmt.Errorf("uploaded file exceeds the size limit of %d bytes", maxBytesErr.Limit),+ http.StatusRequestEntityTooLarge)+ }+ return validate.NewRequestError(errors.New("failed to parse multipart form"), http.StatusBadRequest)+}+type Results[T any] struct {Items []T `json:"items"`}diff --git a/backend/app/api/handlers/v1/v1_ctrl_entities.go b/backend/app/api/handlers/v1/v1_ctrl_entities.goindex a64d5c54..3b3959b7 100644--- a/backend/app/api/handlers/v1/v1_ctrl_entities.go+++ b/backend/app/api/handlers/v1/v1_ctrl_entities.go@@ -484,7 +484,7 @@ func (ctrl *V1Controller) HandleEntitiesImport() errchain.HandlerFunc {parseSpan.End()recordCtrlSpanError(span, err)log.Err(err).Msg("failed to parse multipart form")- return validate.NewRequestError(err, http.StatusInternalServerError)+ return multipartFormError(err)}file, _, err := r.FormFile("csv")diff --git a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.goindex dc80a2cf..bbbd17e7 100644--- a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go+++ b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go@@ -60,7 +60,7 @@ func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {parseSpan.End()recordCtrlSpanError(span, err)log.Err(err).Msg("failed to parse multipart form")- return validate.NewRequestError(errors.New("failed to parse multipart form"), http.StatusBadRequest)+ return multipartFormError(err)}errs := validate.NewFieldErrors()diff --git a/backend/app/api/handlers/v1/v1_ctrl_exports.go b/backend/app/api/handlers/v1/v1_ctrl_exports.goindex bf62bd59..29cc756a 100644--- a/backend/app/api/handlers/v1/v1_ctrl_exports.go+++ b/backend/app/api/handlers/v1/v1_ctrl_exports.go@@ -232,7 +232,7 @@ func (ctrl *V1Controller) HandleCollectionImport() errchain.HandlerFunc {// as the memory-vs-disk threshold so larger archives spool gracefully.if err := r.ParseMultipartForm(ctrl.maxParseMemory << 20); err != nil {log.Err(err).Msg("import: parse multipart")- return validate.NewRequestError(err, http.StatusBadRequest)+ return multipartFormError(err)}// Remove any spooled temp files the multipart parser may have created.// Registered before file.Close so the close (LIFO) runs first — ondiff --git a/backend/app/api/main.go b/backend/app/api/main.goindex c33fa025..202e2a8e 100644--- a/backend/app/api/main.go+++ b/backend/app/api/main.go@@ -236,6 +236,15 @@ func run(cfg *config.Config) error {})}+ // Flush and close the export service's cached publisher topics on exit+ // so buffered messages are not silently dropped.+ runner.AddFunc("export-topics-shutdown", func(ctx context.Context) error {+ <-ctx.Done()+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ return app.services.Exports.Shutdown(shutdownCtx)+ })+runner.AddFunc("server", func(ctx context.Context) error {httpserver := http.Server{Addr: fmt.Sprintf("%s:%s", cfg.Web.Host, cfg.Web.Port),diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.goindex 14753e1c..332ed531 100644--- a/backend/app/api/static/docs/docs.go+++ b/backend/app/api/static/docs/docs.go@@ -4775,6 +4775,19 @@ const docTemplate = `{"entityTypeId": {"type": "string"},+ "manufacturer": {+ "type": "string",+ "maxLength": 255,+ "x-nullable": true,+ "x-omitempty": true+ },+ "modelNumber": {+ "description": "Identifications — optional at create time; populated e.g. by the\nbarcode product-search import flow (#1578).",+ "type": "string",+ "maxLength": 255,+ "x-nullable": true,+ "x-omitempty": true+ },"name": {"type": "string","maxLength": 255,@@ -4905,6 +4918,16 @@ const docTemplate = `{"description": "Warranty","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.",+ "allOf": [+ {+ "$ref": "#/definitions/repo.EntitySummary"+ }+ ],+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.jsonindex b8f96667..c541111a 100644--- a/backend/app/api/static/docs/openapi-3.json+++ b/backend/app/api/static/docs/openapi-3.json@@ -5014,6 +5014,19 @@"entityTypeId": {"type": "string"},+ "manufacturer": {+ "type": "string",+ "maxLength": 255,+ "x-omitempty": true,+ "nullable": true+ },+ "modelNumber": {+ "description": "Identifications — optional at create time; populated e.g. by the\nbarcode product-search import flow (#1578).",+ "type": "string",+ "maxLength": 255,+ "x-omitempty": true,+ "nullable": true+ },"name": {"type": "string","maxLength": 255,@@ -5144,6 +5157,16 @@"description": "Warranty","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.",+ "allOf": [+ {+ "$ref": "#/components/schemas/repo.EntitySummary"+ }+ ],+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string"},diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yamlindex 8c7d8ac0..9b0ce92c 100644--- a/backend/app/api/static/docs/openapi-3.yaml+++ b/backend/app/api/static/docs/openapi-3.yaml@@ -3153,6 +3153,19 @@ components:maxLength: 1000entityTypeId:type: string+ manufacturer:+ type: string+ maxLength: 255+ x-omitempty: true+ nullable: true+ modelNumber:+ description: |-+ Identifications — optional at create time; populated e.g. by the+ barcode product-search import flow (#1578).+ type: string+ maxLength: 255+ x-omitempty: true+ nullable: truename:type: stringmaxLength: 255@@ -3242,6 +3255,16 @@ components:lifetimeWarranty:description: Warrantytype: boolean+ location:+ 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.+ allOf:+ - $ref: "#/components/schemas/repo.EntitySummary"+ x-omitempty: true+ nullable: truemanufacturer:type: stringmodelNumber:diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.jsonindex 5b4a2f3e..d14e5ec3 100644--- a/backend/app/api/static/docs/swagger.json+++ b/backend/app/api/static/docs/swagger.json@@ -4772,6 +4772,19 @@"entityTypeId": {"type": "string"},+ "manufacturer": {+ "type": "string",+ "maxLength": 255,+ "x-nullable": true,+ "x-omitempty": true+ },+ "modelNumber": {+ "description": "Identifications — optional at create time; populated e.g. by the\nbarcode product-search import flow (#1578).",+ "type": "string",+ "maxLength": 255,+ "x-nullable": true,+ "x-omitempty": true+ },"name": {"type": "string","maxLength": 255,@@ -4902,6 +4915,16 @@"description": "Warranty","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.",+ "allOf": [+ {+ "$ref": "#/definitions/repo.EntitySummary"+ }+ ],+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yamlindex 4e35a90e..883fd83a 100644--- a/backend/app/api/static/docs/swagger.yaml+++ b/backend/app/api/static/docs/swagger.yaml@@ -1100,6 +1100,19 @@ definitions:type: stringentityTypeId:type: string+ manufacturer:+ maxLength: 255+ type: string+ x-nullable: true+ x-omitempty: true+ modelNumber:+ description: |-+ Identifications — optional at create time; populated e.g. by the+ barcode product-search import flow (#1578).+ maxLength: 255+ type: string+ x-nullable: true+ x-omitempty: truename:maxLength: 255minLength: 1@@ -1191,6 +1204,16 @@ definitions:lifetimeWarranty:description: Warrantytype: boolean+ location:+ 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.+ x-nullable: true+ x-omitempty: truemanufacturer:type: stringmodelNumber:diff --git a/backend/internal/core/services/service_exports.go b/backend/internal/core/services/service_exports.goindex ac9cfda3..a5a91092 100644--- a/backend/internal/core/services/service_exports.go+++ b/backend/internal/core/services/service_exports.go@@ -11,6 +11,7 @@ import ("os""path""strings"+ "sync""time""github.com/google/uuid"@@ -203,6 +204,14 @@ type ExportService struct {storage config.StoragepubSubConn stringdialect string // "sqlite3" or "postgres"++ // topics caches the publisher topic per topic name so it is opened once+ // and reused for the lifetime of the process. Publishers must never call+ // Shutdown on these: the default mem:// driver returns a shared singleton+ // per URL, so shutting it down after one send permanently breaks every+ // later publish until restart (#1592).+ topicsMu sync.Mutex+ topics map[string]*pubsub.Topic}// Enqueue creates a pending Export row for gid and publishes a job to the@@ -538,17 +547,53 @@ func (s *ExportService) copyAttachmentBlobs(ctx context.Context, zw *zip.Writer,return nil}-// publishExportJob sends a message on the export topic.-func (s *ExportService) publishExportJob(ctx context.Context, gid, exportID uuid.UUID) error {- conn, err := utils.GenerateSubPubConn(s.pubSubConn, TopicCollectionExport)+// openTopic returns the long-lived publisher topic for name, opening and+// caching it on first use. The topic is reused across publishes and stays+// open for the process lifetime — see the topics field doc for why a+// per-publish Shutdown must not be reintroduced here.+func (s *ExportService) openTopic(ctx context.Context, name string) (*pubsub.Topic, error) {+ s.topicsMu.Lock()+ defer s.topicsMu.Unlock()+ if topic, ok := s.topics[name]; ok {+ return topic, nil+ }+ conn, err := utils.GenerateSubPubConn(s.pubSubConn, name)if err != nil {- return err+ return nil, err}topic, err := pubsub.OpenTopic(ctx, conn)+ if err != nil {+ return nil, err+ }+ if s.topics == nil {+ s.topics = make(map[string]*pubsub.Topic)+ }+ s.topics[name] = topic+ return topic, nil+}++// Shutdown flushes and closes every cached publisher topic. It is called+// once from the app's graceful-shutdown path; publishes after Shutdown+// would reopen topics, so it must only run at service teardown.+func (s *ExportService) Shutdown(ctx context.Context) error {+ s.topicsMu.Lock()+ defer s.topicsMu.Unlock()+ var errs []error+ for name, topic := range s.topics {+ if err := topic.Shutdown(ctx); err != nil {+ errs = append(errs, fmt.Errorf("shutdown topic %q: %w", name, err))+ }+ }+ s.topics = nil+ return errors.Join(errs...)+}++// publishExportJob sends a message on the export topic.+func (s *ExportService) publishExportJob(ctx context.Context, gid, exportID uuid.UUID) error {+ topic, err := s.openTopic(ctx, TopicCollectionExport)if err != nil {return err}- defer func() { _ = topic.Shutdown(ctx) }()return topic.Send(ctx, &pubsub.Message{Body: []byte("collection_export:" + exportID.String()),Metadata: map[string]string{@@ -563,15 +608,10 @@ func (s *ExportService) publishExportJob(ctx context.Context, gid, exportID uuid// storage at the row's artifact_path, unzips, restores into the group// identified by gid, then deletes the staged upload.func (s *ExportService) publishImportJob(ctx context.Context, gid, userID, importID uuid.UUID) error {- conn, err := utils.GenerateSubPubConn(s.pubSubConn, TopicCollectionImport)- if err != nil {- return err- }- topic, err := pubsub.OpenTopic(ctx, conn)+ topic, err := s.openTopic(ctx, TopicCollectionImport)if err != nil {return err}- defer func() { _ = topic.Shutdown(ctx) }()return topic.Send(ctx, &pubsub.Message{Body: []byte("collection_import:" + gid.String()),Metadata: map[string]string{diff --git a/backend/internal/core/services/service_exports_test.go b/backend/internal/core/services/service_exports_test.goindex b97560d9..97705bdb 100644--- a/backend/internal/core/services/service_exports_test.go+++ b/backend/internal/core/services/service_exports_test.go@@ -420,6 +420,22 @@ func TestIsGroupReadyForImport_BlocksUserCreatedRows(t *testing.T) {})}+// TestPublishJobsTopicReuse guards against #1592: the mem:// pubsub driver+// returns a shared singleton topic per URL, so the old per-publish Shutdown+// permanently broke every publish after the first ("pubsub: Topic has been+// Shutdown") until the process restarted. Publishing twice on each topic+// must succeed.+func TestPublishJobsTopicReuse(t *testing.T) {+ ctx := context.Background()++ for i := 1; i <= 2; i++ {+ require.NoError(t, tSvc.Exports.publishExportJob(ctx, uuid.New(), uuid.New()),+ "export publish attempt %d", i)+ require.NoError(t, tSvc.Exports.publishImportJob(ctx, uuid.New(), uuid.New(), uuid.New()),+ "import publish attempt %d", i)+ }+}+// copyBlobUnderTest reuses the export service's bucket plumbing to copy a// blob from one key to another in the same backing store. Used to "stage"// the just-produced export under the destination group's import prefix.diff --git a/backend/internal/data/repo/repo_entities.go b/backend/internal/data/repo/repo_entities.goindex 2f550010..e7c5b92e 100644--- a/backend/internal/data/repo/repo_entities.go+++ b/backend/internal/data/repo/repo_entities.go@@ -96,6 +96,11 @@ type (AssetID AssetID `json:"-"`EntityTypeID uuid.UUID `json:"entityTypeId"`+ // Identifications — optional at create time; populated e.g. by the+ // barcode product-search import flow (#1578).+ ModelNumber string `json:"modelNumber" validate:"max=255" extensions:"x-nullable,x-omitempty"`+ Manufacturer string `json:"manufacturer" validate:"max=255" extensions:"x-nullable,x-omitempty"`+// EdgesTagIDs []uuid.UUID `json:"tagIds"`}@@ -181,6 +186,11 @@ 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 *EntitySummary `json:"location,omitempty" extensions:"x-nullable,x-omitempty"`EntitySummaryAssetID AssetID `json:"assetId,string"`@@ -427,7 +437,7 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...prq = r.db.Entity.Query().Where(where...)}- out, err := mapEntityOutErr(q.+ e, err := q.WithFields().WithTag().WithParent(func(eq *ent.EntityQuery) {@@ -439,12 +449,27 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...preq.WithEntityType()}).WithAttachments().- Only(ctx),- )+ Only(ctx)if err != nil {recordSpanError(span, err)- return out, err+ return EntityOut{}, err}++ out := mapEntityOut(e)++ var client *ent.EntityClient+ if tx != nil {+ client = tx.Entity+ } else {+ client = r.db.Entity+ }+ loc, err := nearestLocationAncestor(ctx, client, e.Edges.Parent)+ if err != nil {+ recordSpanError(span, err)+ return EntityOut{}, err+ }+ out.Location = loc+span.SetAttributes(attribute.String("entity.id", out.ID.String()),attribute.Int("entity.fields.count", len(out.Fields)),@@ -455,6 +480,38 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...prreturn out, nil}+// maxAncestorDepth bounds the parent-chain walk in nearestLocationAncestor so+// a corrupted tree with a cycle can't spin forever.+const maxAncestorDepth = 64++// nearestLocationAncestor walks up the parent chain starting at start (an+// already-loaded direct parent, or nil) and returns the first ancestor whose+// entity type is a location. Returns nil when the chain runs out without+// hitting a location. start must have its EntityType edge loaded; ancestors+// above it are fetched one level at a time.+func nearestLocationAncestor(ctx context.Context, client *ent.EntityClient, start *ent.Entity) (*EntitySummary, error) {+ cur := start+ for depth := 0; cur != nil && depth < maxAncestorDepth; depth++ {+ if cur.Edges.EntityType != nil && cur.Edges.EntityType.IsLocation {+ s := mapEntitySummary(cur)+ return &s, nil+ }+ next, err := client.Query().+ Where(entity.ID(cur.ID)).+ QueryParent().+ WithEntityType().+ First(ctx)+ if err != nil {+ if ent.IsNotFound(err) {+ return nil, nil+ }+ return nil, err+ }+ cur = next+ }+ return nil, nil+}+func (r *EntityRepository) getOne(ctx context.Context, where ...predicate.Entity) (EntityOut, error) {return r.getOneTx(ctx, nil, where...)}@@ -971,6 +1028,9 @@ func validateQuantity(op string, quantity float64) error {if math.IsNaN(quantity) || math.IsInf(quantity, 0) {return fmt.Errorf("%s: invalid quantity: must be a finite number", op)}+ if quantity < 0 {+ return fmt.Errorf("%s: invalid quantity: must not be negative", op)+ }return nil}@@ -1015,6 +1075,8 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data EntitSetName(data.Name).SetQuantity(data.Quantity).SetDescription(data.Description).+ SetModelNumber(data.ModelNumber).+ SetManufacturer(data.Manufacturer).SetGroupID(gid).SetAssetID(int64(data.AssetID))@@ -1560,36 +1622,11 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, datq.ClearParent()}- if data.SyncChildEntityLocations {- syncCtx, syncSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.syncChildLocations")- children, err := r.db.Entity.Query().Where(entity.ID(data.ID)).QueryChildren().All(syncCtx)- if err != nil {- recordSpanError(syncSpan, err)- syncSpan.End()- recordSpanError(span, err)- return EntityOut{}, err- }-- syncSpan.SetAttributes(attribute.Int("children.count", len(children)))- updatedCount := 0- for _, child := range children {- if data.ParentID != uuid.Nil {- childParent, err := child.QueryParent().First(syncCtx)- if err != nil || childParent.ID != data.ParentID {- err = child.Update().SetParentID(data.ParentID).Exec(syncCtx)- if err != nil {- recordSpanError(syncSpan, err)- syncSpan.End()- recordSpanError(span, err)- return EntityOut{}, err- }- updatedCount++- }- }- }- syncSpan.SetAttributes(attribute.Int("children.updated.count", updatedCount))- syncSpan.End()- }+ // 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)._, execSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.exec")err = q.Exec(ctx)@@ -1763,57 +1800,6 @@ func patchSyncTags(ctx context.Context, tx *ent.Tx, gid, id uuid.UUID, want []uureturn nil}-// patchSyncChildLocations propagates a parent move down to children when the-// entity has SyncChildEntityLocations enabled. No-op when the flag is off.-func patchSyncChildLocations(ctx context.Context, tx *ent.Tx, gid, id, parentID uuid.UUID) error {- syncCtx, syncSpan := entityTracer().Start(ctx, "repo.EntityRepository.Patch.syncChildLocations")- defer syncSpan.End()-- entityEnt, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).Only(syncCtx)- if err != nil {- recordSpanError(syncSpan, err)- return err- }- syncSpan.SetAttributes(attribute.Bool("entity.sync_child_locations", entityEnt.SyncChildEntityLocations))- if !entityEnt.SyncChildEntityLocations {- return nil- }-- children, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).QueryChildren().All(syncCtx)- if err != nil {- recordSpanError(syncSpan, err)- return err- }- updatedCount := 0- for _, child := range children {- childParent, err := child.QueryParent().First(syncCtx)- switch {- case err == nil:- if childParent.ID == parentID {- continue- }- case ent.IsNotFound(err):- // Child has no parent yet — treat as "needs the new parent."- default:- // Any other error (transient DB failure, context cancel, etc.)- // must NOT be interpreted as "missing parent → reparent" — that- // would silently move rows on a network blip.- recordSpanError(syncSpan, err)- return err- }- if err := child.Update().SetParentID(parentID).Exec(syncCtx); err != nil {- recordSpanError(syncSpan, err)- return err- }- updatedCount++- }- syncSpan.SetAttributes(- attribute.Int("children.count", len(children)),- attribute.Int("children.updated.count", updatedCount),- )- return nil-}-func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data EntityPatch) error {ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.Patch",trace.WithAttributes(@@ -1904,12 +1890,8 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En}}- if data.ParentID != uuid.Nil {- if err := patchSyncChildLocations(ctx, tx, gid, id, data.ParentID); err != nil {- recordSpanError(span, err)- return err- }- }+ // A parent change deliberately leaves children alone: they stay attached+ // to this entity and follow it through the ancestor chain (#1591)._, commitSpan := entityTracer().Start(ctx, "repo.EntityRepository.Patch.commit")if err := tx.Commit(); err != nil {diff --git a/backend/internal/data/repo/repo_entities_test.go b/backend/internal/data/repo/repo_entities_test.goindex 8917f047..02c44150 100644--- a/backend/internal/data/repo/repo_entities_test.go+++ b/backend/internal/data/repo/repo_entities_test.go@@ -794,3 +794,153 @@ func TestEntityRepository_WipeInventory_OnlyItems(t *testing.T) {// Cleanup_ = tRepos.Tags.DeleteByGroup(context.Background(), tGroup.ID, tagObj.ID)}++// mustCreateEntity is a helper for the hierarchy tests below: creates an+// entity with the given type/parent and registers cleanup.+func mustCreateEntity(t *testing.T, name string, entityTypeID, parentID uuid.UUID) EntityOut {+ t.Helper()+ e, err := tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{+ Name: name,+ Description: "hierarchy test entity",+ EntityTypeID: entityTypeID,+ ParentID: parentID,+ })+ require.NoError(t, err)+ t.Cleanup(func() { _ = tRepos.Entities.Delete(context.Background(), e.ID) })+ return e+}++// TestEntityRepository_SyncChildLocations_KeepsChildrenAttached guards+// against #1591: updating a box that has SyncChildEntityLocations enabled+// (with or without a parent change) must NOT reparent the box's children to+// the box's own parent. Children stay attached to the box and follow it+// through the ancestor chain.+func TestEntityRepository_SyncChildLocations_KeepsChildrenAttached(t *testing.T) {+ ctx := context.Background()+ containerET := useContainerEntityType(t)+ itemET := useItemEntityType(t)++ // Location1 > Box1, Box2 > Box2.1 > Item1, Item2 (issue #1591 repro)+ loc1 := mustCreateEntity(t, "Location1", containerET.ID, uuid.Nil)+ box1 := mustCreateEntity(t, "Box1", itemET.ID, loc1.ID)+ box2 := mustCreateEntity(t, "Box2", itemET.ID, loc1.ID)+ box21 := mustCreateEntity(t, "Box2.1", itemET.ID, box2.ID)+ item1 := mustCreateEntity(t, "Item1", itemET.ID, box21.ID)+ item2 := mustCreateEntity(t, "Item2", itemET.ID, box21.ID)++ assertParent := func(childID, wantParent uuid.UUID, msg string) {+ t.Helper()+ out, err := tRepos.Entities.GetOne(ctx, childID)+ require.NoError(t, err)+ require.NotNil(t, out.Parent, msg)+ assert.Equal(t, wantParent, out.Parent.ID, msg)+ }++ update := EntityUpdate{+ ID: box21.ID,+ Name: box21.Name,+ Description: box21.Description,+ Quantity: 1,+ EntityTypeID: itemET.ID,+ SyncChildEntityLocations: true,+ ParentID: box2.ID,+ }++ // Plain save with sync ON and unchanged parent must not touch children.+ _, err := tRepos.Entities.UpdateByGroup(ctx, tGroup.ID, update)+ require.NoError(t, err)+ assertParent(item1.ID, box21.ID, "item1 must stay in box2.1 after plain save")+ assertParent(item2.ID, box21.ID, "item2 must stay in box2.1 after plain save")++ // Move Box2.1 from Box2 into Box1 — the issue's repro.+ update.ParentID = box1.ID+ _, err = tRepos.Entities.UpdateByGroup(ctx, tGroup.ID, update)+ require.NoError(t, err)+ assertParent(box21.ID, box1.ID, "box2.1 must move under box1")+ assertParent(item1.ID, box21.ID, "item1 must stay in box2.1 after move")+ assertParent(item2.ID, box21.ID, "item2 must stay in box2.1 after move")++ // Same guarantee for the Patch path.+ err = tRepos.Entities.Patch(ctx, tGroup.ID, box21.ID, EntityPatch{ID: box21.ID, ParentID: box2.ID})+ require.NoError(t, err)+ assertParent(box21.ID, box2.ID, "box2.1 must move back under box2 via patch")+ assertParent(item1.ID, box21.ID, "item1 must stay in box2.1 after patch")+ assertParent(item2.ID, box21.ID, "item2 must stay in box2.1 after patch")+}++// TestEntityRepository_GetOne_DerivedLocation covers the Location field used+// by the frontend to show where an item lives (#1589): the nearest ancestor+// whose entity type is a location, however deeply the item is nested.+func TestEntityRepository_GetOne_DerivedLocation(t *testing.T) {+ ctx := context.Background()+ containerET := useContainerEntityType(t)+ itemET := useItemEntityType(t)++ loc := mustCreateEntity(t, "Attic", containerET.ID, uuid.Nil)+ box := mustCreateEntity(t, "Testbox", itemET.ID, loc.ID)+ nested := mustCreateEntity(t, "Testbox2", itemET.ID, box.ID)+ direct := mustCreateEntity(t, "DirectItem", itemET.ID, loc.ID)++ out, err := tRepos.Entities.GetOne(ctx, nested.ID)+ require.NoError(t, err)+ require.NotNil(t, out.Location, "nested item must derive a location")+ assert.Equal(t, loc.ID, out.Location.ID, "nested item's location is the box's location")+ require.NotNil(t, out.Parent)+ assert.Equal(t, box.ID, out.Parent.ID, "parent stays the box itself")++ out, err = tRepos.Entities.GetOne(ctx, direct.ID)+ require.NoError(t, err)+ require.NotNil(t, out.Location)+ assert.Equal(t, loc.ID, out.Location.ID, "direct child's location is its parent")++ out, err = tRepos.Entities.GetOne(ctx, loc.ID)+ require.NoError(t, err)+ assert.Nil(t, out.Location, "top-level location has no derived location")+}++// TestEntityRepository_Create_WithManufacturerModel guards #1578: the barcode+// import flow creates items with manufacturer/model in the create payload.+func TestEntityRepository_Create_WithManufacturerModel(t *testing.T) {+ itemET := useItemEntityType(t)++ e, err := tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{+ Name: "Barcode Item",+ Description: "created via barcode import",+ EntityTypeID: itemET.ID,+ Manufacturer: "ACME",+ ModelNumber: "X-1000",+ })+ require.NoError(t, err)+ t.Cleanup(func() { _ = tRepos.Entities.Delete(context.Background(), e.ID) })++ assert.Equal(t, "ACME", e.Manufacturer)+ assert.Equal(t, "X-1000", e.ModelNumber)+}++// TestEntityRepository_RejectsNegativeQuantity guards #1231 across all+// quantity-accepting write paths.+func TestEntityRepository_RejectsNegativeQuantity(t *testing.T) {+ ctx := context.Background()+ itemET := useItemEntityType(t)++ _, err := tRepos.Entities.Create(ctx, tGroup.ID, EntityCreate{+ Name: "Negative",+ EntityTypeID: itemET.ID,+ Quantity: -1,+ })+ require.ErrorContains(t, err, "must not be negative")++ e := mustCreateEntity(t, "QuantityGuard", itemET.ID, uuid.Nil)++ _, err = tRepos.Entities.UpdateByGroup(ctx, tGroup.ID, EntityUpdate{+ ID: e.ID,+ Name: e.Name,+ EntityTypeID: itemET.ID,+ Quantity: -3,+ })+ require.ErrorContains(t, err, "must not be negative")++ negative := -2.0+ err = tRepos.Entities.Patch(ctx, tGroup.ID, e.ID, EntityPatch{ID: e.ID, Quantity: &negative})+ require.ErrorContains(t, err, "must not be negative")+}diff --git a/docs/public/api/openapi-3.0.json b/docs/public/api/openapi-3.0.jsonindex b8f96667..c541111a 100644--- a/docs/public/api/openapi-3.0.json+++ b/docs/public/api/openapi-3.0.json@@ -5014,6 +5014,19 @@"entityTypeId": {"type": "string"},+ "manufacturer": {+ "type": "string",+ "maxLength": 255,+ "x-omitempty": true,+ "nullable": true+ },+ "modelNumber": {+ "description": "Identifications — optional at create time; populated e.g. by the\nbarcode product-search import flow (#1578).",+ "type": "string",+ "maxLength": 255,+ "x-omitempty": true,+ "nullable": true+ },"name": {"type": "string","maxLength": 255,@@ -5144,6 +5157,16 @@"description": "Warranty","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.",+ "allOf": [+ {+ "$ref": "#/components/schemas/repo.EntitySummary"+ }+ ],+ "x-omitempty": true,+ "nullable": true+ },"manufacturer": {"type": "string"},diff --git a/docs/public/api/openapi-3.0.yaml b/docs/public/api/openapi-3.0.yamlindex 8c7d8ac0..9b0ce92c 100644--- a/docs/public/api/openapi-3.0.yaml+++ b/docs/public/api/openapi-3.0.yaml@@ -3153,6 +3153,19 @@ components:maxLength: 1000entityTypeId:type: string+ manufacturer:+ type: string+ maxLength: 255+ x-omitempty: true+ nullable: true+ modelNumber:+ description: |-+ Identifications — optional at create time; populated e.g. by the+ barcode product-search import flow (#1578).+ type: string+ maxLength: 255+ x-omitempty: true+ nullable: truename:type: stringmaxLength: 255@@ -3242,6 +3255,16 @@ components:lifetimeWarranty:description: Warrantytype: boolean+ location:+ 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.+ allOf:+ - $ref: "#/components/schemas/repo.EntitySummary"+ x-omitempty: true+ nullable: truemanufacturer:type: stringmodelNumber:diff --git a/docs/public/api/swagger-2.0.json b/docs/public/api/swagger-2.0.jsonindex 5b4a2f3e..d14e5ec3 100644--- a/docs/public/api/swagger-2.0.json+++ b/docs/public/api/swagger-2.0.json@@ -4772,6 +4772,19 @@"entityTypeId": {"type": "string"},+ "manufacturer": {+ "type": "string",+ "maxLength": 255,+ "x-nullable": true,+ "x-omitempty": true+ },+ "modelNumber": {+ "description": "Identifications — optional at create time; populated e.g. by the\nbarcode product-search import flow (#1578).",+ "type": "string",+ "maxLength": 255,+ "x-nullable": true,+ "x-omitempty": true+ },"name": {"type": "string","maxLength": 255,@@ -4902,6 +4915,16 @@"description": "Warranty","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.",+ "allOf": [+ {+ "$ref": "#/definitions/repo.EntitySummary"+ }+ ],+ "x-nullable": true,+ "x-omitempty": true+ },"manufacturer": {"type": "string"},diff --git a/docs/public/api/swagger-2.0.yaml b/docs/public/api/swagger-2.0.yamlindex 4e35a90e..883fd83a 100644--- a/docs/public/api/swagger-2.0.yaml+++ b/docs/public/api/swagger-2.0.yaml@@ -1100,6 +1100,19 @@ definitions:type: stringentityTypeId:type: string+ manufacturer:+ maxLength: 255+ type: string+ x-nullable: true+ x-omitempty: true+ modelNumber:+ description: |-+ Identifications — optional at create time; populated e.g. by the+ barcode product-search import flow (#1578).+ maxLength: 255+ type: string+ x-nullable: true+ x-omitempty: truename:maxLength: 255minLength: 1@@ -1191,6 +1204,16 @@ definitions:lifetimeWarranty:description: Warrantytype: boolean+ location:+ 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.+ x-nullable: true+ x-omitempty: truemanufacturer:type: stringmodelNumber:diff --git a/frontend/components/Entity/CreateModal.vue b/frontend/components/Entity/CreateModal.vueindex ba1b8641..52d537b9 100644--- a/frontend/components/Entity/CreateModal.vue+++ b/frontend/components/Entity/CreateModal.vue@@ -172,6 +172,7 @@"type="number"step="any"+ :min="0"/><FormTextAreav-model="form.description"@@ -373,6 +374,9 @@quantity: 1,description: "",color: "",+ // Populated by the barcode product-import flow; passed through on create (#1578).+ manufacturer: "",+ modelNumber: "",tags: [] as string[],photos: [] as PhotoPreview[],});@@ -541,6 +545,10 @@if (params.product) {form.name = params.product.item.name;form.description = params.product.item.description;+ // Carry the looked-up identifications into the create payload so the+ // created item isn't missing manufacturer/model (#1578).+ form.manufacturer = params.product.manufacturer ?? "";+ form.modelNumber = params.product.modelNumber ?? "";if (params.product.imageURL) {appendPhotos([@@ -552,10 +560,13 @@},]);}+ } else {+ // Restore last used template if available. Skipped for barcode+ // product imports: a template's defaults (name, quantity, …) would+ // clobber the just-looked-up product data, and the template create+ // endpoint has no way to carry manufacturer/model (#1578).+ await restoreLastTemplate();}-- // Restore last used template if available- await restoreLastTemplate();} else {selectedEntityType.value = entityTypes.value.find(t => t.isLocation) || null;}@@ -640,6 +651,8 @@name: form.name,quantity: form.quantity,description: form.description,+ manufacturer: form.manufacturer,+ modelNumber: form.modelNumber,tagIds: form.tags,entityTypeId: selectedEntityType.value?.id || "",};@@ -694,6 +707,8 @@form.quantity = 1;form.description = "";form.color = "";+ form.manufacturer = "";+ form.modelNumber = "";form.photos = [];form.tags = [];selectedTemplate.value = null;@@ -710,6 +725,11 @@} else {navigateTo(`/item/${data.id}`);}+ } else if (!selectedEntityType.value?.isLocation) {+ // "Create and Add Another" keeps the dialog open, so the open-dialog+ // callback (which normally restores the persisted template) never+ // fires — re-apply it here so the selection isn't cleared (#1489).+ await restoreLastTemplate();}}diff --git a/frontend/components/Form/MarkdownEditor.vue b/frontend/components/Form/MarkdownEditor.vueindex e18293f6..f9e6c601 100644--- a/frontend/components/Form/MarkdownEditor.vue+++ b/frontend/components/Form/MarkdownEditor.vue@@ -1,5 +1,6 @@<script setup lang="ts">import { ref, watch } from "vue";+ import { utf8Length } from "@/lib/utils";import Markdown from "@/components/global/Markdown.vue";import { Checkbox } from "@/components/ui/checkbox";import { Textarea } from "@/components/ui/textarea";@@ -39,7 +40,7 @@const isLengthInvalid = computed(() => {if (typeof local.value !== "string") return false;- const len = local.value.length;+ const len = utf8Length(local.value);const max = props.maxLength ?? -1;const min = props.minLength ?? -1;return (max !== -1 && len > max) || (min !== -1 && len < min);@@ -49,7 +50,7 @@if (typeof local.value !== "string") return "";const max = props.maxLength ?? -1;if (max !== -1) {- return `${local.value.length}/${max}`;+ return `${utf8Length(local.value)}/${max}`;}return "";});diff --git a/frontend/components/Form/TextArea.vue b/frontend/components/Form/TextArea.vueindex 59e2251b..e6f8d6e8 100644--- a/frontend/components/Form/TextArea.vue+++ b/frontend/components/Form/TextArea.vue@@ -36,6 +36,7 @@<script lang="ts" setup>import { computed } from "vue";+ import { utf8Length } from "@/lib/utils";import { Label } from "~/components/ui/label";import { Textarea } from "~/components/ui/textarea";@@ -73,7 +74,7 @@const isLengthInvalid = computed(() => {if (typeof value.value !== "string") return false;- const len = value.value.length;+ const len = utf8Length(value.value);const max = props.maxLength;const min = props.minLength;// invalid if max length exists and is exceeded OR min length exists and is not met@@ -84,7 +85,7 @@if (typeof value.value !== "string") return "";const max = props.maxLength;if (max !== -1) {- return `${value.value.length}/${max}`;+ return `${utf8Length(value.value)}/${max}`;}return "";});diff --git a/frontend/components/Form/TextField.vue b/frontend/components/Form/TextField.vueindex bb467dc3..5bb751fe 100644--- a/frontend/components/Form/TextField.vue+++ b/frontend/components/Form/TextField.vue@@ -67,6 +67,7 @@<script lang="ts" setup>import { useI18n } from "vue-i18n";+ import { utf8Length } from "@/lib/utils";import { Label } from "~/components/ui/label";import { Input } from "~/components/ui/input";@@ -188,8 +189,8 @@}return (- (props.maxLength !== -1 && value.value.length > props.maxLength) ||- (props.minLength !== -1 && value.value.length < props.minLength)+ (props.maxLength !== -1 && utf8Length(value.value) > props.maxLength) ||+ (props.minLength !== -1 && utf8Length(value.value) < props.minLength));});@@ -200,11 +201,11 @@if (props.maxLength !== -1) {const minText = props.minLength !== -1 ? ` (${t("components.form.min_length", { min: props.minLength })})` : "";- return `${value.value.length}/${props.maxLength}${minText}`;+ return `${utf8Length(value.value)}/${props.maxLength}${minText}`;}if (props.minLength !== -1) {- return `${value.value.length} (${t("components.form.min_length", { min: props.minLength })})`;+ return `${utf8Length(value.value)} (${t("components.form.min_length", { min: props.minLength })})`;}return "";diff --git a/frontend/components/global/PasswordScore.vue b/frontend/components/global/PasswordScore.vueindex a22d7c60..760f966e 100644--- a/frontend/components/global/PasswordScore.vue+++ b/frontend/components/global/PasswordScore.vue@@ -2,6 +2,9 @@<div class="py-4"><p class="text-sm">{{ $t("components.global.password_score.password_strength") }}: {{ message }}</p><Progress class="w-full" :model-value="score" />+ <p v-if="password && !isValid" class="mt-1 text-sm text-destructive">+ {{ $t("components.global.password_score.does_not_meet_requirement") }}+ </p></div></template>diff --git a/frontend/lib/api/__test__/user/items.test.ts b/frontend/lib/api/__test__/user/items.test.tsindex d3dfd9e1..456dcedf 100644--- a/frontend/lib/api/__test__/user/items.test.ts+++ b/frontend/lib/api/__test__/user/items.test.ts@@ -13,10 +13,18 @@ describe("user should be able to create an item and add an attachment", () => {* that can be used to delete the location from the backend server.*/async function useLocation(api: UserClient): Promise<[EntityOut, () => Promise<void>]> {+ // Locations must carry the group's location entity type; without an+ // entityTypeId the backend defaults new entities to the item type.+ const { response: typesResponse, data: entityTypes } = await api.entityTypes.getAll();+ expect(typesResponse.status).toBe(200);+ const locationType = entityTypes.find(t => t.isLocation);+ expect(locationType).toBeTruthy();+const { response, data } = await api.items.createLocation({parentId: null,name: `__test__.location.name_${increment}`,description: `__test__.location.description_${increment}`,+ entityTypeId: locationType!.id,});expect(response.status).toBe(201);increment++;@@ -251,13 +259,17 @@ describe("user should be able to create an item and add an attachment", () => {const { response: updateResponse } = await api.items.update(parent.id, itemUpdate);expect(updateResponse.status).toBe(200);+ // Children stay attached to the parent item (#1591) and derive their+ // location from the ancestor chain, so it follows the parent's location.const { response: child1FinalResponse, data: child1FinalData } = await api.items.get(child1Item.id);expect(child1FinalResponse.status).toBe(200);- expect(child1FinalData.parent?.id).toBe(parentLocation.id);+ expect(child1FinalData.parent?.id).toBe(parent.id);+ expect(child1FinalData.location?.id).toBe(parentLocation.id);const { response: child2FinalResponse, data: child2FinalData } = await api.items.get(child2Item.id);expect(child2FinalResponse.status).toBe(200);- expect(child2FinalData.parent?.id).toBe(parentLocation.id);+ expect(child2FinalData.parent?.id).toBe(parent.id);+ expect(child2FinalData.location?.id).toBe(parentLocation.id);parentCleanup();childsCleanup();diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.tsindex 3542cefc..3525f642 100644--- a/frontend/lib/api/types/data-contracts.ts+++ b/frontend/lib/api/types/data-contracts.ts@@ -745,6 +745,14 @@ export interface EntityCreate {/** @maxLength 1000 */description: string;entityTypeId: string;+ /** @maxLength 255 */+ manufacturer?: string | null;+ /**+ * Identifications — optional at create time; populated e.g. by the+ * barcode product-search import flow (#1578).+ * @maxLength 255+ */+ modelNumber?: string | null;/*** @minLength 1* @maxLength 255@@ -791,6 +799,13 @@ export interface EntityOut {itemCount: number;/** 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?: EntitySummary | null;manufacturer: string;modelNumber: string;name: string;diff --git a/frontend/lib/utils.ts b/frontend/lib/utils.tsindex d8473b3d..2e0b4178 100644--- a/frontend/lib/utils.ts+++ b/frontend/lib/utils.ts@@ -90,3 +90,14 @@ export function formatValueAsCsvField(value: unknown): string {// Wrap in double quotesreturn `"${str}"`;}++const utf8Encoder = new TextEncoder();++/**+ * Byte length of a string when UTF-8 encoded. The backend validates string+ * fields by byte length (ent MaxLen), so character counters must use this+ * rather than String.length to match what the server will accept.+ */+export function utf8Length(str: string): number {+ return utf8Encoder.encode(str).length;+}diff --git a/frontend/locales/en.json b/frontend/locales/en.jsonindex d88fe4dd..81d9e2f0 100644--- a/frontend/locales/en.json+++ b/frontend/locales/en.json@@ -173,7 +173,8 @@"qr_tooltip": "Show QR Code"},"password_score": {- "password_strength": "Password Strength"+ "password_strength": "Password Strength",+ "does_not_meet_requirement": "Doesn't meet password strength requirement"}},"entity": {@@ -645,10 +646,11 @@"asset_not_found": "Asset not found","attachment_deleted": "Attachment deleted","attachment_updated": "Attachment updated",+ "attachment_too_large": "Attachment is too large: it exceeds the server's upload size limit","attachment_uploaded": "Attachment uploaded","child_items_location_no_longer_synced": "Child items' locations will no longer be synced with this item.","child_items_location_synced": "Child items' locations have been synced with this item",- "child_location_desync": "Changing location will de-sync it from the parent's location",+ "child_location_desync": "Parent item cleared — the item now lives directly in the selected location","error_loading_parent_data": "Something went wrong trying to load parent data","failed_adjust_quantity": "Failed to adjust quantity","failed_delete_attachment": "Failed to delete attachment",diff --git a/frontend/pages/item/[id]/index/edit.vue b/frontend/pages/item/[id]/index/edit.vueindex 76a07ecb..1bc2424b 100644--- a/frontend/pages/item/[id]/index/edit.vue+++ b/frontend/pages/item/[id]/index/edit.vue@@ -69,6 +69,12 @@parent.value = data.parent;}+ // The "Location" selector shows the derived 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);+return data;});@@ -90,7 +96,7 @@const saving = ref(false);async function saveItem(redirect: boolean) {- if (!item.value.parent?.id && !parent.value?.id) {+ if (!location.value?.id && !parent.value?.id) {toast.error(t("items.toast.failed_save_no_location"));return;}@@ -119,7 +125,9 @@const payload: EntityUpdate = {...item.value,- parentId: parent.value?.id || item.value.parent?.id || null,+ // 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,tagIds: item.value.tagIds,assetId: item.value.assetId,purchasePrice,@@ -165,6 +173,7 @@type: "number";label: string;ref: NonNullableNumberKeys<EntityOut> | NonNullableStringKeys<EntityOut>;+ min?: number;};interface BoolFormField {@@ -193,6 +202,7 @@type: "number",label: "items.quantity",ref: "quantity",+ min: 0,},{type: "markdown",@@ -407,10 +417,10 @@return;}- const { data, error } = await api.items.attachments.add(itemId.value, files[0], files[0].name, type);+ const { data, error, status } = await api.items.attachments.add(itemId.value, files[0], files[0].name, type);if (error) {- toast.error(t("items.toast.failed_upload_attachment"));+ toast.error(status === 413 ? t("items.toast.attachment_too_large") : t("items.toast.failed_upload_attachment"));return;}@@ -506,6 +516,11 @@const { query, results, isLoading, triggerSearch } = useItemSearch(api, { immediate: false });const parent = ref();+ // Derived 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();async function keyboardSave(e: KeyboardEvent) {// Cmd + S@@ -530,37 +545,34 @@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);if (data.syncChildEntityLocations) {toast.info(t("items.toast.sync_child_location"));- item.value.parent = data.parent;}}}- async function informAboutDesyncingLocationFromParent() {+ 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) {- const { data, error } = await api.items.get(parent.value.id);-- if (error) {- toast.error(t("items.toast.error_loading_parent_data"));- return;- }-- if (data.syncChildEntityLocations) {- toast.info(t("items.toast.child_location_desync"));- }+ parent.value = null;+ toast.info(t("items.toast.child_location_desync"));}}async function syncChildEntityLocations() {- if (!item.value.parent?.id && !parent.value?.id) {+ if (!location.value?.id && !parent.value?.id) {toast.error(t("items.toast.failed_save_no_location"));return;}const payload: EntityUpdate = {...item.value,- parentId: parent.value?.id || item.value.parent?.id || null,+ parentId: parent.value?.id || location.value?.id || null,tagIds: item.value.tagIds,assetId: item.value.assetId,syncChildEntityLocations: item.value.syncChildEntityLocations,@@ -662,7 +674,7 @@<BaseCard class="overflow-visible"><template #title> {{ $t("items.edit_details") }} </template><div class="mb-6 grid gap-4 border-t px-5 pt-2 md:grid-cols-2">- <LocationSelector v-model="item.parent" @update:model-value="informAboutDesyncingLocationFromParent()" />+ <LocationSelector v-model="location" @update:model-value="onLocationChanged()" /><ItemSelectorv-model="parent"v-model:search="query"@@ -722,6 +734,7 @@v-model.number="item[field.ref]"type="number"step="any"+ :min="field.min":label="$t(field.label)"inline/>@@ -909,6 +922,7 @@v-model.number="item[field.ref]"type="number"step="any"+ :min="field.min":label="$t(field.label)"inline/>@@ -958,6 +972,7 @@v-model.number="item[field.ref]"type="number"step="any"+ :min="field.min":label="$t(field.label)"inline/>@@ -1007,6 +1022,7 @@v-model.number="item[field.ref]"type="number"step="any"+ :min="field.min":label="$t(field.label)"inline/>diff --git a/frontend/pages/location/[id]/index/edit.vue b/frontend/pages/location/[id]/index/edit.vueindex 3d56d381..bba0aa78 100644--- a/frontend/pages/location/[id]/index/edit.vue+++ b/frontend/pages/location/[id]/index/edit.vue@@ -209,10 +209,10 @@return;}- const { data, error } = await api.items.attachments.add(locationId.value, files[0], files[0].name, type);+ const { data, error, status } = await api.items.attachments.add(locationId.value, files[0], files[0].name, type);if (error) {- toast.error(t("items.toast.failed_upload_attachment"));+ toast.error(status === 413 ? t("items.toast.attachment_too_large") : t("items.toast.failed_upload_attachment"));return;}diff --git a/frontend/pages/reports/label-generator.vue b/frontend/pages/reports/label-generator.vueindex c454a393..75ea76ad 100644--- a/frontend/pages/reports/label-generator.vue+++ b/frontend/pages/reports/label-generator.vue@@ -225,7 +225,10 @@return route(`/qrcode`, { data: encodeURIComponent(data) });}- function getItem(n: number, item: { assetId: string; name: string; location: { name: string } } | null): LabelData {+ function getItem(+ n: number,+ item: { assetId: string; name: string; parent?: { name: string } | null } | null+ ): LabelData {// format n into - seperated string with leading zerosconst assetID = fmtAssetID(item?.assetId ?? n + 1);@@ -233,7 +236,10 @@url: getQRCodeUrl(assetID),assetID: item?.assetId ?? assetID,name: item?.name ?? labelBlankLine,- location: item?.location?.name ?? labelBlankLine,+ // Since the entities refactor an item's whereabouts is its parent+ // entity (a location or a container item) — the old `location` edge no+ // longer exists (#1574).+ location: item?.parent?.name ?? labelBlankLine,};}@@ -263,11 +269,10 @@const items: LabelData[] = [];for (let i = displayProperties.assetRange - 1; i < displayProperties.assetRangeMax - 1; i++) {const item = allFields?.value?.items?.[i];- if (item?.location) {- items.push(getItem(i, item as { assetId: string; location: { name: string }; name: string }));- } else {- items.push(getItem(i, null));- }+ // Real items render their own data; indices past the inventory render+ // as blank pre-printable labels. The old guard required the removed+ // `location` edge and thus blanked every label (#1574).+ items.push(getItem(i, item ?? null));}return items;});