Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(erp): match multi-word and untrimmed list searches (#1235)

layne-sygnet4bf6c7e53e52
diff --git a/apps/erp/app/components/SearchFilter.tsx b/apps/erp/app/components/SearchFilter.tsx
index 82d94764c1..b72af8e754 100644
--- a/apps/erp/app/components/SearchFilter.tsx
+++ b/apps/erp/app/components/SearchFilter.tsx
@@ -17,7 +17,7 @@ const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {
const [params, setParams] = useUrlParams();
const [query, setQuery] = useState(params.get(param) || "");
const debounceQuery = useDebounce((q: string) => {
- setParams({ [param]: q, offset: null, limit: null });
+ setParams({ [param]: q.trim(), offset: null, limit: null });
}, 500);
return (
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 2c3fb8a317..76b4790610 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -10,7 +10,7 @@ import { getNextSequence } from "~/modules/settings";
import type { StorageItem } from "~/types";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters, setSearchFilter } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getItemStorageUnitQuantities } from "../items/items.service";
import type {
@@ -288,11 +288,10 @@ export async function getInventoryItems(
}
);
- if (args?.search) {
- query = query.or(
- `name.ilike.%${args.search}%,readableIdWithRevision.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args?.search, [
+ "name",
+ "readableIdWithRevision"
+ ]);
query = setGenericQueryFilters(query, args, [
{ column: "readableIdWithRevision", ascending: true }
@@ -317,11 +316,10 @@ export async function getInventoryItemsCount(
.neq("itemTrackingType", "Non-Inventory")
.eq("companyId", companyId);
- if (args?.search) {
- query = query.or(
- `name.ilike.%${args.search}%,readableIdWithRevision.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args?.search, [
+ "name",
+ "readableIdWithRevision"
+ ]);
query = setGenericQueryFilters(query, args);
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 26ff165b89..eb431b5502 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -12,7 +12,7 @@ import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters, setSearchFilter } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type { nonConformancePriority } from "../quality/quality.models";
import type {
@@ -528,11 +528,13 @@ export async function getConsumables(
})
.eq("companyId", companyId);
- if (args.search) {
- query = query.or(
- `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%,supplierIds.ilike.%${args.search}%,mpn.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args.search, [
+ "readableIdWithRevision",
+ "name",
+ "description",
+ "supplierIds",
+ "mpn"
+ ]);
if (args.supplierId) {
query = query.contains("supplierIds", [args.supplierId]);
@@ -1223,11 +1225,13 @@ export async function getMaterials(
})
.or(`companyId.eq.${companyId},companyId.is.null`);
- if (args.search) {
- query = query.or(
- `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%,supplierIds.ilike.%${args.search}%,mpn.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args.search, [
+ "readableIdWithRevision",
+ "name",
+ "description",
+ "supplierIds",
+ "mpn"
+ ]);
if (args.supplierId) {
query = query.contains("supplierIds", [args.supplierId]);
@@ -1744,11 +1748,13 @@ export async function getParts(
})
.eq("companyId", companyId);
- if (args.search) {
- query = query.or(
- `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%,supplierIds.ilike.%${args.search}%,mpn.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args.search, [
+ "readableIdWithRevision",
+ "name",
+ "description",
+ "supplierIds",
+ "mpn"
+ ]);
if (args.supplierId) {
query = query.contains("supplierIds", [args.supplierId]);
@@ -1992,11 +1998,12 @@ export async function getServices(
})
.eq("companyId", companyId);
- if (args.search) {
- query = query.or(
- `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%,supplierIds.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args.search, [
+ "readableIdWithRevision",
+ "name",
+ "description",
+ "supplierIds"
+ ]);
if (args.group) {
query = query.eq("itemPostingGroupId", args.group);
@@ -2085,11 +2092,13 @@ export async function getTools(
})
.eq("companyId", companyId);
- if (args.search) {
- query = query.or(
- `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%,supplierIds.ilike.%${args.search}%,mpn.ilike.%${args.search}%`
- );
- }
+ query = setSearchFilter(query, args.search, [
+ "readableIdWithRevision",
+ "name",
+ "description",
+ "supplierIds",
+ "mpn"
+ ]);
if (args.supplierId) {
query = query.contains("supplierIds", [args.supplierId]);
diff --git a/apps/erp/app/utils/query.test.ts b/apps/erp/app/utils/query.test.ts
new file mode 100644
index 0000000000..b6f3f6245e
--- /dev/null
+++ b/apps/erp/app/utils/query.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it, vi } from "vitest";
+
+// @carbon/auth's barrel export pulls in @carbon/glossary, whose Lingui `msg`
+// macro isn't transformed under plain vitest (no lingui plugin configured for
+// apps/erp tests). Mock it the same way traceability.search.test.ts does -
+// getSearchTokens/setSearchFilter don't call badRequest or
+// parseNumberFromUrlParam, so the mock only needs to satisfy the import.
+vi.mock("@carbon/auth", () => ({
+ badRequest: vi.fn(),
+ parseNumberFromUrlParam: vi.fn()
+}));
+
+const { getSearchTokens, setSearchFilter } = await import("./query");
+
+describe("getSearchTokens", () => {
+ it("splits a multi-word search into tokens", () => {
+ expect(getSearchTokens("M8 Washer")).toEqual(["M8", "Washer"]);
+ });
+
+ it("trims and collapses surrounding and repeated whitespace", () => {
+ expect(getSearchTokens(" M8 Washer ")).toEqual(["M8", "Washer"]);
+ });
+
+ it("strips PostgREST-structural characters instead of splitting on them", () => {
+ expect(getSearchTokens("Washer, Flat (M8)")).toEqual([
+ "Washer",
+ "Flat",
+ "M8"
+ ]);
+ });
+
+ it("returns an empty array for a single word", () => {
+ expect(getSearchTokens("M8")).toEqual(["M8"]);
+ });
+
+ it("returns an empty array for whitespace-only input", () => {
+ expect(getSearchTokens(" ")).toEqual([]);
+ });
+});
+
+describe("setSearchFilter", () => {
+ const columns = ["name", "readableIdWithRevision"];
+
+ it("emits one ANDed .or() clause per token, in token order", () => {
+ const query = createQueryStub();
+
+ setSearchFilter(query, "M8 Washer", columns);
+
+ expect(query.or).toHaveBeenNthCalledWith(
+ 1,
+ "name.ilike.%M8%,readableIdWithRevision.ilike.%M8%"
+ );
+ expect(query.or).toHaveBeenNthCalledWith(
+ 2,
+ "name.ilike.%Washer%,readableIdWithRevision.ilike.%Washer%"
+ );
+ expect(query.or).toHaveBeenCalledTimes(2);
+ });
+
+ it("matches today's single-word behavior exactly", () => {
+ const query = createQueryStub();
+
+ setSearchFilter(query, "M8", columns);
+
+ expect(query.or).toHaveBeenCalledTimes(1);
+ expect(query.or).toHaveBeenCalledWith(
+ "name.ilike.%M8%,readableIdWithRevision.ilike.%M8%"
+ );
+ });
+
+ it("does not filter on null, empty, or whitespace-only search", () => {
+ for (const search of [null, "", " "]) {
+ const query = createQueryStub();
+
+ const result = setSearchFilter(query, search, columns);
+
+ expect(query.or).not.toHaveBeenCalled();
+ expect(result).toBe(query);
+ }
+ });
+});
+
+function createQueryStub() {
+ return {
+ or: vi.fn(function (this: unknown) {
+ return this;
+ })
+ };
+}
diff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.ts
index 883f55b44b..1bdb4e4c77 100644
--- a/apps/erp/app/utils/query.ts
+++ b/apps/erp/app/utils/query.ts
@@ -141,6 +141,40 @@ export function setGenericQueryFilters<
return query;
}
+export function getSearchTokens(search: string): string[] {
+ // Strip characters that are structural in a PostgREST `.or(...)` filter
+ // (comma separates conditions, parens group them) so the search value can't
+ // alter the filter shape.
+ return search
+ .replace(/[,()\\]/g, " ")
+ .split(/\s+/)
+ .filter(Boolean);
+}
+
+export function setSearchFilter<
+ T extends GenericSchema,
+ U extends Record<string, unknown>,
+ V
+>(
+ // @ts-expect-error TS2707 - TODO: fix type
+ query: PostgrestFilterBuilder<T, U, V>,
+ search: string | null | undefined,
+ columns: string[]
+ // @ts-expect-error TS2707 - TODO: fix type
+): PostgrestFilterBuilder<T, U, V> {
+ if (!search) return query;
+
+ // Each token must match at least one column, and all tokens must match, so
+ // "M8 washer" finds "Washer, Flat, M8". Chained `.or(...)` calls are ANDed.
+ for (const token of getSearchTokens(search)) {
+ query = query.or(
+ columns.map((column) => `${column}.ilike.%${token}%`).join(",")
+ );
+ }
+
+ return query;
+}
+
const getSafeNumber = (value: string) => {
const number = Number(value);
return Number.isNaN(number) ? value : number;
diff --git a/apps/mes/app/components/SearchFilter.tsx b/apps/mes/app/components/SearchFilter.tsx
index 37c2852a63..d98950c06d 100644
--- a/apps/mes/app/components/SearchFilter.tsx
+++ b/apps/mes/app/components/SearchFilter.tsx
@@ -17,7 +17,7 @@ const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {
const [params, setParams] = useUrlParams();
const [query, setQuery] = useState(params.get(param) || "");
const debounceQuery = useDebounce((q: string) => {
- setParams({ [param]: q });
+ setParams({ [param]: q.trim() });
}, 500);
return (