Skip to content

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

27.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
import {
  getCarbonOrderStatus,
  getCustomerIdAndContactId,
  getCustomerLocationIds,
  getEmployeeAndSalesPersonId,
  getOrderLocationId,
  getPaperlessParts,
  insertOrderLines,
  insertQuoteLines,
  OrderSchema
} from "@carbon/ee/paperless-parts";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import { inngest } from "../../client";

const payloadSchema = z.discriminatedUnion("type", [
  z.object({
    type: z.literal("quote.created"),
    created: z.string(),
    object: z.string(),
    data: z.any()
  }),
  z.object({
    type: z.literal("quote.status_changed"),
    created: z.string(),
    object: z.string(),
    data: z.any()
  }),
  z.object({
    type: z.literal("quote.sent"),
    created: z.string(),
    object: z.string(),
    data: z.object({
      uuid: z.string(),
      number: z.number(),
      status: z.string(),
      created: z.string(),
      expired: z.boolean(),
      due_date: z.string().nullable(),
      erp_code: z.string().nullable(),
      metadata: z.object({}),
      priority: z.number().nullable(),
      tax_rate: z.string().nullable(),
      estimator: z.string().nullable(),
      sent_date: z.string(),
      contact_id: z.number(),
      rfq_number: z.string().nullable(),
      quote_items: z.array(z.string()),
      quote_notes: z.string().nullable(),
      salesperson: z.string().nullable(),
      expired_date: z.string().nullable(),
      private_notes: z.string().nullable(),
      revision_number: z.number().nullable(),
      supporting_files: z.array(z.string()),
      export_controlled: z.boolean(),
      send_from_facility: z.string(),
      request_for_quote_id: z.union([z.string(), z.number()]).nullable(),
      digital_last_viewed_on: z.string().nullable(),
      manual_rfq_received_date: z.string().nullable(),
      authenticated_pdf_quote_url: z.string().nullable()
    })
  }),
  z.object({
    type: z.literal("order.created"),
    created: z.string(),
    object: z.string(),
    data: z.object({
      uuid: z.string(),
      status: z.string(),
      number: z.number().optional()
    })
  }),
  z.object({
    type: z.literal("order.status_changed"),
    created: z.string(),
    object: z.string(),
    data: z.any()
  }),
  z.object({
    type: z.literal("integration_action.requested"),
    created: z.string(),
    object: z.string(),
    data: z.any()
  }),
  z.object({
    type: z.literal("integration.turned_on"),
    created: z.string(),
    object: z.string(),
    data: z.any()
  }),
  z.object({
    type: z.literal("integration.turned_off"),
    created: z.string(),
    object: z.string(),
    data: z.any()
  })
]);

const paperlessPartsSchema = z.object({
  apiKey: z.string(),
  companyId: z.string(),
  payload: payloadSchema
});

const integrationSchema = z.object({
  methodType: z.enum(["Purchase to Order", "Pull from Inventory"]).optional(),
  trackingType: z.enum(["Inventory", "Non-Inventory", "Batch"]).optional(),
  usePaperlessOrderNumber: z.boolean().optional(),
  billOfProcessBlackList: z.array(z.string()).optional()
});

