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
feat: notifications on completed jobs
Brad Barbin8b1e9d538640
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 131eadf8ce..00eb8f8a5f 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -134,6 +134,7 @@ function GenericNotification({{...props}/>);+ case NotificationEvent.JobCompleted:case NotificationEvent.JobAssignment:return (<Notification@@ -146,7 +147,7 @@ function GenericNotification({case NotificationEvent.JobOperationMessage:const [jobId, operationId, makeMethodId, materialId] = id.split(":");const link = materialId- ? path.to.jobMakeMethod(jobId, makeMethodId, materialId)+ ? path.to.jobMakeMethod(jobId, makeMethodId): path.to.jobMethod(jobId, makeMethodId);return (diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex 91dc98685b..bfd3f86c7b 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -40,18 +40,24 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [{name: "Modules",routes: [- {- name: "Sales",- to: path.to.salesSettings,- role: "employee",- icon: <LuCrown />,- },{name: "Purchasing",to: path.to.purchasingSettings,role: "employee",icon: <LuShoppingCart />,},+ {+ name: "Production",+ to: path.to.productionSettings,+ role: "employee",+ icon: <LuFactory />,+ },+ {+ name: "Sales",+ to: path.to.salesSettings,+ role: "employee",+ icon: <LuCrown />,+ },],},{diff --git a/apps/erp/app/novu/workflows.ts b/apps/erp/app/novu/workflows.tsindex 1db87bebac..f15307da0a 100644--- a/apps/erp/app/novu/workflows.ts+++ b/apps/erp/app/novu/workflows.ts@@ -12,6 +12,7 @@ const payloadSchema = z.object({event: z.enum([NotificationEvent.DigitalQuoteResponse,NotificationEvent.JobAssignment,+ NotificationEvent.JobCompleted,NotificationEvent.JobOperationAssignment,NotificationEvent.JobOperationMessage,NotificationEvent.NonConformanceAssignment,@@ -65,6 +66,17 @@ export const expirationWorkflow = workflow({ payloadSchema });+export const jobCompletedWorkflow = workflow(+ NotificationWorkflow.JobCompleted,+ async ({ payload, step }) => {+ await step.inApp(NotificationType.JobCompletedInApp, () => ({+ body: "Job Completed",+ payload,+ }));+ },+ { payloadSchema }+);+export const messageWorkflow = workflow(NotificationWorkflow.Message,async ({ payload, step }) => {diff --git a/apps/erp/app/routes/api+/assign.ts b/apps/erp/app/routes/api+/assign.tsindex b719ca6f11..0fb9b743da 100644--- a/apps/erp/app/routes/api+/assign.ts+++ b/apps/erp/app/routes/api+/assign.ts@@ -99,6 +99,8 @@ function getNotificationEvent(table: string): NotificationEvent | null {return NotificationEvent.SalesOrderAssignment;case "job":return NotificationEvent.JobAssignment;+ case "jobCompleted":+ return NotificationEvent.JobCompleted;case "jobOperation":return NotificationEvent.JobOperationAssignment;case "nonConformanceInvestigationTask":diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsxnew file mode 100644index 0000000000..a8442fee96--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/production.tsx@@ -0,0 +1,158 @@+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Heading,+ Label,+ ScrollArea,+ toast,+ VStack,+} from "@carbon/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { Submit, ValidatedForm, validator } from "@carbon/form";+import { useFetcher, useLoaderData } from "@remix-run/react";+import { useEffect } from "react";+import { z } from "zod";+import { Users } from "~/components/Form";+import { getCompanySettings } from "~/modules/settings";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Production",+ to: path.to.productionSettings,+};++const jobCompletedValidator = z.object({+ inventoryJobCompletedNotificationGroup: z.array(z.string()).optional(),+ salesJobCompletedNotificationGroup: z.array(z.string()).optional(),+});++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings",+ });++ const companySettings = await getCompanySettings(client, companyId);++ if (!companySettings.data)+ throw redirect(+ path.to.settings,+ await flash(+ request,+ error(companySettings.error, "Failed to get company settings")+ )+ );+ return json({ companySettings: companySettings.data });+}++export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings",+ });++ const formData = await request.formData();+ const validation = await validator(jobCompletedValidator).validate(formData);++ if (validation.error) {+ return json({ success: false, message: "Invalid form data" });+ }++ const update = await client+ .from("companySettings")+ .update({+ inventoryJobCompletedNotificationGroup:+ validation.data.inventoryJobCompletedNotificationGroup ?? [],+ salesJobCompletedNotificationGroup:+ validation.data.salesJobCompletedNotificationGroup ?? [],+ })+ .eq("id", companyId);++ if (update.error)+ return json({ success: false, message: update.error.message });++ return json({ success: true, message: "Job notification settings updated" });+}++export default function ProductionSettingsRoute() {+ const { companySettings } = useLoaderData<typeof loader>();+ const fetcher = useFetcher<typeof action>();++ useEffect(() => {+ if (fetcher.data?.success === true && fetcher?.data?.message) {+ toast.success(fetcher.data.message);+ }++ if (fetcher.data?.success === false && fetcher?.data?.message) {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.data?.message, fetcher.data?.success]);++ return (+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">+ <VStack+ spacing={4}+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"+ >+ <Heading size="h3">Production</Heading>++ <Card>+ <ValidatedForm+ method="post"+ validator={jobCompletedValidator}+ defaultValues={{+ inventoryJobCompletedNotificationGroup:+ companySettings.inventoryJobCompletedNotificationGroup ?? [],+ salesJobCompletedNotificationGroup:+ companySettings.salesJobCompletedNotificationGroup ?? [],+ }}+ fetcher={fetcher}+ >+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ Completed Job Notifications+ </CardTitle>+ <CardDescription>+ Configure notifications for when jobs are completed.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <div className="flex flex-col gap-2">+ <Label>Inventory Job Notifications</Label>+ <Users+ name="inventoryJobCompletedNotificationGroup"+ label="Who should receive notifications when an inventory job is completed?"+ />+ </div>+ <div className="flex flex-col gap-2">+ <Label>Sales Job Notifications</Label>+ <Users+ name="salesJobCompletedNotificationGroup"+ label="Who should receive notifications when a sales job is completed?"+ />+ </div>+ </div>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Save+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ </VStack>+ </ScrollArea>+ );+}diff --git a/apps/erp/app/trigger/notify.ts b/apps/erp/app/trigger/notify.tsindex 3fa2788336..d57d3ed15f 100644--- a/apps/erp/app/trigger/notify.ts+++ b/apps/erp/app/trigger/notify.ts@@ -59,6 +59,8 @@ export const notifyTask = task({case NotificationEvent.SalesRfqReady:case NotificationEvent.SupplierQuoteAssignment:return NotificationWorkflow.Assignment;+ case NotificationEvent.JobCompleted:+ return NotificationWorkflow.JobCompleted;case NotificationEvent.DigitalQuoteResponse:return NotificationWorkflow.DigitalQuoteResponse;case NotificationEvent.JobOperationMessage:@@ -141,7 +143,19 @@ export const notifyTask = task({}return `Job ${job?.data?.jobId} assigned to you`;+ case NotificationEvent.JobCompleted:+ const completedJob = await client+ .from("job")+ .select("*")+ .eq("id", documentId)+ .single();++ if (completedJob.error) {+ console.error("Failed to get job", completedJob.error);+ throw completedJob.error;+ }+ return `Job ${completedJob?.data?.jobId} is complete!`;case NotificationEvent.JobOperationAssignment:case NotificationEvent.JobOperationMessage:const [, operationId] = documentId.split(":");diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 82c46b9f5b..15a305c01e 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -965,6 +965,7 @@ export const path = {process: (id: string) => generatePath(`${x}/resources/processes/${id}`),processes: `${x}/resources/processes`,production: `${x}/production`,+ productionSettings: `${x}/settings/production`,profile: `${x}/account/profile`,purchaseInvoice: (id: string) =>generatePath(`${x}/purchase-invoice/${id}`),diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 07b2350428..b1b9f4bf91 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -2092,8 +2092,11 @@ export type Database = {digitalQuoteIncludesPurchaseOrders: booleandigitalQuoteNotificationGroup: string[]id: string+ inventoryJobCompletedNotificationGroup: string[]+ jobCompletedNotificationGroup: string[]productLabelSize: string | nullrfqReadyNotificationGroup: string[]+ salesJobCompletedNotificationGroup: string[]shelfLabelSize: string | null}Insert: {@@ -2101,8 +2104,11 @@ export type Database = {digitalQuoteIncludesPurchaseOrders?: booleandigitalQuoteNotificationGroup?: string[]id: string+ inventoryJobCompletedNotificationGroup?: string[]+ jobCompletedNotificationGroup?: string[]productLabelSize?: string | nullrfqReadyNotificationGroup?: string[]+ salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null}Update: {@@ -2110,8 +2116,11 @@ export type Database = {digitalQuoteIncludesPurchaseOrders?: booleandigitalQuoteNotificationGroup?: string[]id?: string+ inventoryJobCompletedNotificationGroup?: string[]+ jobCompletedNotificationGroup?: string[]productLabelSize?: string | nullrfqReadyNotificationGroup?: string[]+ salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null}Relationships: [@@ -8206,20 +8215,17 @@ export type Database = {createdBy: stringcritical: booleancustomFields: Json | null- demandAccumulationIncludesInventory: booleandemandAccumulationPeriod: number- demandReschedulingPeriod: number+ demandAccumulationSafetyStock: numberitemId: stringlocationId: string+ maximumInventoryQuantity: numbermaximumOrderQuantity: numberminimumOrderQuantity: numberorderMultiple: numberreorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]- reorderMaximumInventory: numberreorderPoint: numberreorderQuantity: number- safetyStockLeadTime: number- safetyStockQuantity: numbertags: string[] | nullupdatedAt: string | nullupdatedBy: string | null@@ -8230,20 +8236,17 @@ export type Database = {createdBy: stringcritical?: booleancustomFields?: Json | null- demandAccumulationIncludesInventory?: booleandemandAccumulationPeriod?: number- demandReschedulingPeriod?: number+ demandAccumulationSafetyStock?: numberitemId: stringlocationId: string+ maximumInventoryQuantity?: numbermaximumOrderQuantity?: numberminimumOrderQuantity?: numberorderMultiple?: numberreorderingPolicy?: Database["public"]["Enums"]["itemReorderingPolicy"]- reorderMaximumInventory?: numberreorderPoint?: numberreorderQuantity?: number- safetyStockLeadTime?: number- safetyStockQuantity?: numbertags?: string[] | nullupdatedAt?: string | nullupdatedBy?: string | null@@ -8254,20 +8257,17 @@ export type Database = {createdBy?: stringcritical?: booleancustomFields?: Json | null- demandAccumulationIncludesInventory?: booleandemandAccumulationPeriod?: number- demandReschedulingPeriod?: number+ demandAccumulationSafetyStock?: numberitemId?: stringlocationId?: string+ maximumInventoryQuantity?: numbermaximumOrderQuantity?: numberminimumOrderQuantity?: numberorderMultiple?: numberreorderingPolicy?: Database["public"]["Enums"]["itemReorderingPolicy"]- reorderMaximumInventory?: numberreorderPoint?: numberreorderQuantity?: number- safetyStockLeadTime?: number- safetyStockQuantity?: numbertags?: string[] | nullupdatedAt?: string | nullupdatedBy?: string | null@@ -37586,8 +37586,11 @@ export type Database = {| Database["public"]["Enums"]["itemTrackingType"]| nulljobId: string | null+ jobMakeMethodId: string | null+ jobReadableId: string | nullleadTime: number | nulllocationId: string | null+ parentMaterialId: string | nullquantityToIssue: number | nullreplenishmentSystem:| Database["public"]["Enums"]["itemReplenishmentSystem"]@@ -37602,6 +37605,27 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"+ columns: ["parentMaterialId"]+ isOneToOne: false+ referencedRelation: "jobMaterial"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"+ columns: ["parentMaterialId"]+ isOneToOne: false+ referencedRelation: "jobMaterialWithMakeMethodId"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"+ columns: ["parentMaterialId"]+ isOneToOne: false+ referencedRelation: "openJobMaterialLines"+ referencedColumns: ["id"]+ },{foreignKeyName: "jobMaterial_companyId_fkey"columns: ["companyId"]@@ -37686,6 +37710,20 @@ export type Database = {referencedRelation: "openProductionOrders"referencedColumns: ["id"]},+ {+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"+ columns: ["jobMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobMakeMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"+ columns: ["jobMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobMaterialWithMakeMethodId"+ referencedColumns: ["jobMaterialMakeMethodId"]+ },{foreignKeyName: "jobMaterial_unitOfMeasureCode_fkey"columns: ["unitOfMeasureCode", "companyId"]@@ -37698,12 +37736,14 @@ export type Database = {openProductionOrders: {Row: {companyId: string | null+ deadlineType: Database["public"]["Enums"]["deadlineType"] | nulldueDate: string | nullid: string | nullitemId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null+ jobId: string | nullleadTime: number | nulllocationId: string | nullquantityToReceive: number | null@@ -41640,14 +41680,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"]@@ -45073,6 +45113,89 @@ export type Database = {}Returns: string[]}+ get_production_planning: {+ Args: {+ company_id: string+ location_id: string+ periods: string[]+ }+ Returns: {+ id: string+ readableIdWithRevision: string+ name: string+ active: boolean+ type: Database["public"]["Enums"]["itemType"]+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailPath: string+ unitOfMeasureCode: string+ leadTime: number+ manufacturingBlocked: boolean+ lotSize: number+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]+ demandAccumulationPeriod: number+ demandAccumulationSafetyStock: number+ reorderPoint: number+ reorderQuantity: number+ minimumOrderQuantity: number+ maximumOrderQuantity: number+ orderMultiple: number+ quantityOnHand: number+ maximumInventoryQuantity: number+ week1: number+ week2: number+ week3: number+ week4: number+ week5: number+ week6: number+ week7: number+ week8: number+ week9: number+ week10: number+ week11: number+ week12: number+ week13: number+ week14: number+ week15: number+ week16: number+ week17: number+ week18: number+ week19: number+ week20: number+ week21: number+ week22: number+ week23: number+ week24: number+ week25: number+ week26: number+ week27: number+ week28: number+ week29: number+ week30: number+ week31: number+ week32: number+ week33: number+ week34: number+ week35: number+ week36: number+ week37: number+ week38: number+ week39: number+ week40: number+ week41: number+ week42: number+ week43: number+ week44: number+ week45: number+ week46: number+ week47: number+ week48: number+ week49: number+ week50: number+ week51: number+ week52: number+ }[]+ }get_quote_methods: {Args: {qid: string@@ -45272,6 +45395,12 @@ export type Database = {Args: Record<PropertyKey, never>Returns: boolean}+ is_last_job_operation: {+ Args: {+ operation_id: string+ }+ Returns: boolean+ }items_search: {Args: {query_embedding: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 07b2350428..b1b9f4bf91 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -2092,8 +2092,11 @@ export type Database = {digitalQuoteIncludesPurchaseOrders: booleandigitalQuoteNotificationGroup: string[]id: string+ inventoryJobCompletedNotificationGroup: string[]+ jobCompletedNotificationGroup: string[]productLabelSize: string | nullrfqReadyNotificationGroup: string[]+ salesJobCompletedNotificationGroup: string[]shelfLabelSize: string | null}Insert: {@@ -2101,8 +2104,11 @@ export type Database = {digitalQuoteIncludesPurchaseOrders?: booleandigitalQuoteNotificationGroup?: string[]id: string+ inventoryJobCompletedNotificationGroup?: string[]+ jobCompletedNotificationGroup?: string[]productLabelSize?: string | nullrfqReadyNotificationGroup?: string[]+ salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null}Update: {@@ -2110,8 +2116,11 @@ export type Database = {digitalQuoteIncludesPurchaseOrders?: booleandigitalQuoteNotificationGroup?: string[]id?: string+ inventoryJobCompletedNotificationGroup?: string[]+ jobCompletedNotificationGroup?: string[]productLabelSize?: string | nullrfqReadyNotificationGroup?: string[]+ salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null}Relationships: [@@ -8206,20 +8215,17 @@ export type Database = {createdBy: stringcritical: booleancustomFields: Json | null- demandAccumulationIncludesInventory: booleandemandAccumulationPeriod: number- demandReschedulingPeriod: number+ demandAccumulationSafetyStock: numberitemId: stringlocationId: string+ maximumInventoryQuantity: numbermaximumOrderQuantity: numberminimumOrderQuantity: numberorderMultiple: numberreorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]- reorderMaximumInventory: numberreorderPoint: numberreorderQuantity: number- safetyStockLeadTime: number- safetyStockQuantity: numbertags: string[] | nullupdatedAt: string | nullupdatedBy: string | null@@ -8230,20 +8236,17 @@ export type Database = {createdBy: stringcritical?: booleancustomFields?: Json | null- demandAccumulationIncludesInventory?: booleandemandAccumulationPeriod?: number- demandReschedulingPeriod?: number+ demandAccumulationSafetyStock?: numberitemId: stringlocationId: string+ maximumInventoryQuantity?: numbermaximumOrderQuantity?: numberminimumOrderQuantity?: numberorderMultiple?: numberreorderingPolicy?: Database["public"]["Enums"]["itemReorderingPolicy"]- reorderMaximumInventory?: numberreorderPoint?: numberreorderQuantity?: number- safetyStockLeadTime?: number- safetyStockQuantity?: numbertags?: string[] | nullupdatedAt?: string | nullupdatedBy?: string | null@@ -8254,20 +8257,17 @@ export type Database = {createdBy?: stringcritical?: booleancustomFields?: Json | null- demandAccumulationIncludesInventory?: booleandemandAccumulationPeriod?: number- demandReschedulingPeriod?: number+ demandAccumulationSafetyStock?: numberitemId?: stringlocationId?: string+ maximumInventoryQuantity?: numbermaximumOrderQuantity?: numberminimumOrderQuantity?: numberorderMultiple?: numberreorderingPolicy?: Database["public"]["Enums"]["itemReorderingPolicy"]- reorderMaximumInventory?: numberreorderPoint?: numberreorderQuantity?: number- safetyStockLeadTime?: number- safetyStockQuantity?: numbertags?: string[] | nullupdatedAt?: string | nullupdatedBy?: string | null@@ -37586,8 +37586,11 @@ export type Database = {| Database["public"]["Enums"]["itemTrackingType"]| nulljobId: string | null+ jobMakeMethodId: string | null+ jobReadableId: string | nullleadTime: number | nulllocationId: string | null+ parentMaterialId: string | nullquantityToIssue: number | nullreplenishmentSystem:| Database["public"]["Enums"]["itemReplenishmentSystem"]@@ -37602,6 +37605,27 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"+ columns: ["parentMaterialId"]+ isOneToOne: false+ referencedRelation: "jobMaterial"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"+ columns: ["parentMaterialId"]+ isOneToOne: false+ referencedRelation: "jobMaterialWithMakeMethodId"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"+ columns: ["parentMaterialId"]+ isOneToOne: false+ referencedRelation: "openJobMaterialLines"+ referencedColumns: ["id"]+ },{foreignKeyName: "jobMaterial_companyId_fkey"columns: ["companyId"]@@ -37686,6 +37710,20 @@ export type Database = {referencedRelation: "openProductionOrders"referencedColumns: ["id"]},+ {+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"+ columns: ["jobMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobMakeMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"+ columns: ["jobMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobMaterialWithMakeMethodId"+ referencedColumns: ["jobMaterialMakeMethodId"]+ },{foreignKeyName: "jobMaterial_unitOfMeasureCode_fkey"columns: ["unitOfMeasureCode", "companyId"]@@ -37698,12 +37736,14 @@ export type Database = {openProductionOrders: {Row: {companyId: string | null+ deadlineType: Database["public"]["Enums"]["deadlineType"] | nulldueDate: string | nullid: string | nullitemId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null+ jobId: string | nullleadTime: number | nulllocationId: string | nullquantityToReceive: number | null@@ -41640,14 +41680,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"]@@ -45073,6 +45113,89 @@ export type Database = {}Returns: string[]}+ get_production_planning: {+ Args: {+ company_id: string+ location_id: string+ periods: string[]+ }+ Returns: {+ id: string+ readableIdWithRevision: string+ name: string+ active: boolean+ type: Database["public"]["Enums"]["itemType"]+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailPath: string+ unitOfMeasureCode: string+ leadTime: number+ manufacturingBlocked: boolean+ lotSize: number+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]+ demandAccumulationPeriod: number+ demandAccumulationSafetyStock: number+ reorderPoint: number+ reorderQuantity: number+ minimumOrderQuantity: number+ maximumOrderQuantity: number+ orderMultiple: number+ quantityOnHand: number+ maximumInventoryQuantity: number+ week1: number+ week2: number+ week3: number+ week4: number+ week5: number+ week6: number+ week7: number+ week8: number+ week9: number+ week10: number+ week11: number+ week12: number+ week13: number+ week14: number+ week15: number+ week16: number+ week17: number+ week18: number+ week19: number+ week20: number+ week21: number+ week22: number+ week23: number+ week24: number+ week25: number+ week26: number+ week27: number+ week28: number+ week29: number+ week30: number+ week31: number+ week32: number+ week33: number+ week34: number+ week35: number+ week36: number+ week37: number+ week38: number+ week39: number+ week40: number+ week41: number+ week42: number+ week43: number+ week44: number+ week45: number+ week46: number+ week47: number+ week48: number+ week49: number+ week50: number+ week51: number+ week52: number+ }[]+ }get_quote_methods: {Args: {qid: string@@ -45272,6 +45395,12 @@ export type Database = {Args: Record<PropertyKey, never>Returns: boolean}+ is_last_job_operation: {+ Args: {+ operation_id: string+ }+ Returns: boolean+ }items_search: {Args: {query_embedding: stringdiff --git a/packages/database/supabase/functions/trigger/index.ts b/packages/database/supabase/functions/trigger/index.tsindex 0106a8fa13..25dd33d48d 100644--- a/packages/database/supabase/functions/trigger/index.ts+++ b/packages/database/supabase/functions/trigger/index.ts@@ -1,10 +1,9 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { z } from "npm:zod@^3.24.1";import { tasks } from "npm:@trigger.dev/[email protected]/v3";+import { z } from "npm:zod@^3.24.1";import type { notifyTask } from "../../../../../apps/erp/app/trigger/notify.ts";import { corsHeaders } from "../lib/headers.ts";-import { getSupabaseServiceRole } from "../lib/supabase.ts";const recipientValidator = z.discriminatedUnion("type", [z.object({@@ -25,6 +24,7 @@ const payloadValidator = z.discriminatedUnion("type", [z.object({type: z.literal("notify"),event: z.enum([+ "job-completed","quote-assignment","sales-rfq-assignment","sales-order-assignment",@@ -52,13 +52,6 @@ serve(async (req: Request) => {...data,});- // verify that the request is authorized by an API key or service role- await getSupabaseServiceRole(- req.headers.get("Authorization"),- req.headers.get("carbon-key") ?? "",- data.companyId- );-switch (type) {case "notify": {await tasks.trigger<typeof notifyTask>("notify", {diff --git a/packages/database/supabase/functions/webhook/index.ts b/packages/database/supabase/functions/webhook/index.tsindex 0b3b6f774a..ddb9014ce4 100644--- a/packages/database/supabase/functions/webhook/index.ts+++ b/packages/database/supabase/functions/webhook/index.ts@@ -1,6 +1,6 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { z } from "npm:zod@^3.24.1";import { createClient } from "https://esm.sh/@supabase/[email protected]";+import { z } from "npm:zod@^3.24.1";import { corsHeaders } from "../lib/headers.ts";import type { Database } from "../lib/types.ts";diff --git a/packages/database/supabase/migrations/20250618134240_complete-job.sql b/packages/database/supabase/migrations/20250618134240_complete-job.sqlnew file mode 100644index 0000000000..3dec866950--- /dev/null+++ b/packages/database/supabase/migrations/20250618134240_complete-job.sql@@ -0,0 +1,99 @@+ALTER TABLE "companySettings"+ ADD COLUMN "inventoryJobCompletedNotificationGroup" TEXT[] NOT NULL DEFAULT '{}',+ ADD COLUMN "salesJobCompletedNotificationGroup" TEXT[] NOT NULL DEFAULT '{}';+++CREATE OR REPLACE FUNCTION is_last_job_operation(operation_id TEXT)+RETURNS BOOLEAN AS $$+BEGIN+ RETURN NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency"+ WHERE "dependsOnId" = operation_id+ );+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE OR REPLACE FUNCTION finish_job_operation()+RETURNS TRIGGER AS $$+BEGIN+ -- Set endTime for all open production events+ UPDATE "productionEvent"+ SET "endTime" = NOW()+ WHERE "jobOperationId" = NEW.id AND "endTime" IS NULL;++ -- Find all operations that depend on this one and might be ready+ UPDATE "jobOperation" op+ SET status = 'Ready'+ WHERE EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ WHERE dep."operationId" = op.id+ AND dep."dependsOnId" = NEW.id+ AND op.status = 'Waiting'+ )+ AND NOT EXISTS (+ -- Check no other dependencies are incomplete+ SELECT 1+ FROM "jobOperationDependency" dep2+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"+ WHERE dep2."operationId" = op.id+ AND jo2.status != 'Done'+ AND jo2.id != NEW.id+ );++ -- Set the job operation status to Done+ NEW.status = 'Done';++ -- If this is the last operation, mark the job as Done+ IF is_last_job_operation(NEW.id) THEN+ DECLARE+ request_id TEXT;+ notify_url TEXT;+ api_url TEXT;+ anon_key TEXT;+ group_ids TEXT[];+ assigned_to TEXT;+ sales_order_id TEXT;+ BEGIN++ SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;+ notify_url := api_url || '/functions/v1/trigger';++ SELECT "assignee", "salesOrderId" INTO assigned_to, sales_order_id FROM "job" WHERE "id" = NEW."jobId";++ IF sales_order_id IS NULL THEN+ SELECT "inventoryJobCompletedNotificationGroup" INTO group_ids FROM "companySettings" WHERE "id" = NEW."companyId";+ ELSE+ SELECT "salesJobCompletedNotificationGroup" INTO group_ids FROM "companySettings" WHERE "id" = NEW."companyId";+ END IF;++ IF assigned_to IS NOT NULL THEN+ SELECT array_append(group_ids, assigned_to) INTO group_ids;+ END IF;++ IF array_length(group_ids, 1) > 0 THEN+ SELECT net.http_post(+ notify_url,+ jsonb_build_object(+ 'type', 'notify',+ 'event', 'job-completed',+ 'documentId', NEW."jobId",+ 'companyId', NEW."companyId",+ 'recipient', jsonb_build_object(+ 'type', 'group',+ 'groupIds', group_ids+ )+ )::jsonb,+ '{}'::jsonb,+ jsonb_build_object('Content-Type', 'application/json', 'Authorization', 'Bearer ' || anon_key)+ ) INTO request_id;+ END IF;++ END;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 4245b21bda..3a7bab6311 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -6,12 +6,14 @@ export enum NotificationWorkflow {Assignment = "assignment",DigitalQuoteResponse = "digital-quote-response",Expiration = "expiration",+ JobCompleted = "job-completed",Message = "message",}export enum NotificationEvent {DigitalQuoteResponse = "digital-quote-response",JobAssignment = "job-assignment",+ JobCompleted = "job-completed",JobOperationAssignment = "job-operation-assignment",JobOperationMessage = "job-operation-message",NonConformanceAssignment = "non-conformance-assignment",@@ -29,6 +31,7 @@ export enum NotificationEvent {export enum NotificationType {AssignmentInApp = "assignment-in-app",DigitalQuoteResponseInApp = "digital-quote-response-in-app",+ JobCompletedInApp = "job-completed-in-app",ExpirationInApp = "expiration-in-app",MessageInApp = "message-in-app",}