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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Search Refactor (#428)
Brad Barbin57a44b64ed72
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsxindex d47b753d87..1e2e406ec9 100644--- a/apps/erp/app/components/CadModel.tsx+++ b/apps/erp/app/components/CadModel.tsx@@ -232,7 +232,7 @@ const CadModelUpload = ({><LuCloudUpload className="mx-auto h-12 w-12 text-muted-foreground group-hover:text-primary-foreground" /></div>- <p className="text-lg text-muted-foreground group-hover:text-foreground mt-8">+ <p className="text-base text-muted-foreground group-hover:text-foreground mt-8">Choose file to upload or drag and drop</p><p className="text-xs text-muted-foreground group-hover:text-foreground">diff --git a/apps/erp/app/components/Layout/Topbar/Search.tsx b/apps/erp/app/components/Layout/Topbar/Search.tsxindex c31a108143..2f331a572b 100644--- a/apps/erp/app/components/Layout/Topbar/Search.tsx+++ b/apps/erp/app/components/Layout/Topbar/Search.tsx@@ -1,10 +1,7 @@-import { useCarbon } from "@carbon/auth";-import type { Database } from "@carbon/database";import type { ShortcutDefinition } from "@carbon/react";import {Button,Command,- CommandEmpty,CommandGroup,CommandInput,CommandItem,@@ -15,30 +12,29 @@ import {ModalContent,ShortcutKey,useDebounce,- useMount,useShortcutKeys,VStack} from "@carbon/react";import idb from "localforage";import { nanoid } from "nanoid";-import { memo, useCallback, useEffect, useState } from "react";+import { memo, useEffect, useState } from "react";import {+ LuChevronRight,+ LuClock,+ LuDraftingCompass,LuFileCheck,LuHardHat,LuSearch,+ LuShieldX,LuShoppingCart,LuSquareUser,LuUser,- LuWrench+ LuX} from "react-icons/lu";import { PiShareNetworkFill } from "react-icons/pi";-import {- RiProgress2Line,- RiProgress4Line,- RiProgress8Line-} from "react-icons/ri";+import { RiProgress8Line } from "react-icons/ri";import { RxMagnifyingGlass } from "react-icons/rx";-import { useNavigate } from "react-router";+import { useFetcher, useNavigate } from "react-router";import { MethodItemTypeIcon } from "~/components/Icons";import { useModules, useUser } from "~/hooks";import useAccountSubmodules from "~/modules/account/ui/useAccountSubmodules";@@ -55,17 +51,16 @@ import useResourcesSubmodules from "~/modules/resources/ui/useResourcesSubmoduleimport useSalesSubmodules from "~/modules/sales/ui/useSalesSubmodules";import useSettingsSubmodules from "~/modules/settings/ui/useSettingsSubmodules";import useUsersSubmodules from "~/modules/users/ui/useUsersSubmodules";+import type { SearchResponse } from "~/routes/api+/search";import { useUIStore } from "~/stores/ui";import type { Authenticated, Route } from "~/types";+import { SearchEmptyState } from "./Search/SearchEmptyState";-type SearchResult = {- id: number;- name: string;- entity: Database["public"]["Enums"]["searchEntity"] | null;- uuid: string | null;- link: string;- description: string | null;+type RecentSearch = Route & {+ entityType?: string;+ module?: string;+ description?: string;};const shortcut: ShortcutDefinition = {@@ -74,19 +69,19 @@ const shortcut: ShortcutDefinition = {};const SearchModal = () => {- const { company } = useUser();- const { carbon } = useCarbon();const navigate = useNavigate();- const [loading, setLoading] = useState(false);+ const fetcher = useFetcher<SearchResponse>();const { isSearchModalOpen, closeSearchModal } = useUIStore();+ const { company } = useUser();+ const storageKey = `recentSearches_${company.id}`;const [input, setInput] = useState("");+ const [isDebouncing, setIsDebouncing] = useState(false);const debounceSearch = useDebounce((q: string) => {- if (q) {- getSearchResults(q);- } else {- setSearchResults([]);+ if (q && q.length >= 2) {+ fetcher.load(`/api/search?q=${encodeURIComponent(q)}`);}+ setIsDebouncing(false);}, 500);useEffect(() => {@@ -96,69 +91,89 @@ const SearchModal = () => {}, [isSearchModalOpen]);const staticResults = useGroupedSubmodules();+ const modules = useModules();- const [recentResults, setRecentResults] = useState<Route[]>([]);- useMount(async () => {- const recentResultsFromStorage =- await idb.getItem<Route[]>("recentSearches");- if (recentResultsFromStorage) {- setRecentResults(recentResultsFromStorage);- }- });-- const [searchResults, setSearchResults] = useState<SearchResult[]>([]);+ const getModuleIcon = (moduleName: string) => {+ const module = modules.find(+ (m) => m.name.toLowerCase() === moduleName.toLowerCase()+ );+ return module?.icon;+ };- const getSearchResults = useCallback(- async (q: string) => {- if (!carbon || !company.id) return;+ const [recentResults, setRecentResults] = useState<RecentSearch[]>([]);+ useEffect(() => {+ const loadRecentSearches = async () => {+ const recentResultsFromStorage =+ await idb.getItem<RecentSearch[]>(storageKey);+ if (recentResultsFromStorage) {+ setRecentResults(recentResultsFromStorage);+ } else {+ setRecentResults([]);+ }+ };+ loadRecentSearches();+ }, [storageKey]);- setLoading(true);- const tokens = q.split(" ");- const search =- tokens.length > 1- ? tokens.map((token) => `"${token}"`).join(" <-> ")- : q;+ const recentPaths = new Set(recentResults.map((r) => r.to));+ const searchResults = input.length >= 2 ? (fetcher.data?.results ?? []) : [];+ const loading = fetcher.state === "loading";- const result = await carbon- ?.from("search")- .select()- .textSearch("fts", `*${search}:*`)- .eq("companyId", company.id)- .limit(20);+ // Filter static results based on input for empty state detection+ const normalizedInput = input.toLowerCase().trim();+ const hasMatchingStaticResults =+ normalizedInput.length === 0 ||+ Object.entries(staticResults).some(([module, submodules]) =>+ submodules.some(+ (s) =>+ !recentPaths.has(s.to) &&+ `${module} ${s.name}`.toLowerCase().includes(normalizedInput)+ )+ );+ const hasMatchingRecentResults =+ normalizedInput.length === 0 ||+ recentResults.some((r) => r.name.toLowerCase().includes(normalizedInput));- if (result?.data) {- setSearchResults(result.data);- } else {- setSearchResults([]);- }- setLoading(false);- },- [company.id, carbon]- );+ const hasAnyResults =+ searchResults.length > 0 ||+ hasMatchingStaticResults ||+ hasMatchingRecentResults;const onInputChange = (value: string) => {setInput(value);- if (value) {- setLoading(true);- } else {- setLoading(false);+ if (value && value.length >= 2) {+ setIsDebouncing(true);}debounceSearch(value);};- const onSelect = async (route: Route) => {+ const onSelect = async (+ route: Route,+ entityType?: string,+ module?: string,+ description?: string+ ) => {const { to, name } = route;navigate(route.to);closeSearchModal();- const newRecentSearches = [- { to, name },- ...((await idb.getItem<Route[]>("recentSearches"))?.filter(+ const newRecentSearches: RecentSearch[] = [+ { to, name, entityType, module, description },+ ...((await idb.getItem<RecentSearch[]>(storageKey))?.filter((item) => item.to !== to) ?? [])].slice(0, 5);setRecentResults(newRecentSearches);- idb.setItem("recentSearches", newRecentSearches);+ idb.setItem(storageKey, newRecentSearches);+ };++ const removeRecentSearch = async (path: string, e: React.MouseEvent) => {+ e.stopPropagation();+ const existingRecent =+ (await idb.getItem<RecentSearch[]>(storageKey)) ?? [];+ const updated = existingRecent.filter((item) => item.to !== path);++ setRecentResults(updated);+ await idb.setItem(storageKey, updated);};return (@@ -170,125 +185,239 @@ const SearchModal = () => {}}><ModalContent- className="rounded-lg translate-y-0 p-0 h-[343px]"+ className="rounded-xl p-0 h-[520px] max-w-2xl overflow-hidden dark:shadow-button"withCloseButton={false}>- <Command>+ <Command className="h-full flex flex-col">+ {/* Search Input */}+<CommandInput- placeholder="Type a command or search..."+ placeholder="Search across your workspace..."value={input}onValueChange={onInputChange}+ className="h-14 text-base"/>- <CommandList>- <CommandEmpty key="empty">- {loading ? "Loading..." : "No results found."}- </CommandEmpty>- {recentResults.length > 0 && (- <>- <CommandGroup heading="Recent Searches" key="recent">- {recentResults.map((result, index) => (- <CommandItem- key={`${result.to}-${nanoid()}-${index}`}- onSelect={() => onSelect(result)}- // append with : so we're not sharing a value with a static result- value={`:${result.to}`}- >- <RxMagnifyingGlass className="w-4 h-4 flex-shrink-0 mr-2" />- {result.name}- </CommandItem>- ))}- </CommandGroup>- <CommandSeparator />- </>- )}- {Object.entries(staticResults).map(([module, submodules]) => (++ {/* Results */}+ <CommandList className="flex-1 max-h-none overflow-y-auto px-2 py-2">+ {loading || isDebouncing ? (+ <SearchEmptyState type="loading" />+ ) : !hasAnyResults ? (+ <SearchEmptyState type="no-results" query={input} />+ ) : (<>- <CommandGroup heading={module} key={`static-${module}`}>- {submodules.map((submodule, index) => (- <CommandItem- key={`${submodule.to}-${submodule.name}-${index}`}- onSelect={() => onSelect(submodule)}- value={`${module} ${submodule.name}`}+ {/* Recent Searches */}+ {recentResults.length > 0 && (+ <>+ <CommandGroup+ heading={+ <span className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground">+ <LuClock className="w-3 h-3" />+ Recent+ </span>+ }+ key="recent">- {submodule.icon && (- <submodule.icon className="w-4 h-4 flex-shrink-0 mr-2" />- )}- <span>{submodule.name}</span>- </CommandItem>- ))}- </CommandGroup>- <CommandSeparator />- </>- ))}- {searchResults.length > 0 && (- <CommandGroup heading="Search Results" key="search">- {searchResults.map((result) => (- <CommandItem- key={`${result.id}-${nanoid()}`}- value={`${input}${result.id}`}- onSelect={() =>- onSelect({- to: result.link,- name: result.name- })+ {recentResults.map((result, index) => {+ const ModuleIcon = result.module+ ? getModuleIcon(result.module)+ : undefined;+ return (+ <CommandItem+ key={`${result.to}-${nanoid()}-${index}`}+ onSelect={() =>+ onSelect(+ result,+ result.entityType,+ result.module,+ result.description+ )+ }+ value={`:${result.to}`}+ className="flex items-center gap-3 px-3 py-2.5 rounded-lg group"+ >+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-muted flex items-center justify-center">+ {result.entityType ? (+ <ResultIcon entityType={result.entityType} />+ ) : ModuleIcon ? (+ <ModuleIcon className="w-4 h-4 text-muted-foreground" />+ ) : (+ <RxMagnifyingGlass className="w-4 h-4 text-muted-foreground" />+ )}+ </div>+ <VStack spacing={0} className="flex-1 min-w-0">+ <span className="font-medium truncate">+ {result.name}+ </span>+ {result.description && (+ <span className="text-sm text-muted-foreground truncate">+ {result.description}+ </span>+ )}+ </VStack>+ <button+ type="button"+ onClick={(e) => removeRecentSearch(result.to, e)}+ className="flex-shrink-0 p-1 rounded hover:bg-muted opacity-0 group-hover:opacity-100 transition-opacity"+ >+ <LuX className="w-4 h-4 text-muted-foreground" />+ </button>+ </CommandItem>+ );+ })}+ </CommandGroup>+ <CommandSeparator className="my-2" />+ </>+ )}++ {/* Search Results */}+ {searchResults.length > 0 && (+ <CommandGroup+ heading={+ <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">+ Results+ </span>}+ key="search">- <HStack>- <ResultIcon entity={result.entity} />- <VStack spacing={0}>- <span>{result.name}</span>- {result.description && (- <span className="text-xs text-muted-foreground">- {result.description}+ {searchResults.map((result) => (+ <CommandItem+ key={`${result.id}-${nanoid()}`}+ value={`${input}${result.id}`}+ onSelect={() =>+ onSelect(+ {+ to: result.link,+ name: result.title+ },+ result.entityType,+ undefined,+ result.description+ )+ }+ className="flex items-center gap-3 px-3 py-3 rounded-lg group"+ >+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-muted flex items-center justify-center">+ <ResultIcon entityType={result.entityType} />+ </div>+ <VStack spacing={0} className="flex-1 min-w-0">+ <span className="font-medium text-foreground truncate">+ {result.title}</span>- )}- </VStack>- </HStack>- </CommandItem>- ))}- </CommandGroup>+ {result.description && (+ <span className="text-sm text-muted-foreground truncate">+ {result.description}+ </span>+ )}+ </VStack>+ <LuChevronRight className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />+ </CommandItem>+ ))}+ </CommandGroup>+ )}++ {/* Module Navigation */}+ {Object.entries(staticResults).map(([module, submodules]) => {+ const filteredSubmodules = submodules.filter(+ (s) => !recentPaths.has(s.to)+ );+ if (filteredSubmodules.length === 0) return null;+ return (+ <div key={`static-${module}`}>+ <CommandGroup+ heading={+ <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">+ {module}+ </span>+ }+ >+ {filteredSubmodules.map((submodule, index) => {+ const hasIconElement =+ "iconElement" in submodule && submodule.iconElement;+ return (+ <CommandItem+ key={`${submodule.to}-${submodule.name}-${index}`}+ onSelect={() =>+ onSelect(submodule, undefined, module)+ }+ value={`${module} ${submodule.name}`}+ className="flex items-center gap-3 px-3 py-2 rounded-lg group"+ >+ <div className="flex-shrink-0 w-7 h-7 rounded-md bg-muted/50 flex items-center justify-center text-muted-foreground [&>svg]:w-4 [&>svg]:h-4">+ {hasIconElement ? (+ submodule.iconElement+ ) : submodule.icon ? (+ <submodule.icon className="w-4 h-4" />+ ) : null}+ </div>+ <span className="flex-1 text-sm">+ {submodule.name}+ </span>+ <LuChevronRight className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />+ </CommandItem>+ );+ })}+ </CommandGroup>+ <CommandSeparator className="my-2" />+ </div>+ );+ })}+ </>)}</CommandList>++ {/* Footer */}+ <div className="border-t border-border px-4 py-2 flex items-center justify-between text-xs text-muted-foreground">+ <div className="flex items-center gap-3">+ <span className="flex items-center gap-1">+ <kbd className="px-1.5 py-0.5 rounded bg-muted font-mono text-[10px]">+ ↑↓+ </kbd>+ Navigate+ </span>+ <span className="flex items-center gap-1">+ <kbd className="px-1.5 py-0.5 rounded bg-muted font-mono text-[10px]">+ ↵+ </kbd>+ Select+ </span>+ <span className="flex items-center gap-1">+ <kbd className="px-1.5 py-0.5 rounded bg-muted font-mono text-[10px]">+ esc+ </kbd>+ Close+ </span>+ </div>+ </div></Command></ModalContent></Modal>);};-function ResultIcon({ entity }: { entity: SearchResult["entity"] | "Module" }) {- switch (entity) {- case "Customer":- return <LuSquareUser className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Document":- return <LuFileCheck className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Job":- return <LuHardHat className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Part":- case "Material":- case "Tool":- case "Consumable":- return (- <MethodItemTypeIcon- type={entity}- className="w-4 h-4 flex-shrink-0 mr-2"- />- );- case "Person":- return <LuUser className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Resource":- return <LuWrench className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Purchase Order":- return <LuShoppingCart className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Opportunity":- case "Lead":- case "Sales RFQ":- return <RiProgress2Line className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Quotation":- return <RiProgress4Line className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Sales Order":- return <RiProgress8Line className="w-4 h-4 flex-shrink-0 mr-2" />;- case "Supplier":- return <PiShareNetworkFill className="w-4 h-4 flex-shrink-0 mr-2" />;+function ResultIcon({ entityType }: { entityType: string }) {+ const iconClass = "w-4 h-4 text-muted-foreground";+ switch (entityType) {+ case "customer":+ return <LuSquareUser className={iconClass} />;+ case "employee":+ return <LuUser className={iconClass} />;+ case "gauge":+ return <LuDraftingCompass className={iconClass} />;+ case "job":+ return <LuHardHat className={iconClass} />;+ case "issue":+ return <LuShieldX className={iconClass} />;+ case "item":+ return <MethodItemTypeIcon type="Part" className={iconClass} />;+ case "purchaseOrder":+ return <LuShoppingCart className={iconClass} />;+ case "salesInvoice":+ return <RiProgress8Line className={iconClass} />;+ case "purchaseInvoice":+ return <LuFileCheck className={iconClass} />;+ case "supplier":+ return <PiShareNetworkFill className={iconClass} />;default:return null;}@@ -328,7 +457,6 @@ function useGroupedSubmodules() {const sales = useSalesSubmodules();const purchasing = usePurchasingSubmodules();const documents = useDocumentsSubmodules();- // const messages = useMessagesSidebar();const accounting = useAccountingSubmodules();const invoicing = useInvoicingSubmodules();const users = useUsersSubmodules();@@ -366,7 +494,9 @@ function useGroupedSubmodules() {"my account": account};- const shortcuts = modules.reduce<Record<string, Route[]>>((acc, module) => {+ const shortcuts = modules.reduce<+ Record<string, (Route & { iconElement?: React.ReactNode })[]>+ >((acc, module) => {const moduleName = module.name.toLowerCase();if (moduleName in groupedSubmodules) {@@ -377,7 +507,8 @@ function useGroupedSubmodules() {group.routes.map((route) => ({to: route.to,name: route.name,- icon: module.icon+ icon: module.icon,+ iconElement: route.icon})))};diff --git a/apps/erp/app/components/Layout/Topbar/Search/SearchEmptyState.tsx b/apps/erp/app/components/Layout/Topbar/Search/SearchEmptyState.tsxnew file mode 100644index 0000000000..22caf0228c--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Search/SearchEmptyState.tsx@@ -0,0 +1,61 @@+import { Skeleton } from "@carbon/react";+import { motion } from "framer-motion";+import { LuSearch } from "react-icons/lu";+import type { SearchEmptyStateProps } from "./types";++export function SearchEmptyState({ type, query }: SearchEmptyStateProps) {+ if (type === "loading") {+ return (+ <div className="px-3 py-2 space-y-2">+ {[1, 2, 3].map((i) => (+ <motion.div+ key={i}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ delay: i * 0.05 }}+ className="flex items-center gap-3 px-3 py-3"+ >+ <Skeleton className="w-9 h-9 rounded-lg flex-shrink-0" />+ <div className="flex-1 space-y-2">+ <Skeleton className="h-4 w-3/4" />+ <Skeleton className="h-3 w-1/2" />+ </div>+ </motion.div>+ ))}+ </div>+ );+ }++ if (type === "no-results") {+ return (+ <motion.div+ initial={{ opacity: 0, y: 4 }}+ animate={{ opacity: 1, y: 0 }}+ className="flex flex-col items-center justify-center py-12 px-4 text-center"+ >+ <div className="w-12 h-12 rounded-full bg-muted flex items-center justify-center mb-4">+ <LuSearch className="w-6 h-6 text-muted-foreground" />+ </div>+ <p className="text-sm font-medium text-foreground mb-1">+ No results found+ </p>+ <p className="text-sm text-muted-foreground">+ No matches for "{query}". Try a different search term.+ </p>+ </motion.div>+ );+ }++ // Initial state - shown before user starts typing+ return (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ className="flex flex-col items-center justify-center py-12 px-4 text-center"+ >+ <p className="text-sm text-muted-foreground">+ Type to search across your workspace+ </p>+ </motion.div>+ );+}diff --git a/apps/erp/app/components/Layout/Topbar/Search/SearchResultItem.tsx b/apps/erp/app/components/Layout/Topbar/Search/SearchResultItem.tsxnew file mode 100644index 0000000000..617892c1d0--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Search/SearchResultItem.tsx@@ -0,0 +1,84 @@+import { cn } from "@carbon/react";+import { LuChevronRight } from "react-icons/lu";+import { getEntityTypeConfig, getEntityTypeLabel } from "./config";+import type { SearchResultItemProps } from "./types";++export function SearchResultItem({+ result,+ onSelect,+ searchQuery+}: SearchResultItemProps) {+ const config = getEntityTypeConfig(result.entityType);+ const Icon = config.icon;+ const entityLabel = getEntityTypeLabel(result.entityType);++ return (+ <button+ type="button"+ onClick={onSelect}+ className={cn(+ "w-full flex items-center gap-3 px-3 py-3 rounded-lg text-left",+ "transition-colors duration-150",+ "hover:bg-accent focus:bg-accent focus:outline-none",+ "group cursor-pointer"+ )}+ >+ {/* Icon */}+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-muted flex items-center justify-center">+ {Icon && <Icon className="w-4 h-4 text-muted-foreground" />}+ </div>++ {/* Content */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-medium text-foreground truncate">+ <HighlightedText text={result.title} query={searchQuery} />+ </span>+ </div>+ {result.description && (+ <p className="text-sm text-muted-foreground truncate mt-0.5">+ {result.description}+ </p>+ )}+ </div>++ {/* Entity type label + chevron */}+ <div className="flex-shrink-0 flex items-center gap-2 text-muted-foreground">+ <span className="text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity">+ {entityLabel}+ </span>+ <LuChevronRight className="w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity" />+ </div>+ </button>+ );+}++// Helper to highlight matching text+function HighlightedText({ text, query }: { text: string; query?: string }) {+ if (!query || query.length < 2) {+ return <>{text}</>;+ }++ const parts = text.split(new RegExp(`(${escapeRegExp(query)})`, "gi"));++ return (+ <>+ {parts.map((part, i) =>+ part.toLowerCase() === query.toLowerCase() ? (+ <mark+ key={i}+ className="bg-yellow-200 dark:bg-yellow-900/50 text-inherit rounded-sm px-0.5"+ >+ {part}+ </mark>+ ) : (+ part+ )+ )}+ </>+ );+}++function escapeRegExp(string: string) {+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}diff --git a/apps/erp/app/components/Layout/Topbar/Search/config.ts b/apps/erp/app/components/Layout/Topbar/Search/config.tsnew file mode 100644index 0000000000..00808f5641--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Search/config.ts@@ -0,0 +1,96 @@+import type { IconType } from "react-icons";+import {+ LuFileCheck,+ LuGauge,+ LuHardHat,+ LuOctagonAlert,+ LuShoppingCart,+ LuSquareUser,+ LuUser,+ LuWrench+} from "react-icons/lu";+import { PiShareNetworkFill } from "react-icons/pi";+import { RiProgress8Line } from "react-icons/ri";++// Entity type styling configuration+export const entityTypeConfig: Record<+ string,+ { bgColor: string; textColor: string; icon: IconType }+> = {+ customer: {+ bgColor: "bg-blue-100 dark:bg-blue-900/30",+ textColor: "text-blue-600 dark:text-blue-400",+ icon: LuSquareUser+ },+ supplier: {+ bgColor: "bg-purple-100 dark:bg-purple-900/30",+ textColor: "text-purple-600 dark:text-purple-400",+ icon: PiShareNetworkFill+ },+ gauge: {+ bgColor: "",+ textColor: "",+ icon: LuGauge+ },+ issue: {+ bgColor: "",+ textColor: "",+ icon: LuOctagonAlert+ },+ item: {+ bgColor: "bg-emerald-100 dark:bg-emerald-900/30",+ textColor: "text-emerald-600 dark:text-emerald-400",+ icon: LuWrench+ },+ job: {+ bgColor: "bg-orange-100 dark:bg-orange-900/30",+ textColor: "text-orange-600 dark:text-orange-400",+ icon: LuHardHat+ },+ employee: {+ bgColor: "bg-cyan-100 dark:bg-cyan-900/30",+ textColor: "text-cyan-600 dark:text-cyan-400",+ icon: LuUser+ },+ purchaseOrder: {+ bgColor: "bg-yellow-100 dark:bg-yellow-900/30",+ textColor: "text-yellow-600 dark:text-yellow-400",+ icon: LuShoppingCart+ },+ salesInvoice: {+ bgColor: "bg-green-100 dark:bg-green-900/30",+ textColor: "text-green-600 dark:text-green-400",+ icon: RiProgress8Line+ },+ purchaseInvoice: {+ bgColor: "bg-red-100 dark:bg-red-900/30",+ textColor: "text-red-600 dark:text-red-400",+ icon: LuFileCheck+ }+};++export function getEntityTypeConfig(entityType: string) {+ return (+ entityTypeConfig[entityType] ?? {+ bgColor: "bg-muted",+ textColor: "text-muted-foreground",+ icon: null+ }+ );+}++export function getEntityTypeLabel(entityType: string): string {+ const labels: Record<string, string> = {+ customer: "Customer",+ supplier: "Supplier",+ gauge: "Gauge",+ issue: "Issue",+ item: "Item",+ job: "Job",+ employee: "Person",+ purchaseOrder: "Purchase Order",+ salesInvoice: "Sales Invoice",+ purchaseInvoice: "Purchase Invoice"+ };+ return labels[entityType] ?? entityType;+}diff --git a/apps/erp/app/components/Layout/Topbar/Search/index.ts b/apps/erp/app/components/Layout/Topbar/Search/index.tsnew file mode 100644index 0000000000..b887e3f9a3--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Search/index.ts@@ -0,0 +1,6 @@+export * from "./config";+export { SearchEmptyState } from "./SearchEmptyState";+export { SearchFilterChips } from "./SearchFilterChips";+export { SearchResultItem } from "./SearchResultItem";+export * from "./types";+export { useSearch } from "./useSearch";diff --git a/apps/erp/app/components/Layout/Topbar/Search/types.ts b/apps/erp/app/components/Layout/Topbar/Search/types.tsnew file mode 100644index 0000000000..1a6d1b0157--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Search/types.ts@@ -0,0 +1,62 @@+import type { IconType } from "react-icons";+import type { SearchResult } from "~/routes/api+/search";+import type { Route } from "~/types";++export type { SearchResult };++export type RecentSearch = Route & {+ entityType?: string;+ module?: string;+};++export type EntityType =+ | "customer"+ | "supplier"+ | "item"+ | "job"+ | "employee"+ | "purchaseOrder"+ | "salesInvoice"+ | "purchaseInvoice"+ | "equipmentType"+ | "workCellType";++export type EntityTypeFilter = "all" | EntityType;++export interface EntityTypeConfig {+ value: EntityTypeFilter;+ label: string;+ icon: IconType | null;+ bgColor: string;+ textColor: string;+}++export interface SearchResultItemProps {+ result: SearchResult;+ onSelect: () => void;+ searchQuery?: string;+}++export interface RecentSearchItemProps {+ result: RecentSearch;+ onSelect: () => void;+ onRemove: () => void;+ icon?: IconType;+}++export interface ModuleItemProps {+ name: string;+ to: string;+ icon?: IconType;+ onSelect: () => void;+}++export interface SearchFilterChipsProps {+ selectedFilter: EntityTypeFilter;+ onFilterChange: (filter: EntityTypeFilter) => void;+}++export interface SearchEmptyStateProps {+ type: "loading" | "no-results" | "initial";+ query?: string;+}diff --git a/apps/erp/app/components/Layout/Topbar/Search/useSearch.ts b/apps/erp/app/components/Layout/Topbar/Search/useSearch.tsnew file mode 100644index 0000000000..ee3117b7aa--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Search/useSearch.ts@@ -0,0 +1,138 @@+import { useDebounce } from "@carbon/react";+import idb from "localforage";+import { useCallback, useEffect, useState } from "react";+import { useFetcher, useNavigate } from "react-router";+import type { SearchResponse } from "~/routes/api+/search";+import type { RecentSearch, SearchResult } from "./types";++interface UseSearchOptions {+ companyId: string;+ onClose: () => void;+}++interface UseSearchReturn {+ input: string;+ setInput: (value: string) => void;+ isLoading: boolean;+ isDebouncing: boolean;+ searchResults: SearchResult[];+ recentSearches: RecentSearch[];+ onSelect: (+ route: { to: string; name: string },+ entityType?: string,+ module?: string+ ) => void;+ removeRecentSearch: (path: string) => void;+ resetInput: () => void;+}++export function useSearch({+ companyId,+ onClose+}: UseSearchOptions): UseSearchReturn {+ const navigate = useNavigate();+ const fetcher = useFetcher<SearchResponse>();+ const storageKey = `recentSearches_${companyId}`;++ const [input, setInputState] = useState("");+ const [isDebouncing, setIsDebouncing] = useState(false);+ const [recentSearches, setRecentSearches] = useState<RecentSearch[]>([]);++ const debounceSearch = useDebounce((q: string) => {+ if (q && q.length >= 2) {+ fetcher.load(`/api/search?q=${encodeURIComponent(q)}`);+ }+ setIsDebouncing(false);+ }, 500);++ // Load recent searches from IndexedDB+ useEffect(() => {+ const loadRecentSearches = async () => {+ const stored = await idb.getItem<RecentSearch[]>(storageKey);+ if (stored) {+ setRecentSearches(stored);+ } else {+ setRecentSearches([]);+ }+ };+ loadRecentSearches();+ }, [storageKey]);++ // Handle input changes with debounced search+ const setInput = useCallback(+ (value: string) => {+ setInputState(value);+ if (value && value.length >= 2) {+ setIsDebouncing(true);+ debounceSearch(value);+ }+ },+ [debounceSearch]+ );++ // Reset input without triggering search+ const resetInput = useCallback(() => {+ setInputState("");+ }, []);++ // Select a result and save to recent searches+ const onSelect = useCallback(+ async (+ route: { to: string; name: string },+ entityType?: string,+ module?: string+ ) => {+ navigate(route.to);+ onClose();++ const newRecent: RecentSearch = {+ to: route.to,+ name: route.name,+ entityType,+ module+ };++ const existingRecent =+ (await idb.getItem<RecentSearch[]>(storageKey)) ?? [];+ const filtered = existingRecent.filter((item) => item.to !== route.to);+ const updated = [newRecent, ...filtered].slice(0, 5);++ setRecentSearches(updated);+ await idb.setItem(storageKey, updated);+ },+ [navigate, onClose, storageKey]+ );++ // Remove a recent search+ const removeRecentSearch = useCallback(+ async (path: string) => {+ const existingRecent =+ (await idb.getItem<RecentSearch[]>(storageKey)) ?? [];+ const updated = existingRecent.filter((item) => item.to !== path);++ setRecentSearches(updated);+ await idb.setItem(storageKey, updated);+ },+ [storageKey]+ );++ // Filter out recent searches from API results+ const recentPaths = new Set(recentSearches.map((r) => r.to));+ const searchResults = (fetcher.data?.results ?? []).filter(+ (r) => !recentPaths.has(r.link)+ );++ const isLoading = fetcher.state === "loading";++ return {+ input,+ setInput,+ isLoading,+ isDebouncing,+ searchResults,+ recentSearches,+ onSelect,+ removeRecentSearch,+ resetInput+ };+}diff --git a/apps/erp/app/routes/api+/search.tsx b/apps/erp/app/routes/api+/search.tsxnew file mode 100644index 0000000000..2f40b1c056--- /dev/null+++ b/apps/erp/app/routes/api+/search.tsx@@ -0,0 +1,93 @@+import { getCarbonServiceRole } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getUserClaims } from "@carbon/auth/users.server";+import type { LoaderFunctionArgs } from "react-router";++// Map entity types to the permission module required to view them+const entityPermissionMap: Record<string, string> = {+ employee: "resources",+ customer: "sales",+ supplier: "purchasing",+ issue: "quality",+ gauge: "quality",+ item: "parts",+ job: "production",+ purchaseOrder: "purchasing",+ salesInvoice: "invoicing",+ purchaseInvoice: "invoicing"+};++export type SearchResult = {+ id: number;+ entityType: string;+ entityId: string;+ title: string;+ description: string | null;+ link: string;+ tags: string[];+ metadata: Record<string, unknown>;+};++export type SearchResponse = {+ results: SearchResult[];+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { companyId, userId } = await requirePermissions(request, {});++ const url = new URL(request.url);+ const query = url.searchParams.get("q")?.trim();+ const typeFilter = url.searchParams.get("type")?.trim();++ if (!query || query.length < 2) {+ return Response.json({ results: [] } satisfies SearchResponse);+ }++ // Get user's permissions to filter which entity types they can see+ const claims = await getUserClaims(userId, companyId);++ // Determine which entity types the user has permission to view+ let allowedEntityTypes = Object.entries(entityPermissionMap)+ .filter(([_, permissionModule]) => {+ const permission = claims.permissions[permissionModule];+ if (!permission) return false;+ // Check if user has view permission for this company+ return (+ permission.view.includes("0") || permission.view.includes(companyId)+ );+ })+ .map(([entityType]) => entityType);++ // Apply type filter if provided+ if (typeFilter && typeFilter !== "all") {+ allowedEntityTypes = allowedEntityTypes.filter((t) => t === typeFilter);+ }++ if (allowedEntityTypes.length === 0) {+ return Response.json({ results: [] } satisfies SearchResponse);+ }++ // Use service role to call the search function+ const serviceRole = getCarbonServiceRole();++ try {+ const { data, error } = await serviceRole.rpc("search_company_index", {+ p_company_id: companyId,+ p_query: query,+ p_entity_types: allowedEntityTypes,+ p_limit: 20+ });++ if (error) {+ console.error("Search error:", error);+ return Response.json({ results: [] } satisfies SearchResponse);+ }++ return Response.json({+ results: (data ?? []) as SearchResult[]+ } satisfies SearchResponse);+ } catch (err) {+ console.error("Search error:", err);+ return Response.json({ results: [] } satisfies SearchResponse);+ }+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 5092592172..d650651e38 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -143,6 +143,7 @@ export const path = {salesKpi: (key: string) => generatePath(`${api}/sales/kpi/${key}`),salesOrders: `${api}/sales/orders`,scrapReasons: `${api}/production/scrap-reasons`,+ search: `${api}/search`,seedQualityDocuments: `${api}/quality/documents/seed`,sequences: (table: string) => `${api}/settings/sequences?table=${table}`,serialNumbers: (itemId: string, isReadOnly: boolean) =>diff --git a/llm/cache/database-migration-patterns.md b/llm/cache/database-migration-patterns.mdindex 0307f485c8..b59b3920fb 100644--- a/llm/cache/database-migration-patterns.md+++ b/llm/cache/database-migration-patterns.md@@ -16,7 +16,7 @@ Most tables follow this pattern:```sqlCREATE TABLE "tableName" (- "id" TEXT NOT NULL DEFAULT xid(),+ "id" TEXT NOT NULL DEFAULT id('tbl'),-- other columns"companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,@@ -33,11 +33,13 @@ CREATE TABLE "tableName" (## 2. ID Generation-### XID Function+### ID Function-- Primary keys use `TEXT NOT NULL DEFAULT xid()` for globally unique IDs-- XID generates 20-character ordered IDs using a custom domain: `CREATE DOMAIN public.xid AS CHAR(20)`-- The xid() function combines timestamp, machine ID, process ID, and counter for uniqueness+- Primary keys use `TEXT NOT NULL DEFAULT id()` for globally unique IDs+- The `id()` function accepts an optional prefix parameter: `id('prefix')`+- Without a prefix, generates 20-character ordered IDs+- With a prefix, generates IDs in format: `prefix_<random>`+- Common prefixes include table abbreviations like `id('usr')`, `id('cmp')`, `id('inv')`### Composite Primary Keysdiff --git a/llm/recommendations/global-search-architecture.md b/llm/recommendations/global-search-architecture.mdnew file mode 100644index 0000000000..06b235c33e--- /dev/null+++ b/llm/recommendations/global-search-architecture.md@@ -0,0 +1,862 @@+# ERP Global Search Architecture++PostgreSQL Full-Text Search with Table-Per-Company Design++Technical Implementation Guide++January 2026++## Table of Contents++1. Executive Summary+2. Architecture Overview+3. Database Schema Design+4. Search Index Tables+5. Core SQL Functions+6. Entity Synchronization+7. Application Layer Implementation+8. REST API Design+9. Performance Optimization+10. Usage Examples+11. Maintenance & Operations++## 1. Executive Summary++This document outlines a comprehensive global search architecture for an ERP system using PostgreSQL's native full-text search capabilities combined with array-based tagging. The solution provides fast, scalable search across multiple entity types (invoices, items, purchases, jobs) with strong data isolation using a table-per-company approach.++Key Features:++| Feature | Description |+|------------------|--------------------------------------------------|+| Multi-Entity Search | Search across invoices, items, purchases, jobs, and more |+| Full-Text Search | Leverages PostgreSQL's tsvector and GIN indexes |+| Tag-Based Filtering | Array-based tags with efficient overlap operators |+| Data Isolation | Separate table per company for security and performance |+| Faceted Search | Filter by entity type with result counts |+| Real-Time Sync | Automatic index updates via database triggers |++## 2. Architecture Overview++The architecture follows a table-per-company design pattern where each company has its own dedicated search index table. This provides strong data isolation, improved query performance, and simplified data management.++### 2.1 Design Principles++- **Data Isolation**: Each company's search data is physically separated in its own table+- **Performance**: Smaller tables mean faster queries and more efficient indexes+- **Scalability**: Add new companies without impacting existing ones+- **Security**: Company data cannot accidentally leak across boundaries+- **Maintainability**: Can reindex, backup, or modify individual company data++### 2.2 Architecture Components++| Component | Purpose |+|-----------------|----------------------------------------------|+| Registry Table | Tracks all company search tables |+| Company Tables | Individual search indexes per company |+| Sync Functions | Automatically update search indexes |+| Search Functions| Dynamic queries across company tables |+| Triggers | Real-time synchronization from source entities |++## 3. Database Schema Design++### 3.1 Registry Table++The registry table maintains a catalog of all company search tables. It serves as the central directory for the search system.+```sql+CREATE TABLE "searchIndexRegistry" (+ "id" BIGSERIAL PRIMARY KEY,+ "companyId" TEXT UNIQUE NOT NULL,+ "tableName" TEXT UNIQUE NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "lastIndexedAt" TIMESTAMP WITH TIME ZONE,+ "rowCount" BIGINT DEFAULT 0,++ CONSTRAINT "searchIndexRegistry_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE+);++CREATE INDEX "searchIndexRegistry_companyId_idx"+ ON "searchIndexRegistry"("companyId");+```++### 3.2 Company Search Table Structure++Each company has its own search table with the following structure. Tables are created dynamically when a company is first registered.++```sql+CREATE TABLE "searchIndex_{companyId}" (+ "id" BIGSERIAL PRIMARY KEY,+ "entityType" TEXT NOT NULL,+ "entityId" TEXT NOT NULL,+ "title" TEXT NOT NULL,+ "description" TEXT,+ "searchVector" tsvector,+ "tags" TEXT[] DEFAULT '{}',+ "metadata" JSONB DEFAULT '{}',+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "searchIndex_{companyId}_entityType_entityId_key" UNIQUE ("entityType", "entityId")+);+```++Field Descriptions:++| Field | Type | Description |+|--------------|----------|------------------------------------------|+| entityType | TEXT | Type of entity (invoice, item, purchase, job) |+| entityId | TEXT | Unique identifier of the source entity |+| title | TEXT | Primary searchable text (weighted highest) |+| description | TEXT | Secondary searchable text |+| searchVector | tsvector | Full-text search index |+| tags | TEXT[] | Array of tags for filtering |+| metadata | JSONB | Additional structured data |++## 4. Search Index Tables++### 4.1 Index Creation++Each company search table has several indexes to optimize different query patterns:++```sql+-- GIN index for full-text search (most important)+CREATE INDEX "searchIndex_{companyId}_searchVector_idx"+ ON "searchIndex_{companyId}" USING GIN("searchVector");++-- GIN index for tag array operations+CREATE INDEX "searchIndex_{companyId}_tags_idx"+ ON "searchIndex_{companyId}" USING GIN("tags");++-- B-tree indexes for filtering+CREATE INDEX "searchIndex_{companyId}_entityType_idx"+ ON "searchIndex_{companyId}"("entityType");++CREATE INDEX "searchIndex_{companyId}_updatedAt_idx"+ ON "searchIndex_{companyId}"("updatedAt" DESC);++-- Composite index for lookups+CREATE INDEX "searchIndex_{companyId}_entityType_entityId_idx"+ ON "searchIndex_{companyId}"("entityType", "entityId");+```++### 4.2 Automatic Table Creation++The system automatically creates search tables for new companies using a function that handles all necessary setup including indexes and triggers:++```sql+CREATE OR REPLACE FUNCTION create_company_search_table(+ p_company_id TEXT+) RETURNS TEXT AS $$+DECLARE+ v_table_name TEXT;+ v_safe_company_id TEXT;+BEGIN+ -- Sanitize companyId for table name+ v_safe_company_id := regexp_replace(+ p_company_id, '[^a-zA-Z0-9]', '_', 'g'+ );+ v_table_name := 'searchIndex_' || v_safe_company_id;++ -- Create table, indexes, and triggers+ -- (Full implementation in source code)++ RETURN v_table_name;+END;+$$ LANGUAGE plpgsql;+```++## 5. Core SQL Functions++### 5.1 Global Search Function++The main search function dynamically queries the appropriate company table and returns ranked results:++```sql+CREATE OR REPLACE FUNCTION global_search(+ p_company_id TEXT,+ p_query TEXT,+ p_entity_types TEXT[] DEFAULT NULL,+ p_tags TEXT[] DEFAULT NULL,+ p_limit INT DEFAULT 20,+ p_offset INT DEFAULT 0+) RETURNS TABLE (+ "entityType" TEXT,+ "entityId" TEXT,+ "title" TEXT,+ "description" TEXT,+ "tags" TEXT[],+ "metadata" JSONB,+ "rank" REAL+) AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := get_search_table_name(p_company_id);++ RETURN QUERY EXECUTE format('+ SELECT "entityType", "entityId", "title", "description",+ "tags", "metadata",+ ts_rank("searchVector",+ websearch_to_tsquery(''english'', $1)) AS rank+ FROM %I+ WHERE "searchVector" @@ websearch_to_tsquery(''english'', $1)+ AND ($2::TEXT[] IS NULL OR "entityType" = ANY($2))+ AND ($3::TEXT[] IS NULL OR "tags" && $3)+ ORDER BY rank DESC, "updatedAt" DESC+ LIMIT $4 OFFSET $5+ ', v_table_name)+ USING p_query, p_entity_types, p_tags, p_limit, p_offset;+END;+$$ LANGUAGE plpgsql;+```++### 5.2 Tag Suggestion Function++Suggests relevant tags based on search query or shows all available tags:++```sql+CREATE OR REPLACE FUNCTION suggest_tags(+ p_company_id TEXT,+ p_query TEXT DEFAULT '',+ p_limit INT DEFAULT 10+) RETURNS TABLE ("tag" TEXT, "count" BIGINT) AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := get_search_table_name(p_company_id);++ IF p_query = '' THEN+ -- Return all tags with counts+ RETURN QUERY EXECUTE format('+ SELECT UNNEST("tags") AS tag, COUNT(*) AS count+ FROM %I+ GROUP BY tag+ ORDER BY count DESC+ LIMIT $1+ ', v_table_name) USING p_limit;+ ELSE+ -- Return tags from matching documents+ RETURN QUERY EXECUTE format('+ SELECT UNNEST("tags") AS tag, COUNT(*) AS count+ FROM %I+ WHERE "searchVector" @@+ websearch_to_tsquery(''english'', $1)+ GROUP BY tag+ ORDER BY count DESC+ LIMIT $2+ ', v_table_name) USING p_query, p_limit;+ END IF;+END;+$$ LANGUAGE plpgsql;+```++### 5.3 Faceted Search Function++Returns entity type counts for a given search query, enabling faceted filtering in the UI:++```sql+CREATE OR REPLACE FUNCTION get_search_facets(+ p_company_id TEXT,+ p_query TEXT+) RETURNS TABLE ("entityType" TEXT, "count" BIGINT) AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := get_search_table_name(p_company_id);++ RETURN QUERY EXECUTE format('+ SELECT "entityType", COUNT(*) as count+ FROM %I+ WHERE "searchVector" @@+ websearch_to_tsquery(''english'', $1)+ GROUP BY "entityType"+ ORDER BY count DESC+ ', v_table_name) USING p_query;+END;+$$ LANGUAGE plpgsql;+```++## 6. Entity Synchronization++### 6.1 Generic Sync Function++A generic function handles inserting or updating search index entries for any entity type:++```sql+CREATE OR REPLACE FUNCTION sync_to_company_search(+ p_company_id TEXT,+ p_entity_type TEXT,+ p_entity_id TEXT,+ p_title TEXT,+ p_description TEXT,+ p_tags TEXT[],+ p_metadata JSONB+) RETURNS VOID AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := get_search_table_name(p_company_id);++ EXECUTE format('+ INSERT INTO %I (+ "entityType", "entityId", "title",+ "description", "tags", "metadata"+ ) VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT ("entityType", "entityId")+ DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "updatedAt" = NOW()+ ', v_table_name)+ USING p_entity_type, p_entity_id, p_title,+ p_description, p_tags, p_metadata;+END;+$$ LANGUAGE plpgsql;+```++### 6.2 Entity-Specific Triggers++Each entity type (invoices, items, purchases, jobs) has its own trigger function that extracts relevant data and calls the generic sync function:++Invoice Sync Example:++```sql+CREATE OR REPLACE FUNCTION sync_invoice_to_search()+RETURNS TRIGGER AS $$+BEGIN+ IF (TG_OP = 'DELETE') THEN+ PERFORM delete_from_company_search(+ OLD."companyId", 'invoice', OLD."id"::TEXT+ );+ RETURN OLD;+ ELSE+ PERFORM sync_to_company_search(+ NEW."companyId",+ 'invoice',+ NEW."id"::TEXT,+ CONCAT('Invoice #', NEW."invoiceNumber"),+ CONCAT('Customer: ', NEW."customerName",+ ' Amount: ', NEW."totalAmount"),+ ARRAY[NEW."status", NEW."paymentStatus"] ||+ COALESCE(NEW."tags", '{}'),+ jsonb_build_object(+ 'invoiceNumber', NEW."invoiceNumber",+ 'totalAmount', NEW."totalAmount",+ 'customerName', NEW."customerName",+ 'dueDate', NEW."dueDate"+ )+ );+ RETURN NEW;+ END IF;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER "invoice_search_sync"+ AFTER INSERT OR UPDATE OR DELETE ON "invoice"+ FOR EACH ROW+ EXECUTE FUNCTION sync_invoice_to_search();+```++Item Sync Example:++```sql+CREATE OR REPLACE FUNCTION sync_item_to_search()+RETURNS TRIGGER AS $$+BEGIN+ IF (TG_OP = 'DELETE') THEN+ PERFORM delete_from_company_search(+ OLD."companyId", 'item', OLD."id"::TEXT+ );+ RETURN OLD;+ ELSE+ PERFORM sync_to_company_search(+ NEW."companyId",+ 'item',+ NEW."id"::TEXT,+ NEW."name",+ CONCAT('SKU: ', NEW."sku", ' Category: ', NEW."category"),+ ARRAY[NEW."category", NEW."itemType"] ||+ COALESCE(NEW."tags", '{}'),+ jsonb_build_object(+ 'sku', NEW."sku",+ 'category', NEW."category",+ 'price', NEW."price"+ )+ );+ RETURN NEW;+ END IF;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER "item_search_sync"+ AFTER INSERT OR UPDATE OR DELETE ON "part"+ FOR EACH ROW+ EXECUTE FUNCTION sync_item_to_search();+```++Note: Similar trigger functions should be created for purchases, jobs, and any other searchable entities in your ERP system.++## 7. Application Layer Implementation++### 7.1 TypeScript Service Class++A service class encapsulates all search functionality with type-safe interfaces:++```typescript+// TypeScript interfaces+interface SearchParams {+ query: string;+ companyId: string;+ entityTypes?: string[];+ tags?: string[];+ limit?: number;+ offset?: number;+}++interface SearchResult {+ entityType: string;+ entityId: string;+ title: string;+ description: string;+ tags: string[];+ metadata: Record;+ rank: number;+}++// Main service class+class GlobalSearchService {+ async search(params: SearchParams): Promise {+ const { query, companyId, entityTypes, tags,+ limit = 20, offset = 0 } = params;++ const result = await db.query(+ `SELECT * FROM global_search($1, $2, $3, $4, $5, $6)`,+ [companyId, query, entityTypes, tags, limit, offset]+ );++ return result.rows;+ }++ async searchWithFacets(params: SearchParams) {+ const [results, facets] = await Promise.all([+ this.search(params),+ this.getFacets(params.companyId, params.query)+ ]);++ return { results, facets };+ }++ async getFacets(companyId: string, query: string) {+ const result = await db.query(+ `SELECT * FROM get_search_facets($1, $2)`,+ [companyId, query]+ );+ return result.rows;+ }++ async suggestTags(companyId: string, query: string = '') {+ const result = await db.query(+ `SELECT * FROM suggest_tags($1, $2, 10)`,+ [companyId, query]+ );+ return result.rows;+ }+}+```++## 8. REST API Design++### 8.1 Search Endpoint++The main search endpoint accepts query parameters and returns paginated results with facets:++```javascript+// GET /api/search+app.get('/api/search', async (req, res) => {+ try {+ const {+ q: query, // Search query+ types, // Comma-separated entity types+ tags, // Comma-separated tags+ limit = 20, // Results per page+ offset = 0 // Pagination offset+ } = req.query;++ const companyId = req.user.companyId; // From auth++ if (!query || typeof query !== 'string') {+ return res.status(400).json({+ error: 'Query parameter is required'+ });+ }++ const searchService = new GlobalSearchService();+ const results = await searchService.searchWithFacets({+ query,+ companyId,+ entityTypes: types ? types.split(',') : undefined,+ tags: tags ? tags.split(',') : undefined,+ limit: parseInt(limit),+ offset: parseInt(offset)+ });++ res.json(results);+ } catch (error) {+ console.error('Search error:', error);+ res.status(500).json({ error: 'Search failed' });+ }+});+```++Example Request:++GET /api/search?q=invoice+2024&types=invoice,purchase&tags=urgent&limit=10++Response:+```json+{+ "results": [+ {+ "entityType": "invoice",+ "entityId": "inv_123",+ "title": "Invoice #INV-2024-001",+ "description": "Customer: Acme Corp Amount: $5,000",+ "tags": ["urgent", "paid"],+ "metadata": {+ "invoiceNumber": "INV-2024-001",+ "totalAmount": 5000,+ "customerName": "Acme Corp"+ },+ "rank": 0.9876+ }+ ],+ "facets": [+ { "entityType": "invoice", "count": 15 },+ { "entityType": "purchase", "count": 3 }+ ]+}+```++### 8.2 Tag Suggestions Endpoint++```javascript+// GET /api/search/tags+app.get('/api/search/tags', async (req, res) => {+ try {+ const { q: query = '' } = req.query;+ const companyId = req.user.companyId;++ const searchService = new GlobalSearchService();+ const tags = await searchService.suggestTags(+ companyId,+ query+ );++ res.json(tags);+ } catch (error) {+ console.error('Tag suggestion error:', error);+ res.status(500).json({ error: 'Failed to fetch tags' });+ }+});+```++### 8.3 Search Statistics Endpoint++```javascript+// GET /api/search/stats+app.get('/api/search/stats', async (req, res) => {+ try {+ const companyId = req.user.companyId;++ const result = await db.query(+ `SELECT * FROM get_index_stats($1)`,+ [companyId]+ );++ res.json(result.rows);+ } catch (error) {+ console.error('Stats error:', error);+ res.status(500).json({ error: 'Failed to fetch stats' });+ }+});+```++## 9. Performance Optimization++### 9.1 Index Optimization++GIN indexes are crucial for full-text search performance. Monitor and maintain them regularly:++| Strategy | Implementation | Benefit |+|-------------------|----------------------------------|----------------------------------|+| Regular VACUUM | Schedule weekly VACUUM ANALYZE | Keeps indexes efficient |+| Index Monitoring | Track index size and usage | Identify unused indexes |+| Query Planning | Use EXPLAIN ANALYZE | Optimize query performance |+| Connection Pooling | Use pgBouncer or similar | Reduce connection overhead |++### 9.2 Search Vector Weights++The search vector uses weighted components to prioritize different fields:++| Weight | Field | Priority |+|------------|-------------|------------------|+| A (highest)| Title | Primary searchable content |+| B | Description | Secondary content |+| C (lowest) | Tags | Metadata and keywords |++### 9.3 Caching Strategy++Implement caching at multiple levels for frequently accessed searches:++- **Application Cache**: Cache popular searches in Redis (5-15 minute TTL)+- **Query Result Cache**: PostgreSQL can cache query plans automatically+- **Tag Cache**: Cache tag suggestions as they change infrequently+- **Facet Cache**: Cache entity type counts for common queries++## 10. Usage Examples++### 10.1 Basic Search++```typescript+// Search for "invoice" across all entity types+const results = await searchService.search({+ query: 'invoice',+ companyId: 'company_abc123'+});++// Results contain ranked matches with highlighting+console.log(results);+// [+// {+// entityType: 'invoice',+// entityId: 'inv_001',+// title: 'Invoice #2024-001',+// rank: 0.9876+// }+// ]+```++### 10.2 Filtered Search++```typescript+// Search only invoices with specific tags+const results = await searchService.search({+ query: 'urgent payment',+ companyId: 'company_abc123',+ entityTypes: ['invoice'],+ tags: ['urgent', 'overdue'],+ limit: 10+});+```++### 10.3 Faceted Search with Pagination++```typescript+// Get search results with entity type facets+const { results, facets } = await searchService.searchWithFacets({+ query: 'acme corp',+ companyId: 'company_abc123',+ limit: 20,+ offset: 0+});++// facets shows distribution:+// [+// { entityType: 'invoice', count: 45 },+// { entityType: 'purchase', count: 12 },+// { entityType: 'job', count: 8 }+// ]++// User can then filter by clicking a facet+const filteredResults = await searchService.search({+ query: 'acme corp',+ companyId: 'company_abc123',+ entityTypes: ['invoice'] // Now only invoices+});+```++### 10.4 Tag Autocomplete++```typescript+// Get tag suggestions for autocomplete+const tags = await searchService.suggestTags(+ 'company_abc123',+ 'payment' // Context query+);++// Returns tags with counts:+// [+// { tag: 'payment_pending', count: 23 },+// { tag: 'payment_received', count: 156 },+// { tag: 'payment_overdue', count: 7 }+// ]+```++### 10.5 Frontend React Component++```javascript+import { useState, useEffect, useMemo } from 'react';+import { debounce } from 'lodash';++const SearchBar = () => {+ const [query, setQuery] = useState('');+ const [results, setResults] = useState([]);+ const [facets, setFacets] = useState([]);+ const [selectedTypes, setSelectedTypes] = useState([]);+ const [tags, setTags] = useState([]);++ const debouncedSearch = useMemo(+ () => debounce(async (searchQuery) => {+ const params = new URLSearchParams({+ q: searchQuery,+ types: selectedTypes.join(','),+ tags: tags.join(',')+ });++ const response = await fetch(`/api/search?${params}`);+ const data = await response.json();++ setResults(data.results);+ setFacets(data.facets);+ }, 300),+ [selectedTypes, tags]+ );++ useEffect(() => {+ if (query.length > 2) {+ debouncedSearch(query);+ }+ }, [query, debouncedSearch]);++ return (+ <div>+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search invoices, items, jobs..."+ className="search-input"+ />++ {facets.length > 0 && (+ <div>+ {facets.map(f => (+ <button+ key={f.entityType}+ onClick={() =>+ setSelectedTypes([f.entityType])+ }+ className="facet-button"+ >+ {f.entityType} ({f.count})+ </button>+ ))}+ </div>+ )}+++ </div>+ );+};+```++## 11. Maintenance & Operations++### 11.1 Reindexing++Reindex a company's search data to rebuild search vectors:++```sql+-- Reindex all search vectors for a company+SELECT reindex_company_search('company_abc123');++-- Or rebuild from source entities+DO $$+DECLARE+ company_id_val TEXT := 'company_abc123';+BEGIN+ -- Clear existing index+ EXECUTE format('TRUNCATE TABLE %I',+ get_search_table_name(company_id_val));++ -- Trigger re-sync from source tables+ -- (Depends on your data model)+END $$;+```++### 11.2 Monitoring Queries++```sql+-- Check index health+SELECT+ schemaname,+ tablename,+ indexname,+ idx_scan as index_scans,+ idx_tup_read as tuples_read,+ idx_tup_fetch as tuples_fetched+FROM pg_stat_user_indexes+WHERE tablename LIKE 'searchIndex_%'+ORDER BY idx_scan DESC;++-- Find slow queries+SELECT+ query,+ calls,+ total_exec_time,+ mean_exec_time,+ max_exec_time+FROM pg_stat_statements+WHERE query LIKE '%global_search%'+ORDER BY mean_exec_time DESC+LIMIT 10;+```++### 11.3 Backup and Restore++Company search tables can be backed up independently:++```+# Backup single company+pg_dump -t 'searchIndex_abc123' \+ -t 'searchIndexRegistry' \+ your_database > company_abc123_search.sql++# Restore+psql your_database < company_abc123_search.sql+```++### 11.4 Cleanup Old Companies++```sql+-- Drop search table for inactive company+SELECT drop_company_search_table('old_company_id');++-- Remove orphaned registry entries+DELETE FROM "searchIndexRegistry"+WHERE "companyId" NOT IN (SELECT "id" FROM "company");+```++## Conclusion++This architecture provides a robust, scalable foundation for global search across your ERP system. The table-per-company design ensures data isolation and performance, while PostgreSQL's native full-text search capabilities deliver fast, relevant results.++Key Takeaways:++- **Scalability**: Each company's search data is isolated and independently scalable+- **Performance**: GIN indexes and ts_rank provide sub-second search results+- **Flexibility**: Tag-based filtering and faceted search enable powerful UIs+- **Maintainability**: Automatic triggers keep search index in sync with source data+- **Security**: Physical table separation prevents cross-company data leaks++Next Steps:++- Implement the registry and table creation functions+- Create sync triggers for all entity types in your ERP+- Build the application service layer and REST APIs+- Design and implement the frontend search UI+- Set up monitoring and alerting for search performance+- Consider adding fuzzy matching with pg_trgm extension+- Implement search analytics to track popular queries++For additional support or questions about implementing this architecture, refer to the PostgreSQL documentation on full-text search and the Crunch Data blog articles on tags and arrays.diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 4931b8974d..bbb499b68a 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -28911,6 +28911,123 @@ export default {tags: ["trackedActivity"],},},+ "/searchIndexRegistry": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.lastRebuiltAt",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/searchIndexRegistry",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["searchIndexRegistry"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.searchIndexRegistry",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["searchIndexRegistry"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.lastRebuiltAt",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["searchIndexRegistry"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.searchIndexRegistry.lastRebuiltAt",+ },+ {+ $ref: "#/parameters/body.searchIndexRegistry",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["searchIndexRegistry"],+ },+ },"/suppliers": {get: {parameters: [@@ -49086,168 +49203,6 @@ export default {tags: ["challengeAttempt"],},},- "/search": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.search.id",- },- {- $ref: "#/parameters/rowFilter.search.name",- },- {- $ref: "#/parameters/rowFilter.search.description",- },- {- $ref: "#/parameters/rowFilter.search.entity",- },- {- $ref: "#/parameters/rowFilter.search.uuid",- },- {- $ref: "#/parameters/rowFilter.search.link",- },- {- $ref: "#/parameters/rowFilter.search.companyId",- },- {- $ref: "#/parameters/rowFilter.search.fts",- },- {- $ref: "#/parameters/select",- },- {- $ref: "#/parameters/order",- },- {- $ref: "#/parameters/range",- },- {- $ref: "#/parameters/rangeUnit",- },- {- $ref: "#/parameters/offset",- },- {- $ref: "#/parameters/limit",- },- {- $ref: "#/parameters/preferCount",- },- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/search",- },- type: "array",- },- },- "206": {- description: "Partial Content",- },- },- tags: ["search"],- },- post: {- parameters: [- {- $ref: "#/parameters/body.search",- },- {- $ref: "#/parameters/select",- },- {- $ref: "#/parameters/preferPost",- },- ],- responses: {- "201": {- description: "Created",- },- },- tags: ["search"],- },- delete: {- parameters: [- {- $ref: "#/parameters/rowFilter.search.id",- },- {- $ref: "#/parameters/rowFilter.search.name",- },- {- $ref: "#/parameters/rowFilter.search.description",- },- {- $ref: "#/parameters/rowFilter.search.entity",- },- {- $ref: "#/parameters/rowFilter.search.uuid",- },- {- $ref: "#/parameters/rowFilter.search.link",- },- {- $ref: "#/parameters/rowFilter.search.companyId",- },- {- $ref: "#/parameters/rowFilter.search.fts",- },- {- $ref: "#/parameters/preferReturn",- },- ],- responses: {- "204": {- description: "No Content",- },- },- tags: ["search"],- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.search.id",- },- {- $ref: "#/parameters/rowFilter.search.name",- },- {- $ref: "#/parameters/rowFilter.search.description",- },- {- $ref: "#/parameters/rowFilter.search.entity",- },- {- $ref: "#/parameters/rowFilter.search.uuid",- },- {- $ref: "#/parameters/rowFilter.search.link",- },- {- $ref: "#/parameters/rowFilter.search.companyId",- },- {- $ref: "#/parameters/rowFilter.search.fts",- },- {- $ref: "#/parameters/body.search",- },- {- $ref: "#/parameters/preferReturn",- },- ],- responses: {- "204": {- description: "No Content",- },- },- tags: ["search"],- },- },"/nonConformanceSupplier": {get: {parameters: [@@ -58683,6 +58638,9 @@ export default {{$ref: "#/parameters/rowFilter.quote.customerEngineeringContactId",},+ {+ $ref: "#/parameters/rowFilter.quote.externalId",+ },{$ref: "#/parameters/select",},@@ -58844,6 +58802,9 @@ export default {{$ref: "#/parameters/rowFilter.quote.customerEngineeringContactId",},+ {+ $ref: "#/parameters/rowFilter.quote.externalId",+ },{$ref: "#/parameters/preferReturn",},@@ -58959,6 +58920,9 @@ export default {{$ref: "#/parameters/rowFilter.quote.customerEngineeringContactId",},+ {+ $ref: "#/parameters/rowFilter.quote.externalId",+ },{$ref: "#/parameters/body.quote",},@@ -62501,6 +62465,41 @@ export default {tags: ["(rpc) get_active_job_operations_by_location"],},},+ "/rpc/populate_company_search_index": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_company_id"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) populate_company_search_index"],+ },+ },"/rpc/get_next_numeric_sequence": {post: {parameters: [@@ -63985,6 +63984,56 @@ export default {tags: ["(rpc) has_valid_api_key_for_company"],},},+ "/rpc/search_company_index": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ p_entity_types: {+ format: "text[]",+ items: {+ type: "string",+ },+ type: "array",+ },+ p_limit: {+ format: "integer",+ type: "integer",+ },+ p_query: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_company_id", "p_query", "p_entity_types"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) search_company_index"],+ },+ },"/rpc/get_job_methods_by_method_id": {get: {parameters: [@@ -64201,6 +64250,41 @@ export default {tags: ["(rpc) get_active_job_operations_by_employee"],},},+ "/rpc/create_company_search_index": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_company_id"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) create_company_search_index"],+ },+ },"/rpc/get_material_details": {get: {parameters: [@@ -64339,6 +64423,41 @@ export default {tags: ["(rpc) get_production_planning"],},},+ "/rpc/drop_company_search_index": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_company_id"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) drop_company_search_index"],+ },+ },"/rpc/update_receipt_line_batch_tracking": {post: {parameters: [@@ -78161,6 +78280,27 @@ export default {},type: "object",},+ searchIndexRegistry: {+ required: ["companyId", "createdAt"],+ properties: {+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string",+ },+ lastRebuiltAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ },+ type: "object",+ },suppliers: {properties: {id: {@@ -87829,71 +87969,6 @@ export default {},type: "object",},- search: {- required: ["id", "name", "link"],- properties: {- id: {- description: "Note:\nThis is a Primary Key.<pk/>",- format: "bigint",- type: "integer",- },- name: {- format: "text",- type: "string",- },- description: {- default: "",- format: "text",- type: "string",- },- entity: {- enum: [- "Resource",- "Person",- "Customer",- "Supplier",- "Job",- "Part",- "Purchase Order",- "Lead",- "Opportunity",- "Quotation",- "Sales Order",- "Request for Quotation",- "Sales Invoice",- "Purchase Invoice",- "Document",- "Sales RFQ",- "Service",- "Tool",- "Consumable",- "Material",- "Fixture",- ],- format: 'public."searchEntity"',- type: "string",- },- uuid: {- format: "text",- type: "string",- },- link: {- format: "text",- type: "string",- },- companyId: {- description:- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",- format: "text",- type: "string",- },- fts: {- format: "tsvector",- type: "string",- },- },- type: "object",- },nonConformanceSupplier: {required: ["id",@@ -92849,6 +92924,9 @@ export default {format: "text",type: "string",},+ externalId: {+ format: "jsonb",+ },},type: "object",},@@ -108693,6 +108771,33 @@ export default {in: "query",type: "string",},+ "body.searchIndexRegistry": {+ name: "searchIndexRegistry",+ description: "searchIndexRegistry",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/searchIndexRegistry",+ },+ },+ "rowFilter.searchIndexRegistry.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.searchIndexRegistry.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.searchIndexRegistry.lastRebuiltAt": {+ name: "lastRebuiltAt",+ required: false,+ in: "query",+ type: "string",+ },"body.suppliers": {name: "suppliers",description: "suppliers",@@ -119656,63 +119761,6 @@ export default {in: "query",type: "string",},- "body.search": {- name: "search",- description: "search",- required: false,- in: "body",- schema: {- $ref: "#/definitions/search",- },- },- "rowFilter.search.id": {- name: "id",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.name": {- name: "name",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.description": {- name: "description",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.entity": {- name: "entity",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.uuid": {- name: "uuid",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.link": {- name: "link",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.companyId": {- name: "companyId",- required: false,- in: "query",- type: "string",- },- "rowFilter.search.fts": {- name: "fts",- required: false,- in: "query",- type: "string",- },"body.nonConformanceSupplier": {name: "nonConformanceSupplier",description: "nonConformanceSupplier",@@ -125320,6 +125368,12 @@ export default {in: "query",type: "string",},+ "rowFilter.quote.externalId": {+ name: "externalId",+ required: false,+ in: "query",+ type: "string",+ },"body.salesInvoiceLine": {name: "salesInvoiceLine",description: "salesInvoiceLine",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex edc52da2e9..aff5043295 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -31315,63 +31315,48 @@ export type Database = {},]}- search: {+ searchIndexRegistry: {Row: {- companyId: string | null- description: string | null- entity: Database["public"]["Enums"]["searchEntity"] | null- fts: unknown- id: number- link: string- name: string- uuid: string | null+ companyId: string+ createdAt: string+ lastRebuiltAt: string | null}Insert: {- companyId?: string | null- description?: string | null- entity?: Database["public"]["Enums"]["searchEntity"] | null- fts?: unknown- id?: number- link: string- name: string- uuid?: string | null+ companyId: string+ createdAt?: string+ lastRebuiltAt?: string | null}Update: {- companyId?: string | null- description?: string | null- entity?: Database["public"]["Enums"]["searchEntity"] | null- fts?: unknown- id?: number- link?: string- name?: string- uuid?: string | null+ companyId?: string+ createdAt?: string+ lastRebuiltAt?: string | null}Relationships: [{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "integrations"referencedColumns: ["companyId"]},@@ -46756,14 +46741,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -49447,14 +49432,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -52801,6 +52786,10 @@ export type Database = {Args: { operation_id: string }Returns: boolean}+ create_company_search_index: {+ Args: { p_company_id: string }+ Returns: undefined+ }create_rfq_from_model_v1: {Args: {company_id: string@@ -52843,6 +52832,10 @@ export type Database = {rfq_readable_id: string}[]}+ drop_company_search_index: {+ Args: { p_company_id: string }+ Returns: undefined+ }employee_requires_period: {Args: { employee_start_date: string; period: string }Returns: boolean@@ -54225,6 +54218,28 @@ export type Database = {Args: { alphabet: string; mask: number; size: number; step: number }Returns: string}+ populate_company_search_index: {+ Args: { p_company_id: string }+ Returns: undefined+ }+ search_company_index: {+ Args: {+ p_company_id: string+ p_entity_types: string[]+ p_limit?: number+ p_query: string+ }+ Returns: {+ description: string+ entityId: string+ entityType: string+ id: number+ link: string+ metadata: Json+ tags: string[]+ title: string+ }[]+ }suppliers_search: {Args: {match_count: number@@ -54690,28 +54705,6 @@ export type Database = {| "Reject"| "Request Approval"salesRfqStatus: "Draft" | "Ready for Quote" | "Closed" | "Quoted"- searchEntity:- | "Resource"- | "Person"- | "Customer"- | "Supplier"- | "Job"- | "Part"- | "Purchase Order"- | "Lead"- | "Opportunity"- | "Quotation"- | "Sales Order"- | "Request for Quotation"- | "Sales Invoice"- | "Purchase Invoice"- | "Document"- | "Sales RFQ"- | "Service"- | "Tool"- | "Consumable"- | "Material"- | "Fixture"serviceType: "Internal" | "External"shipmentSourceDocument:| "Sales Order"@@ -55859,29 +55852,6 @@ export const Constants = {"Request Approval",],salesRfqStatus: ["Draft", "Ready for Quote", "Closed", "Quoted"],- searchEntity: [- "Resource",- "Person",- "Customer",- "Supplier",- "Job",- "Part",- "Purchase Order",- "Lead",- "Opportunity",- "Quotation",- "Sales Order",- "Request for Quotation",- "Sales Invoice",- "Purchase Invoice",- "Document",- "Sales RFQ",- "Service",- "Tool",- "Consumable",- "Material",- "Fixture",- ],serviceType: ["Internal", "External"],shipmentSourceDocument: ["Sales Order",diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex edc52da2e9..aff5043295 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -31315,63 +31315,48 @@ export type Database = {},]}- search: {+ searchIndexRegistry: {Row: {- companyId: string | null- description: string | null- entity: Database["public"]["Enums"]["searchEntity"] | null- fts: unknown- id: number- link: string- name: string- uuid: string | null+ companyId: string+ createdAt: string+ lastRebuiltAt: string | null}Insert: {- companyId?: string | null- description?: string | null- entity?: Database["public"]["Enums"]["searchEntity"] | null- fts?: unknown- id?: number- link: string- name: string- uuid?: string | null+ companyId: string+ createdAt?: string+ lastRebuiltAt?: string | null}Update: {- companyId?: string | null- description?: string | null- entity?: Database["public"]["Enums"]["searchEntity"] | null- fts?: unknown- id?: number- link?: string- name?: string- uuid?: string | null+ companyId?: string+ createdAt?: string+ lastRebuiltAt?: string | null}Relationships: [{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "search_companyid_fkey"+ foreignKeyName: "searchIndexRegistry_companyId_fkey"columns: ["companyId"]- isOneToOne: false+ isOneToOne: truereferencedRelation: "integrations"referencedColumns: ["companyId"]},@@ -46756,14 +46741,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -49447,14 +49432,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -52801,6 +52786,10 @@ export type Database = {Args: { operation_id: string }Returns: boolean}+ create_company_search_index: {+ Args: { p_company_id: string }+ Returns: undefined+ }create_rfq_from_model_v1: {Args: {company_id: string@@ -52843,6 +52832,10 @@ export type Database = {rfq_readable_id: string}[]}+ drop_company_search_index: {+ Args: { p_company_id: string }+ Returns: undefined+ }employee_requires_period: {Args: { employee_start_date: string; period: string }Returns: boolean@@ -54225,6 +54218,28 @@ export type Database = {Args: { alphabet: string; mask: number; size: number; step: number }Returns: string}+ populate_company_search_index: {+ Args: { p_company_id: string }+ Returns: undefined+ }+ search_company_index: {+ Args: {+ p_company_id: string+ p_entity_types: string[]+ p_limit?: number+ p_query: string+ }+ Returns: {+ description: string+ entityId: string+ entityType: string+ id: number+ link: string+ metadata: Json+ tags: string[]+ title: string+ }[]+ }suppliers_search: {Args: {match_count: number@@ -54690,28 +54705,6 @@ export type Database = {| "Reject"| "Request Approval"salesRfqStatus: "Draft" | "Ready for Quote" | "Closed" | "Quoted"- searchEntity:- | "Resource"- | "Person"- | "Customer"- | "Supplier"- | "Job"- | "Part"- | "Purchase Order"- | "Lead"- | "Opportunity"- | "Quotation"- | "Sales Order"- | "Request for Quotation"- | "Sales Invoice"- | "Purchase Invoice"- | "Document"- | "Sales RFQ"- | "Service"- | "Tool"- | "Consumable"- | "Material"- | "Fixture"serviceType: "Internal" | "External"shipmentSourceDocument:| "Sales Order"@@ -55859,29 +55852,6 @@ export const Constants = {"Request Approval",],salesRfqStatus: ["Draft", "Ready for Quote", "Closed", "Quoted"],- searchEntity: [- "Resource",- "Person",- "Customer",- "Supplier",- "Job",- "Part",- "Purchase Order",- "Lead",- "Opportunity",- "Quotation",- "Sales Order",- "Request for Quotation",- "Sales Invoice",- "Purchase Invoice",- "Document",- "Sales RFQ",- "Service",- "Tool",- "Consumable",- "Material",- "Fixture",- ],serviceType: ["Internal", "External"],shipmentSourceDocument: ["Sales Order",diff --git a/packages/database/supabase/migrations/20260109134902_search-refactor.sql b/packages/database/supabase/migrations/20260109134902_search-refactor.sqlnew file mode 100644index 0000000000..f36ed3197e--- /dev/null+++ b/packages/database/supabase/migrations/20260109134902_search-refactor.sql@@ -0,0 +1,1130 @@+-- =============================================================================+-- Global Search Architecture Refactor+-- Migrate from single-table multi-tenant search to table-per-company design+-- =============================================================================++-- =============================================================================+-- PART 0: Drop Old Triggers and Functions FIRST+-- =============================================================================++-- Employee triggers+DROP TRIGGER IF EXISTS create_employee_search_result ON "employee";+DROP TRIGGER IF EXISTS update_employee_search_result ON "user";++-- Customer triggers+DROP TRIGGER IF EXISTS create_customer_search_result ON "customer";+DROP TRIGGER IF EXISTS update_customer_search_result ON "customer";++-- Supplier triggers+DROP TRIGGER IF EXISTS create_supplier_search_result ON "supplier";+DROP TRIGGER IF EXISTS update_supplier_search_result ON "supplier";++-- Item triggers+DROP TRIGGER IF EXISTS create_item_search_result ON "item";+DROP TRIGGER IF EXISTS update_item_search_result ON "item";+DROP TRIGGER IF EXISTS delete_item_search_result ON "item";++-- Job triggers+DROP TRIGGER IF EXISTS create_job_search_result ON "job";+DROP TRIGGER IF EXISTS update_job_search_result ON "job";+DROP TRIGGER IF EXISTS delete_job_search_result ON "job";++-- Purchase Order triggers+DROP TRIGGER IF EXISTS create_purchase_order_search_result ON "purchaseOrder";+DROP TRIGGER IF EXISTS update_purchase_order_search_result ON "purchaseOrder";+DROP TRIGGER IF EXISTS delete_purchase_order_search_result ON "purchaseOrder";++-- Sales Order triggers+DROP TRIGGER IF EXISTS create_sales_order_search_result ON "salesOrder";+DROP TRIGGER IF EXISTS update_sales_order_search_result ON "salesOrder";+DROP TRIGGER IF EXISTS delete_sales_order_search_result ON "salesOrder";++-- Quotation triggers+DROP TRIGGER IF EXISTS create_quotation_search_result ON "quote";+DROP TRIGGER IF EXISTS update_quotation_search_result ON "quote";+DROP TRIGGER IF EXISTS delete_quotation_search_result ON "quote";++-- Sales RFQ triggers+DROP TRIGGER IF EXISTS create_sales_rfq_search_result ON "salesRfq";+DROP TRIGGER IF EXISTS update_sales_rfq_search_result ON "salesRfq";+DROP TRIGGER IF EXISTS delete_sales_rfq_search_result ON "salesRfq";+++++-- Drop old functions+DROP FUNCTION IF EXISTS create_employee_search_result();+DROP FUNCTION IF EXISTS update_employee_search_result();+DROP FUNCTION IF EXISTS create_customer_search_result();+DROP FUNCTION IF EXISTS update_customer_search_result();+DROP FUNCTION IF EXISTS create_supplier_search_result();+DROP FUNCTION IF EXISTS update_supplier_search_result();+DROP FUNCTION IF EXISTS create_item_search_result();+DROP FUNCTION IF EXISTS update_item_search_result();+DROP FUNCTION IF EXISTS delete_item_search_result();+DROP FUNCTION IF EXISTS create_job_search_result();+DROP FUNCTION IF EXISTS update_job_search_result();+DROP FUNCTION IF EXISTS delete_job_search_result();+DROP FUNCTION IF EXISTS create_purchase_order_search_result();+DROP FUNCTION IF EXISTS update_purchase_order_search_result();+DROP FUNCTION IF EXISTS delete_purchase_order_search_result();+DROP FUNCTION IF EXISTS create_sales_order_search_result();+DROP FUNCTION IF EXISTS update_sales_order_search_result();+DROP FUNCTION IF EXISTS delete_sales_order_search_result();+DROP FUNCTION IF EXISTS create_quotation_search_result();+DROP FUNCTION IF EXISTS update_quotation_search_result();+DROP FUNCTION IF EXISTS delete_quotation_search_result();+DROP FUNCTION IF EXISTS create_sales_rfq_search_result();+DROP FUNCTION IF EXISTS update_sales_rfq_search_result();+DROP FUNCTION IF EXISTS delete_sales_rfq_search_result();+DROP FUNCTION IF EXISTS create_work_cell_type_search_result();+DROP FUNCTION IF EXISTS update_work_cell_type_search_result();+DROP FUNCTION IF EXISTS delete_work_cell_type_search_result();+DROP FUNCTION IF EXISTS create_equipment_type_search_result();+DROP FUNCTION IF EXISTS update_equipment_type_search_result();+DROP FUNCTION IF EXISTS delete_equipment_type_search_result();+DROP FUNCTION IF EXISTS create_equipment_search_result();+DROP FUNCTION IF EXISTS update_equipment_search_result();+++-- Drop old table and type+DROP TABLE IF EXISTS "search";+DROP TYPE IF EXISTS "searchEntity";++-- =============================================================================+-- PART 1: Create Registry Table+-- =============================================================================++CREATE TABLE "searchIndexRegistry" (+ "companyId" TEXT NOT NULL PRIMARY KEY,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "lastRebuiltAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "searchIndexRegistry_companyId_fkey"+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- Enable RLS (no policies - access via service role bypass only)+ALTER TABLE "searchIndexRegistry" ENABLE ROW LEVEL SECURITY;++-- =============================================================================+-- PART 2: Create Table Creation Function+-- =============================================================================++CREATE OR REPLACE FUNCTION create_company_search_index(p_company_id TEXT)+RETURNS VOID AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := 'searchIndex_' || p_company_id;++ -- Create the search index table+ EXECUTE format('+ CREATE TABLE IF NOT EXISTS %I (+ "id" BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,+ "entityType" TEXT NOT NULL,+ "entityId" TEXT NOT NULL,+ "title" TEXT NOT NULL,+ "description" TEXT DEFAULT '''',+ "link" TEXT NOT NULL,+ "tags" TEXT[] DEFAULT ''{}'',+ "metadata" JSONB DEFAULT ''{}'',+ "searchVector" TSVECTOR,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT %I UNIQUE ("entityType", "entityId")+ )', v_table_name, v_table_name || '_entity_unique');++ -- Create indexes+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("searchVector")',+ v_table_name || '_fts_idx', v_table_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType")',+ v_table_name || '_entityType_idx', v_table_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("updatedAt" DESC)',+ v_table_name || '_updatedAt_idx', v_table_name);++ -- Enable RLS (no SELECT policies - access via service role bypass)+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', v_table_name);++ -- Register the company in the registry+ INSERT INTO "searchIndexRegistry" ("companyId")+ VALUES (p_company_id)+ ON CONFLICT ("companyId") DO NOTHING;+END;+$$ LANGUAGE plpgsql SECURITY INVOKER;++-- =============================================================================+-- PART 2.1: Create Table Deletion Function+-- =============================================================================++CREATE OR REPLACE FUNCTION drop_company_search_index(p_company_id TEXT)+RETURNS VOID AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := 'searchIndex_' || p_company_id;++ -- Drop the search index table if it exists+ EXECUTE format('DROP TABLE IF EXISTS %I', v_table_name);++ -- Remove from registry+ DELETE FROM "searchIndexRegistry" WHERE "companyId" = p_company_id;+END;+$$ LANGUAGE plpgsql SECURITY INVOKER;++-- =============================================================================+-- PART 3: Create Company Trigger (auto-create search index for new companies)+-- =============================================================================++CREATE OR REPLACE FUNCTION on_company_created_search_index()+RETURNS TRIGGER AS $$+BEGIN+ PERFORM create_company_search_index(NEW.id);+ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER company_search_index_trigger+ AFTER INSERT ON "company"+ FOR EACH ROW EXECUTE FUNCTION on_company_created_search_index();++-- =============================================================================+-- PART 4: Create Sync Functions+-- =============================================================================++-- -----------------------------------------------------------------------------+-- 4.1 Employee Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_employee_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_emp_name TEXT;+ v_emp_type TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'employee', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ -- Get employee name from user table+ SELECT "fullName" INTO v_emp_name FROM "user" WHERE id = NEW.id;++ -- Get employee type name+ SELECT name INTO v_emp_type FROM "employeeType" WHERE id = NEW."employeeTypeId";++ IF NEW.active = false THEN+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'employee', NEW.id;+ RETURN NEW;+ END IF;++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, to_tsvector(''english'', $3 || '' '' || COALESCE(array_to_string($5, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'employee',+ NEW.id,+ COALESCE(v_emp_name, ''),+ '/x/person/' || NEW.id,+ ARRAY_REMOVE(ARRAY[v_emp_type], NULL),+ jsonb_build_object('active', NEW.active);++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.2 Customer Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_customer_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_cust_type TEXT;+ v_cust_status TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'customer', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_cust_type FROM "customerType" WHERE id = NEW."customerTypeId";+ SELECT name INTO v_cust_status FROM "customerStatus" WHERE id = NEW."customerStatusId";++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, to_tsvector(''english'', $3 || '' '' || COALESCE(array_to_string($5, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'customer',+ NEW.id,+ NEW.name,+ '/x/customer/' || NEW.id,+ ARRAY_REMOVE(ARRAY[v_cust_type, v_cust_status], NULL),+ jsonb_build_object('taxId', NEW."taxId");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.3 Supplier Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_supplier_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_supp_type TEXT;+ v_supp_status TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'supplier', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_supp_type FROM "supplierType" WHERE id = NEW."supplierTypeId";+ SELECT name INTO v_supp_status FROM "supplierStatus" WHERE id = NEW."supplierStatusId";++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, to_tsvector(''english'', $3 || '' '' || COALESCE(array_to_string($5, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'supplier',+ NEW.id,+ NEW.name,+ '/x/supplier/' || NEW.id,+ ARRAY_REMOVE(ARRAY[v_supp_type, v_supp_status], NULL),+ jsonb_build_object('taxId', NEW."taxId");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.4 Item Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_item_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_link TEXT;+ v_description TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'item', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ -- Determine link based on item type+ v_link := CASE NEW.type+ WHEN 'Part' THEN '/x/part/' || NEW.id+ WHEN 'Service' THEN '/x/service/' || NEW.id+ WHEN 'Tool' THEN '/x/tool/' || NEW.id+ WHEN 'Consumable' THEN '/x/consumable/' || NEW.id+ WHEN 'Material' THEN '/x/material/' || NEW.id+ WHEN 'Fixture' THEN '/x/fixture/' || NEW.id+ ELSE '/x/part/' || NEW.id+ END;++ v_description := NEW.name || ' ' || COALESCE(NEW.description, '');++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "link" = EXCLUDED."link",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'item',+ NEW.id,+ NEW."readableId",+ v_description,+ v_link,+ ARRAY_REMOVE(ARRAY[NEW.type::TEXT, NEW."replenishmentSystem"::TEXT], NULL),+ jsonb_build_object('active', NEW.active);++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE OR REPLACE FUNCTION sync_job_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_item_name TEXT;+ v_cust_name TEXT;+ v_description TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'job', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_item_name FROM "item" WHERE id = NEW."itemId";+ SELECT name INTO v_cust_name FROM "customer" WHERE id = NEW."customerId";++ v_description := COALESCE(v_item_name, '') || ' ' || COALESCE(v_cust_name, '');++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'job',+ NEW.id,+ NEW."jobId",+ v_description,+ '/x/job/' || NEW.id,+ ARRAY_REMOVE(ARRAY[NEW.status::TEXT, NEW."deadlineType"::TEXT], NULL),+ jsonb_build_object('quantity', NEW.quantity, 'dueDate', NEW."dueDate");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.8 Purchase Order Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_purchase_order_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_supp_name TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'purchaseOrder', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_supp_name FROM "supplier" WHERE id = NEW."supplierId";++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'purchaseOrder',+ NEW.id,+ NEW."purchaseOrderId",+ COALESCE(v_supp_name, ''),+ '/x/purchase-order/' || NEW.id,+ ARRAY_REMOVE(ARRAY[NEW.status::TEXT], NULL),+ jsonb_build_object('orderDate', NEW."orderDate", 'supplierReference', NEW."supplierReference");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.9 Sales Invoice Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_sales_invoice_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_cust_name TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'salesInvoice', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_cust_name FROM "customer" WHERE id = NEW."customerId";++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'salesInvoice',+ NEW.id,+ NEW."invoiceId",+ COALESCE(v_cust_name, ''),+ '/x/invoicing/sales/' || NEW.id,+ ARRAY_REMOVE(ARRAY[NEW.status::TEXT], NULL),+ jsonb_build_object('totalAmount', NEW."totalAmount", 'dateDue', NEW."dateDue");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.10 Purchase Invoice Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_purchase_invoice_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_supp_name TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'purchaseInvoice', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_supp_name FROM "supplier" WHERE id = NEW."supplierId";++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'purchaseInvoice',+ NEW.id,+ NEW."invoiceId",+ COALESCE(v_supp_name, ''),+ '/x/invoicing/purchasing/' || NEW.id,+ ARRAY_REMOVE(ARRAY[NEW.status::TEXT], NULL),+ jsonb_build_object('totalAmount', NEW."totalAmount", 'dateDue', NEW."dateDue");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.11 Non-Conformance (Issue) Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_non_conformance_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_nc_type TEXT;+ v_description TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'issue', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_nc_type FROM "nonConformanceType" WHERE id = NEW."nonConformanceTypeId";++ v_description := NEW.name || ' ' || COALESCE(NEW.description, '');++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'issue',+ NEW.id,+ NEW."nonConformanceId",+ v_description,+ '/x/issue/' || NEW.id,+ ARRAY_REMOVE(ARRAY[NEW.status::TEXT, NEW.priority::TEXT, v_nc_type], NULL),+ jsonb_build_object('source', NEW.source, 'dueDate', NEW."dueDate");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- -----------------------------------------------------------------------------+-- 4.12 Gauge Sync+-- -----------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_gauge_to_search_index()+RETURNS TRIGGER AS $$+DECLARE+ v_table_name TEXT;+ v_gauge_type TEXT;+ v_description TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_table_name := 'searchIndex_' || OLD."companyId";+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)+ USING 'gauge', OLD.id;+ RETURN OLD;+ END IF;++ v_table_name := 'searchIndex_' || NEW."companyId";++ SELECT name INTO v_gauge_type FROM "gaugeType" WHERE id = NEW."gaugeTypeId";++ v_description := COALESCE(NEW.description, '') || ' ' || COALESCE(NEW."serialNumber", '');++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $3 || '' '' || $4 || '' '' || COALESCE(array_to_string($6, '' ''), '''')))+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || EXCLUDED."description" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),+ "updatedAt" = NOW()+ ', v_table_name) USING+ 'gauge',+ NEW.id,+ NEW."gaugeId",+ v_description,+ '/x/quality/gauges/' || NEW.id,+ ARRAY_REMOVE(ARRAY[NEW."gaugeStatus"::TEXT, NEW."gaugeCalibrationStatus"::TEXT, v_gauge_type], NULL),+ jsonb_build_object('nextCalibrationDate', NEW."nextCalibrationDate", 'serialNumber', NEW."serialNumber");++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- =============================================================================+-- PART 5: Create Entity Table Triggers+-- =============================================================================++-- Employee triggers+CREATE TRIGGER sync_employee_search_insert+ AFTER INSERT ON "employee"+ FOR EACH ROW EXECUTE FUNCTION sync_employee_to_search_index();++CREATE TRIGGER sync_employee_search_update+ AFTER UPDATE ON "employee"+ FOR EACH ROW EXECUTE FUNCTION sync_employee_to_search_index();++CREATE TRIGGER sync_employee_search_delete+ AFTER DELETE ON "employee"+ FOR EACH ROW EXECUTE FUNCTION sync_employee_to_search_index();++-- Customer triggers+CREATE TRIGGER sync_customer_search_insert+ AFTER INSERT ON "customer"+ FOR EACH ROW EXECUTE FUNCTION sync_customer_to_search_index();++CREATE TRIGGER sync_customer_search_update+ AFTER UPDATE ON "customer"+ FOR EACH ROW EXECUTE FUNCTION sync_customer_to_search_index();++CREATE TRIGGER sync_customer_search_delete+ AFTER DELETE ON "customer"+ FOR EACH ROW EXECUTE FUNCTION sync_customer_to_search_index();++-- Supplier triggers+CREATE TRIGGER sync_supplier_search_insert+ AFTER INSERT ON "supplier"+ FOR EACH ROW EXECUTE FUNCTION sync_supplier_to_search_index();++CREATE TRIGGER sync_supplier_search_update+ AFTER UPDATE ON "supplier"+ FOR EACH ROW EXECUTE FUNCTION sync_supplier_to_search_index();++CREATE TRIGGER sync_supplier_search_delete+ AFTER DELETE ON "supplier"+ FOR EACH ROW EXECUTE FUNCTION sync_supplier_to_search_index();++-- Item triggers+CREATE TRIGGER sync_item_search_insert+ AFTER INSERT ON "item"+ FOR EACH ROW EXECUTE FUNCTION sync_item_to_search_index();++CREATE TRIGGER sync_item_search_update+ AFTER UPDATE ON "item"+ FOR EACH ROW EXECUTE FUNCTION sync_item_to_search_index();++CREATE TRIGGER sync_item_search_delete+ AFTER DELETE ON "item"+ FOR EACH ROW EXECUTE FUNCTION sync_item_to_search_index();++-- Job triggers+CREATE TRIGGER sync_job_search_insert+ AFTER INSERT ON "job"+ FOR EACH ROW EXECUTE FUNCTION sync_job_to_search_index();++CREATE TRIGGER sync_job_search_update+ AFTER UPDATE ON "job"+ FOR EACH ROW EXECUTE FUNCTION sync_job_to_search_index();++CREATE TRIGGER sync_job_search_delete+ AFTER DELETE ON "job"+ FOR EACH ROW EXECUTE FUNCTION sync_job_to_search_index();++-- Purchase Order triggers+CREATE TRIGGER sync_purchase_order_search_insert+ AFTER INSERT ON "purchaseOrder"+ FOR EACH ROW EXECUTE FUNCTION sync_purchase_order_to_search_index();++CREATE TRIGGER sync_purchase_order_search_update+ AFTER UPDATE ON "purchaseOrder"+ FOR EACH ROW EXECUTE FUNCTION sync_purchase_order_to_search_index();++CREATE TRIGGER sync_purchase_order_search_delete+ AFTER DELETE ON "purchaseOrder"+ FOR EACH ROW EXECUTE FUNCTION sync_purchase_order_to_search_index();++-- Sales Invoice triggers+CREATE TRIGGER sync_sales_invoice_search_insert+ AFTER INSERT ON "salesInvoice"+ FOR EACH ROW EXECUTE FUNCTION sync_sales_invoice_to_search_index();++CREATE TRIGGER sync_sales_invoice_search_update+ AFTER UPDATE ON "salesInvoice"+ FOR EACH ROW EXECUTE FUNCTION sync_sales_invoice_to_search_index();++CREATE TRIGGER sync_sales_invoice_search_delete+ AFTER DELETE ON "salesInvoice"+ FOR EACH ROW EXECUTE FUNCTION sync_sales_invoice_to_search_index();++-- Purchase Invoice triggers+CREATE TRIGGER sync_purchase_invoice_search_insert+ AFTER INSERT ON "purchaseInvoice"+ FOR EACH ROW EXECUTE FUNCTION sync_purchase_invoice_to_search_index();++CREATE TRIGGER sync_purchase_invoice_search_update+ AFTER UPDATE ON "purchaseInvoice"+ FOR EACH ROW EXECUTE FUNCTION sync_purchase_invoice_to_search_index();++CREATE TRIGGER sync_purchase_invoice_search_delete+ AFTER DELETE ON "purchaseInvoice"+ FOR EACH ROW EXECUTE FUNCTION sync_purchase_invoice_to_search_index();++-- Non-Conformance (Issue) triggers+CREATE TRIGGER sync_non_conformance_search_insert+ AFTER INSERT ON "nonConformance"+ FOR EACH ROW EXECUTE FUNCTION sync_non_conformance_to_search_index();++CREATE TRIGGER sync_non_conformance_search_update+ AFTER UPDATE ON "nonConformance"+ FOR EACH ROW EXECUTE FUNCTION sync_non_conformance_to_search_index();++CREATE TRIGGER sync_non_conformance_search_delete+ AFTER DELETE ON "nonConformance"+ FOR EACH ROW EXECUTE FUNCTION sync_non_conformance_to_search_index();++-- Gauge triggers+CREATE TRIGGER sync_gauge_search_insert+ AFTER INSERT ON "gauge"+ FOR EACH ROW EXECUTE FUNCTION sync_gauge_to_search_index();++CREATE TRIGGER sync_gauge_search_update+ AFTER UPDATE ON "gauge"+ FOR EACH ROW EXECUTE FUNCTION sync_gauge_to_search_index();++CREATE TRIGGER sync_gauge_search_delete+ AFTER DELETE ON "gauge"+ FOR EACH ROW EXECUTE FUNCTION sync_gauge_to_search_index();++-- =============================================================================+-- PART 6: Create Population Function+-- =============================================================================++CREATE OR REPLACE FUNCTION populate_company_search_index(p_company_id TEXT)+RETURNS VOID AS $$+DECLARE+ v_table_name TEXT := 'searchIndex_' || p_company_id;+BEGIN+ -- Populate employees+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")+ SELECT+ ''employee'',+ e.id,+ COALESCE(u."fullName", ''''),+ ''/x/person/'' || e.id,+ ARRAY_REMOVE(ARRAY[et.name], NULL),+ jsonb_build_object(''active'', e.active),+ to_tsvector(''english'', COALESCE(u."fullName", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[et.name], NULL), '' ''), ''''))+ FROM "employee" e+ INNER JOIN "user" u ON u.id = e.id+ LEFT JOIN "employeeType" et ON et.id = e."employeeTypeId"+ WHERE e."companyId" = $1 AND e.active = true+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate customers+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")+ SELECT+ ''customer'',+ c.id,+ c.name,+ ''/x/customer/'' || c.id,+ ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL),+ jsonb_build_object(''taxId'', c."taxId"),+ to_tsvector(''english'', c.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL), '' ''), ''''))+ FROM "customer" c+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"+ WHERE c."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate suppliers+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")+ SELECT+ ''supplier'',+ s.id,+ s.name,+ ''/x/supplier/'' || s.id,+ ARRAY_REMOVE(ARRAY[st.name, ss.name], NULL),+ jsonb_build_object(''taxId'', s."taxId"),+ to_tsvector(''english'', s.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[st.name, ss.name], NULL), '' ''), ''''))+ FROM "supplier" s+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"+ LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"+ WHERE s."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate items+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''item'',+ i.id,+ i."readableId",+ i.name || '' '' || COALESCE(i.description, ''''),+ CASE i.type+ WHEN ''Part'' THEN ''/x/part/'' || i.id+ WHEN ''Service'' THEN ''/x/service/'' || i.id+ WHEN ''Tool'' THEN ''/x/tool/'' || i.id+ WHEN ''Consumable'' THEN ''/x/consumable/'' || i.id+ WHEN ''Material'' THEN ''/x/material/'' || i.id+ WHEN ''Fixture'' THEN ''/x/fixture/'' || i.id+ ELSE ''/x/part/'' || i.id+ END,+ ARRAY_REMOVE(ARRAY[i.type::TEXT, i."replenishmentSystem"::TEXT], NULL),+ jsonb_build_object(''active'', i.active),+ to_tsvector(''english'', i."readableId" || '' '' || i.name || '' '' || COALESCE(i.description, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[i.type::TEXT, i."replenishmentSystem"::TEXT], NULL), '' ''), ''''))+ FROM "item" i+ WHERE i."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "link" = EXCLUDED."link",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;+++ -- Populate jobs+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''job'',+ j.id,+ j."jobId",+ COALESCE(i.name, '''') || '' '' || COALESCE(c.name, ''''),+ ''/x/job/'' || j.id,+ ARRAY_REMOVE(ARRAY[j.status::TEXT, j."deadlineType"::TEXT], NULL),+ jsonb_build_object(''quantity'', j.quantity, ''dueDate'', j."dueDate"),+ to_tsvector(''english'', j."jobId" || '' '' || COALESCE(i.name, '''') || '' '' || COALESCE(c.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[j.status::TEXT, j."deadlineType"::TEXT], NULL), '' ''), ''''))+ FROM "job" j+ LEFT JOIN "item" i ON i.id = j."itemId"+ LEFT JOIN "customer" c ON c.id = j."customerId"+ WHERE j."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate purchase orders+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''purchaseOrder'',+ po.id,+ po."purchaseOrderId",+ COALESCE(s.name, ''''),+ ''/x/purchase-order/'' || po.id,+ ARRAY_REMOVE(ARRAY[po.status::TEXT], NULL),+ jsonb_build_object(''orderDate'', po."orderDate", ''supplierReference'', po."supplierReference"),+ to_tsvector(''english'', po."purchaseOrderId" || '' '' || COALESCE(s.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[po.status::TEXT], NULL), '' ''), ''''))+ FROM "purchaseOrder" po+ LEFT JOIN "supplier" s ON s.id = po."supplierId"+ WHERE po."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate sales invoices+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''salesInvoice'',+ si.id,+ si."invoiceId",+ COALESCE(c.name, ''''),+ ''/x/invoicing/sales/'' || si.id,+ ARRAY_REMOVE(ARRAY[si.status::TEXT], NULL),+ jsonb_build_object(''totalAmount'', si."totalAmount", ''dateDue'', si."dateDue"),+ to_tsvector(''english'', si."invoiceId" || '' '' || COALESCE(c.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[si.status::TEXT], NULL), '' ''), ''''))+ FROM "salesInvoice" si+ LEFT JOIN "customer" c ON c.id = si."customerId"+ WHERE si."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate purchase invoices+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''purchaseInvoice'',+ pi.id,+ pi."invoiceId",+ COALESCE(s.name, ''''),+ ''/x/invoicing/purchasing/'' || pi.id,+ ARRAY_REMOVE(ARRAY[pi.status::TEXT], NULL),+ jsonb_build_object(''totalAmount'', pi."totalAmount", ''dateDue'', pi."dateDue"),+ to_tsvector(''english'', pi."invoiceId" || '' '' || COALESCE(s.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[pi.status::TEXT], NULL), '' ''), ''''))+ FROM "purchaseInvoice" pi+ LEFT JOIN "supplier" s ON s.id = pi."supplierId"+ WHERE pi."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate non-conformances (issues)+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''issue'',+ nc.id,+ nc."nonConformanceId",+ nc.name || '' '' || COALESCE(nc.description, ''''),+ ''/x/issue/'' || nc.id,+ ARRAY_REMOVE(ARRAY[nc.status::TEXT, nc.priority::TEXT, nct.name], NULL),+ jsonb_build_object(''source'', nc.source, ''dueDate'', nc."dueDate"),+ to_tsvector(''english'', nc."nonConformanceId" || '' '' || nc.name || '' '' || COALESCE(nc.description, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[nc.status::TEXT, nc.priority::TEXT, nct.name], NULL), '' ''), ''''))+ FROM "nonConformance" nc+ LEFT JOIN "nonConformanceType" nct ON nct.id = nc."nonConformanceTypeId"+ WHERE nc."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Populate gauges+ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ SELECT+ ''gauge'',+ g.id,+ g."gaugeId",+ COALESCE(g.description, '''') || '' '' || COALESCE(g."serialNumber", ''''),+ ''/x/quality/gauges/'' || g.id,+ ARRAY_REMOVE(ARRAY[g."gaugeStatus"::TEXT, g."gaugeCalibrationStatus"::TEXT, gt.name], NULL),+ jsonb_build_object(''nextCalibrationDate'', g."nextCalibrationDate", ''serialNumber'', g."serialNumber"),+ to_tsvector(''english'', g."gaugeId" || '' '' || COALESCE(g.description, '''') || '' '' || COALESCE(g."serialNumber", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[g."gaugeStatus"::TEXT, g."gaugeCalibrationStatus"::TEXT, gt.name], NULL), '' ''), ''''))+ FROM "gauge" g+ LEFT JOIN "gaugeType" gt ON gt.id = g."gaugeTypeId"+ WHERE g."companyId" = $1+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET+ "title" = EXCLUDED."title",+ "description" = EXCLUDED."description",+ "tags" = EXCLUDED."tags",+ "metadata" = EXCLUDED."metadata",+ "searchVector" = EXCLUDED."searchVector",+ "updatedAt" = NOW()+ ', v_table_name) USING p_company_id;++ -- Update registry+ UPDATE "searchIndexRegistry"+ SET "lastRebuiltAt" = NOW()+ WHERE "companyId" = p_company_id;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- =============================================================================+-- PART 7: Create Search Function for API+-- =============================================================================++CREATE OR REPLACE FUNCTION search_company_index(+ p_company_id TEXT,+ p_query TEXT,+ p_entity_types TEXT[],+ p_limit INT DEFAULT 20+)+RETURNS TABLE (+ id BIGINT,+ "entityType" TEXT,+ "entityId" TEXT,+ title TEXT,+ description TEXT,+ link TEXT,+ tags TEXT[],+ metadata JSONB+) AS $$+DECLARE+ v_table_name TEXT;+ v_like_pattern TEXT;+BEGIN+ v_table_name := 'searchIndex_' || p_company_id;+ v_like_pattern := '%' || p_query || '%';++ RETURN QUERY EXECUTE format('+ SELECT+ si.id,+ si."entityType",+ si."entityId",+ si.title,+ si.description,+ si.link,+ si.tags,+ si.metadata+ FROM %I si+ WHERE (+ si.title ILIKE $1+ OR si.description ILIKE $1+ OR si."searchVector" @@ websearch_to_tsquery(''english'', $2)+ )+ AND si."entityType" = ANY($3)+ ORDER BY+ -- Prefix match on title first (starts with query)+ CASE WHEN lower(si.title) LIKE lower($4) THEN 0 ELSE 1 END,+ -- Contains match in title+ CASE WHEN si.title ILIKE $1 THEN 0 ELSE 1 END,+ -- Then by recency (higher id = more recent)+ si.id DESC+ LIMIT $5+ ', v_table_name)+ USING v_like_pattern, p_query, p_entity_types, p_query || '%', p_limit;+END;+$$ LANGUAGE plpgsql SECURITY INVOKER;++-- =============================================================================+-- PART 8: Create Search Indexes for Existing Companies and Populate Data+-- =============================================================================++DO $$+DECLARE+ company_record RECORD;+BEGIN+ FOR company_record IN SELECT id FROM "company"+ LOOP+ PERFORM create_company_search_index(company_record.id);+ PERFORM populate_company_search_index(company_record.id);+ END LOOP;+END $$;diff --git a/packages/jobs/trigger/weekly.ts b/packages/jobs/trigger/weekly.tsindex 8f53340ae2..6547ceab67 100644--- a/packages/jobs/trigger/weekly.ts+++ b/packages/jobs/trigger/weekly.ts@@ -90,6 +90,8 @@ export const weekly = schedules.task({console.log(`Companies to delete: ${companiesToDelete.length}`);++const { error: deletedCompaniesError } = await serviceRole.from("company").delete()@@ -109,6 +111,21 @@ export const weekly = schedules.task({console.log(`Deleted company ${company.name}`);}}++ // Drop search index tables for companies being deleted+ for (const company of companiesToDelete) {+ const { error: dropSearchError } = await serviceRole.rpc(+ "drop_company_search_index",+ { p_company_id: company.id }+ );+ if (dropSearchError) {+ console.error(+ `Failed to drop search index for company ${company.name}: ${dropSearchError.message}`+ );+ } else {+ console.log(`Dropped search index for company ${company.name}`);+ }+ }}// Notify employees with outstanding trainings (Pending or Overdue)