feat: enhanced search functions (#260)

* make login case insensitive

* expand query to support by Field and By AID search

* type generation

* new API callers

* rework search to support field queries

* improve unnecessary data fetches

* clear stores on logout

* change verbage

* add labels
This commit is contained in:
Hayden 2023-02-05 12:12:54 -09:00 committed by GitHub
parent 7b28973c60
commit bd06fdafaf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 637 additions and 133 deletions

View file

@ -3,6 +3,7 @@ package v1
import ( import (
"errors" "errors"
"net/http" "net/http"
"strings"
"time" "time"
"github.com/hay-kot/homebox/backend/internal/core/services" "github.com/hay-kot/homebox/backend/internal/core/services"
@ -70,7 +71,7 @@ func (ctrl *V1Controller) HandleAuthLogin() server.HandlerFunc {
) )
} }
newToken, err := ctrl.svc.User.Login(r.Context(), loginForm.Username, loginForm.Password) newToken, err := ctrl.svc.User.Login(r.Context(), strings.ToLower(loginForm.Username), loginForm.Password)
if err != nil { if err != nil {
return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError) return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError)

View file

@ -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

View file

@ -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...)

View file

@ -383,6 +383,60 @@ const docTemplate = `{
} }
} }
}, },
"/v1/items/fields": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Items"
],
"summary": "imports items into the database",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/items/fields/values": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Items"
],
"summary": "imports items into the database",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/items/import": { "/v1/items/import": {
"post": { "post": {
"security": [ "security": [

View file

@ -375,6 +375,60 @@
} }
} }
}, },
"/v1/items/fields": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Items"
],
"summary": "imports items into the database",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/items/fields/values": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Items"
],
"summary": "imports items into the database",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/items/import": { "/v1/items/import": {
"post": { "post": {
"security": [ "security": [

View file

@ -1094,6 +1094,38 @@ paths:
summary: Update Maintenance Entry summary: Update Maintenance Entry
tags: tags:
- Maintenance - Maintenance
/v1/items/fields:
get:
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
type: string
type: array
security:
- Bearer: []
summary: imports items into the database
tags:
- Items
/v1/items/fields/values:
get:
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
type: string
type: array
security:
- Bearer: []
summary: imports items into the database
tags:
- Items
/v1/items/import: /v1/items/import:
post: post:
parameters: parameters:

View file

@ -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
} }

View file

@ -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
}

View file

@ -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)
}
}

View file

@ -69,7 +69,7 @@ func (e *UserRepository) GetOneId(ctx context.Context, id uuid.UUID) (UserOut, e
func (e *UserRepository) GetOneEmail(ctx context.Context, email string) (UserOut, error) { func (e *UserRepository) GetOneEmail(ctx context.Context, email string) (UserOut, error) {
return mapUserOutErr(e.db.User.Query(). return mapUserOutErr(e.db.User.Query().
Where(user.Email(email)). Where(user.EmailEqualFold(email)).
WithGroup(). WithGroup().
Only(ctx), Only(ctx),
) )

View file

@ -85,6 +85,6 @@
importRef.value.value = ""; importRef.value.value = "";
} }
eventBus.emit(EventTypes.ClearStores); eventBus.emit(EventTypes.InvalidStores);
} }
</script> </script>

View file

@ -4,7 +4,7 @@ import { Requests } from "~~/lib/requests";
import { useAuthStore } from "~~/stores/auth"; import { useAuthStore } from "~~/stores/auth";
export type Observer = { export type Observer = {
handler: (r: Response) => void; handler: (r: Response, req?: RequestInit) => void;
}; };
export type RemoveObserver = () => void; export type RemoveObserver = () => void;

View file

@ -2,7 +2,7 @@ export enum EventTypes {
// ClearStores event is used to inform the stores that _all_ the data they are using // ClearStores event is used to inform the stores that _all_ the data they are using
// is now out of date and they should refresh - This is used when the user makes large // is now out of date and they should refresh - This is used when the user makes large
// changes to the data such as bulk actions or importing a CSV file // changes to the data such as bulk actions or importing a CSV file
ClearStores, InvalidStores,
} }
export type EventFn = () => void; export type EventFn = () => void;
@ -15,7 +15,7 @@ export interface IEventBus {
class EventBus implements IEventBus { class EventBus implements IEventBus {
private listeners: Record<EventTypes, Record<string, EventFn>> = { private listeners: Record<EventTypes, Record<string, EventFn>> = {
[EventTypes.ClearStores]: {}, [EventTypes.InvalidStores]: {},
}; };
on(event: EventTypes, fn: EventFn, key: string): void { on(event: EventTypes, fn: EventFn, key: string): void {

View file

@ -181,11 +181,18 @@
}, },
]; ];
function isMutation(method: string | undefined) {
return method === "POST" || method === "PUT" || method === "DELETE";
}
function isSuccess(status: number) {
return status >= 200 && status < 300;
}
const labelStore = useLabelStore(); const labelStore = useLabelStore();
const reLabel = /\/api\/v1\/labels\/.*/gm; const reLabel = /\/api\/v1\/labels\/.*/gm;
const rmLabelStoreObserver = defineObserver("labelStore", { const rmLabelStoreObserver = defineObserver("labelStore", {
handler: r => { handler: (resp, req) => {
if (r.status === 201 || r.url.match(reLabel)) { if (isMutation(req?.method) && isSuccess(resp.status) && resp.url.match(reLabel)) {
labelStore.refresh(); labelStore.refresh();
} }
console.debug("labelStore handler called by observer"); console.debug("labelStore handler called by observer");
@ -195,18 +202,19 @@
const locationStore = useLocationStore(); const locationStore = useLocationStore();
const reLocation = /\/api\/v1\/locations\/.*/gm; const reLocation = /\/api\/v1\/locations\/.*/gm;
const rmLocationStoreObserver = defineObserver("locationStore", { const rmLocationStoreObserver = defineObserver("locationStore", {
handler: r => { handler: (resp, req) => {
if (r.status === 201 || r.url.match(reLocation)) { if (isMutation(req?.method) && isSuccess(resp.status) && resp.url.match(reLocation)) {
locationStore.refreshChildren(); locationStore.refreshChildren();
locationStore.refreshParents(); locationStore.refreshParents();
} }
console.debug("locationStore handler called by observer"); console.debug("locationStore handler called by observer");
}, },
}); });
const eventBus = useEventBus(); const eventBus = useEventBus();
eventBus.on( eventBus.on(
EventTypes.ClearStores, EventTypes.InvalidStores,
() => { () => {
labelStore.refresh(); labelStore.refresh();
locationStore.refreshChildren(); locationStore.refreshChildren();
@ -218,7 +226,7 @@
onUnmounted(() => { onUnmounted(() => {
rmLabelStoreObserver(); rmLabelStoreObserver();
rmLocationStoreObserver(); rmLocationStoreObserver();
eventBus.off(EventTypes.ClearStores, "stores"); eventBus.off(EventTypes.InvalidStores, "stores");
}); });
const authStore = useAuthStore(); const authStore = useAuthStore();

View file

@ -21,6 +21,7 @@ export type ItemsQuery = {
locations?: string[]; locations?: string[];
labels?: string[]; labels?: string[];
q?: string; q?: string;
fields?: string[];
}; };
export class AttachmentsAPI extends BaseAPI { export class AttachmentsAPI extends BaseAPI {
@ -48,6 +49,16 @@ export class AttachmentsAPI extends BaseAPI {
} }
} }
export class FieldsAPI extends BaseAPI {
getAll() {
return this.http.get<string[]>({ url: route("/items/fields") });
}
getAllValues(field: string) {
return this.http.get<string[]>({ url: route(`/items/fields/values`, { field }) });
}
}
export class MaintenanceAPI extends BaseAPI { export class MaintenanceAPI extends BaseAPI {
getLog(itemId: string) { getLog(itemId: string) {
return this.http.get<MaintenanceLog>({ url: route(`/items/${itemId}/maintenance`) }); return this.http.get<MaintenanceLog>({ url: route(`/items/${itemId}/maintenance`) });
@ -75,9 +86,11 @@ export class MaintenanceAPI extends BaseAPI {
export class ItemsApi extends BaseAPI { export class ItemsApi extends BaseAPI {
attachments: AttachmentsAPI; attachments: AttachmentsAPI;
maintenance: MaintenanceAPI; maintenance: MaintenanceAPI;
fields: FieldsAPI;
constructor(http: Requests, token: string) { constructor(http: Requests, token: string) {
super(http, token); super(http, token);
this.fields = new FieldsAPI(http);
this.attachments = new AttachmentsAPI(http); this.attachments = new AttachmentsAPI(http);
this.maintenance = new MaintenanceAPI(http); this.maintenance = new MaintenanceAPI(http);
} }

View file

@ -17,11 +17,11 @@ export interface DocumentOut {
} }
export interface Group { export interface Group {
createdAt: Date; createdAt: string;
currency: string; currency: string;
id: string; id: string;
name: string; name: string;
updatedAt: Date; updatedAt: string;
} }
export interface GroupStatistics { export interface GroupStatistics {
@ -39,11 +39,11 @@ export interface GroupUpdate {
} }
export interface ItemAttachment { export interface ItemAttachment {
createdAt: Date; createdAt: string;
document: DocumentOut; document: DocumentOut;
id: string; id: string;
type: string; type: string;
updatedAt: Date; updatedAt: string;
} }
export interface ItemAttachmentUpdate { export interface ItemAttachmentUpdate {
@ -76,7 +76,7 @@ export interface ItemOut {
assetId: string; assetId: string;
attachments: ItemAttachment[]; attachments: ItemAttachment[];
children: ItemSummary[]; children: ItemSummary[];
createdAt: Date; createdAt: string;
description: string; description: string;
fields: ItemField[]; fields: ItemField[];
id: string; id: string;
@ -103,16 +103,16 @@ export interface ItemOut {
/** @example "0" */ /** @example "0" */
soldPrice: string; soldPrice: string;
/** Sold */ /** Sold */
soldTime: Date; soldTime: string;
soldTo: string; soldTo: string;
updatedAt: Date; updatedAt: string;
warrantyDetails: string; warrantyDetails: string;
warrantyExpires: Date; warrantyExpires: string;
} }
export interface ItemSummary { export interface ItemSummary {
archived: boolean; archived: boolean;
createdAt: Date; createdAt: string;
description: string; description: string;
id: string; id: string;
insured: boolean; insured: boolean;
@ -123,7 +123,7 @@ export interface ItemSummary {
/** @example "0" */ /** @example "0" */
purchasePrice: string; purchasePrice: string;
quantity: number; quantity: number;
updatedAt: Date; updatedAt: string;
} }
export interface ItemUpdate { export interface ItemUpdate {
@ -156,10 +156,10 @@ export interface ItemUpdate {
/** @example "0" */ /** @example "0" */
soldPrice: string; soldPrice: string;
/** Sold */ /** Sold */
soldTime: Date; soldTime: string;
soldTo: string; soldTo: string;
warrantyDetails: string; warrantyDetails: string;
warrantyExpires: Date; warrantyExpires: string;
} }
export interface LabelCreate { export interface LabelCreate {
@ -169,20 +169,20 @@ export interface LabelCreate {
} }
export interface LabelOut { export interface LabelOut {
createdAt: Date; createdAt: string;
description: string; description: string;
id: string; id: string;
items: ItemSummary[]; items: ItemSummary[];
name: string; name: string;
updatedAt: Date; updatedAt: string;
} }
export interface LabelSummary { export interface LabelSummary {
createdAt: Date; createdAt: string;
description: string; description: string;
id: string; id: string;
name: string; name: string;
updatedAt: Date; updatedAt: string;
} }
export interface LocationCreate { export interface LocationCreate {
@ -193,30 +193,30 @@ export interface LocationCreate {
export interface LocationOut { export interface LocationOut {
children: LocationSummary[]; children: LocationSummary[];
createdAt: Date; createdAt: string;
description: string; description: string;
id: string; id: string;
items: ItemSummary[]; items: ItemSummary[];
name: string; name: string;
parent: LocationSummary; parent: LocationSummary;
updatedAt: Date; updatedAt: string;
} }
export interface LocationOutCount { export interface LocationOutCount {
createdAt: Date; createdAt: string;
description: string; description: string;
id: string; id: string;
itemCount: number; itemCount: number;
name: string; name: string;
updatedAt: Date; updatedAt: string;
} }
export interface LocationSummary { export interface LocationSummary {
createdAt: Date; createdAt: string;
description: string; description: string;
id: string; id: string;
name: string; name: string;
updatedAt: Date; updatedAt: string;
} }
export interface LocationUpdate { export interface LocationUpdate {

View file

@ -5,8 +5,7 @@ export enum Method {
DELETE = "DELETE", DELETE = "DELETE",
} }
export type RequestInterceptor = (r: Response) => void; export type ResponseInterceptor = (r: Response, rq?: RequestInit) => void;
export type ResponseInterceptor = (r: Response) => void;
export interface TResponse<T> { export interface TResponse<T> {
status: number; status: number;
@ -32,8 +31,8 @@ export class Requests {
this.responseInterceptors.push(interceptor); this.responseInterceptors.push(interceptor);
} }
private callResponseInterceptors(response: Response) { private callResponseInterceptors(response: Response, request?: RequestInit) {
this.responseInterceptors.forEach(i => i(response)); this.responseInterceptors.forEach(i => i(response, request));
} }
private url(rest: string): string { private url(rest: string): string {
@ -90,7 +89,7 @@ export class Requests {
} }
const response = await fetch(this.url(rargs.url), payload); const response = await fetch(this.url(rargs.url), payload);
this.callResponseInterceptors(response); this.callResponseInterceptors(response, payload);
const data: T = await (async () => { const data: T = await (async () => {
if (response.status === 204) { if (response.status === 204) {

View file

@ -1,5 +1,4 @@
<script setup lang="ts"> <script setup lang="ts">
import { watchPostEffect } from "vue";
import { ItemSummary, LabelSummary, LocationOutCount } from "~~/lib/api/types/data-contracts"; import { ItemSummary, LabelSummary, LocationOutCount } from "~~/lib/api/types/data-contracts";
import { useLabelStore } from "~~/stores/labels"; import { useLabelStore } from "~~/stores/labels";
import { useLocationStore } from "~~/stores/locations"; import { useLocationStore } from "~~/stores/locations";
@ -47,54 +46,6 @@
page.value = Math.min(Math.ceil(total.value / pageSize.value), page.value + 1); page.value = Math.min(Math.ceil(total.value / pageSize.value), page.value + 1);
} }
async function resetPageSearch() {
if (searchLocked.value) {
return;
}
if (!initialSearch.value) {
page.value = 1;
}
items.value = [];
await search();
}
async function search() {
if (searchLocked.value) {
return;
}
loading.value = true;
const { data, error } = await api.items.getAll({
q: query.value || "",
locations: locIDs.value,
labels: labIDs.value,
includeArchived: includeArchived.value,
page: page.value,
pageSize: pageSize.value,
});
if (error) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
if (!data.items || data.items.length === 0) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
total.value = data.total;
items.value = data.items;
loading.value = false;
initialSearch.value = false;
}
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
@ -122,6 +73,17 @@
queryParamsInitialized.value = true; queryParamsInitialized.value = true;
searchLocked.value = false; searchLocked.value = false;
const qFields = route.query.fields as string[];
if (qFields) {
fieldTuples.value = qFields.map(f => f.split("=") as [string, string]);
for (const t of fieldTuples.value) {
if (t[0] && t[1]) {
await fetchValues(t[0]);
}
}
}
// trigger search if no changes // trigger search if no changes
if (!qLab && !qLoc) { if (!qLab && !qLoc) {
search(); search();
@ -147,75 +109,187 @@
const locIDs = computed(() => selectedLocations.value.map(l => l.id)); const locIDs = computed(() => selectedLocations.value.map(l => l.id));
const labIDs = computed(() => selectedLabels.value.map(l => l.id)); const labIDs = computed(() => selectedLabels.value.map(l => l.id));
watchPostEffect(() => { function parseAssetIDString(d: string) {
if (!queryParamsInitialized.value) { d = d.replace(/"/g, "").replace(/-/g, "");
return;
const aidInt = parseInt(d);
if (isNaN(aidInt)) {
return [-1, false];
} }
router.push({ return [aidInt, true];
query: {
...router.currentRoute.value.query,
lab: labIDs.value,
},
});
});
watchPostEffect(() => {
if (!queryParamsInitialized.value) {
return;
} }
router.push({ const byAssetId = computed(() => query.value?.startsWith("#") || false);
query: { const parsedAssetId = computed(() => {
...router.currentRoute.value.query, if (!byAssetId.value) {
loc: locIDs.value, return "";
}, } else {
}); const [aid, valid] = parseAssetIDString(query.value.replace("#", ""));
if (!valid) {
return "Invalid Asset ID";
} else {
return aid;
}
}
}); });
watchEffect(() => { const fieldTuples = ref<[string, string][]>([]);
if (!advanced.value) { const fieldValuesCache = ref<Record<string, string[]>>({});
const { data: allFields } = useAsyncData(async () => {
const { data, error } = await api.items.fields.getAll();
if (error) {
return [];
}
return data;
});
async function fetchValues(field: string): Promise<string[]> {
if (fieldValuesCache.value[field]) {
return fieldValuesCache.value[field];
}
const { data, error } = await api.items.fields.getAllValues(field);
if (error) {
return [];
}
fieldValuesCache.value[field] = data;
return data;
}
watch(advanced, (v, lv) => {
if (v === false && lv === true) {
selectedLocations.value = []; selectedLocations.value = [];
selectedLabels.value = []; selectedLabels.value = [];
fieldTuples.value = [];
console.log("advanced", advanced.value);
router.push({
query: {
advanced: route.query.advanced,
q: query.value,
page: page.value,
pageSize: pageSize.value,
includeArchived: includeArchived.value ? "true" : "false",
},
});
} }
}); });
// resetPageHash computes a JSON string that is used to detect if the search async function search() {
// parameters have changed. If they have changed, the page is reset to 1. if (searchLocked.value) {
const resetPageHash = computed(() => { return;
const map = { }
q: query.value,
includeArchived: includeArchived.value, loading.value = true;
const fields = [];
for (const t of fieldTuples.value) {
if (t[0] && t[1]) {
fields.push(`${t[0]}=${t[1]}`);
}
}
const { data, error } = await api.items.getAll({
q: query.value || "",
locations: locIDs.value, locations: locIDs.value,
labels: labIDs.value, labels: labIDs.value,
}; includeArchived: includeArchived.value,
page: page.value,
return JSON.stringify(map); pageSize: pageSize.value,
fields,
}); });
watchDebounced(resetPageHash, resetPageSearch, { debounce: 250, maxWait: 1000 }); if (error) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
watchDebounced([page, pageSize], search, { debounce: 250, maxWait: 1000 }); if (!data.items || data.items.length === 0) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
total.value = data.total;
items.value = data.items;
loading.value = false;
initialSearch.value = false;
}
watchDebounced([page, pageSize, query, advanced], search, { debounce: 250, maxWait: 1000 });
async function submit() {
// Set URL Params
const fields = [];
for (const t of fieldTuples.value) {
if (t[0] && t[1]) {
fields.push(`${t[0]}=${t[1]}`);
}
}
// Push non-reactive query fields
await router.push({
query: {
// Reactive
advanced: "true",
includeArchived: includeArchived.value ? "true" : "false",
pageSize: pageSize.value,
page: page.value,
q: query.value,
// Non-reactive
loc: locIDs.value,
lab: labIDs.value,
fields,
},
});
// Reset Pagination
page.value = 1;
// Perform Search
await search();
}
</script> </script>
<template> <template>
<BaseContainer class="mb-16"> <BaseContainer class="mb-16">
<FormTextField v-model="query" placeholder="Search" /> <FormTextField v-model="query" placeholder="Search" />
<div class="text-sm pl-2 pt-2">
<p v-if="byAssetId">Querying Asset ID Number: {{ parsedAssetId }}</p>
</div>
<div class="flex mt-1"> <div class="flex mt-1">
<label class="ml-auto label cursor-pointer"> <label class="ml-auto label cursor-pointer">
<input v-model="advanced" type="checkbox" class="toggle toggle-primary" /> <input v-model="advanced" type="checkbox" class="toggle toggle-primary" />
<span class="label-text text-base-content ml-2"> Filters </span> <span class="label-text text-base-content ml-2"> Advanced Search </span>
</label> </label>
</div> </div>
<BaseCard v-if="advanced" class="my-1 overflow-visible"> <BaseCard v-if="advanced" class="my-1 overflow-visible">
<template #title> Filters </template> <template #title> Search Tips </template>
<template #subtitle> <template #subtitle>
Location and label filters use the 'OR' operation. If more than one is selected only one will be required for a <ul class="mt-1 list-disc pl-6">
match <li>
Location and label filters use the 'OR' operation. If more than one is selected only one will be required
for a match.
</li>
<li>Searches prefixed with '#'' will query for a asset ID (example '#000-001')</li>
<li>
Field filters use the 'OR' operation. If more than one is selected only one will be required for a match.
</li>
</ul>
</template> </template>
<div class="px-4 pb-4"> <form class="px-4 pb-4">
<FormMultiselect v-model="selectedLabels" label="Labels" :items="labels ?? []" />
<FormMultiselect v-model="selectedLocations" label="Locations" :items="locations ?? []" />
<div class="flex pb-2 pt-5"> <div class="flex pb-2 pt-5">
<label class="label cursor-pointer mr-auto"> <label class="label cursor-pointer mr-auto">
<input v-model="includeArchived" type="checkbox" class="toggle toggle-primary" /> <input v-model="includeArchived" type="checkbox" class="toggle toggle-primary" />
@ -223,7 +297,46 @@
</label> </label>
<Spacer /> <Spacer />
</div> </div>
<FormMultiselect v-model="selectedLabels" label="Labels" :items="labels ?? []" />
<FormMultiselect v-model="selectedLocations" label="Locations" :items="locations ?? []" />
<div class="py-4 space-y-2">
<p>Custom Fields</p>
<div v-for="(f, idx) in fieldTuples" :key="idx" class="flex flex-wrap gap-2">
<div class="form-control w-full max-w-xs">
<label class="label">
<span class="label-text">Field</span>
</label>
<select
v-model="fieldTuples[idx][0]"
class="select-bordered select"
:items="allFields ?? []"
@change="fetchValues(f[0])"
>
<option v-for="fv in allFields" :key="fv" :value="fv">{{ fv }}</option>
</select>
</div> </div>
<div class="form-control w-full max-w-xs">
<label class="label">
<span class="label-text">Field Value</span>
</label>
<select v-model="fieldTuples[idx][1]" class="select-bordered select" :items="fieldValuesCache[f[0]]">
<option v-for="v in fieldValuesCache[f[0]]" :key="v" :value="v">{{ v }}</option>
</select>
</div>
<button
type="button"
class="btn btn-square btn-sm md:ml-0 ml-auto mt-auto mb-2"
@click="fieldTuples.splice(idx, 1)"
>
<Icon name="mdi-trash" class="w-5 h-5" />
</button>
</div>
<BaseButton type="button" class="btn-sm mt-2" @click="() => fieldTuples.push(['', ''])"> Add</BaseButton>
</div>
<div class="flex justify-end gap-2">
<BaseButton @click.prevent="submit">Search</BaseButton>
</div>
</form>
</BaseCard> </BaseCard>
<section class="mt-10"> <section class="mt-10">
<BaseSectionHeader ref="itemsTitle"> Items </BaseSectionHeader> <BaseSectionHeader ref="itemsTitle"> Items </BaseSectionHeader>