export const paperlessPartsFunction = inngest.createFunction(
  { id: "paperless-parts", retries: 1 },
  { event: "carbon/paperless-parts" },
  async ({ event, step, logger }) => {
    const payload = paperlessPartsSchema.parse(event.data);
    let result: { success: boolean; message: string };

    logger.info(`Paperless Parts webhook received: ${payload.payload.type}`, {
      payload
    });

    const carbon = getCarbonServiceRole();
    const paperless = await getPaperlessParts(payload.apiKey);

    const [company, integration] = await Promise.all([
      carbon.from("company").select("*").eq("id", payload.companyId).single(),
      carbon
        .from("companyIntegration")
        .select("*")
        .eq("companyId", payload.companyId)
        .eq("id", "paperless-parts")
        .single()
    ]);

    if (company.error || !company.data) {
      throw new Error("Failed to fetch company from Carbon");
    }

    if (integration.error || !integration.data) {
      throw new Error("Failed to fetch integration from Carbon");
    }

    const integrationData = integrationSchema.safeParse(
      integration.data.metadata
    );
    let usePaperlessOrderNumber = false;
    let methodType: "Purchase to Order" | "Pull from Inventory" =
      "Pull from Inventory";
    let trackingType: "Inventory" | "Non-Inventory" | "Batch" = "Inventory";
    let billOfProcessBlackList: string[] = [];
    if (integrationData.success) {
      methodType = integrationData.data.methodType ?? "Pull from Inventory";
      trackingType = integrationData.data.trackingType ?? "Inventory";
      if (integrationData.data.usePaperlessOrderNumber) {
        usePaperlessOrderNumber = true;
      }
      if (integrationData.data.billOfProcessBlackList) {
        billOfProcessBlackList = integrationData.data.billOfProcessBlackList;
      }
    }

    switch (payload.payload.type) {
      case "quote.created":
        logger.info(`Processing quote created event`);
        result = {
          success: true,
          message: "Quote created event processed successfully"
        };
        break;
      case "quote.status_changed":
        logger.info(`Processing quote status changed event`);
        result = {
          success: true,
          message: "Quote status changed event processed successfully"
        };
        break;
      case "quote.sent":
        logger.info(`Processing quote sent event`);
        const quotePayload = payload.payload.data;

        const ppQuoteNumber = quotePayload.number;
        const ppQuoteRevisionNumber = quotePayload.revision_number;

        const ppQuote = await paperless.quotes.quoteDetails(
          ppQuoteNumber,
          ppQuoteRevisionNumber
            ? { revision: ppQuoteRevisionNumber }
            : undefined
        );

        if (ppQuote.error || !ppQuote.data) {
          throw new Error("Failed to fetch quote details from Paperless Parts");
        }

        if (!ppQuote.data.contact) {
          // This should never happen based on the validation rules in Paperless Parts
          throw new Error(
            "Quote contact not found in Paperless Parts - cannot create Carbon Quote"
          );
        }

        // Check if quote already exists via the mapping table
        const existingQuoteMapping = await carbon
          .from("externalIntegrationMapping")
          .select("entityId")
          .eq("entityType", "quote")
          .eq("integration", "paperlessId")
          .eq("externalId", quotePayload.uuid)
          .eq("companyId", payload.companyId)
          .maybeSingle();

        if (existingQuoteMapping?.data?.entityId) {
          logger.info(
            "Quote already exists",
            existingQuoteMapping.data.entityId
          );
          result = {
            success: true,
            message: "Quote already exists"
          };
          break;
        }

        const [
          {
            customerId: quoteCustomerId,
            customerContactId: quoteCustomerContactId
          },
          { createdBy: quoteCreatedBy },
          quoteLocationId
        ] = await Promise.all([
          getCustomerIdAndContactId(carbon, paperless, {
            company: company.data,
            contact: ppQuote.data.contact
          }),
          getEmployeeAndSalesPersonId(carbon, {
            company: company.data,
            estimator: ppQuote.data.estimator,
            salesPerson: ppQuote.data.salesperson
          }),
          getOrderLocationId(carbon, {
            company: company.data,
            sendFrom: (ppQuote.data as any).send_from_facility
          })
        ]);

        if (!quoteCustomerId) {
          throw new Error("Failed to get customer ID");
        }
        if (!quoteCustomerContactId) {
          throw new Error("Failed to get customer contact ID");
        }

        let quoteReadableId: string;
        if (usePaperlessOrderNumber) {
          quoteReadableId = ppQuote.data.number!.toString();
        } else {
          const nextSequence = await getNextSequence(
            carbon,
            "quote",
            payload.companyId
          );

          if (!nextSequence.data) {
            throw new Error("Failed to get next sequence number for quote");
          }

          quoteReadableId = nextSequence.data;
        }

        // Create a quote object from the Paperless Parts data
        const quote: Database["public"]["Tables"]["quote"]["Insert"] = {
          companyId: payload.companyId,
          customerId: quoteCustomerId,
          customerContactId: quoteCustomerContactId,
          quoteId: quoteReadableId,
          locationId: quoteLocationId,
          status: "Draft" as const,
          currencyCode: company.data.baseCurrencyCode,
          createdBy: quoteCreatedBy,
          exchangeRate: 1 as number | undefined,
          exchangeRateUpdatedAt: undefined as string | undefined,
          expirationDate: undefined as string | undefined,
          revisionId: ppQuoteRevisionNumber ?? 0
        };

        const [quoteCustomerPayment, quoteCustomerShipping, quoteOpportunity] =
          await Promise.all([
            getCustomerPayment(carbon, quote.customerId),
            getCustomerShipping(carbon, quote.customerId),
            carbon
              .from("opportunity")
              .insert([
                {
                  companyId: quote.companyId,
                  customerId: quote.customerId
                }
              ])
              .select("id")
              .single()
          ]);

        if (quoteCustomerPayment.error) return quoteCustomerPayment;
        if (quoteCustomerShipping.error) return quoteCustomerShipping;

        const {
          paymentTermId: quotePaymentTermId,
          invoiceCustomerId: quoteInvoiceCustomerId,
          invoiceCustomerContactId: quoteInvoiceCustomerContactId,
          invoiceCustomerLocationId: quoteInvoiceCustomerLocationId
        } = quoteCustomerPayment.data;

        const {
          shippingMethodId: quoteShippingMethodId,
          shippingTermId: quoteShippingTermId
        } = quoteCustomerShipping.data;

        if (quote.currencyCode) {
          const exchangeRate = await carbon.rpc("get_exchange_rate", {
            p_company_id: payload.companyId,
            p_currency_code: quote.currencyCode
          });
          if (exchangeRate.error) {
            logger.warn(
              "Failed to resolve exchange rate for imported quote, keeping default",
              {
                currencyCode: quote.currencyCode,
                error: exchangeRate.error
              }
            );
          } else if (exchangeRate.data !== null) {
            quote.exchangeRate = exchangeRate.data;
            quote.exchangeRateUpdatedAt = new Date().toISOString();
          }
        } else {
          quote.exchangeRate = 1;
          quote.exchangeRateUpdatedAt = new Date().toISOString();
        }

        const insert = await carbon
          .from("quote")
          .insert([
            {
              ...quote,
              opportunityId: quoteOpportunity.data?.id
            }
          ])
          .select("id, quoteId");
        if (insert.error) {
          return insert;
        }

        const quoteId = insert.data?.[0]?.id;
        if (!quoteId) return insert;

        // Create the mapping for the new quote
        await carbon.from("externalIntegrationMapping").insert({
          entityType: "quote",
          entityId: quoteId,
          integration: "paperlessId",
          externalId: quotePayload.uuid,
          companyId: payload.companyId,
          allowDuplicateExternalId: false
        });

        const [quoteShipment, quotePayment, quoteExternalLink] =
          await Promise.all([
            carbon.from("quoteShipment").insert([
              {
                id: quoteId,
                locationId: quoteLocationId,
                shippingMethodId: quoteShippingMethodId,
                shippingTermId: quoteShippingTermId,
                companyId: quote.companyId
              }
            ]),
            carbon.from("quotePayment").insert([
              {
                id: quoteId,
                invoiceCustomerId: quoteInvoiceCustomerId,
                invoiceCustomerContactId: quoteInvoiceCustomerContactId,
                invoiceCustomerLocationId: quoteInvoiceCustomerLocationId,
                paymentTermId: quotePaymentTermId,
                companyId: quote.companyId
              }
            ]),
            upsertExternalLink(carbon, {
              documentType: "Quote" as const,
              documentId: quoteId,
              customerId: quote.customerId,
              expiresAt: quote.expirationDate ?? undefined,
              companyId: quote.companyId
            })
          ]);

        if (quoteShipment.error) {
          await deleteQuote(carbon, quoteId);
          return quoteShipment;
        }
        if (quotePayment.error) {
          await deleteQuote(carbon, quoteId);
          return quotePayment;
        }
        if (quoteOpportunity.error) {
          await deleteQuote(carbon, quoteId);
          return quoteOpportunity;
        }
        if (quoteExternalLink.data) {
          await carbon
            .from("quote")
            .update({ externalLinkId: quoteExternalLink.data.id })
            .eq("id", quoteId);
        }

        // Insert quote lines from Paperless Parts quote items
        try {
          await insertQuoteLines(carbon, {
            quoteId,
            opportunityId: quoteOpportunity.data?.id,
            locationId: quoteLocationId,
            companyId: payload.companyId,
            createdBy: quoteCreatedBy,
            quoteItems: ppQuote.data.quote_items ?? [],
            defaultMethodType: methodType,
            defaultTrackingType: trackingType,
            billOfProcessBlackList
          });
          logger.info("Quote lines successfully created");
        } catch (error) {
          logger.error("Failed to insert quote lines:", error);
          await deleteQuote(carbon, quoteId);
          result = {
            success: false,
            message: "Failed to insert quote lines"
          };
          break;
        }

        logger.info("New Carbon quote created from Paperless Parts");

        result = {
          success: true,
          message: "Quote sent event processed successfully"
        };
        break;
      case "order.status_changed":
      case "order.created":
        logger.info(`Processing order created event`);

        const orderPayload = payload.payload.data;
        const orderNumber = orderPayload.number;

        if (!orderNumber) {
          throw new Error("Order number is required");
        }

        const order = await paperless.orders.orderDetails(orderNumber);

        if (order.error || !order.data) {
          throw new Error("Failed to fetch order details from Paperless Parts");
        }

        const orderData = OrderSchema.parse(order.data);

        // Check if order already exists via the mapping table
        const existingOrderMapping = await carbon
          .from("externalIntegrationMapping")
          .select("entityId")
          .eq("entityType", "salesOrder")
          .eq("integration", "paperlessId")
          .eq("externalId", orderPayload.uuid)
          .eq("companyId", payload.companyId)
          .maybeSingle();

        if (existingOrderMapping?.data?.entityId) {
          logger.info(
            "Order already exists",
            existingOrderMapping.data.entityId
          );

          const status = getCarbonOrderStatus(orderData.status);

          const update = await carbon
            .from("salesOrder")
            .update({ status })
            .eq("id", existingOrderMapping.data.entityId);

          if (update.error) {
            logger.info("Failed to update sales order", update.error);
            result = {
              success: false,
              message: "Failed to update sales order"
            };
            break;
          }

          result = {
            success: true,
            message: "Order already exists"
          };
          break;
        }

        const [
          {
            customerId: orderCustomerId,
            customerContactId: orderCustomerContactId
          },
          { createdBy: orderCreatedBy, salesPersonId: orderSalesPersonId },
          orderLocationId
        ] = await Promise.all([
          getCustomerIdAndContactId(carbon, paperless, {
            company: company.data,
            contact: orderData.contact!
          }),
          getEmployeeAndSalesPersonId(carbon, {
            company: company.data,
            estimator: orderData.estimator!,
            salesPerson: orderData.sales_person!
          }),
          getOrderLocationId(carbon, {
            company: company.data,
            sendFrom: orderData.send_from_facility as any
          })
        ]);

        if (!orderCustomerId) {
          throw new Error("Failed to get customer ID");
        }
        if (!orderCustomerContactId) {
          throw new Error("Failed to get customer contact ID");
        }

        const {
          shipmentLocationId: orderShipmentLocationId,
          invoiceLocationId: orderInvoiceLocationId
        } = await getCustomerLocationIds(carbon, {
          company: company.data,
          customerId: orderCustomerId,
          billingInfo: orderData.billing_info ?? undefined,
          shippingInfo: orderData.shipping_info ?? undefined
        });

        const [orderCustomerPayment, orderCustomerShipping, orderOpportunity] =
          await Promise.all([
            getCustomerPayment(carbon, orderCustomerId),
            getCustomerShipping(carbon, orderCustomerId),
            carbon
              .from("opportunity")
              .insert([
                {
                  customerId: orderCustomerId,
                  companyId: payload.companyId
                }
              ])
              .select("id")
              .single()
          ]);

        let salesOrderReadableId: string;
        if (usePaperlessOrderNumber) {
          salesOrderReadableId = orderNumber.toString();
        } else {
          const nextSequence = await getNextSequence(
            carbon,
            "salesOrder",
            payload.companyId
          );
          if (nextSequence.error) {
            throw new Error("Failed to get sequence");
          }
          salesOrderReadableId = nextSequence.data;
        }
        if (orderCustomerPayment.error) {
          throw new Error("Failed to get customer payment");
        }
        if (orderCustomerShipping.error) {
          throw new Error("Failed to get customer shipping");
        }

        const {
          paymentTermId: orderPaymentTermId,
          invoiceCustomerId: orderInvoiceCustomerId,
          invoiceCustomerContactId: orderInvoiceCustomerContactId,
          invoiceCustomerLocationId: orderInvoiceCustomerLocationId
        } = orderCustomerPayment.data;

        const {
          shippingMethodId: orderShippingMethodId,
          shippingTermId: orderShippingTermId
        } = orderCustomerShipping.data;
        if (orderOpportunity.error) {
          throw new Error("Failed to create opportunity");
        }

        const salesOrderInsert = await carbon
          .from("salesOrder")
          .insert([
            {
              salesOrderId: salesOrderReadableId,
              companyId: payload.companyId,
              createdBy: orderCreatedBy,
              currencyCode: company.data?.baseCurrencyCode,
              customerId: orderCustomerId,
              customerContactId: orderCustomerContactId,
              customerLocationId: orderShipmentLocationId,
              customerReference:
                orderData.payment_details?.purchase_order_number ?? "",
              locationId: orderLocationId,
              opportunityId: orderOpportunity.data?.id,
              orderDate: new Date(orderData.created ?? "").toISOString(),
              salesPersonId: orderSalesPersonId,
              status: getCarbonOrderStatus(orderData.status),
              internalNotes: orderData.private_notes
                ? {
                    type: "doc",
                    content: [
                      {
                        type: "paragraph",
                        content: [
                          { type: "text", text: orderData.private_notes }
                        ]
                      }
                    ]
                  }
                : null
            }
          ])
          .select("id, salesOrderId");

        if (salesOrderInsert.error) {
          logger.info("Failed to create sales order", salesOrderInsert.error);
          result = {
            success: false,
            message: "Failed to create sales order"
          };
          break;
        }
        const salesOrderId = salesOrderInsert.data?.[0]?.id;
        if (!salesOrderId) {
          logger.info("Failed to get sales order ID");
          result = {
            success: false,
            message: "Failed to get sales order ID"
          };
          break;
        }

        // Create the mapping for the new sales order
        await carbon.from("externalIntegrationMapping").insert({
          entityType: "salesOrder",
          entityId: salesOrderId,
          integration: "paperlessId",
          externalId: orderData.uuid,
          companyId: payload.companyId,
          allowDuplicateExternalId: false
        });

        const [orderShipment, orderPayment] = await Promise.all([
          carbon.from("salesOrderShipment").insert([
            {
              id: salesOrderId,
              locationId: orderLocationId,
              customerId: orderCustomerId,
              shippingCost: parseFloat(
                orderData.payment_details?.shipping_cost ?? "0"
              ),
              customerLocationId: orderShipmentLocationId,
              shippingMethodId: orderShippingMethodId,
              shippingTermId: orderShippingTermId,
              companyId: payload.companyId
            }
          ]),
          carbon.from("salesOrderPayment").insert([
            {
              id: salesOrderId,
              invoiceCustomerId: orderInvoiceCustomerId,
              invoiceCustomerContactId: orderInvoiceCustomerContactId,
              invoiceCustomerLocationId:
                orderInvoiceCustomerId === orderCustomerId
                  ? (orderInvoiceLocationId ?? orderInvoiceCustomerLocationId)
                  : orderInvoiceCustomerLocationId,
              paymentTermId: orderPaymentTermId,
              companyId: payload.companyId
            }
          ])
        ]);

        if (orderShipment.error) {
          logger.info("Failed to create shipment", orderShipment.error);
          await deleteSalesOrder(carbon, salesOrderId);
          result = {
            success: false,
            message: "Failed to create shipment"
          };
          break;
        }
        if (orderPayment.error) {
          logger.info("Failed to create payment", orderPayment.error);
          await deleteSalesOrder(carbon, salesOrderId);
          result = {
            success: false,
            message: "Failed to create payment"
          };
          break;
        }

        // Insert order lines after successful sales order creation
        try {
          await insertOrderLines(carbon, {
            salesOrderId: salesOrderId,
            opportunityId: orderOpportunity.data?.id,
            locationId: orderLocationId!,
            companyId: payload.companyId,
            createdBy: orderCreatedBy,
            orderItems: orderData.order_items || [],
            defaultMethodType: methodType,
            defaultTrackingType: trackingType,
            billOfProcessBlackList
          });
          logger.info("Order lines successfully created");
        } catch (error) {
          logger.error("Failed to insert order lines:", error);
          await deleteSalesOrder(carbon, salesOrderId);
          result = {
            success: false,
            message: "Failed to insert order lines"
          };
          break;
        }

        logger.info("New Carbon sales order created from Paperless Parts");

        result = {
          success: true,
          message: "Order created event processed successfully"
        };
        break;
      case "integration_action.requested":
        logger.info(`Processing integration action requested event`);
        result = {
          success: true,
          message: "Integration action requested event processed successfully"
        };
        break;
      case "integration.turned_on":
        logger.info(`Processing integration turned on event`);
        result = {
          success: true,
          message: "Integration turned on event processed successfully"
        };
        break;
      case "integration.turned_off":
        logger.info(`Processing integration turned off event`);
        result = {
          success: true,
          message: "Integration turned off event processed successfully"
        };
        break;
      default:
        logger.error("Unsupported event type: {payload}", {
          payload: payload.payload
        });
        result = {
          success: false,
          message: `Unsupported event type`
        };
        break;
    }

    if (result.success) {
      logger.info(`Successfully processed ${payload.payload.type} event`);
    } else {
      logger.error("Failed to process {payloadType} event: {resultMessage}", {
        payloadType: payload.payload.type,
        resultMessage: result.message
      });
    }

    return result;
  }
);

