mirror of
https://github.com/hay-kot/homebox.git
synced 2025-08-04 16:50:27 +00:00
expand query to support by Field and By AID search
This commit is contained in:
parent
6c2d1fd60f
commit
0e7535b610
5 changed files with 236 additions and 6 deletions
|
@ -4,6 +4,7 @@ import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||||
|
@ -29,18 +30,48 @@ func (ctrl *V1Controller) HandleItemsGetAll() server.HandlerFunc {
|
||||||
extractQuery := func(r *http.Request) repo.ItemQuery {
|
extractQuery := func(r *http.Request) repo.ItemQuery {
|
||||||
params := r.URL.Query()
|
params := r.URL.Query()
|
||||||
|
|
||||||
return repo.ItemQuery{
|
filterFieldItems := func(raw []string) []repo.FieldQuery {
|
||||||
|
var items []repo.FieldQuery
|
||||||
|
|
||||||
|
for _, v := range raw {
|
||||||
|
parts := strings.SplitN(v, "=", 2)
|
||||||
|
if len(parts) == 2 {
|
||||||
|
items = append(items, repo.FieldQuery{
|
||||||
|
Name: parts[0],
|
||||||
|
Value: parts[1],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
v := repo.ItemQuery{
|
||||||
Page: queryIntOrNegativeOne(params.Get("page")),
|
Page: queryIntOrNegativeOne(params.Get("page")),
|
||||||
PageSize: queryIntOrNegativeOne(params.Get("pageSize")),
|
PageSize: queryIntOrNegativeOne(params.Get("pageSize")),
|
||||||
Search: params.Get("q"),
|
Search: params.Get("q"),
|
||||||
LocationIDs: queryUUIDList(params, "locations"),
|
LocationIDs: queryUUIDList(params, "locations"),
|
||||||
LabelIDs: queryUUIDList(params, "labels"),
|
LabelIDs: queryUUIDList(params, "labels"),
|
||||||
IncludeArchived: queryBool(params.Get("includeArchived")),
|
IncludeArchived: queryBool(params.Get("includeArchived")),
|
||||||
|
Fields: filterFieldItems(params["fields"]),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(v.Search, "#") {
|
||||||
|
aidStr := strings.TrimPrefix(v.Search, "#")
|
||||||
|
|
||||||
|
aid, ok := repo.ParseAssetID(aidStr)
|
||||||
|
if ok {
|
||||||
|
v.Search = ""
|
||||||
|
v.AssetID = aid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) error {
|
return func(w http.ResponseWriter, r *http.Request) error {
|
||||||
ctx := services.NewContext(r.Context())
|
ctx := services.NewContext(r.Context())
|
||||||
|
|
||||||
items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GID, extractQuery(r))
|
items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GID, extractQuery(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
@ -161,6 +192,48 @@ func (ctrl *V1Controller) handleItemsGeneral() server.HandlerFunc {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HandleGetAllCustomFieldNames godocs
|
||||||
|
// @Summary imports items into the database
|
||||||
|
// @Tags Items
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200
|
||||||
|
// @Router /v1/items/fields [GET]
|
||||||
|
// @Success 200 {object} []string
|
||||||
|
// @Security Bearer
|
||||||
|
func (ctrl *V1Controller) HandleGetAllCustomFieldNames() server.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
ctx := services.NewContext(r.Context())
|
||||||
|
|
||||||
|
v, err := ctrl.repo.Items.GetAllCustomFieldNames(r.Context(), ctx.GID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return server.Respond(w, http.StatusOK, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandleGetAllCustomFieldValues godocs
|
||||||
|
// @Summary imports items into the database
|
||||||
|
// @Tags Items
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200
|
||||||
|
// @Router /v1/items/fields/values [GET]
|
||||||
|
// @Success 200 {object} []string
|
||||||
|
// @Security Bearer
|
||||||
|
func (ctrl *V1Controller) HandleGetAllCustomFieldValues() server.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
ctx := services.NewContext(r.Context())
|
||||||
|
|
||||||
|
v, err := ctrl.repo.Items.GetAllCustomFieldValues(r.Context(), ctx.GID, r.URL.Query().Get("field"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return server.Respond(w, http.StatusOK, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// HandleItemsImport godocs
|
// HandleItemsImport godocs
|
||||||
// @Summary imports items into the database
|
// @Summary imports items into the database
|
||||||
// @Tags Items
|
// @Tags Items
|
||||||
|
|
|
@ -103,8 +103,11 @@ func (a *app) mountRoutes(repos *repo.AllRepos) {
|
||||||
a.server.Delete(v1Base("/labels/{id}"), v1Ctrl.HandleLabelDelete(), userMW...)
|
a.server.Delete(v1Base("/labels/{id}"), v1Ctrl.HandleLabelDelete(), userMW...)
|
||||||
|
|
||||||
a.server.Get(v1Base("/items"), v1Ctrl.HandleItemsGetAll(), userMW...)
|
a.server.Get(v1Base("/items"), v1Ctrl.HandleItemsGetAll(), userMW...)
|
||||||
a.server.Post(v1Base("/items/import"), v1Ctrl.HandleItemsImport(), userMW...)
|
|
||||||
a.server.Post(v1Base("/items"), v1Ctrl.HandleItemsCreate(), userMW...)
|
a.server.Post(v1Base("/items"), v1Ctrl.HandleItemsCreate(), userMW...)
|
||||||
|
a.server.Post(v1Base("/items/import"), v1Ctrl.HandleItemsImport(), userMW...)
|
||||||
|
a.server.Get(v1Base("/items/fields"), v1Ctrl.HandleGetAllCustomFieldNames(), userMW...)
|
||||||
|
a.server.Get(v1Base("/items/fields/values"), v1Ctrl.HandleGetAllCustomFieldValues(), userMW...)
|
||||||
|
|
||||||
a.server.Get(v1Base("/items/{id}"), v1Ctrl.HandleItemGet(), userMW...)
|
a.server.Get(v1Base("/items/{id}"), v1Ctrl.HandleItemGet(), userMW...)
|
||||||
a.server.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate(), userMW...)
|
a.server.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate(), userMW...)
|
||||||
a.server.Delete(v1Base("/items/{id}"), v1Ctrl.HandleItemDelete(), userMW...)
|
a.server.Delete(v1Base("/items/{id}"), v1Ctrl.HandleItemDelete(), userMW...)
|
||||||
|
|
|
@ -8,11 +8,34 @@ import (
|
||||||
|
|
||||||
type AssetID int
|
type AssetID int
|
||||||
|
|
||||||
|
func (aid AssetID) Nil() bool {
|
||||||
|
return aid.Int() <= 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (aid AssetID) Int() int {
|
||||||
|
return int(aid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseAssetIDBytes(d []byte) (AID AssetID, ok bool) {
|
||||||
|
d = bytes.Replace(d, []byte(`"`), []byte(``), -1)
|
||||||
|
d = bytes.Replace(d, []byte(`-`), []byte(``), -1)
|
||||||
|
|
||||||
|
aidInt, err := strconv.Atoi(string(d))
|
||||||
|
if err != nil {
|
||||||
|
return AssetID(-1), false
|
||||||
|
}
|
||||||
|
|
||||||
|
return AssetID(aidInt), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseAssetID(s string) (AID AssetID, ok bool) {
|
||||||
|
return ParseAssetIDBytes([]byte(s))
|
||||||
|
}
|
||||||
|
|
||||||
func (aid AssetID) MarshalJSON() ([]byte, error) {
|
func (aid AssetID) MarshalJSON() ([]byte, error) {
|
||||||
aidStr := fmt.Sprintf("%06d", aid)
|
aidStr := fmt.Sprintf("%06d", aid)
|
||||||
aidStr = fmt.Sprintf("%s-%s", aidStr[:3], aidStr[3:])
|
aidStr = fmt.Sprintf("%s-%s", aidStr[:3], aidStr[3:])
|
||||||
return []byte(fmt.Sprintf(`"%s"`, aidStr)), nil
|
return []byte(fmt.Sprintf(`"%s"`, aidStr)), nil
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (aid *AssetID) UnmarshalJSON(d []byte) error {
|
func (aid *AssetID) UnmarshalJSON(d []byte) error {
|
||||||
|
@ -26,5 +49,4 @@ func (aid *AssetID) UnmarshalJSON(d []byte) error {
|
||||||
|
|
||||||
*aid = AssetID(aidInt)
|
*aid = AssetID(aidInt)
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,6 +2,7 @@ package repo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
@ -19,14 +20,21 @@ type ItemsRepository struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type (
|
type (
|
||||||
|
FieldQuery struct {
|
||||||
|
Name string
|
||||||
|
Value string
|
||||||
|
}
|
||||||
|
|
||||||
ItemQuery struct {
|
ItemQuery struct {
|
||||||
Page int
|
Page int
|
||||||
PageSize int
|
PageSize int
|
||||||
Search string `json:"search"`
|
Search string `json:"search"`
|
||||||
|
AssetID AssetID `json:"assetId"`
|
||||||
LocationIDs []uuid.UUID `json:"locationIds"`
|
LocationIDs []uuid.UUID `json:"locationIds"`
|
||||||
LabelIDs []uuid.UUID `json:"labelIds"`
|
LabelIDs []uuid.UUID `json:"labelIds"`
|
||||||
SortBy string `json:"sortBy"`
|
SortBy string `json:"sortBy"`
|
||||||
IncludeArchived bool `json:"includeArchived"`
|
IncludeArchived bool `json:"includeArchived"`
|
||||||
|
Fields []FieldQuery
|
||||||
}
|
}
|
||||||
|
|
||||||
ItemField struct {
|
ItemField struct {
|
||||||
|
@ -326,7 +334,26 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !q.AssetID.Nil() {
|
||||||
|
qb = qb.Where(item.AssetID(q.AssetID.Int()))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(q.Fields) > 0 {
|
||||||
|
predicates := make([]predicate.Item, 0, len(q.Fields))
|
||||||
|
for _, f := range q.Fields {
|
||||||
|
predicates = append(predicates, item.HasFieldsWith(
|
||||||
|
itemfield.And(
|
||||||
|
itemfield.Name(f.Name),
|
||||||
|
itemfield.TextValue(f.Value),
|
||||||
|
),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
qb = qb.Where(item.Or(predicates...))
|
||||||
|
}
|
||||||
|
|
||||||
count, err := qb.Count(ctx)
|
count, err := qb.Count(ctx)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return PaginationResult[ItemSummary]{}, err
|
return PaginationResult[ItemSummary]{}, err
|
||||||
}
|
}
|
||||||
|
@ -473,8 +500,8 @@ func (e *ItemsRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *ItemsRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data ItemUpdate) (ItemOut, error) {
|
func (e *ItemsRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data ItemUpdate) (ItemOut, error) {
|
||||||
q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(gid))).
|
q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(GID))).
|
||||||
SetName(data.Name).
|
SetName(data.Name).
|
||||||
SetDescription(data.Description).
|
SetDescription(data.Description).
|
||||||
SetLocationID(data.LocationID).
|
SetLocationID(data.LocationID).
|
||||||
|
@ -587,3 +614,62 @@ func (e *ItemsRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data
|
||||||
|
|
||||||
return e.GetOne(ctx, data.ID)
|
return e.GetOne(ctx, data.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid.UUID, name string) ([]string, error) {
|
||||||
|
type st struct {
|
||||||
|
Value string `json:"text_value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var values []st
|
||||||
|
|
||||||
|
err := e.db.Item.Query().
|
||||||
|
Where(
|
||||||
|
item.HasGroupWith(group.ID(GID)),
|
||||||
|
).
|
||||||
|
QueryFields().
|
||||||
|
Where(
|
||||||
|
itemfield.Name(name),
|
||||||
|
).
|
||||||
|
Unique(true).
|
||||||
|
Select(itemfield.FieldTextValue).
|
||||||
|
Scan(ctx, &values)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get field values: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
valueStrings := make([]string, len(values))
|
||||||
|
for i, f := range values {
|
||||||
|
valueStrings[i] = f.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
return valueStrings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.UUID) ([]string, error) {
|
||||||
|
type st struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var fields []st
|
||||||
|
|
||||||
|
err := e.db.Debug().Item.Query().
|
||||||
|
Where(
|
||||||
|
item.HasGroupWith(group.ID(GID)),
|
||||||
|
).
|
||||||
|
QueryFields().
|
||||||
|
Unique(true).
|
||||||
|
Select(itemfield.FieldName).
|
||||||
|
Scan(ctx, &fields)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get custom fields: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldNames := make([]string, len(fields))
|
||||||
|
for i, f := range fields {
|
||||||
|
fieldNames[i] = f.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
return fieldNames, nil
|
||||||
|
}
|
||||||
|
|
|
@ -7,6 +7,7 @@ import (
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func itemFactory() ItemCreate {
|
func itemFactory() ItemCreate {
|
||||||
|
@ -273,3 +274,48 @@ func TestItemsRepository_Update(t *testing.T) {
|
||||||
assert.Equal(t, updateData.WarrantyDetails, got.WarrantyDetails)
|
assert.Equal(t, updateData.WarrantyDetails, got.WarrantyDetails)
|
||||||
assert.Equal(t, updateData.LifetimeWarranty, got.LifetimeWarranty)
|
assert.Equal(t, updateData.LifetimeWarranty, got.LifetimeWarranty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestItemRepository_GetAllCustomFields(t *testing.T) {
|
||||||
|
const FIELDS_COUNT = 5
|
||||||
|
|
||||||
|
entity := useItems(t, 1)[0]
|
||||||
|
|
||||||
|
fields := make([]ItemField, FIELDS_COUNT)
|
||||||
|
names := make([]string, FIELDS_COUNT)
|
||||||
|
values := make([]string, FIELDS_COUNT)
|
||||||
|
|
||||||
|
for i := 0; i < FIELDS_COUNT; i++ {
|
||||||
|
name := fk.Str(10)
|
||||||
|
fields[i] = ItemField{
|
||||||
|
Name: name,
|
||||||
|
Type: "text",
|
||||||
|
TextValue: fk.Str(10),
|
||||||
|
}
|
||||||
|
names[i] = name
|
||||||
|
values[i] = fields[i].TextValue
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := tRepos.Items.UpdateByGroup(context.Background(), tGroup.ID, ItemUpdate{
|
||||||
|
ID: entity.ID,
|
||||||
|
Name: entity.Name,
|
||||||
|
LocationID: entity.Location.ID,
|
||||||
|
Fields: fields,
|
||||||
|
})
|
||||||
|
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Test getting all fields
|
||||||
|
{
|
||||||
|
results, err := tRepos.Items.GetAllCustomFieldNames(context.Background(), tGroup.ID)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.ElementsMatch(t, names, results)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test getting all values from field
|
||||||
|
{
|
||||||
|
results, err := tRepos.Items.GetAllCustomFieldValues(context.Background(), tUser.GroupID, names[0])
|
||||||
|
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.ElementsMatch(t, values[:1], results)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue