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: Approval Notifications workflow (#469)
Ayush Sonia12b1a767cdc
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 1c982c3f09..f3221b6557 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -21,6 +21,7 @@ import {LuBell,LuCalendarX,LuCircleGauge,+ LuClipboardCheck,LuDollarSign,LuGraduationCap,LuHammer,@@ -42,6 +43,7 @@ import {} from "react-icons/ri";import { Link, useFetcher } from "react-router";import { useNotifications, useUser } from "~/hooks";+import type { ApprovalDocumentType } from "~/modules/shared";import { usePeople } from "~/stores";import { path } from "~/utils/path";@@ -174,6 +176,7 @@ function Notification({function GenericNotification({id,event,+ documentType,...props}: {id: string;@@ -181,10 +184,25 @@ function GenericNotification({description: string;event: NotificationEvent;from?: string;+ documentType?: ApprovalDocumentType;markMessageAsRead?: () => void;onClose: () => void;}) {switch (event) {+ case NotificationEvent.ApprovalApproved:+ case NotificationEvent.ApprovalRejected:+ case NotificationEvent.ApprovalRequested:+ return (+ <Notification+ icon={<LuClipboardCheck />}+ to={+ documentType === "qualityDocument"+ ? path.to.qualityDocument(id)+ : path.to.purchaseOrderDetails(id)+ }+ {...props}+ />+ );case NotificationEvent.DigitalQuoteResponse:return (<Notification@@ -474,6 +492,11 @@ const Notifications = () => {description={notification.payload.description as string}event={notification.payload.event as NotificationEvent}from={notification.payload.from as string | undefined}+ documentType={+ notification.payload.documentType as+ | ApprovalDocumentType+ | undefined+ }markMessageAsRead={() =>markMessageAsRead(notification._id)}@@ -541,6 +564,11 @@ const Notifications = () => {description={notification.payload.description as string}event={notification.payload.event as NotificationEvent}from={notification.payload.from as string | undefined}+ documentType={+ notification.payload.documentType as+ | ApprovalDocumentType+ | undefined+ }onClose={() => setOpen(false)}/>);diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsxindex d90272094d..cbf7ed8fa2 100644--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx@@ -20,9 +20,9 @@ import { LuEllipsisVertical, LuPencil, LuTrash } from "react-icons/lu";import { useNavigate } from "react-router";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { useCurrencyFormatter, usePermissions, useUrlParams } from "~/hooks";-import type { ApprovalRule } from "~/modules/shared";import {type ApprovalDocumentType,+ type ApprovalRule,approvalDocumentTypeLabel,approvalDocumentTypesWithAmounts} from "~/modules/shared";diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 9441057783..b1723e24a1 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -11,6 +11,7 @@ import type {ApprovalRequestForApproveCheck,ApprovalRequestForCancelCheck,ApprovalRequestForViewCheck,+ ApprovalRule,CreateApprovalRequestInput,UpsertApprovalRuleInput} from "./types";@@ -376,6 +377,35 @@ export async function getApprovalRuleByAmount(.maybeSingle();}+export async function getApproverUserIdsForRule(+ client: SupabaseClient<Database>,+ rule: Pick<ApprovalRule, "approverGroupIds" | "defaultApproverId">+): Promise<string[]> {+ const groupIds = rule.approverGroupIds?.filter(Boolean) ?? [];+ const defaultId = rule.defaultApproverId ?? null;++ const fromGroups =+ groupIds.length > 0+ ? await client.rpc("users_for_groups", { groups: groupIds })+ : { data: [] as string[], error: null };++ if (fromGroups.error) {+ console.error(+ "getApproverUserIdsForRule: users_for_groups failed",+ fromGroups.error+ );+ return defaultId ? [defaultId] : [];+ }++ const ids = Array.isArray(fromGroups.data)+ ? (fromGroups.data as string[])+ : [];+ const combined = defaultId+ ? [...new Set([...ids, defaultId])]+ : [...new Set(ids)];+ return combined;+}+export async function getApprovalRuleById(client: SupabaseClient<Database>,id: string,diff --git a/apps/erp/app/novu/workflows.ts b/apps/erp/app/novu/workflows.tsindex f536e3b18c..4677f9eede 100644--- a/apps/erp/app/novu/workflows.ts+++ b/apps/erp/app/novu/workflows.ts@@ -10,6 +10,9 @@ const payloadSchema = z.object({recordId: z.string(),description: z.string(),event: z.enum([+ NotificationEvent.ApprovalApproved,+ NotificationEvent.ApprovalRejected,+ NotificationEvent.ApprovalRequested,NotificationEvent.DigitalQuoteResponse,NotificationEvent.GaugeCalibrationExpired,NotificationEvent.JobAssignment,@@ -34,7 +37,8 @@ const payloadSchema = z.object({NotificationEvent.SupplierQuoteResponse,NotificationEvent.TrainingAssignment]),- from: z.string().optional()+ from: z.string().optional(),+ documentType: z.enum(["purchaseOrder", "qualityDocument"]).optional()});export const assignmentWorkflow = workflow(@@ -118,6 +122,17 @@ export const suggestionResponseWorkflow = workflow({ payloadSchema });+export const approvalWorkflow = workflow(+ NotificationWorkflow.Approval,+ async ({ payload, step }) => {+ await step.inApp(NotificationType.ApprovalInApp, () => ({+ body: payload.description,+ payload+ }));+ },+ { payloadSchema }+);+export const supplierQuoteResponseWorkflow = workflow(NotificationWorkflow.SupplierQuoteResponse,async ({ payload, step }) => {diff --git a/apps/erp/app/routes/api+/novu.ts b/apps/erp/app/routes/api+/novu.tsindex b8028bc18c..2aa66bc740 100644--- a/apps/erp/app/routes/api+/novu.ts+++ b/apps/erp/app/routes/api+/novu.ts@@ -1,5 +1,6 @@import { serve } from "@novu/framework/remix";import {+ approvalWorkflow,assignmentWorkflow,digitalQuoteResponseWorkflow,expirationWorkflow,@@ -12,6 +13,7 @@ import {const handler = serve({workflows: [+ approvalWorkflow,assignmentWorkflow,digitalQuoteResponseWorkflow,expirationWorkflow,diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsxindex ed57b28d32..e811419634 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx@@ -9,6 +9,7 @@ import { flash } from "@carbon/auth/session.server";import { PurchaseOrderEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend"; // Assuming you have a sendEmail task defined+import { NotificationEvent } from "@carbon/notifications";import { renderAsync } from "@react-email/components";import { FunctionRegion } from "@supabase/supabase-js";import { tasks } from "@trigger.dev/sdk";@@ -28,6 +29,8 @@ import {import { getCompany, getCompanySettings } from "~/modules/settings";import {createApprovalRequest,+ getApprovalRuleByAmount,+ getApproverUserIdsForRule,hasPendingApproval,isApprovalRequired} from "~/modules/shared";@@ -111,6 +114,31 @@ export async function action(args: ActionFunctionArgs) {createdBy: userId,amount: orderAmount});++ const rule = await getApprovalRuleByAmount(+ serviceRole,+ "purchaseOrder",+ companyId,+ orderAmount+ );+ const approverIds = rule.data+ ? await getApproverUserIdsForRule(serviceRole, rule.data)+ : [];++ if (approverIds.length > 0) {+ try {+ await tasks.trigger("notify", {+ event: NotificationEvent.ApprovalRequested,+ companyId,+ documentId: orderId,+ documentType: "purchaseOrder",+ recipient: { type: "users", userIds: approverIds },+ from: userId+ });+ } catch (e) {+ console.error("Failed to trigger approval notification", e);+ }+ }}await updatePurchaseOrderStatus(client, {diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsxindex 9eecc0f9ff..a6851e390e 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx@@ -9,6 +9,7 @@ import { flash } from "@carbon/auth/session.server";import { PurchaseOrderEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend";+import { NotificationEvent } from "@carbon/notifications";import { VStack } from "@carbon/react";import { renderAsync } from "@react-email/components";import { FunctionRegion } from "@supabase/supabase-js";@@ -131,6 +132,25 @@ export async function action(args: ActionFunctionArgs) {);}+ const requestedBy = approvalRequest.data?.requestedBy;+ if (requestedBy && requestedBy !== userId) {+ try {+ await tasks.trigger("notify", {+ event:+ decision === "Approved"+ ? NotificationEvent.ApprovalApproved+ : NotificationEvent.ApprovalRejected,+ companyId,+ documentId: orderId,+ documentType: "purchaseOrder",+ recipient: { type: "user", userId: requestedBy },+ from: userId+ });+ } catch (e) {+ console.error("Failed to trigger approval decision notification", e);+ }+ }+// If approved, handle post-approval tasks: PDF generation, document creation, email, price updatesif (decision === "Approved") {const purchaseOrder = await getPurchaseOrder(serviceRole, orderId);diff --git a/apps/erp/app/routes/x+/quality-document+/$id.tsx b/apps/erp/app/routes/x+/quality-document+/$id.tsxindex 924aaaa4d0..210523837c 100644--- a/apps/erp/app/routes/x+/quality-document+/$id.tsx+++ b/apps/erp/app/routes/x+/quality-document+/$id.tsx@@ -8,7 +8,9 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import { validationError, validator } from "@carbon/form";+import { NotificationEvent } from "@carbon/notifications";import type { SupabaseClient } from "@supabase/supabase-js";+import { tasks } from "@trigger.dev/sdk";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useLoaderData, useParams } from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";@@ -187,6 +189,26 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const requestedBy = approvalRequest.data?.requestedBy;+ const companyId = approvalRequest.data?.companyId;+ if (requestedBy && companyId && requestedBy !== userId) {+ try {+ await tasks.trigger("notify", {+ event:+ decision === "Approved"+ ? NotificationEvent.ApprovalApproved+ : NotificationEvent.ApprovalRejected,+ companyId,+ documentId: id,+ documentType: "qualityDocument",+ recipient: { type: "user", userId: requestedBy },+ from: userId+ });+ } catch (e) {+ console.error("Failed to trigger approval decision notification", e);+ }+ }+throw redirect(path.to.qualityDocument(id),await flash(diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsxindex 3b158da828..df1f35d15d 100644--- a/apps/erp/app/routes/x+/quality-document+/update.tsx+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx@@ -1,12 +1,16 @@import { getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import type { Database } from "@carbon/database";+import { NotificationEvent } from "@carbon/notifications";import type { SupabaseClient } from "@supabase/supabase-js";+import { tasks } from "@trigger.dev/sdk";import { type ActionFunctionArgs } from "react-router";import { qualityDocumentStatus } from "~/modules/quality/quality.models";import {canApproveRequest,createApprovalRequest,+ getApprovalRuleByAmount,+ getApproverUserIdsForRule,getLatestApprovalRequestForDocument,hasPendingApproval,isApprovalRequired@@ -59,6 +63,32 @@ async function processToActive(createdBy: userId,amount: undefined});++ const rule = await getApprovalRuleByAmount(+ serviceRole,+ "qualityDocument",+ companyId,+ undefined+ );+ const approverIds = rule.data+ ? await getApproverUserIdsForRule(serviceRole, rule.data)+ : [];++ if (approverIds.length > 0) {+ try {+ await tasks.trigger("notify", {+ event: NotificationEvent.ApprovalRequested,+ companyId,+ documentId: doc.id,+ documentType: "qualityDocument",+ recipient: { type: "users", userIds: approverIds },+ from: userId+ });+ } catch (e) {+ console.error("Failed to trigger approval notification", e);+ }+ }+idsToSkipActive.push(doc.id);if (doc.status === "Archived") {archivedIdsToMoveToDraft.push(doc.id);diff --git a/package-lock.json b/package-lock.jsonindex d641d8b998..f5dd6d415d 100644--- a/package-lock.json+++ b/package-lock.json@@ -27603,6 +27603,7 @@"nanoid": "5.0.4"},"devDependencies": {+ "@carbon/database": "*","@carbon/tsconfig": "*","typescript": "^5.2.2"}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex d247ed6160..3a101832da 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -45988,14 +45988,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -50059,14 +50059,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"]@@ -50602,14 +50602,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d247ed6160..3a101832da 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -45988,14 +45988,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -50059,14 +50059,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"]@@ -50602,14 +50602,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/jobs/trigger/notify.ts b/packages/jobs/trigger/notify.tsindex fdd768de3e..effbae64e8 100644--- a/packages/jobs/trigger/notify.ts+++ b/packages/jobs/trigger/notify.ts@@ -4,6 +4,7 @@ import {VERCEL_URL,} from "@carbon/auth";+import type { Database } from "@carbon/database";import { notifyTaskAssigned } from "@carbon/ee/notifications";import {getSubscriberId,@@ -16,6 +17,9 @@ import {import { Novu } from "@novu/node";import { task } from "@trigger.dev/sdk";+type ApprovalDocumentType =+ Database["public"]["Enums"]["approvalDocumentType"];+const novu = new Novu(NOVU_SECRET_KEY!);const isLocal = VERCEL_URL === undefined || VERCEL_URL.includes("localhost");@@ -34,19 +38,20 @@ export const notifyTask = task({companyId: string;documentId: string;recipient:- | {- type: "user";- userId: string;- }- | {- type: "group";- groupIds: string[];- }- | {- type: "users";- userIds: string[];- };+ | {+ type: "user";+ userId: string;+ }+ | {+ type: "group";+ groupIds: string[];+ }+ | {+ type: "users";+ userIds: string[];+ };from?: string;+ documentType?: ApprovalDocumentType;}) => {if (isLocal) {console.log("Skipping notify task on local", { payload });@@ -84,12 +89,20 @@ export const notifyTask = task({return NotificationWorkflow.SupplierQuoteResponse;case NotificationEvent.JobOperationMessage:return NotificationWorkflow.Message;+ case NotificationEvent.ApprovalApproved:+ case NotificationEvent.ApprovalRejected:+ case NotificationEvent.ApprovalRequested:+ return NotificationWorkflow.Approval;default:return null;}}- async function getDescription(type: NotificationEvent, documentId: string) {+ async function getDescription(+ type: NotificationEvent,+ documentId: string,+ documentType?: ApprovalDocumentType+ ) {switch (type) {case NotificationEvent.SalesRfqReady:case NotificationEvent.SalesRfqAssignment:@@ -142,7 +155,7 @@ export const notifyTask = task({.select("*").eq("id", documentId).single();-+if (maintenanceDispatchCreated.error) {console.error("Failed to get maintenanceDispatchCreated", maintenanceDispatchCreated.error);throw maintenanceDispatchCreated.error;@@ -155,7 +168,7 @@ export const notifyTask = task({.select("*").eq("id", documentId).single();-+if (maintenanceDispatchAssignment.error) {console.error("Failed to get maintenanceDispatchAssignment", maintenanceDispatchAssignment.error);throw maintenanceDispatchAssignment.error;@@ -369,7 +382,7 @@ export const notifyTask = task({.eq("id", documentId).single();-+if (supplierQuote.error) {console.error("Failed to get supplier quote", supplierQuote.error);throw supplierQuote.error;@@ -379,6 +392,97 @@ export const notifyTask = task({const respondedBy = externalNotes?.lastSubmittedBy as string | undefined || "Supplier";return `Supplier Quote ${supplierQuote?.data?.supplierQuoteId} was submitted by ${respondedBy}`;+ case NotificationEvent.ApprovalRequested:+ if (documentType === "purchaseOrder") {+ const purchaseOrderResult = await client+ .from("purchaseOrder")+ .select("purchaseOrderId")+ .eq("id", documentId)+ .single();++ if (purchaseOrderResult.error || !purchaseOrderResult.data) {+ console.error(+ "Failed to retrieve purchase order for approval notification",+ purchaseOrderResult.error+ );+ return "Purchase order requires your approval";+ }++ const purchaseOrderId = purchaseOrderResult.data.purchaseOrderId;+ return `Purchase order ${purchaseOrderId} requires your approval`;+ }++ if (documentType === "qualityDocument") {+ const qualityDocumentResult = await client+ .from("qualityDocument")+ .select("name")+ .eq("id", documentId)+ .single();++ if (qualityDocumentResult.error || !qualityDocumentResult.data) {+ console.error(+ "Failed to retrieve quality document for approval notification",+ qualityDocumentResult.error+ );+ return "Quality document requires your approval";+ }++ const qualityDocumentName =+ qualityDocumentResult.data.name ?? "Untitled";+ return `Quality document "${qualityDocumentName}" requires your approval`;+ }+ return `Approval requested`;++ case NotificationEvent.ApprovalApproved:+ if (documentType === "purchaseOrder") {+ const poApproved = await client+ .from("purchaseOrder")+ .select("purchaseOrderId")+ .eq("id", documentId)+ .single();+ if (poApproved.error || !poApproved.data) {+ return "Your purchase order was approved";+ }+ return `Purchase order ${poApproved.data.purchaseOrderId} was approved`;+ }+ if (documentType === "qualityDocument") {+ const qdApproved = await client+ .from("qualityDocument")+ .select("name")+ .eq("id", documentId)+ .single();+ if (qdApproved.error || !qdApproved.data) {+ return "Your quality document was approved";+ }+ return `Quality document "${qdApproved.data.name ?? "Untitled"}" was approved`;+ }+ return "Your approval request was approved";++ case NotificationEvent.ApprovalRejected:+ if (documentType === "purchaseOrder") {+ const poRejected = await client+ .from("purchaseOrder")+ .select("purchaseOrderId")+ .eq("id", documentId)+ .single();+ if (poRejected.error || !poRejected.data) {+ return "Your purchase order was rejected";+ }+ return `Purchase order ${poRejected.data.purchaseOrderId} was rejected`;+ }+ if (documentType === "qualityDocument") {+ const qdRejected = await client+ .from("qualityDocument")+ .select("name")+ .eq("id", documentId)+ .single();+ if (qdRejected.error || !qdRejected.data) {+ return "Your quality document was rejected";+ }+ return `Quality document "${qdRejected.data.name ?? "Untitled"}" was rejected`;+ }+ return "Your approval request was rejected";+default:return null;}@@ -393,7 +497,11 @@ export const notifyTask = task({);}- const description = await getDescription(payload.event, payload.documentId);+ const description = await getDescription(+ payload.event,+ payload.documentId,+ payload.documentType+ );if (!description) {console.error(@@ -448,15 +556,18 @@ export const notifyTask = task({}}+ const baseNotificationPayload = {+ recordId: payload.documentId,+ description,+ event: payload.event,+ from: payload.from,+ ...(payload.documentType && { documentType: payload.documentType }),+ };+if (payload.recipient.type === "user") {const novuPayload = {workflow,- payload: {- recordId: payload.documentId,- description,- event: payload.event,- from: payload.from,- },+ payload: baseNotificationPayload,user: {subscriberId: getSubscriberId({companyId: payload.companyId,@@ -489,12 +600,12 @@ export const notifyTask = task({const userIds =payload.recipient.type === "group"? await client.rpc("users_for_groups", {- groups: payload.recipient.groupIds,- })+ groups: payload.recipient.groupIds,+ }): {- data: payload.recipient.userIds,- error: null,- };+ data: payload.recipient.userIds,+ error: null,+ };if (userIds.error) {console.error("Failed to get userIds", userIds.error);@@ -539,12 +650,7 @@ export const notifyTask = task({const notificationPayloads: TriggerPayload[] =[...new Set(filteredUserIds)].map((userId) => ({workflow,- payload: {- recordId: payload.documentId,- description,- event: payload.event,- from: payload.from,- },+ payload: baseNotificationPayload,user: {subscriberId: getSubscriberId({companyId: payload.companyId,diff --git a/packages/notifications/package.json b/packages/notifications/package.jsonindex c61d2497f5..cd05e66b30 100644--- a/packages/notifications/package.json+++ b/packages/notifications/package.json@@ -6,6 +6,7 @@"nanoid": "5.0.4"},"devDependencies": {+ "@carbon/database": "*","@carbon/tsconfig": "*","typescript": "^5.2.2"},diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex c62adf8ebc..e813d89dd5 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -1,8 +1,12 @@+import type { Database } from "@carbon/database";import { nanoid } from "nanoid";+type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];+const API_ENDPOINT = "https://api.novu.co/v1";export enum NotificationWorkflow {+ Approval = "approval",Assignment = "assignment",DigitalQuoteResponse = "digital-quote-response",Expiration = "expiration",@@ -14,6 +18,9 @@ export enum NotificationWorkflow {}export enum NotificationEvent {+ ApprovalApproved = "approval-approved",+ ApprovalRejected = "approval-rejected",+ ApprovalRequested = "approval-requested",DigitalQuoteResponse = "digital-quote-response",GaugeCalibrationExpired = "gauge-calibration-expired",JobAssignment = "job-assignment",@@ -40,6 +47,7 @@ export enum NotificationEvent {}export enum NotificationType {+ ApprovalInApp = "approval-in-app",AssignmentInApp = "assignment-in-app",DigitalQuoteResponseInApp = "digital-quote-response-in-app",JobCompletedInApp = "job-completed-in-app",@@ -58,6 +66,7 @@ export type NotificationPayload = {description: string;event: NotificationEvent;from?: string;+ documentType?: ApprovalDocumentType;};export type TriggerPayload = {