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: logic for creating new quote in PP integration
Brad Barbin03babfb1f8bc
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 6b9b26cc12..5fec6316aa 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -237,7 +237,6 @@ export async function getIntegration(return client.from("companyIntegration").select("*")- .eq("active", true).eq("id", id).eq("companyId", companyId).maybeSingle();diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 3ee463c7c3..a98c55f212 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -48069,6 +48069,7 @@ export type Database = {owner_id: string | nullpath_tokens: string[] | nullupdated_at: string | null+ user_metadata: Json | nullversion: string | null}Insert: {@@ -48082,6 +48083,7 @@ export type Database = {owner_id?: string | nullpath_tokens?: string[] | nullupdated_at?: string | null+ user_metadata?: Json | nullversion?: string | null}Update: {@@ -48095,6 +48097,7 @@ export type Database = {owner_id?: string | nullpath_tokens?: string[] | nullupdated_at?: string | null+ user_metadata?: Json | nullversion?: string | null}Relationships: [@@ -48116,6 +48119,7 @@ export type Database = {key: stringowner_id: string | nullupload_signature: string+ user_metadata: Json | nullversion: string}Insert: {@@ -48126,6 +48130,7 @@ export type Database = {key: stringowner_id?: string | nullupload_signature: string+ user_metadata?: Json | nullversion: string}Update: {@@ -48136,6 +48141,7 @@ export type Database = {key?: stringowner_id?: string | nullupload_signature?: string+ user_metadata?: Json | nullversion?: string}Relationships: [@@ -48272,6 +48278,10 @@ export type Database = {updated_at: string}[]}+ operation: {+ Args: Record<PropertyKey, never>+ Returns: string+ }search: {Args: {prefix: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 3ee463c7c3..a98c55f212 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -48069,6 +48069,7 @@ export type Database = {owner_id: string | nullpath_tokens: string[] | nullupdated_at: string | null+ user_metadata: Json | nullversion: string | null}Insert: {@@ -48082,6 +48083,7 @@ export type Database = {owner_id?: string | nullpath_tokens?: string[] | nullupdated_at?: string | null+ user_metadata?: Json | nullversion?: string | null}Update: {@@ -48095,6 +48097,7 @@ export type Database = {owner_id?: string | nullpath_tokens?: string[] | nullupdated_at?: string | null+ user_metadata?: Json | nullversion?: string | null}Relationships: [@@ -48116,6 +48119,7 @@ export type Database = {key: stringowner_id: string | nullupload_signature: string+ user_metadata: Json | nullversion: string}Insert: {@@ -48126,6 +48130,7 @@ export type Database = {key: stringowner_id?: string | nullupload_signature: string+ user_metadata?: Json | nullversion: string}Update: {@@ -48136,6 +48141,7 @@ export type Database = {key?: stringowner_id?: string | nullupload_signature?: string+ user_metadata?: Json | nullversion?: string}Relationships: [@@ -48272,6 +48278,10 @@ export type Database = {updated_at: string}[]}+ operation: {+ Args: Record<PropertyKey, never>+ Returns: string+ }search: {Args: {prefix: stringdiff --git a/packages/database/supabase/migrations/20241226162611_external-id-indices.sql b/packages/database/supabase/migrations/20241226162611_external-id-indices.sqlnew file mode 100644index 0000000000..5c5cdd4b83--- /dev/null+++ b/packages/database/supabase/migrations/20241226162611_external-id-indices.sql@@ -0,0 +1,8 @@+-- Create GIN index on external_id column+CREATE INDEX idx_contact_external_id ON contact USING GIN ("externalId");+CREATE INDEX idx_item_external_id ON item USING GIN ("externalId");+CREATE INDEX idx_part_external_id ON part USING GIN ("externalId");+CREATE INDEX idx_material_external_id ON material USING GIN ("externalId");+CREATE INDEX idx_tool_external_id ON tool USING GIN ("externalId");+CREATE INDEX idx_fixture_external_id ON fixture USING GIN ("externalId");+CREATE INDEX idx_consumable_external_id ON consumable USING GIN ("externalId");diff --git a/packages/integrations/src/paperless-parts/lib/client.ts b/packages/integrations/src/paperless-parts/lib/client.tsindex 0e4f97b6a6..f565884be4 100644--- a/packages/integrations/src/paperless-parts/lib/client.ts+++ b/packages/integrations/src/paperless-parts/lib/client.ts@@ -2040,12 +2040,12 @@ export class PaperlessPartsClient<* @description Creates a new account.** @tags Customers- * @name CreateAccoumt+ * @name CreateAccount* @summary Create new Account* @request POST:/accounts/public* @secure*/- createAccoumt: (+ createAccount: (data: {/*** (Required) Account Name (must be non-null and non-blank)diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.tsindex f59afd8bc2..7ccab061ea 100644--- a/packages/jobs/trigger/paperless-parts.ts+++ b/packages/jobs/trigger/paperless-parts.ts@@ -1,3 +1,6 @@+import { getCarbonServiceRole } from "@carbon/auth";+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";import { task } from "@trigger.dev/sdk/v3";import { z } from "zod";@@ -88,6 +91,9 @@ const paperlessPartsSchema = z.object({export const paperlessPartsTask = task({id: "paperless-parts",+ retry: {+ maxAttempts: 1,+ },run: async (payload: z.infer<typeof paperlessPartsSchema>) => {let result: { success: boolean; message: string };@@ -96,7 +102,7 @@ export const paperlessPartsTask = task({);console.info(`📦 Payload:`, payload);- // const carbon = getCarbonServiceRole();+ const carbon = getCarbonServiceRole();// const paperless = new PaperlessPartsClient(payload.apiKey);switch (payload.payload.type) {@@ -120,9 +126,7 @@ export const paperlessPartsTask = task({const ppQuoteNumber = quotePayload.number;const ppQuoteRevisionNumber = quotePayload.revision_number;- console.log(- `📦 PP Quote Number: ${ppQuoteNumber}, Revision Number: ${ppQuoteRevisionNumber}`- );+const ppQuote = await paperless.quotes.quoteDetails(ppQuoteNumber,ppQuoteRevisionNumber@@ -134,6 +138,231 @@ export const paperlessPartsTask = task({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 CarbonOS Quote"+ );+ }++ let customerId: string;+ let customerContactId: string;+ // If the Paperless Parts quote contact has an account, get the customer from Carbon+ // based on the Paperless Parts ID+ // If the customer does not exist, create a new customer in CarbonOS+ if (ppQuote.data.contact?.account) {+ const paperlessPartsCustomerId = ppQuote.data.contact?.account?.id;+ const existingCustomer = await carbon+ .from("customer")+ .select("id")+ .eq("companyId", payload.companyId)+ // @ts-expect-error - JSONB column+ .eq("externalId->paperlessPartsId", paperlessPartsCustomerId)+ .maybeSingle();++ if (existingCustomer.data) {+ customerId = existingCustomer.data.id;+ } else {+ const customerName = ppQuote.data.contact?.account?.name!;+ const newCustomer = await carbon+ .from("customer")+ .insert({+ companyId: payload.companyId,+ name: customerName,+ externalId: {+ paperlessPartsId: ppQuote.data.contact.account.id,+ },+ currencyCode: "USD",+ createdBy: "system",+ })+ .select()+ .single();++ if (newCustomer.error || !newCustomer.data) {+ throw new Error("Failed to create customer in CarbonOS");+ }++ customerId = newCustomer.data.id;+ }+ } else {+ // If the quote contact does not have an account, we need to create a new customer in CarbonOS+ // and also create a corresponding account in Paperless Parts+ const customerName = `${ppQuote.data.contact?.first_name} ${ppQuote.data.contact?.last_name}`;++ // Create a new account in Paperless Parts+ const newPaperlessPartsAccount =+ await paperless.accounts.createAccount({+ name: customerName,+ });++ if (+ newPaperlessPartsAccount.error ||+ !newPaperlessPartsAccount.data+ ) {+ throw new Error("Failed to create account in Paperless Parts");+ }++ const newPaperlessPartsAccountId = newPaperlessPartsAccount.data.id;++ const newCustomer = await carbon+ .from("customer")+ .insert({+ companyId: payload.companyId,+ name: customerName,+ externalId: {+ paperlessPartsId: newPaperlessPartsAccountId,+ },+ currencyCode: "USD",+ createdBy: "system",+ })+ .select()+ .single();++ if (newCustomer.error || !newCustomer.data) {+ throw new Error("Failed to create customer in CarbonOS");+ }++ console.info("🔰 New CarbonOS customer created");++ customerId = newCustomer.data.id;+ }++ // Get the contact ID from Carbon based on the Paperless Parts ID+ const paperlessPartsContactId = ppQuote.data.contact?.id;+ const existingCustomerContact = await carbon+ .from("customerContact")+ .select(+ `+ id,+ contact!inner (+ id,+ companyId,+ externalId+ )+ `+ )+ .eq("contact.companyId", payload.companyId)+ // @ts-expect-error - JSONB column+ .eq("contact.externalId->paperlessPartsId", paperlessPartsContactId)+ .maybeSingle();++ if (existingCustomerContact.data) {+ customerContactId = existingCustomerContact.data.id;+ } else {+ // If there is no matching contact in CarbonOS, we need to create a new contact in CarbonOS+ const newContact = await carbon+ .from("contact")+ .insert({+ companyId: payload.companyId,+ firstName: ppQuote.data.contact?.first_name!,+ lastName: ppQuote.data.contact?.last_name!,+ email: ppQuote.data.contact?.email!,+ externalId: {+ paperlessPartsId: ppQuote.data.contact?.id,+ },+ })+ .select()+ .single();++ if (newContact.error || !newContact.data) {+ throw new Error("Failed to create contact in CarbonOS");+ }++ console.info("🔰 New CarbonOS contact created");++ const newCustomerContact = await carbon+ .from("customerContact")+ .insert({+ customerId,+ contactId: newContact.data.id,+ })+ .select()+ .single();++ if (newCustomerContact.error || !newCustomerContact.data) {+ throw new Error("Failed to create customer contact in CarbonOS");+ }++ console.info("🔰 OS customerContact created");++ customerContactId = newCustomerContact.data.id;+ }++ // Create a new quote in CarbonOS+ const nextSequence = await getNextSequence(+ carbon,+ "quote",+ payload.companyId+ );++ if (!nextSequence.data) {+ throw new Error("Failed to get next sequence number for quote");+ }++ const newCarbonQuote = await carbon+ .from("quote")+ .insert({+ quoteId: nextSequence.data,+ companyId: payload.companyId,+ customerId,+ customerContactId,+ createdBy: "system",+ currencyCode: "USD",+ })+ .select()+ .single();++ if (newCarbonQuote.error || !newCarbonQuote.data) {+ throw new Error("Failed to create quote in CarbonOS");+ }+ console.info("🔰 New CarbonOS quote created");++ // Create a new QuoteShipment+ const newQuoteShipment = await carbon+ .from("quoteShipment")+ .insert({+ companyId: payload.companyId,+ id: newCarbonQuote.data.id,+ })+ .select()+ .single();++ if (newQuoteShipment.error || !newQuoteShipment.data) {+ throw new Error("Failed to create quote shipment in CarbonOS");+ }+ console.info("🔰 New CarbonOS quoteShipment created");++ // Create a new QuotePayment+ const newQuotePayment = await carbon+ .from("quotePayment")+ .insert({+ companyId: payload.companyId,+ id: newCarbonQuote.data.id,+ })+ .select()+ .single();++ if (newQuotePayment.error || !newQuotePayment.data) {+ throw new Error("Failed to create quote payment in CarbonOS");+ }+ console.info("🔰 New CarbonOS quotePayment created");++ // Create a new Opportunity for the quote+ const newOpportunity = await carbon+ .from("opportunity")+ .insert({+ quoteId: newCarbonQuote.data.id,+ companyId: payload.companyId,+ })+ .select()+ .single();++ if (newOpportunity.error || !newOpportunity.data) {+ throw new Error("Failed to create opportunity in CarbonOS");+ }++ console.info("🔰 New CarbonOS opportunity created");+result = {success: true,message: "Quote sent event processed successfully",@@ -194,3 +423,14 @@ export const paperlessPartsTask = task({return result;},});++async function getNextSequence(+ client: SupabaseClient<Database>,+ table: string,+ companyId: string+) {+ return client.rpc("get_next_sequence", {+ sequence_name: table,+ company_id: companyId,+ });+}