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

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