async function getNextSequence(
  client: SupabaseClient<Database>,
  table: string,
  companyId: string
) {
  return client.rpc("get_next_sequence", {
    sequence_name: table,
    company_id: companyId
  });
}

async function getCustomerPayment(
  client: SupabaseClient<Database>,
  customerId: string
) {
  return client
    .from("customerPayment")
    .select("*")
    .eq("customerId", customerId)
    .single();
}

async function getCustomerShipping(
  client: SupabaseClient<Database>,
  customerId: string
) {
  return client
    .from("customerShipping")
    .select("*")
    .eq("customerId", customerId)
    .single();
}

async function deleteQuote(client: SupabaseClient<Database>, quoteId: string) {
  return client.from("quote").delete().eq("id", quoteId);
}

async function deleteSalesOrder(
  client: SupabaseClient<Database>,
  salesOrderId: string
) {
  return client.from("salesOrder").delete().eq("id", salesOrderId);
}

async function upsertExternalLink(
  client: SupabaseClient<Database>,
  externalLink: {
    documentType: "Quote" | "SupplierQuote" | "Customer";
    documentId: string;
    customerId: string;
    expiresAt?: string;
    companyId: string;
  }
) {
  return client
    .from("externalLink")
    .insert({
      documentType: externalLink.documentType,
      documentId: externalLink.documentId,
      customerId: externalLink.customerId,
      expiresAt: externalLink.expiresAt,
      companyId: externalLink.companyId
    })
    .select("id")
    .single();
}