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: create util function for parsing customer and contact form paperless

Brad Barbin1fbcf0c033c9
diff --git a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
index e671b8c134..b0bb869817 100644
--- a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
+++ b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
@@ -89,10 +89,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
return json({ success: false }, { status: 401 });
}
+ const payload = JSON.parse(payloadText);
+ console.log("payload", payload);
+
await tasks.trigger<typeof paperlessPartsTask>("paperless-parts", {
apiKey,
companyId,
- payload: JSON.parse(payloadText),
+ payload,
});
return json({ success: true });
diff --git a/packages/integrations/package.json b/packages/integrations/package.json
index 57b0676aab..dd92f4e977 100644
--- a/packages/integrations/package.json
+++ b/packages/integrations/package.json
@@ -7,7 +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",
+ "./paperless-parts": "./src/paperless-parts/lib/index.ts",
"./slack.server": "./src/slack.server.ts",
"./slack/messages": "./src/slack/lib/messages.ts"
},
diff --git a/packages/integrations/src/paperless-parts/lib/client.ts b/packages/integrations/src/paperless-parts/lib/client.ts
index f565884be4..c04abaafb6 100644
--- a/packages/integrations/src/paperless-parts/lib/client.ts
+++ b/packages/integrations/src/paperless-parts/lib/client.ts
@@ -1224,7 +1224,7 @@ export enum ContentType {
}
export class HttpClient<SecurityDataType = unknown> {
- public baseUrl: string = "https://api.paperlessparts.com/";
+ public baseUrl: string = "https://api.paperlessparts.com";
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private abortControllers = new Map<CancelToken, AbortController>();
diff --git a/packages/integrations/src/paperless-parts/lib/index.ts b/packages/integrations/src/paperless-parts/lib/index.ts
new file mode 100644
index 0000000000..ee5a82e3b6
--- /dev/null
+++ b/packages/integrations/src/paperless-parts/lib/index.ts
@@ -0,0 +1,9 @@
+import { PaperlessPartsClient } from "./client";
+
+export * from "./schemas";
+export * from "./utils";
+
+export async function getPaperlessParts(apiKey: string) {
+ const client = new PaperlessPartsClient(apiKey);
+ return client;
+}
diff --git a/packages/integrations/src/paperless-parts/lib/schemas.ts b/packages/integrations/src/paperless-parts/lib/schemas.ts
new file mode 100644
index 0000000000..32190eaf16
--- /dev/null
+++ b/packages/integrations/src/paperless-parts/lib/schemas.ts
@@ -0,0 +1,221 @@
+import { z } from "zod";
+
+// Address schema
+export const AddressSchema = z.object({
+ id: z.number().optional(),
+ erp_code: z.string().nullable().optional(),
+ attention: z.string().optional(),
+ address1: z.string().optional(),
+ address2: z.string().optional(),
+ business_name: z.string().optional(),
+ city: z.string().optional(),
+ country: z.string().optional(),
+ facility_name: z.string().nullable().optional(),
+ phone: z.string().optional(),
+ phone_ext: z.string().optional(),
+ postal_code: z.string().optional(),
+ state: z.string().optional(),
+});
+
+// Account metrics schema
+export const AccountMetricsSchema = z.object({
+ order_revenue_all_time: z.number().optional(),
+ order_revenue_last_thirty_days: z.number().optional(),
+ quotes_sent_all_time: z.number().optional(),
+ quotes_sent_last_thirty_days: z.number().optional(),
+});
+
+// Account schema
+export const AccountSchema = z.object({
+ erp_code: z.string().nullable().optional(),
+ id: z.number().optional(),
+ metrics: AccountMetricsSchema.optional(),
+ notes: z.string().nullable().optional(),
+ name: z.string().optional(),
+ payment_terms: z.string().optional(),
+ payment_terms_period: z.number().optional(),
+});
+
+// Contact schema
+export const ContactSchema = z.object({
+ account: AccountSchema.optional(),
+ email: z.string().email().optional(),
+ first_name: z.string().optional(),
+ id: z.number().optional(),
+ last_name: z.string().optional(),
+ notes: z.string().optional(),
+ phone: z.string().optional(),
+ phone_ext: z.string().optional(),
+});
+
+// Company schema for customer
+export const CompanySchema = z.object({
+ business_name: z.string().optional(),
+ erp_code: z.string().nullable().optional(),
+ id: z.number().nullable().optional(),
+ metrics: AccountMetricsSchema.optional(),
+ notes: z.string().nullable().optional(),
+ phone: z.string().optional(),
+ phone_ext: z.string().optional(),
+});
+
+// Customer schema
+export const CustomerSchema = z.object({
+ id: z.number().nullable().optional(),
+ company: CompanySchema.optional(),
+ email: z.string().email().optional(),
+ first_name: z.string().optional(),
+ last_name: z.string().optional(),
+ notes: z.string().optional(),
+ phone: z.string().optional(),
+ phone_ext: z.string().optional(),
+});
+
+// Sales person schema
+export const SalesPersonSchema = z.object({
+ first_name: z.string().optional(),
+ last_name: z.string().optional(),
+ avatar_color: z.string().optional(),
+ email: z.string().email().optional(),
+ erp_code: z.string().optional(),
+});
+
+// Facility schema
+export const FacilitySchema = z.object({
+ name: z.string().optional(),
+ address: AddressSchema.optional(),
+ is_default: z.boolean().optional(),
+ phone: z.string().optional(),
+ phone_ext: z.string().optional(),
+ url: z.string().optional(),
+});
+
+// Component schema
+export const ComponentSchema = z.object({
+ id: z.number().optional(),
+ child_ids: z.array(z.number()).optional(),
+ children: z.array(z.unknown()).optional(), // recursive, so using unknown
+ description: z.string().nullable().optional(),
+ export_controlled: z.boolean().optional(),
+ finishes: z.array(z.unknown()).optional(),
+ innate_quantity: z.number().optional(),
+ is_assembly: z.boolean().optional(),
+ is_root_component: z.boolean().optional(),
+ material: z.unknown().nullable().optional(),
+ material_operations: z.array(z.unknown()).optional(),
+ obtain_method: z.string().optional(),
+ parent_ids: z.array(z.number()).optional(),
+ part_custom_attrs: z.array(z.unknown()).optional(),
+ part_name: z.string().optional(),
+ part_number: z.string().optional(),
+ part_url: z.string().url().optional(),
+ part_uuid: z.string().uuid().optional(),
+ process: z.unknown().nullable().optional(),
+ purchased_component: z.unknown().nullable().optional(),
+ revision: z.string().optional(),
+ shop_operations: z.array(z.unknown()).optional(),
+ supporting_files: z.array(z.unknown()).optional(),
+ thumbnail_url: z.string().url().optional(),
+ type: z.string().optional(),
+ deliver_quantity: z.number().optional(),
+ make_quantity: z.number().optional(),
+});
+
+// Order item schema
+export const OrderItemSchema = z.object({
+ id: z.number().optional(),
+ components: z.array(ComponentSchema).optional(),
+ description: z.string().nullable().optional(),
+ expedite_revenue: z.string().optional(), // API returns as string
+ export_controlled: z.boolean().optional(),
+ filename: z.string().optional(),
+ lead_days: z.number().optional(),
+ markup_1_price: z.string().optional(), // API returns as string
+ markup_1_name: z.string().nullable().optional(),
+ markup_2_price: z.string().optional(), // API returns as string
+ markup_2_name: z.string().nullable().optional(),
+ private_notes: z.string().nullable().optional(),
+ public_notes: z.string().optional(),
+ quantity: z.number().optional(),
+ quantity_outstanding: z.number().optional(),
+ quote_item_id: z.number().optional(),
+ quote_item_type: z.enum(["automatic", "manual"]).optional(),
+ root_component_id: z.number().optional(),
+ ships_on: z.string().optional(), // Date string
+ total_price: z.string().optional(), // API returns as string
+ unit_price: z.string().optional(), // API returns as string
+ base_price: z.string().optional(), // API returns as string
+ add_on_fees: z.unknown().nullable().optional(),
+ unit_price_before_discounts: z.string().optional(), // API returns as string
+ ordered_add_ons: z.array(z.unknown()).optional(),
+ pricing_items: z.array(z.unknown()).optional(),
+});
+
+// Payment details schema
+export const PaymentDetailsSchema = z.object({
+ card_brand: z.string().nullable().optional(),
+ card_last4: z.string().nullable().optional(),
+ net_payout: z.string().optional(), // API returns as string
+ payment_type: z.enum(["credit_card", "purchase_order"]).nullable().optional(),
+ purchase_order_number: z.string().optional(),
+ purchasing_dept_contact_email: z.string().email().nullable().optional(),
+ purchasing_dept_contact_name: z.string().optional(),
+ shipping_cost: z.string().optional(), // API returns as string
+ subtotal: z.string().optional(), // API returns as string
+ tax_cost: z.string().optional(), // API returns as string
+ tax_rate: z.string().optional(), // API returns as string
+ payment_terms: z.string().optional(),
+ total_price: z.string().optional(), // API returns as string
+});
+
+// Shipping option schema
+export const ShippingOptionSchema = z.object({
+ customers_account_number: z.string().nullable().optional(),
+ customers_carrier: z.string().nullable().optional(),
+ shipping_method: z.string().optional(),
+ type: z.string().optional(),
+});
+
+// Shipment schema
+export const ShipmentSchema = z.array(z.unknown()); // Empty array in the example
+
+// Main Order schema
+export const OrderSchema = z.object({
+ uuid: z.string().uuid().optional(),
+ billing_info: AddressSchema.optional(),
+ created: z.string().optional(), // Loosened datetime restriction
+ contact: ContactSchema.optional(),
+ customer: CustomerSchema.optional(),
+ deliver_by: z.string().nullable().optional(),
+ estimator: SalesPersonSchema.optional(),
+ send_from_facility: FacilitySchema.optional(),
+ erp_code: z.string().nullable().optional(),
+ number: z.number().optional(),
+ order_items: z.array(OrderItemSchema).optional(),
+ payment_details: PaymentDetailsSchema.optional(),
+ private_notes: z.string().optional(),
+ purchase_order_file_url: z.string().url().nullable().optional(),
+ quote_erp_code: z.string().nullable().optional(),
+ quote_number: z.number().optional(),
+ quote_revision_number: z.number().nullable().optional(),
+ sales_person: SalesPersonSchema.optional(),
+ salesperson: SalesPersonSchema.optional(),
+ shipments: ShipmentSchema.optional(),
+ shipping_info: AddressSchema.optional(),
+ shipping_option: ShippingOptionSchema.optional(),
+ ships_on: z.string().optional(), // Date string
+ status: z
+ .enum([
+ "pending",
+ "confirmed",
+ "on_hold",
+ "in_process",
+ "completed",
+ "cancelled",
+ ])
+ .optional(),
+ quote_rfq_number: z.string().optional(),
+});
+
+// Export the inferred type
+export type Order = z.infer<typeof OrderSchema>;
diff --git a/packages/integrations/src/paperless-parts/lib/utils.ts b/packages/integrations/src/paperless-parts/lib/utils.ts
new file mode 100644
index 0000000000..6e52e9a0ed
--- /dev/null
+++ b/packages/integrations/src/paperless-parts/lib/utils.ts
@@ -0,0 +1,168 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type z from "zod";
+import type { PaperlessPartsClient } from "./client";
+import type { ContactSchema } from "./schemas";
+
+export async function getCarbonCustomerIdAndContactId(
+ carbon: SupabaseClient<Database>,
+ paperless: PaperlessPartsClient<unknown>,
+ company: Database["public"]["Tables"]["company"]["Row"],
+ contact: z.infer<typeof ContactSchema>
+) {
+ let customerId: string;
+ let customerContactId: string;
+
+ if (!contact) {
+ throw new Error("Missing contact from Paperless Parts");
+ }
+
+ // 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 Carbon
+
+ if (contact.account) {
+ const paperlessPartsCustomerId = contact.account?.id;
+
+ // @ts-expect-error - JSONB column
+ const existingCustomer = await carbon
+ .from("customer")
+ .select("id")
+ .eq("companyId", company.id)
+ .eq("externalId->paperlessPartsId", paperlessPartsCustomerId!)
+ .maybeSingle();
+
+ if (existingCustomer.data) {
+ customerId = existingCustomer.data.id;
+ } else {
+ const customerName = contact.account?.name!;
+ const newCustomer = await carbon
+ .from("customer")
+ .upsert(
+ {
+ companyId: company.id,
+ name: customerName,
+ externalId: {
+ paperlessPartsId: contact.account.id,
+ },
+ currencyCode: company.baseCurrencyCode,
+ createdBy: "system",
+ },
+ {
+ onConflict: "name, companyId",
+ }
+ )
+ .select()
+ .single();
+
+ if (newCustomer.error || !newCustomer.data) {
+ console.error(newCustomer.error);
+ throw new Error("Failed to create customer in Carbon");
+ }
+
+ customerId = newCustomer.data.id;
+ }
+ } else {
+ // If the quote contact does not have an account, we need to create a new customer in Carbon
+ // and also create a corresponding account in Paperless Parts
+ const customerName = `${contact.first_name} ${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: company.id,
+ name: customerName,
+ externalId: {
+ paperlessPartsId: newPaperlessPartsAccountId,
+ },
+ currencyCode: company.baseCurrencyCode,
+ createdBy: "system",
+ })
+ .select()
+ .single();
+
+ if (newCustomer.error || !newCustomer.data) {
+ throw new Error("Failed to create customer in Carbon");
+ }
+
+ console.info("🔰 New Carbon customer created");
+
+ customerId = newCustomer.data.id;
+ }
+
+ // Get the contact ID from Carbon based on the Paperless Parts ID
+ const paperlessPartsContactId = contact.id;
+ const existingCustomerContact = await carbon
+ .from("customerContact")
+ .select(
+ `
+ id,
+ contact!inner (
+ id,
+ companyId,
+ externalId
+ )
+ `
+ )
+ .eq("contact.companyId", company.id)
+ .eq("contact.externalId->paperlessPartsId", paperlessPartsContactId!)
+ .maybeSingle();
+
+ if (existingCustomerContact.data) {
+ customerContactId = existingCustomerContact.data.id;
+ } else {
+ // If there is no matching contact in Carbon, we need to create a new contact in Carbon
+ const newContact = await carbon
+ .from("contact")
+ .insert({
+ companyId: company.id,
+ firstName: contact.first_name!,
+ lastName: contact.last_name!,
+ email: contact.email!,
+ externalId: {
+ paperlessPartsId: contact.id,
+ },
+ })
+ .select()
+ .single();
+
+ if (newContact.error || !newContact.data) {
+ throw new Error("Failed to create contact in Carbon");
+ }
+
+ console.info("🔰 New Carbon 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 Carbon");
+ }
+
+ console.info("🔰 Carbon customerContact created");
+
+ customerContactId = newCustomerContact.data.id;
+ }
+
+ return {
+ customerId,
+ customerContactId,
+ };
+}
diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
index d163d0f9c8..0be1bf5913 100644
--- a/packages/jobs/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import type { Database } from "@carbon/database";
-import { PaperlessPartsClient } from "@carbon/integrations/paperless-parts";
+import { getPaperlessParts } from "@carbon/integrations/paperless-parts";
import type { SupabaseClient } from "@supabase/supabase-js";
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
@@ -56,7 +56,11 @@ const payloadSchema = z.discriminatedUnion("type", [
type: z.literal("order.created"),
created: z.string(),
object: z.string(),
- data: z.any(),
+ data: z.object({
+ uuid: z.string(),
+ status: z.string(),
+ number: z.number().optional(),
+ }),
}),
z.object({
type: z.literal("order.status_changed"),
@@ -104,7 +108,7 @@ export const paperlessPartsTask = task({
console.info(`📦 Payload:`, payload);
const carbon = getCarbonServiceRole();
- const paperless = new PaperlessPartsClient(payload.apiKey);
+ const paperless = await getPaperlessParts(payload.apiKey);
switch (payload.payload.type) {
case "quote.created":
@@ -142,7 +146,7 @@ export const paperlessPartsTask = task({
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"
+ "Quote contact not found in Paperless Parts - cannot create Carbon Quote"
);
}
@@ -150,7 +154,7 @@ export const paperlessPartsTask = task({
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 the customer does not exist, create a new customer in Carbon
if (ppQuote.data.contact?.account) {
const paperlessPartsCustomerId = ppQuote.data.contact?.account?.id;
// @ts-expect-error - JSONB column
@@ -180,13 +184,13 @@ export const paperlessPartsTask = task({
.single();
if (newCustomer.error || !newCustomer.data) {
- throw new Error("Failed to create customer in CarbonOS");
+ throw new Error("Failed to create customer in Carbon");
}
customerId = newCustomer.data.id;
}
} else {
- // If the quote contact does not have an account, we need to create a new customer in CarbonOS
+ // If the quote contact does not have an account, we need to create a new customer in Carbon
// and also create a corresponding account in Paperless Parts
const customerName = `${ppQuote.data.contact?.first_name} ${ppQuote.data.contact?.last_name}`;
@@ -220,10 +224,10 @@ export const paperlessPartsTask = task({
.single();
if (newCustomer.error || !newCustomer.data) {
- throw new Error("Failed to create customer in CarbonOS");
+ throw new Error("Failed to create customer in Carbon");
}
- console.info("🔰 New CarbonOS customer created");
+ console.info("🔰 New Carbon customer created");
customerId = newCustomer.data.id;
}
@@ -249,7 +253,7 @@ export const paperlessPartsTask = task({
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
+ // If there is no matching contact in Carbon, we need to create a new contact in Carbon
const newContact = await carbon
.from("contact")
.insert({
@@ -265,10 +269,10 @@ export const paperlessPartsTask = task({
.single();
if (newContact.error || !newContact.data) {
- throw new Error("Failed to create contact in CarbonOS");
+ throw new Error("Failed to create contact in Carbon");
}
- console.info("🔰 New CarbonOS contact created");
+ console.info("🔰 New Carbon contact created");
const newCustomerContact = await carbon
.from("customerContact")
@@ -280,7 +284,7 @@ export const paperlessPartsTask = task({
.single();
if (newCustomerContact.error || !newCustomerContact.data) {
- throw new Error("Failed to create customer contact in CarbonOS");
+ throw new Error("Failed to create customer contact in Carbon");
}
console.info("🔰 OS customerContact created");
@@ -288,7 +292,7 @@ export const paperlessPartsTask = task({
customerContactId = newCustomerContact.data.id;
}
- // Create a new quote in CarbonOS
+ // Create a new quote in Carbon
const nextSequence = await getNextSequence(
carbon,
"quote",
@@ -426,7 +430,7 @@ export const paperlessPartsTask = task({
.eq("id", quoteId);
}
- console.info("🔰 New CarbonOS quote created from Paperless Parts");
+ console.info("🔰 New Carbon quote created from Paperless Parts");
result = {
success: true,
diff --git a/scripts/paperless-test.ts b/scripts/paperless-test.ts
new file mode 100644
index 0000000000..0574f82e08
--- /dev/null
+++ b/scripts/paperless-test.ts
@@ -0,0 +1,229 @@
+import * as dotenv from "dotenv";
+
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { createClient } from "@supabase/supabase-js";
+import type { Database } from "../packages/database/src/types";
+import {
+ getCarbonCustomerIdAndContactId,
+ getPaperlessParts,
+} from "../packages/integrations/src/paperless-parts/lib/index";
+import { OrderSchema } from "../packages/integrations/src/paperless-parts/lib/schemas";
+const orderNumber = 1;
+const apiKey = "3c82924535cc39a51cbb59c1350754f92fb65742";
+const companyId = "SanLTzPk93kscfQ7oCnSSu";
+
+dotenv.config();
+
+const SUPABASE_URL = process.env.SUPABASE_URL;
+const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
+
+(async () => {
+ const carbon = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
+ const paperless = await getPaperlessParts(apiKey);
+ const company = await carbon
+ .from("company")
+ .select("*")
+ .eq("id", companyId)
+ .single();
+
+ const order = await paperless.orders.orderDetails(orderNumber);
+ if (order.data) {
+ const orderData = OrderSchema.parse(order.data);
+ console.log(orderData);
+
+ const { customerId, customerContactId } =
+ await getCarbonCustomerIdAndContactId(
+ carbon,
+ paperless,
+ company.data!,
+ orderData.contact!
+ );
+
+ if (!customerId) {
+ throw new Error("Failed to get customer ID");
+ }
+ if (!customerContactId) {
+ throw new Error("Failed to get customer contact ID");
+ }
+
+ const [customerPayment, customerShipping, employee, opportunity] =
+ await Promise.all([
+ getCustomerPayment(carbon, customerId),
+ getCustomerShipping(carbon, customerId),
+ getEmployeeJob(carbon, salesOrder.createdBy, companyId),
+ carbon
+ .from("opportunity")
+ .insert([
+ {
+ companyId: companyId,
+ customerId: 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;
+
+ const locationId = employee?.data?.locationId ?? null;
+
+ let salesOrderInsert: Database["public"]["Tables"]["salesOrder"]["Insert"] =
+ {
+ companyId: companyId,
+ createdBy: employee?.data?.id ?? "system",
+ currencyCode: company.data?.baseCurrencyCode,
+ customerId: customerId,
+ opportunityId: opportunity.data?.id,
+ };
+
+ const insertedSalesOrder = await carbon
+ .from("salesOrder")
+ .insert([salesOrderInsert])
+ .select("id, salesOrderId");
+
+ if (order.error) return order;
+
+ const salesOrderId = order.data[0].id;
+
+ const [shipment, payment] = await Promise.all([
+ carbon.from("salesOrderShipment").insert([
+ {
+ id: salesOrderId,
+ locationId: locationId,
+ shippingMethodId: shippingMethodId,
+ shippingTermId: shippingTermId,
+ companyId: companyId,
+ },
+ ]),
+ carbon.from("salesOrderPayment").insert([
+ {
+ id: salesOrderId,
+ invoiceCustomerId: invoiceCustomerId,
+ invoiceCustomerContactId: invoiceCustomerContactId,
+ invoiceCustomerLocationId: invoiceCustomerLocationId,
+ paymentTermId: paymentTermId,
+ companyId: companyId,
+ },
+ ]),
+ ]);
+
+ if (shipment.error) {
+ await deleteSalesOrder(carbon, salesOrderId);
+ return payment;
+ }
+ if (payment.error) {
+ await deleteSalesOrder(carbon, salesOrderId);
+ return payment;
+ }
+ if (opportunity.error) {
+ await deleteSalesOrder(carbon, salesOrderId);
+ return opportunity;
+ }
+ } else {
+ console.error("No order data found");
+ return;
+ }
+})();
+
+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 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 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();
+}