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.

refactor: update integration lib

Brad Barbinf0b7b05bdee0
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a98c55f212..71674670f9 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -39682,14 +39682,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -44057,14 +44057,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -48069,7 +48069,6 @@ export type Database = {
owner_id: string | null
path_tokens: string[] | null
updated_at: string | null
- user_metadata: Json | null
version: string | null
}
Insert: {
@@ -48083,7 +48082,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Update: {
@@ -48097,7 +48095,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Relationships: [
@@ -48119,7 +48116,6 @@ export type Database = {
key: string
owner_id: string | null
upload_signature: string
- user_metadata: Json | null
version: string
}
Insert: {
@@ -48130,7 +48126,6 @@ export type Database = {
key: string
owner_id?: string | null
upload_signature: string
- user_metadata?: Json | null
version: string
}
Update: {
@@ -48141,7 +48136,6 @@ export type Database = {
key?: string
owner_id?: string | null
upload_signature?: string
- user_metadata?: Json | null
version?: string
}
Relationships: [
@@ -48278,10 +48272,6 @@ export type Database = {
updated_at: string
}[]
}
- operation: {
- Args: Record<PropertyKey, never>
- Returns: string
- }
search: {
Args: {
prefix: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a98c55f212..71674670f9 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -39682,14 +39682,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -44057,14 +44057,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -48069,7 +48069,6 @@ export type Database = {
owner_id: string | null
path_tokens: string[] | null
updated_at: string | null
- user_metadata: Json | null
version: string | null
}
Insert: {
@@ -48083,7 +48082,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Update: {
@@ -48097,7 +48095,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Relationships: [
@@ -48119,7 +48116,6 @@ export type Database = {
key: string
owner_id: string | null
upload_signature: string
- user_metadata: Json | null
version: string
}
Insert: {
@@ -48130,7 +48126,6 @@ export type Database = {
key: string
owner_id?: string | null
upload_signature: string
- user_metadata?: Json | null
version: string
}
Update: {
@@ -48141,7 +48136,6 @@ export type Database = {
key?: string
owner_id?: string | null
upload_signature?: string
- user_metadata?: Json | null
version?: string
}
Relationships: [
@@ -48278,10 +48272,6 @@ export type Database = {
updated_at: string
}[]
}
- operation: {
- Args: Record<PropertyKey, never>
- Returns: string
- }
search: {
Args: {
prefix: string
diff --git a/packages/integrations/package.json b/packages/integrations/package.json
index 5cc0d9c89c..57b0676aab 100644
--- a/packages/integrations/package.json
+++ b/packages/integrations/package.json
@@ -7,6 +7,7 @@
"./exchange-rates/exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",
"./notifications": "./src/notifications/index.ts",
"./onshape": "./src/onshape/lib/index.ts",
+ "./paperless-parts": "./src/paperless-parts/lib/client.ts",
"./slack.server": "./src/slack.server.ts",
"./slack/messages": "./src/slack/lib/messages.ts"
},
diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
index 7ccab061ea..d163d0f9c8 100644
--- a/packages/jobs/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -1,5 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import { PaperlessPartsClient } from "@carbon/integrations/paperless-parts";
import type { SupabaseClient } from "@supabase/supabase-js";
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
@@ -103,7 +104,7 @@ export const paperlessPartsTask = task({
console.info(`📦 Payload:`, payload);
const carbon = getCarbonServiceRole();
- // const paperless = new PaperlessPartsClient(payload.apiKey);
+ const paperless = new PaperlessPartsClient(payload.apiKey);
switch (payload.payload.type) {
case "quote.created":
@@ -152,11 +153,11 @@ export const paperlessPartsTask = task({
// If the customer does not exist, create a new customer in CarbonOS
if (ppQuote.data.contact?.account) {
const paperlessPartsCustomerId = ppQuote.data.contact?.account?.id;
+ // @ts-expect-error - JSONB column
const existingCustomer = await carbon
.from("customer")
.select("id")
.eq("companyId", payload.companyId)
- // @ts-expect-error - JSONB column
.eq("externalId->paperlessPartsId", paperlessPartsCustomerId)
.maybeSingle();
@@ -242,7 +243,6 @@ export const paperlessPartsTask = task({
`
)
.eq("contact.companyId", payload.companyId)
- // @ts-expect-error - JSONB column
.eq("contact.externalId->paperlessPartsId", paperlessPartsContactId)
.maybeSingle();
@@ -299,69 +299,134 @@ export const paperlessPartsTask = task({
throw new Error("Failed to get next sequence number for quote");
}
- const newCarbonQuote = await carbon
+ // Create a quote object from the Paperless Parts data
+ const quote = {
+ companyId: payload.companyId,
+ customerId: customerId,
+ customerContactId: customerContactId,
+ quoteId: nextSequence.data.toString(),
+ name: `Quote for ${
+ ppQuote.data.contact?.account?.name ||
+ `${ppQuote.data.contact?.first_name} ${ppQuote.data.contact?.last_name}`
+ }`,
+ status: "Draft" as const,
+ currencyCode: "USD",
+ createdBy: "system",
+ exchangeRate: 1 as number | undefined,
+ exchangeRateUpdatedAt: undefined as string | undefined,
+ expirationDate: undefined as string | undefined,
+ externalId: {
+ paperlessPartsId: quotePayload.uuid,
+ },
+ };
+
+ const [customerPayment, customerShipping, employee, opportunity] =
+ await Promise.all([
+ getCustomerPayment(carbon, quote.customerId),
+ getCustomerShipping(carbon, quote.customerId),
+ getEmployeeJob(carbon, quote.createdBy, quote.companyId),
+ carbon
+ .from("opportunity")
+ .insert([
+ { companyId: quote.companyId, customerId: quote.customerId },
+ ])
+ .select("id")
+ .single(),
+ ]);
+
+ if (customerPayment.error) return customerPayment;
+ if (customerShipping.error) return customerShipping;
+
+ const {
+ paymentTermId,
+ invoiceCustomerId,
+ invoiceCustomerContactId,
+ invoiceCustomerLocationId,
+ } = customerPayment.data;
+
+ const { shippingMethodId, shippingTermId } = customerShipping.data;
+
+ if (quote.currencyCode) {
+ const currency = await getCurrencyByCode(
+ carbon,
+ quote.companyId,
+ quote.currencyCode
+ );
+ if (currency.data) {
+ quote.exchangeRate = currency.data.exchangeRate ?? undefined;
+ quote.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+ } else {
+ quote.exchangeRate = 1;
+ quote.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+
+ const locationId = employee?.data?.locationId ?? null;
+ const insert = 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");
+ .insert([
+ {
+ ...quote,
+ opportunityId: opportunity.data?.id,
+ },
+ ])
+ .select("id, quoteId");
+ if (insert.error) {
+ return insert;
}
- 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");
+
+ const quoteId = insert.data?.[0]?.id;
+ if (!quoteId) return insert;
+
+ const [shipment, payment, externalLink] = await Promise.all([
+ carbon.from("quoteShipment").insert([
+ {
+ id: quoteId,
+ locationId: locationId,
+ shippingMethodId: shippingMethodId,
+ shippingTermId: shippingTermId,
+ companyId: quote.companyId,
+ },
+ ]),
+ carbon.from("quotePayment").insert([
+ {
+ id: quoteId,
+ invoiceCustomerId: invoiceCustomerId,
+ invoiceCustomerContactId: invoiceCustomerContactId,
+ invoiceCustomerLocationId: invoiceCustomerLocationId,
+ paymentTermId: paymentTermId,
+ companyId: quote.companyId,
+ },
+ ]),
+ upsertExternalLink(carbon, {
+ documentType: "Quote" as const,
+ documentId: quoteId,
+ customerId: quote.customerId,
+ expiresAt: quote.expirationDate,
+ companyId: quote.companyId,
+ }),
+ ]);
+
+ if (shipment.error) {
+ await deleteQuote(carbon, quoteId);
+ return payment;
+ }
+ if (payment.error) {
+ await deleteQuote(carbon, quoteId);
+ return payment;
}
- 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");
+ if (opportunity.error) {
+ await deleteQuote(carbon, quoteId);
+ return opportunity;
}
- 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");
+ if (externalLink.data) {
+ await carbon
+ .from("quote")
+ .update({ externalLinkId: externalLink.data.id })
+ .eq("id", quoteId);
}
- console.info("🔰 New CarbonOS opportunity created");
+ console.info("🔰 New CarbonOS quote created from Paperless Parts");
result = {
success: true,
@@ -434,3 +499,78 @@ async function getNextSequence(
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 getEmployeeJob(
+ client: SupabaseClient<Database>,
+ employeeId: string,
+ companyId: string
+) {
+ return client
+ .from("employeeJob")
+ .select("*")
+ .eq("id", employeeId)
+ .eq("companyId", companyId)
+ .single();
+}
+
+async function getCurrencyByCode(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ currencyCode: string
+) {
+ return client
+ .from("currency")
+ .select("exchangeRate")
+ .eq("companyId", companyId)
+ .eq("code", currencyCode)
+ .single();
+}
+
+async function deleteQuote(client: SupabaseClient<Database>, quoteId: string) {
+ return client.from("quote").delete().eq("id", quoteId);
+}
+
+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();
+}
diff --git a/packages/jobs/trigger/slack-document-sync.ts b/packages/jobs/trigger/slack-document-sync.ts
index e7db487ee9..ce116b35e5 100644
--- a/packages/jobs/trigger/slack-document-sync.ts
+++ b/packages/jobs/trigger/slack-document-sync.ts
@@ -1,7 +1,6 @@
import { getCarbonServiceRole, VERCEL_URL } from "@carbon/auth";
import type { Database } from "@carbon/database";
import {
- type DocumentData,
type DocumentType,
type IssueAssignmentUpdate,
type IssueStatusUpdate,
@@ -343,7 +342,7 @@ async function getDocumentData(
documentType: DocumentType,
documentId: string,
companyId: string
-): Promise<DocumentData | null> {
+): Promise<any | null> {
switch (documentType) {
case "nonConformance": {
const { data } = await serviceRole
@@ -368,9 +367,78 @@ async function getDocumentData(
} as NonConformanceData;
}
- case "quote":
- case "salesOrder":
- case "job":
+ case "quote": {
+ const { data } = await serviceRole
+ .from("quote")
+ .select("id, quoteId, customerReference, status, createdBy, createdAt")
+ .eq("id", documentId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (!data) return null;
+
+ return {
+ documentType: "quote",
+ id: data.id,
+ readableId: data.quoteId,
+ title: data.customerReference,
+ description: data.customerReference,
+ status: data.status,
+ createdBy: data.createdBy,
+ createdAt: data.createdAt,
+ };
+ }
+
+ case "salesOrder": {
+ const { data } = await serviceRole
+ .from("salesOrder")
+ .select(
+ "id, salesOrderId, customerReference, status, createdBy, createdAt"
+ )
+ .eq("id", documentId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (!data) return null;
+
+ return {
+ documentType: "salesOrder",
+ id: data.id,
+ readableId: data.salesOrderId,
+ title: data.customerReference,
+ description: data.customerReference,
+ status: data.status,
+ createdBy: data.createdBy,
+ createdAt: data.createdAt,
+ };
+ }
+
+ case "job": {
+ const { data } = await serviceRole
+ .from("job")
+ .select("id, jobId, status, createdBy, createdAt")
+ .eq("id", documentId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (!data) return null;
+
+ return {
+ documentType: "job",
+ id: data.id,
+ readableId: data.jobId,
+ title: data.jobId,
+ description: data.jobId,
+ status: data.status,
+ createdBy: data.createdBy,
+ createdAt: data.createdAt,
+ };
+ }
+
+ case "purchaseOrder":
+ case "invoice":
+ case "receipt":
+ case "shipment":
default:
console.warn(`Document type ${documentType} not yet implemented`);
return null;