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
Move search indexing to async event system
Sidwebworks859caac92347
diff --git a/packages/database/src/event.ts b/packages/database/src/event.tsindex 28fad30db9..ddc501e951 100644--- a/packages/database/src/event.ts+++ b/packages/database/src/event.ts@@ -1,6 +1,5 @@-import type { Kysely } from "kysely";+import type { SupabaseClient } from "@supabase/supabase-js";import { z } from "zod";-import type { KyselyDatabase } from "./client.ts";export const OperationSchema = z.enum(["INSERT",@@ -9,7 +8,7 @@ export const OperationSchema = z.enum(["TRUNCATE"]);-const HandlerTypeSchema = z.enum(["WEBHOOK", "WORKFLOW", "SYNC"]);+const HandlerTypeSchema = z.enum(["WEBHOOK", "WORKFLOW", "SYNC", "SEARCH"]);export const EventSchema = z.discriminatedUnion("operation", [z.object({@@ -50,17 +49,13 @@ export const QueueMessageSchema = z.object({export type EventSystemEvent = z.infer<typeof EventSchema>;export type HandlerType = z.infer<typeof HandlerTypeSchema>;export type QueueMessage = z.infer<typeof QueueMessageSchema>;+export type Operation = z.infer<typeof OperationSchema>;// The Main Subscription Schemaexport const CreateSubscriptionSchema = z.object({name: z.string().min(1, "Name is required"),// The table name in your database- table: z.custom<keyof Pick<KyselyDatabase, keyof KyselyDatabase>>(- (val) => typeof val === "string",- {- message: "Table name must be a string"- }- ),+ table: z.string().min(1, "Table name is required"),// The company this subscription belongs tocompanyId: z.string().min(1, "Company ID is required"),// Must provide at least one operation (e.g. ['INSERT'])@@ -80,61 +75,135 @@ export const CreateSubscriptionSchema = z.object({export type CreateSubscriptionParams = z.input<typeof CreateSubscriptionSchema>;+// Return type for subscription creation+export type SubscriptionResult = {+ id: string;+ name: string;+ handlerType: string;+ table: string;+};++// Type for Supabase client with our custom RPC functions+// These RPC functions are defined in the migration+type EventSystemRpcClient = {+ rpc(+ fn: "create_event_system_subscription",+ params: {+ p_name: string;+ p_table: string;+ p_company_id: string;+ p_operations: string[];+ p_handler_type: string;+ p_config?: Record<string, any>;+ p_filter?: Record<string, any>;+ p_active?: boolean;+ }+ ): Promise<{ data: SubscriptionResult[] | null; error: any }>;+ rpc(+ fn: "delete_event_system_subscription",+ params: { p_subscription_id: string }+ ): Promise<{ data: any; error: any }>;+ rpc(+ fn: "delete_event_system_subscriptions_by_name",+ params: { p_company_id: string; p_name: string }+ ): Promise<{ data: any; error: any }>;+};++/**+ * Creates or updates an event system subscription using RPC.+ *+ * @param client - Supabase client (e.g., from getCarbonServiceRole())+ * @param input - Subscription parameters+ * @returns The created/updated subscription+ * @throws Error if the RPC call fails+ *+ * @example+ * ```ts+ * const client = getCarbonServiceRole();+ * const subscription = await createEventSystemSubscription(client, {+ * name: "my-webhook",+ * table: "customer",+ * companyId: "company-123",+ * operations: ["INSERT", "UPDATE"],+ * type: "WEBHOOK",+ * config: { url: "https://example.com/webhook" },+ * });+ * ```+ */export async function createEventSystemSubscription(- client: Kysely<KyselyDatabase>,+ client: SupabaseClient | EventSystemRpcClient,input: CreateSubscriptionParams-) {+): Promise<SubscriptionResult | undefined> {// 1. Runtime Validation- // This throws a clear ZodError if inputs are wrong (e.g. missing 'table' or invalid 'type')const params = CreateSubscriptionSchema.parse(input);- // 2. Database Insert- // Note: We cast arrays/objects to ensure Postgres driver handles them correctly- const result = await client- .insertInto("eventSystemSubscription")- .values({- name: params.name,- table: params.table,- companyId: params.companyId,- operations: params.operations,- filter: params.filter,- handlerType: params.type,- config: params.config,- active: params.active- })- .onConflict((oc) =>- oc.constraint("unique_subscription_name_per_company").doUpdateSet({- operations: params.operations,- filter: params.filter,- handlerType: params.type,- config: params.config,- active: params.active- })- )- .returning(["id", "name", "handlerType", "table"])- .executeTakeFirst();-- return result;+ // 2. Call RPC function+ const { data, error } = await (client as EventSystemRpcClient).rpc(+ "create_event_system_subscription",+ {+ p_name: params.name,+ p_table: params.table,+ p_company_id: params.companyId,+ p_operations: params.operations,+ p_handler_type: params.type,+ p_config: params.config,+ p_filter: params.filter,+ p_active: params.active+ }+ );++ if (error) {+ throw new Error(`Failed to create subscription: ${error.message}`);+ }++ return data?.[0];}+/**+ * Deletes an event system subscription by ID.+ *+ * @param client - Supabase client+ * @param subscriptionId - The ID of the subscription to delete+ * @throws Error if the RPC call fails+ */export async function deleteEventSystemSubscription(- client: Kysely<KyselyDatabase>,+ client: SupabaseClient | EventSystemRpcClient,subscriptionId: string-) {- await client- .deleteFrom("eventSystemSubscription")- .where("id", "=", subscriptionId)- .execute();+): Promise<void> {+ const { error } = await (client as EventSystemRpcClient).rpc(+ "delete_event_system_subscription",+ {+ p_subscription_id: subscriptionId+ }+ );++ if (error) {+ throw new Error(`Failed to delete subscription: ${error.message}`);+ }}+/**+ * Deletes all event system subscriptions with a given name for a company.+ *+ * @param client - Supabase client+ * @param companyId - The company ID+ * @param name - The subscription name to delete+ * @throws Error if the RPC call fails+ */export async function deleteEventSystemSubscriptionsByName(- client: Kysely<KyselyDatabase>,+ client: SupabaseClient | EventSystemRpcClient,companyId: string,name: string-) {- await client- .deleteFrom("eventSystemSubscription")- .where("companyId", "=", companyId)- .where("name", "=", name)- .execute();+): Promise<void> {+ const { error } = await (client as EventSystemRpcClient).rpc(+ "delete_event_system_subscriptions_by_name",+ {+ p_company_id: companyId,+ p_name: name+ }+ );++ if (error) {+ throw new Error(`Failed to delete subscriptions: ${error.message}`);+ }}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 3cfb25bb53..7da731c605 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -4041,9 +4041,6 @@ export default {{$ref: "#/parameters/rowFilter.approvalRequests.requestedAt",},- {- $ref: "#/parameters/rowFilter.approvalRequests.approverId",- },{$ref: "#/parameters/rowFilter.approvalRequests.decisionBy",},@@ -40611,9 +40608,6 @@ export default {{$ref: "#/parameters/rowFilter.approvalRequest.requestedAt",},- {- $ref: "#/parameters/rowFilter.approvalRequest.approverId",- },{$ref: "#/parameters/rowFilter.approvalRequest.decisionBy",},@@ -40718,9 +40712,6 @@ export default {{$ref: "#/parameters/rowFilter.approvalRequest.requestedAt",},- {- $ref: "#/parameters/rowFilter.approvalRequest.approverId",- },{$ref: "#/parameters/rowFilter.approvalRequest.decisionBy",},@@ -40779,9 +40770,6 @@ export default {{$ref: "#/parameters/rowFilter.approvalRequest.requestedAt",},- {- $ref: "#/parameters/rowFilter.approvalRequest.approverId",- },{$ref: "#/parameters/rowFilter.approvalRequest.decisionBy",},@@ -63454,6 +63442,49 @@ export default {tags: ["(rpc) get_unscheduled_jobs"],},},+ "/rpc/delete_from_search_index": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ p_entity_id: {+ format: "text",+ type: "string",+ },+ p_entity_type: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_company_id", "p_entity_type", "p_entity_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) delete_from_search_index"],+ },+ },"/rpc/get_direct_ancestors_of_tracked_entity": {post: {parameters: [@@ -64992,6 +65023,80 @@ export default {tags: ["(rpc) xid_pid"],},},+ "/rpc/upsert_to_search_index": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ p_description: {+ format: "text",+ type: "string",+ },+ p_entity_id: {+ format: "text",+ type: "string",+ },+ p_entity_type: {+ format: "text",+ type: "string",+ },+ p_link: {+ format: "text",+ type: "string",+ },+ p_metadata: {+ format: "jsonb",+ },+ p_tags: {+ format: "text[]",+ items: {+ type: "string",+ },+ type: "array",+ },+ p_title: {+ format: "text",+ type: "string",+ },+ },+ required: [+ "p_company_id",+ "p_entity_type",+ "p_entity_id",+ "p_title",+ "p_description",+ "p_link",+ "p_tags",+ "p_metadata",+ ],+ 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) upsert_to_search_index"],+ },+ },"/rpc/get_active_job_count": {post: {parameters: [@@ -65031,6 +65136,45 @@ export default {tags: ["(rpc) get_active_job_count"],},},+ "/rpc/delete_event_system_subscriptions_by_name": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string",+ },+ p_name: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_company_id", "p_name"],+ 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) delete_event_system_subscriptions_by_name"],+ },+ },"/rpc/groups_for_user": {post: {parameters: [@@ -66330,6 +66474,41 @@ export default {tags: ["(rpc) has_role"],},},+ "/rpc/delete_event_system_subscription": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_subscription_id: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_subscription_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) delete_event_system_subscription"],+ },+ },"/rpc/has_valid_api_key_for_company": {post: {parameters: [@@ -66472,6 +66651,41 @@ export default {tags: ["(rpc) get_job_methods_by_method_id"],},},+ "/rpc/create_search_subscriptions_for_company": {+ 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_search_subscriptions_for_company"],+ },+ },"/rpc/groups_query": {post: {parameters: [@@ -66944,6 +67158,76 @@ export default {tags: ["(rpc) get_purchasing_planning"],},},+ "/rpc/create_event_system_subscription": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_active: {+ format: "boolean",+ type: "boolean",+ },+ p_company_id: {+ format: "text",+ type: "string",+ },+ p_config: {+ format: "jsonb",+ },+ p_filter: {+ format: "jsonb",+ },+ p_handler_type: {+ format: "text",+ type: "string",+ },+ p_name: {+ format: "text",+ type: "string",+ },+ p_operations: {+ format: "text[]",+ items: {+ type: "string",+ },+ type: "array",+ },+ p_table: {+ format: "text",+ type: "string",+ },+ },+ required: [+ "p_name",+ "p_table",+ "p_company_id",+ "p_operations",+ "p_handler_type",+ ],+ 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_event_system_subscription"],+ },+ },"/rpc/get_maintenance_dispatches_by_location": {post: {parameters: [@@ -69072,12 +69356,6 @@ export default {format: "timestamp with time zone",type: "string",},- approverId: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string",- },decisionBy: {description:"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",@@ -86141,12 +86419,6 @@ export default {format: "timestamp with time zone",type: "string",},- approverId: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string",- },decisionBy: {description:"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",@@ -99354,12 +99626,6 @@ export default {in: "query",type: "string",},- "rowFilter.approvalRequests.approverId": {- name: "approverId",- required: false,- in: "query",- type: "string",- },"rowFilter.approvalRequests.decisionBy": {name: "decisionBy",required: false,@@ -118566,12 +118832,6 @@ export default {in: "query",type: "string",},- "rowFilter.approvalRequest.approverId": {- name: "approverId",- required: false,- in: "query",- type: "string",- },"rowFilter.approvalRequest.decisionBy": {name: "decisionBy",required: false,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex be46e6ae26..42c490c16c 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -32978,48 +32978,6 @@ export type Database = {},]}- searchIndex_KyfnMsRatxt2eAMBNgdxQK: {- Row: {- createdAt: string- description: string | null- entityId: string- entityType: string- id: number- link: string- metadata: Json | null- searchVector: unknown- tags: string[] | null- title: string- updatedAt: string | null- }- Insert: {- createdAt?: string- description?: string | null- entityId: string- entityType: string- id?: number- link: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title: string- updatedAt?: string | null- }- Update: {- createdAt?: string- description?: string | null- entityId?: string- entityType?: string- id?: number- link?: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title?: string- updatedAt?: string | null- }- Relationships: []- }searchIndexRegistry: {Row: {companyId: string@@ -47323,14 +47281,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -48719,14 +48677,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"]@@ -51850,14 +51808,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"]@@ -55432,6 +55390,24 @@ export type Database = {Args: { p_company_id: string }Returns: undefined}+ create_event_system_subscription: {+ Args: {+ p_active?: boolean+ p_company_id: string+ p_config?: Json+ p_filter?: Json+ p_handler_type: string+ p_name: string+ p_operations: string[]+ p_table: string+ }+ Returns: {+ handlerType: string+ id: string+ name: string+ table: string+ }[]+ }create_rfq_from_model_v1: {Args: {company_id: string@@ -55474,6 +55450,26 @@ export type Database = {rfq_readable_id: string}[]}+ create_search_subscriptions_for_company: {+ Args: { p_company_id: string }+ Returns: undefined+ }+ delete_event_system_subscription: {+ Args: { p_subscription_id: string }+ Returns: undefined+ }+ delete_event_system_subscriptions_by_name: {+ Args: { p_company_id: string; p_name: string }+ Returns: undefined+ }+ delete_from_search_index: {+ Args: {+ p_company_id: string+ p_entity_id: string+ p_entity_type: string+ }+ Returns: undefined+ }drop_company_search_index: {Args: { p_company_id: string }Returns: undefined@@ -56928,6 +56924,19 @@ export type Database = {}Returns: undefined}+ upsert_to_search_index: {+ Args: {+ p_company_id: string+ p_description: string+ p_entity_id: string+ p_entity_type: string+ p_link: string+ p_metadata: Json+ p_tags: string[]+ p_title: string+ }+ Returns: undefined+ }users_for_groups: { Args: { groups: string[] }; Returns: Json }uuid_generate_v4: { Args: never; Returns: string }uuid_to_base58: { Args: { _uuid: string }; Returns: string }diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 8d0b9e6a8f..42c490c16c 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1692,7 +1692,6 @@ export type Database = {approvalRequest: {Row: {amount: number | null- approverId: string | nullcompanyId: stringcreatedAt: stringcreatedBy: string@@ -1710,7 +1709,6 @@ export type Database = {}Insert: {amount?: number | null- approverId?: string | nullcompanyId: stringcreatedAt?: stringcreatedBy: string@@ -1728,7 +1726,6 @@ export type Database = {}Update: {amount?: number | null- approverId?: string | nullcompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -1745,41 +1742,6 @@ export type Database = {updatedBy?: string | null}Relationships: [- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },{foreignKeyName: "approvalRequest_companyId_fkey"columns: ["companyId"]@@ -42680,7 +42642,6 @@ export type Database = {}approvalRequests: {Row: {- approverId: string | nullcompanyId: string | nullcreatedAt: string | nulldecisionAt: string | null@@ -42698,41 +42659,6 @@ export type Database = {status: Database["public"]["Enums"]["approvalStatus"] | null}Relationships: [- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "approvalRequest_approverId_fkey"- columns: ["approverId"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },{foreignKeyName: "approvalRequest_companyId_fkey"columns: ["companyId"]@@ -55464,6 +55390,24 @@ export type Database = {Args: { p_company_id: string }Returns: undefined}+ create_event_system_subscription: {+ Args: {+ p_active?: boolean+ p_company_id: string+ p_config?: Json+ p_filter?: Json+ p_handler_type: string+ p_name: string+ p_operations: string[]+ p_table: string+ }+ Returns: {+ handlerType: string+ id: string+ name: string+ table: string+ }[]+ }create_rfq_from_model_v1: {Args: {company_id: string@@ -55506,6 +55450,26 @@ export type Database = {rfq_readable_id: string}[]}+ create_search_subscriptions_for_company: {+ Args: { p_company_id: string }+ Returns: undefined+ }+ delete_event_system_subscription: {+ Args: { p_subscription_id: string }+ Returns: undefined+ }+ delete_event_system_subscriptions_by_name: {+ Args: { p_company_id: string; p_name: string }+ Returns: undefined+ }+ delete_from_search_index: {+ Args: {+ p_company_id: string+ p_entity_id: string+ p_entity_type: string+ }+ Returns: undefined+ }drop_company_search_index: {Args: { p_company_id: string }Returns: undefined@@ -56960,6 +56924,19 @@ export type Database = {}Returns: undefined}+ upsert_to_search_index: {+ Args: {+ p_company_id: string+ p_description: string+ p_entity_id: string+ p_entity_type: string+ p_link: string+ p_metadata: Json+ p_tags: string[]+ p_title: string+ }+ Returns: undefined+ }users_for_groups: { Args: { groups: string[] }; Returns: Json }uuid_generate_v4: { Args: never; Returns: string }uuid_to_base58: { Args: { _uuid: string }; Returns: string }diff --git a/packages/database/supabase/migrations/20260204080000_async-search-triggers.sql b/packages/database/supabase/migrations/20260204080000_async-search-triggers.sqlnew file mode 100644index 0000000000..cc3630884a--- /dev/null+++ b/packages/database/supabase/migrations/20260204080000_async-search-triggers.sql@@ -0,0 +1,352 @@+-- =============================================================================+-- Migrate Search Triggers to Async Event System+-- This migration:+-- 1. Adds SEARCH to handlerType enum+-- 2. Creates helper RPC functions for search index operations+-- 3. Drops old row-level search triggers+-- 4. Attaches async statement-level triggers via event system+-- 5. Creates internal search subscriptions for all companies+-- =============================================================================++-- =============================================================================+-- PART 1: Update handlerType CHECK constraint to include SEARCH+-- =============================================================================++ALTER TABLE "eventSystemSubscription"+DROP CONSTRAINT IF EXISTS "eventSystemSubscription_handlerType_check";++ALTER TABLE "eventSystemSubscription"+ADD CONSTRAINT "eventSystemSubscription_handlerType_check"+CHECK ("handlerType" IN ('WEBHOOK', 'WORKFLOW', 'SYNC', 'SEARCH'));+++-- =============================================================================+-- PART 2: Create Helper RPC Functions for Search Index Operations+-- =============================================================================++-- Delete from search index (handles dynamic table name)+CREATE OR REPLACE FUNCTION delete_from_search_index(+ p_company_id TEXT,+ p_entity_type TEXT,+ p_entity_id TEXT+)+RETURNS VOID AS $$+DECLARE+ v_table_name TEXT;+BEGIN+ v_table_name := 'searchIndex_' || p_company_id;++ EXECUTE format(+ 'DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2',+ v_table_name+ ) USING p_entity_type, p_entity_id;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+++-- Upsert to search index (handles dynamic table name)+CREATE OR REPLACE FUNCTION upsert_to_search_index(+ p_company_id TEXT,+ p_entity_type TEXT,+ p_entity_id TEXT,+ p_title TEXT,+ p_description TEXT,+ p_link TEXT,+ p_tags TEXT[],+ p_metadata JSONB+)+RETURNS VOID AS $$+DECLARE+ v_table_name TEXT;+ v_search_text TEXT;+BEGIN+ v_table_name := 'searchIndex_' || p_company_id;+ v_search_text := p_title || ' ' || COALESCE(p_description, '') || ' ' || COALESCE(array_to_string(p_tags, ' '), '');++ EXECUTE format('+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $8))+ 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_entity_type,+ p_entity_id,+ p_title,+ COALESCE(p_description, ''),+ p_link,+ COALESCE(p_tags, ARRAY[]::text[]),+ COALESCE(p_metadata, '{}'::jsonb),+ v_search_text;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+++-- =============================================================================+-- PART 3: Drop Old Row-Level Search Triggers+-- =============================================================================++-- Employee triggers+DROP TRIGGER IF EXISTS sync_employee_search_insert ON "employee";+DROP TRIGGER IF EXISTS sync_employee_search_update ON "employee";+DROP TRIGGER IF EXISTS sync_employee_search_delete ON "employee";++-- Customer triggers+DROP TRIGGER IF EXISTS sync_customer_search_insert ON "customer";+DROP TRIGGER IF EXISTS sync_customer_search_update ON "customer";+DROP TRIGGER IF EXISTS sync_customer_search_delete ON "customer";++-- Supplier triggers+DROP TRIGGER IF EXISTS sync_supplier_search_insert ON "supplier";+DROP TRIGGER IF EXISTS sync_supplier_search_update ON "supplier";+DROP TRIGGER IF EXISTS sync_supplier_search_delete ON "supplier";++-- Item triggers+DROP TRIGGER IF EXISTS sync_item_search_insert ON "item";+DROP TRIGGER IF EXISTS sync_item_search_update ON "item";+DROP TRIGGER IF EXISTS sync_item_search_delete ON "item";++-- Job triggers+DROP TRIGGER IF EXISTS sync_job_search_insert ON "job";+DROP TRIGGER IF EXISTS sync_job_search_update ON "job";+DROP TRIGGER IF EXISTS sync_job_search_delete ON "job";++-- Purchase Order triggers+DROP TRIGGER IF EXISTS sync_purchase_order_search_insert ON "purchaseOrder";+DROP TRIGGER IF EXISTS sync_purchase_order_search_update ON "purchaseOrder";+DROP TRIGGER IF EXISTS sync_purchase_order_search_delete ON "purchaseOrder";++-- Sales Invoice triggers+DROP TRIGGER IF EXISTS sync_sales_invoice_search_insert ON "salesInvoice";+DROP TRIGGER IF EXISTS sync_sales_invoice_search_update ON "salesInvoice";+DROP TRIGGER IF EXISTS sync_sales_invoice_search_delete ON "salesInvoice";++-- Purchase Invoice triggers+DROP TRIGGER IF EXISTS sync_purchase_invoice_search_insert ON "purchaseInvoice";+DROP TRIGGER IF EXISTS sync_purchase_invoice_search_update ON "purchaseInvoice";+DROP TRIGGER IF EXISTS sync_purchase_invoice_search_delete ON "purchaseInvoice";++-- Non-Conformance triggers+DROP TRIGGER IF EXISTS sync_non_conformance_search_insert ON "nonConformance";+DROP TRIGGER IF EXISTS sync_non_conformance_search_update ON "nonConformance";+DROP TRIGGER IF EXISTS sync_non_conformance_search_delete ON "nonConformance";++-- Gauge triggers+DROP TRIGGER IF EXISTS sync_gauge_search_insert ON "gauge";+DROP TRIGGER IF EXISTS sync_gauge_search_update ON "gauge";+DROP TRIGGER IF EXISTS sync_gauge_search_delete ON "gauge";++-- Quote triggers+DROP TRIGGER IF EXISTS sync_quote_search_insert ON "quote";+DROP TRIGGER IF EXISTS sync_quote_search_update ON "quote";+DROP TRIGGER IF EXISTS sync_quote_search_delete ON "quote";++-- Sales RFQ triggers+DROP TRIGGER IF EXISTS sync_sales_rfq_search_insert ON "salesRfq";+DROP TRIGGER IF EXISTS sync_sales_rfq_search_update ON "salesRfq";+DROP TRIGGER IF EXISTS sync_sales_rfq_search_delete ON "salesRfq";++-- Sales Order triggers+DROP TRIGGER IF EXISTS sync_sales_order_search_insert ON "salesOrder";+DROP TRIGGER IF EXISTS sync_sales_order_search_update ON "salesOrder";+DROP TRIGGER IF EXISTS sync_sales_order_search_delete ON "salesOrder";++-- Supplier Quote triggers+DROP TRIGGER IF EXISTS sync_supplier_quote_search_insert ON "supplierQuote";+DROP TRIGGER IF EXISTS sync_supplier_quote_search_update ON "supplierQuote";+DROP TRIGGER IF EXISTS sync_supplier_quote_search_delete ON "supplierQuote";+++-- =============================================================================+-- PART 4: Attach Async Event Triggers to All Search Tables+-- =============================================================================++-- These tables will now use the event system's async batch triggers+-- Note: attach_event_trigger creates AFTER INSERT/UPDATE/DELETE statement-level triggers++SELECT attach_event_trigger('employee', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('customer', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('supplier', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('item', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('job', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('purchaseOrder', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('salesInvoice', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('purchaseInvoice', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('nonConformance', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('gauge', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('quote', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('salesRfq', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('salesOrder', ARRAY[]::TEXT[]);+SELECT attach_event_trigger('supplierQuote', ARRAY[]::TEXT[]);+++-- =============================================================================+-- PART 5: Create Search Subscriptions for All Existing Companies+-- =============================================================================++-- Helper function to create search subscriptions for a company+CREATE OR REPLACE FUNCTION create_search_subscriptions_for_company(p_company_id TEXT)+RETURNS VOID AS $$+DECLARE+ v_tables TEXT[] := ARRAY[+ 'employee', 'customer', 'supplier', 'item', 'job',+ 'purchaseOrder', 'salesInvoice', 'purchaseInvoice',+ 'nonConformance', 'gauge', 'quote', 'salesRfq',+ 'salesOrder', 'supplierQuote'+ ];+ v_table TEXT;+BEGIN+ FOREACH v_table IN ARRAY v_tables LOOP+ INSERT INTO "eventSystemSubscription" (+ "name",+ "table",+ "companyId",+ "operations",+ "handlerType",+ "config",+ "filter",+ "active"+ )+ VALUES (+ 'search-index-' || v_table,+ v_table,+ p_company_id,+ ARRAY['INSERT', 'UPDATE', 'DELETE'],+ 'SEARCH',+ '{}'::jsonb,+ '{}'::jsonb,+ TRUE+ )+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"+ DO UPDATE SET+ "operations" = EXCLUDED."operations",+ "handlerType" = EXCLUDED."handlerType",+ "active" = EXCLUDED."active";+ END LOOP;+END;+$$ LANGUAGE plpgsql;+++-- Create subscriptions for all existing companies+DO $$+DECLARE+ company_record RECORD;+BEGIN+ FOR company_record IN SELECT id FROM "company" LOOP+ PERFORM create_search_subscriptions_for_company(company_record.id);+ END LOOP;+END $$;+++-- =============================================================================+-- PART 6: Update company creation trigger to also create search subscriptions+-- =============================================================================++-- Modify the existing on_company_created_search_index function to also create subscriptions+CREATE OR REPLACE FUNCTION on_company_created_search_index()+RETURNS TRIGGER AS $$+BEGIN+ -- Create the search index table+ PERFORM create_company_search_index(NEW.id);++ -- Create search subscriptions for the event system+ PERFORM create_search_subscriptions_for_company(NEW.id);++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+++-- =============================================================================+-- PART 7: RPC Functions for Event System Subscription Management+-- =============================================================================++-- Create or update an event system subscription+CREATE OR REPLACE FUNCTION create_event_system_subscription(+ p_name TEXT,+ p_table TEXT,+ p_company_id TEXT,+ p_operations TEXT[],+ p_handler_type TEXT,+ p_config JSONB DEFAULT '{}',+ p_filter JSONB DEFAULT '{}',+ p_active BOOLEAN DEFAULT TRUE+)+RETURNS TABLE (id TEXT, name TEXT, "handlerType" TEXT, "table" TEXT) AS $$+BEGIN+ RETURN QUERY+ INSERT INTO "eventSystemSubscription" (+ "name", "table", "companyId", "operations",+ "handlerType", "config", "filter", "active"+ )+ VALUES (+ p_name, p_table, p_company_id, p_operations,+ p_handler_type, p_config, p_filter, p_active+ )+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"+ DO UPDATE SET+ "operations" = EXCLUDED."operations",+ "filter" = EXCLUDED."filter",+ "handlerType" = EXCLUDED."handlerType",+ "config" = EXCLUDED."config",+ "active" = EXCLUDED."active"+ RETURNING+ "eventSystemSubscription"."id",+ "eventSystemSubscription"."name",+ "eventSystemSubscription"."handlerType",+ "eventSystemSubscription"."table";+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+++-- Delete an event system subscription by ID+CREATE OR REPLACE FUNCTION delete_event_system_subscription(+ p_subscription_id TEXT+)+RETURNS VOID AS $$+BEGIN+ DELETE FROM "eventSystemSubscription" WHERE "id" = p_subscription_id;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+++-- Delete event system subscriptions by name and company+CREATE OR REPLACE FUNCTION delete_event_system_subscriptions_by_name(+ p_company_id TEXT,+ p_name TEXT+)+RETURNS VOID AS $$+BEGIN+ DELETE FROM "eventSystemSubscription"+ WHERE "companyId" = p_company_id AND "name" = p_name;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+++-- =============================================================================+-- PART 8: Drop old sync functions (keeping them for now as they may be useful)+-- =============================================================================++-- Note: We're keeping the old sync_*_to_search_index functions for now+-- They could be useful for manual re-indexing or debugging+-- If you want to drop them, uncomment the following:++-- DROP FUNCTION IF EXISTS sync_employee_to_search_index();+-- DROP FUNCTION IF EXISTS sync_customer_to_search_index();+-- DROP FUNCTION IF EXISTS sync_supplier_to_search_index();+-- DROP FUNCTION IF EXISTS sync_item_to_search_index();+-- DROP FUNCTION IF EXISTS sync_job_to_search_index();+-- DROP FUNCTION IF EXISTS sync_purchase_order_to_search_index();+-- DROP FUNCTION IF EXISTS sync_sales_invoice_to_search_index();+-- DROP FUNCTION IF EXISTS sync_purchase_invoice_to_search_index();+-- DROP FUNCTION IF EXISTS sync_non_conformance_to_search_index();+-- DROP FUNCTION IF EXISTS sync_gauge_to_search_index();+-- DROP FUNCTION IF EXISTS sync_quote_to_search_index();+-- DROP FUNCTION IF EXISTS sync_sales_rfq_to_search_index();+-- DROP FUNCTION IF EXISTS sync_sales_order_to_search_index();+-- DROP FUNCTION IF EXISTS sync_supplier_quote_to_search_index();diff --git a/packages/jobs/trigger/event/queue.ts b/packages/jobs/trigger/event/queue.tsindex d076ac619f..cab00f1e42 100644--- a/packages/jobs/trigger/event/queue.ts+++ b/packages/jobs/trigger/event/queue.ts@@ -7,6 +7,7 @@ import { HandlerType, QueueMessage } from "@carbon/database/event";import { all } from "@carbon/utils";import { schedules } from "@trigger.dev/sdk";import { Kysely, PostgresDriver, sql } from "kysely";+import { searchTask } from "./search.ts";import { syncTask } from "./sync.ts";import { webhookTask } from "./webhook.ts";import { workflowDispatchTask } from "./workflow.ts";@@ -54,6 +55,7 @@ export const eventQueueTask = schedules.task({WEBHOOK: [],WORKFLOW: [],SYNC: [],+ SEARCH: [],};// 2. Sort into Buckets@@ -61,7 +63,7 @@ export const eventQueueTask = schedules.task({grouped[job.message.handlerType].push(job);}- const { webhooks, syncs, workflows } = await all({+ const { webhooks, syncs, workflows, searches } = await all({async webhooks() {let queue: number[] = [];@@ -134,11 +136,31 @@ export const eventQueueTask = schedules.task({records,});+ return queue;+ },+ async searches() {+ let queue: number[] = [];++ if (grouped.SEARCH.length === 0) return queue;++ const records = grouped.SEARCH.map((job) => {+ queue.push(job.msg_id);++ return {+ event: job.message.event,+ companyId: job.message.companyId,+ };+ });++ await searchTask.trigger({+ records,+ });+return queue;},});- total = total.concat(webhooks, workflows, syncs);+ total = total.concat(webhooks, workflows, syncs, searches);// 5. Delete from PGMQ// We delete immediately because we have successfully offloadeddiff --git a/packages/jobs/trigger/event/search.ts b/packages/jobs/trigger/event/search.tsnew file mode 100644index 0000000000..5cf3fe4c8f--- /dev/null+++ b/packages/jobs/trigger/event/search.ts@@ -0,0 +1,478 @@+import { getCarbonServiceRole } from "@carbon/auth";+import { groupBy } from "@carbon/utils";+import { logger, task } from "@trigger.dev/sdk/v3";+import { z } from "zod";++// Type for the Supabase client with our custom RPC functions+// These are defined in the migration but types won't be generated until after migration runs+type SearchRpcClient = ReturnType<typeof getCarbonServiceRole> & {+ rpc(+ fn: "delete_from_search_index",+ params: { p_company_id: string; p_entity_type: string; p_entity_id: string }+ ): Promise<any>;+ rpc(+ fn: "upsert_to_search_index",+ params: {+ p_company_id: string;+ p_entity_type: string;+ p_entity_id: string;+ p_title: string;+ p_description: string;+ p_link: string;+ p_tags: string[];+ p_metadata: Record<string, any>;+ }+ ): Promise<any>;+};++// Configuration for each entity type's search indexing+type SearchEntityConfig = {+ entityType: string;+ getTitle: (record: Record<string, any>) => string;+ getDescription?: (record: Record<string, any>) => string;+ getLink: (record: Record<string, any>) => string;+ getTags: (record: Record<string, any>) => string[];+ getMetadata: (record: Record<string, any>) => Record<string, any>;+ // Optional: lookup additional data from related tables+ enrichRecord?: (+ record: Record<string, any>,+ client: ReturnType<typeof getCarbonServiceRole>+ ) => Promise<Record<string, any>>;+};++// Entity configurations matching the existing sync functions+const SEARCH_ENTITY_CONFIGS: Record<string, SearchEntityConfig> = {+ employee: {+ entityType: "employee",+ getTitle: (r) => r.fullName || "",+ getLink: (r) => `/x/person/${r.id}`,+ getTags: (r) => [r.employeeTypeName].filter(Boolean),+ getMetadata: (r) => ({ active: r.active }),+ enrichRecord: async (record, client) => {+ const { data: user } = await client+ .from("user")+ .select("fullName")+ .eq("id", record.id)+ .single();+ const { data: empType } = await client+ .from("employeeType")+ .select("name")+ .eq("id", record.employeeTypeId)+ .single();+ return {+ ...record,+ fullName: user?.fullName,+ employeeTypeName: empType?.name,+ };+ },+ },+ customer: {+ entityType: "customer",+ getTitle: (r) => r.name,+ getLink: (r) => `/x/customer/${r.id}`,+ getTags: (r) => [r.customerTypeName, r.customerStatusName].filter(Boolean),+ getMetadata: (r) => ({ taxId: r.taxId }),+ enrichRecord: async (record, client) => {+ const { data: custType } = await client+ .from("customerType")+ .select("name")+ .eq("id", record.customerTypeId)+ .single();+ const { data: custStatus } = await client+ .from("customerStatus")+ .select("name")+ .eq("id", record.customerStatusId)+ .single();+ return {+ ...record,+ customerTypeName: custType?.name,+ customerStatusName: custStatus?.name,+ };+ },+ },+ supplier: {+ entityType: "supplier",+ getTitle: (r) => r.name,+ getLink: (r) => `/x/supplier/${r.id}`,+ getTags: (r) => [r.supplierTypeName, r.supplierStatusName].filter(Boolean),+ getMetadata: (r) => ({ taxId: r.taxId }),+ enrichRecord: async (record, client) => {+ const { data: suppType } = await client+ .from("supplierType")+ .select("name")+ .eq("id", record.supplierTypeId)+ .single();+ const { data: suppStatus } = await client+ .from("supplierStatus")+ .select("name")+ .eq("id", record.supplierStatusId)+ .single();+ return {+ ...record,+ supplierTypeName: suppType?.name,+ supplierStatusName: suppStatus?.name,+ };+ },+ },+ item: {+ entityType: "item",+ getTitle: (r) => r.readableId,+ getDescription: (r) => `${r.name} ${r.description || ""}`,+ getLink: (r) => {+ const typeLinks: Record<string, string> = {+ Part: "/x/part/",+ Service: "/x/service/",+ Tool: "/x/tool/",+ Consumable: "/x/consumable/",+ Material: "/x/material/",+ Fixture: "/x/fixture/",+ };+ return (typeLinks[r.type] || "/x/part/") + r.id;+ },+ getTags: (r) => [r.type, r.replenishmentSystem].filter(Boolean),+ getMetadata: (r) => ({ active: r.active }),+ },+ job: {+ entityType: "job",+ getTitle: (r) => r.jobId,+ getDescription: (r) => `${r.itemName || ""} ${r.customerName || ""}`,+ getLink: (r) => `/x/job/${r.id}`,+ getTags: (r) => [r.status, r.deadlineType].filter(Boolean),+ getMetadata: (r) => ({ quantity: r.quantity, dueDate: r.dueDate }),+ enrichRecord: async (record, client) => {+ const { data: item } = await client+ .from("item")+ .select("name")+ .eq("id", record.itemId)+ .single();+ const { data: customer } = await client+ .from("customer")+ .select("name")+ .eq("id", record.customerId)+ .single();+ return {+ ...record,+ itemName: item?.name,+ customerName: customer?.name,+ };+ },+ },+ purchaseOrder: {+ entityType: "purchaseOrder",+ getTitle: (r) => r.purchaseOrderId,+ getDescription: (r) => r.supplierName || "",+ getLink: (r) => `/x/purchase-order/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ orderDate: r.orderDate,+ supplierReference: r.supplierReference,+ }),+ enrichRecord: async (record, client) => {+ const { data: supplier } = await client+ .from("supplier")+ .select("name")+ .eq("id", record.supplierId)+ .single();+ return { ...record, supplierName: supplier?.name };+ },+ },+ salesInvoice: {+ entityType: "salesInvoice",+ getTitle: (r) => r.invoiceId,+ getDescription: (r) => r.customerName || "",+ getLink: (r) => `/x/invoicing/sales/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({ totalAmount: r.totalAmount, dateDue: r.dateDue }),+ enrichRecord: async (record, client) => {+ const { data: customer } = await client+ .from("customer")+ .select("name")+ .eq("id", record.customerId)+ .single();+ return { ...record, customerName: customer?.name };+ },+ },+ purchaseInvoice: {+ entityType: "purchaseInvoice",+ getTitle: (r) => r.invoiceId,+ getDescription: (r) => r.supplierName || "",+ getLink: (r) => `/x/invoicing/purchasing/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({ totalAmount: r.totalAmount, dateDue: r.dateDue }),+ enrichRecord: async (record, client) => {+ const { data: supplier } = await client+ .from("supplier")+ .select("name")+ .eq("id", record.supplierId)+ .single();+ return { ...record, supplierName: supplier?.name };+ },+ },+ nonConformance: {+ entityType: "issue",+ getTitle: (r) => r.nonConformanceId,+ getDescription: (r) => `${r.name} ${r.description || ""}`,+ getLink: (r) => `/x/issue/${r.id}`,+ getTags: (r) => [r.status, r.priority, r.ncTypeName].filter(Boolean),+ getMetadata: (r) => ({ source: r.source, dueDate: r.dueDate }),+ enrichRecord: async (record, client) => {+ const { data: ncType } = await client+ .from("nonConformanceType")+ .select("name")+ .eq("id", record.nonConformanceTypeId)+ .single();+ return { ...record, ncTypeName: ncType?.name };+ },+ },+ gauge: {+ entityType: "gauge",+ getTitle: (r) => r.gaugeId,+ getDescription: (r) => `${r.description || ""} ${r.serialNumber || ""}`,+ getLink: (r) => `/x/quality/gauges/${r.id}`,+ getTags: (r) =>+ [r.gaugeStatus, r.gaugeCalibrationStatus, r.gaugeTypeName].filter(+ Boolean+ ),+ getMetadata: (r) => ({+ nextCalibrationDate: r.nextCalibrationDate,+ serialNumber: r.serialNumber,+ }),+ enrichRecord: async (record, client) => {+ const { data: gaugeType } = await client+ .from("gaugeType")+ .select("name")+ .eq("id", record.gaugeTypeId)+ .single();+ return { ...record, gaugeTypeName: gaugeType?.name };+ },+ },+ quote: {+ entityType: "quote",+ getTitle: (r) => r.quoteId,+ getDescription: (r) =>+ `${r.customerName || ""} ${r.customerReference || ""}`,+ getLink: (r) => `/x/quote/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ customerId: r.customerId,+ expirationDate: r.expirationDate,+ customerReference: r.customerReference,+ }),+ enrichRecord: async (record, client) => {+ const { data: customer } = await client+ .from("customer")+ .select("name")+ .eq("id", record.customerId)+ .single();+ return { ...record, customerName: customer?.name };+ },+ },+ salesRfq: {+ entityType: "salesRfq",+ getTitle: (r) => r.rfqId,+ getDescription: (r) => r.customerName || "",+ getLink: (r) => `/x/rfq/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ customerId: r.customerId,+ expirationDate: r.expirationDate,+ }),+ enrichRecord: async (record, client) => {+ const { data: customer } = await client+ .from("customer")+ .select("name")+ .eq("id", record.customerId)+ .single();+ return { ...record, customerName: customer?.name };+ },+ },+ salesOrder: {+ entityType: "salesOrder",+ getTitle: (r) => r.salesOrderId,+ getDescription: (r) =>+ `${r.customerName || ""} ${r.customerReference || ""}`,+ getLink: (r) => `/x/sales-order/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ customerId: r.customerId,+ orderDate: r.orderDate,+ customerReference: r.customerReference,+ }),+ enrichRecord: async (record, client) => {+ const { data: customer } = await client+ .from("customer")+ .select("name")+ .eq("id", record.customerId)+ .single();+ return { ...record, customerName: customer?.name };+ },+ },+ supplierQuote: {+ entityType: "supplierQuote",+ getTitle: (r) => r.supplierQuoteId,+ getDescription: (r) => r.supplierName || "",+ getLink: (r) => `/x/supplier-quote/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ supplierId: r.supplierId,+ expirationDate: r.expirationDate,+ }),+ enrichRecord: async (record, client) => {+ const { data: supplier } = await client+ .from("supplier")+ .select("name")+ .eq("id", record.supplierId)+ .single();+ return { ...record, supplierName: supplier?.name };+ },+ },+};++const SearchRecordSchema = z.object({+ event: z.object({+ table: z.string(),+ operation: z.enum(["INSERT", "UPDATE", "DELETE", "TRUNCATE"]),+ recordId: z.string(),+ new: z.record(z.any()).nullable(),+ old: z.record(z.any()).nullable(),+ timestamp: z.string(),+ }),+ companyId: z.string(),+});++const SearchPayloadSchema = z.object({+ records: z.array(SearchRecordSchema),+});++export type SearchPayload = z.infer<typeof SearchPayloadSchema>;++export const searchTask = task({+ id: "event-handler-search",+ retry: {+ maxAttempts: 3,+ factor: 2,+ randomize: true,+ },+ run: async (input: unknown) => {+ const payload = SearchPayloadSchema.parse(input);++ logger.info(`Processing ${payload.records.length} search index events`);++ const results = {+ updated: 0,+ deleted: 0,+ skipped: 0,+ failed: 0,+ };++ // Cast to include our custom RPC functions (defined in migration)+ const client = getCarbonServiceRole() as unknown as SearchRpcClient;++ // Group by companyId for efficient processing+ type SearchRecord = (typeof payload.records)[number];+ const byCompany = groupBy(payload.records, (r) => r.companyId);++ for (const [companyId, records] of Object.entries(byCompany) as [+ string,+ SearchRecord[]+ ][]) {+ if (!companyId || companyId === "undefined") {+ results.skipped += records.length;+ continue;+ }++ // Process deletions first+ const deletes = records.filter(+ (r) =>+ r.event.operation === "DELETE" || r.event.operation === "TRUNCATE"+ );++ for (const del of deletes) {+ const config = SEARCH_ENTITY_CONFIGS[del.event.table];+ if (!config) {+ results.skipped++;+ continue;+ }++ try {+ // Use RPC to delete from dynamic table+ await client.rpc("delete_from_search_index", {+ p_company_id: companyId,+ p_entity_type: config.entityType,+ p_entity_id: del.event.recordId,+ });+ results.deleted++;+ } catch (error) {+ logger.error(`Failed to delete from search index:`, {+ error,+ record: del,+ });+ results.failed++;+ }+ }++ // Process inserts and updates+ const upserts = records.filter(+ (r) => r.event.operation === "INSERT" || r.event.operation === "UPDATE"+ );++ for (const upsert of upserts) {+ const config = SEARCH_ENTITY_CONFIGS[upsert.event.table];+ if (!config) {+ results.skipped++;+ continue;+ }++ try {+ let record = upsert.event.new as Record<string, any>;++ // Special handling for employee - skip inactive employees+ if (upsert.event.table === "employee" && record.active === false) {+ await client.rpc("delete_from_search_index", {+ p_company_id: companyId,+ p_entity_type: config.entityType,+ p_entity_id: upsert.event.recordId,+ });+ results.deleted++;+ continue;+ }++ // Enrich record with related data if needed+ if (config.enrichRecord) {+ record = await config.enrichRecord(record, client);+ }++ const title = config.getTitle(record);+ const description = config.getDescription?.(record) || "";+ const link = config.getLink(record);+ const tags = config.getTags(record);+ const metadata = config.getMetadata(record);++ // Use RPC to upsert to dynamic table+ await client.rpc("upsert_to_search_index", {+ p_company_id: companyId,+ p_entity_type: config.entityType,+ p_entity_id: upsert.event.recordId,+ p_title: title,+ p_description: description,+ p_link: link,+ p_tags: tags,+ p_metadata: metadata,+ });++ results.updated++;+ } catch (error) {+ logger.error(`Failed to update search index:`, {+ error,+ record: upsert,+ });+ results.failed++;+ }+ }+ }++ logger.info("Search task completed", results);++ return results;+ },+});