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 (
"errors"
"net/http"
"strings"
"time"
"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 {
return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError)

View file

@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"net/http"
"strings"
"github.com/hay-kot/homebox/backend/internal/core/services"
"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 {
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")),
PageSize: queryIntOrNegativeOne(params.Get("pageSize")),
Search: params.Get("q"),
LocationIDs: queryUUIDList(params, "locations"),
LabelIDs: queryUUIDList(params, "labels"),
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 {
ctx := services.NewContext(r.Context())
items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GID, extractQuery(r))
if err != nil {
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
// @Summary imports items into the database
// @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.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/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.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate(), 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": {
"post": {
"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": {
"post": {
"security": [

View file

@ -1094,6 +1094,38 @@ paths:
summary: Update Maintenance Entry
tags:
- 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:
post:
parameters:

View file

@ -8,11 +8,34 @@ import (
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) {
aidStr := fmt.Sprintf("%06d", aid)
aidStr = fmt.Sprintf("%s-%s", aidStr[:3], aidStr[3:])
return []byte(fmt.Sprintf(`"%s"`, aidStr)), nil
}
func (aid *AssetID) UnmarshalJSON(d []byte) error {
@ -26,5 +49,4 @@ func (aid *AssetID) UnmarshalJSON(d []byte) error {
*aid = AssetID(aidInt)
return nil
}

View file

@ -2,6 +2,7 @@ package repo
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
@ -19,14 +20,21 @@ type ItemsRepository struct {
}
type (
FieldQuery struct {
Name string
Value string
}
ItemQuery struct {
Page int
PageSize int
Search string `json:"search"`
AssetID AssetID `json:"assetId"`
LocationIDs []uuid.UUID `json:"locationIds"`
LabelIDs []uuid.UUID `json:"labelIds"`
SortBy string `json:"sortBy"`
IncludeArchived bool `json:"includeArchived"`
Fields []FieldQuery
}
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)
if err != nil {
return PaginationResult[ItemSummary]{}, err
}
@ -473,8 +500,8 @@ func (e *ItemsRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID)
return err
}
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))).
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))).
SetName(data.Name).
SetDescription(data.Description).
SetLocationID(data.LocationID).
@ -587,3 +614,62 @@ func (e *ItemsRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data
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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func itemFactory() ItemCreate {
@ -273,3 +274,48 @@ func TestItemsRepository_Update(t *testing.T) {
assert.Equal(t, updateData.WarrantyDetails, got.WarrantyDetails)
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) {
return mapUserOutErr(e.db.User.Query().
Where(user.Email(email)).
Where(user.EmailEqualFold(email)).
WithGroup().
Only(ctx),
)

View file

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

View file

@ -4,7 +4,7 @@ import { Requests } from "~~/lib/requests";
import { useAuthStore } from "~~/stores/auth";
export type Observer = {
handler: (r: Response) => void;
handler: (r: Response, req?: RequestInit) => 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
// 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
ClearStores,
InvalidStores,
}
export type EventFn = () => void;
@ -15,7 +15,7 @@ export interface IEventBus {
class EventBus implements IEventBus {
private listeners: Record<EventTypes, Record<string, EventFn>> = {
[EventTypes.ClearStores]: {},
[EventTypes.InvalidStores]: {},
};
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 reLabel = /\/api\/v1\/labels\/.*/gm;
const rmLabelStoreObserver = defineObserver("labelStore", {
handler: r => {
if (r.status === 201 || r.url.match(reLabel)) {
handler: (resp, req) => {
if (isMutation(req?.method) && isSuccess(resp.status) && resp.url.match(reLabel)) {
labelStore.refresh();
}
console.debug("labelStore handler called by observer");
@ -195,18 +202,19 @@
const locationStore = useLocationStore();
const reLocation = /\/api\/v1\/locations\/.*/gm;
const rmLocationStoreObserver = defineObserver("locationStore", {
handler: r => {
if (r.status === 201 || r.url.match(reLocation)) {
handler: (resp, req) => {
if (isMutation(req?.method) && isSuccess(resp.status) && resp.url.match(reLocation)) {
locationStore.refreshChildren();
locationStore.refreshParents();
}
console.debug("locationStore handler called by observer");
},
});
const eventBus = useEventBus();
eventBus.on(
EventTypes.ClearStores,
EventTypes.InvalidStores,
() => {
labelStore.refresh();
locationStore.refreshChildren();
@ -218,7 +226,7 @@
onUnmounted(() => {
rmLabelStoreObserver();
rmLocationStoreObserver();
eventBus.off(EventTypes.ClearStores, "stores");
eventBus.off(EventTypes.InvalidStores, "stores");
});
const authStore = useAuthStore();

View file

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

View file

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

View file

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

View file

@ -1,5 +1,4 @@
<script setup lang="ts">
import { watchPostEffect } from "vue";
import { ItemSummary, LabelSummary, LocationOutCount } from "~~/lib/api/types/data-contracts";
import { useLabelStore } from "~~/stores/labels";
import { useLocationStore } from "~~/stores/locations";
@ -47,54 +46,6 @@
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 router = useRouter();
@ -122,6 +73,17 @@
queryParamsInitialized.value = true;
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
if (!qLab && !qLoc) {
search();
@ -147,75 +109,187 @@
const locIDs = computed(() => selectedLocations.value.map(l => l.id));
const labIDs = computed(() => selectedLabels.value.map(l => l.id));
watchPostEffect(() => {
if (!queryParamsInitialized.value) {
return;
function parseAssetIDString(d: string) {
d = d.replace(/"/g, "").replace(/-/g, "");
const aidInt = parseInt(d);
if (isNaN(aidInt)) {
return [-1, false];
}
router.push({
query: {
...router.currentRoute.value.query,
lab: labIDs.value,
},
});
return [aidInt, true];
}
const byAssetId = computed(() => query.value?.startsWith("#") || false);
const parsedAssetId = computed(() => {
if (!byAssetId.value) {
return "";
} else {
const [aid, valid] = parseAssetIDString(query.value.replace("#", ""));
if (!valid) {
return "Invalid Asset ID";
} else {
return aid;
}
}
});
watchPostEffect(() => {
if (!queryParamsInitialized.value) {
return;
const fieldTuples = ref<[string, string][]>([]);
const fieldValuesCache = ref<Record<string, string[]>>({});
const { data: allFields } = useAsyncData(async () => {
const { data, error } = await api.items.fields.getAll();
if (error) {
return [];
}
router.push({
query: {
...router.currentRoute.value.query,
loc: locIDs.value,
},
});
return data;
});
watchEffect(() => {
if (!advanced.value) {
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 = [];
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
// parameters have changed. If they have changed, the page is reset to 1.
const resetPageHash = computed(() => {
const map = {
q: query.value,
includeArchived: includeArchived.value,
async function search() {
if (searchLocked.value) {
return;
}
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,
labels: labIDs.value,
};
includeArchived: includeArchived.value,
page: page.value,
pageSize: pageSize.value,
fields,
});
return JSON.stringify(map);
});
if (error) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
watchDebounced(resetPageHash, resetPageSearch, { debounce: 250, maxWait: 1000 });
if (!data.items || data.items.length === 0) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
watchDebounced([page, pageSize], search, { debounce: 250, maxWait: 1000 });
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>
<template>
<BaseContainer class="mb-16">
<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">
<label class="ml-auto label cursor-pointer">
<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>
</div>
<BaseCard v-if="advanced" class="my-1 overflow-visible">
<template #title> Filters </template>
<template #title> Search Tips </template>
<template #subtitle>
Location and label filters use the 'OR' operation. If more than one is selected only one will be required for a
match
<ul class="mt-1 list-disc pl-6">
<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>
<div class="px-4 pb-4">
<FormMultiselect v-model="selectedLabels" label="Labels" :items="labels ?? []" />
<FormMultiselect v-model="selectedLocations" label="Locations" :items="locations ?? []" />
<form class="px-4 pb-4">
<div class="flex pb-2 pt-5">
<label class="label cursor-pointer mr-auto">
<input v-model="includeArchived" type="checkbox" class="toggle toggle-primary" />
@ -223,7 +297,46 @@
</label>
<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 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>
<section class="mt-10">
<BaseSectionHeader ref="itemsTitle"> Items </BaseSectionHeader>