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.

feat: finalize quote

Brad Barbin208a67451d62
diff --git a/apps/carbon/app/jobs.server/autodesk-poll.server.ts b/apps/carbon/app/jobs.server/autodesk-poll.server.ts
deleted file mode 100644
index 60e9c72c3c..0000000000
--- a/apps/carbon/app/jobs.server/autodesk-poll.server.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { eventTrigger } from "@trigger.dev/sdk";
-import { z } from "zod";
-import { getAutodeskToken, getManifest } from "~/lib/autodesk/autodesk.server";
-
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-import { upsertModelUpload } from "~/modules/shared";
-
-const supabaseClient = getSupabaseServiceRole();
-
-const job = triggerClient.defineJob({
- id: "autodesk-poll",
- name: "Poll Autodesk for Translation Progress",
- version: "0.0.1",
- trigger: eventTrigger({
- name: "autodesk.poll",
- schema: z.object({
- id: z.string(),
- name: z.string(),
- size: z.number(),
- autodeskUrn: z.string(),
- companyId: z.string(),
- }),
- }),
- run: async (payload, io, ctx) => {
- const { companyId, id, name, size, autodeskUrn } = payload;
-
- await io.runTask(
- "autodesk-manifest-poll",
- async () => {
- const token = await getAutodeskToken();
- if (token.error) {
- throw new Error(
- "Failed to get Autodesk token: " + token.error.message
- );
- }
-
- const manifest = await getManifest(
- autodeskUrn,
- token.data.token,
- companyId
- );
- if (manifest.error) {
- throw new Error("Failed to get manifest: " + manifest.error.message);
- }
-
- const modelRecord = await upsertModelUpload(supabaseClient, {
- id,
- name,
- size,
- thumbnailPath: manifest.data.thumbnailPath,
- autodeskUrn,
- });
-
- if (modelRecord.error) {
- throw new Error(
- "Failed to record upload: " + modelRecord.error.message
- );
- }
- },
- {
- name: "Autodesk Manifest Poll",
- retry: {
- limit: 5,
- maxTimeoutInMs: 1000 * 15,
- },
- }
- );
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs.server/autodesk-upload.server.ts b/apps/carbon/app/jobs.server/autodesk-upload.server.ts
deleted file mode 100644
index b8fef39f9e..0000000000
--- a/apps/carbon/app/jobs.server/autodesk-upload.server.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { eventTrigger } from "@trigger.dev/sdk";
-import { z } from "zod";
-import {
- finalizeAutodeskUpload,
- getAutodeskSignedUrl,
- getAutodeskToken,
- translateFile,
- uploadToAutodesk,
-} from "~/lib/autodesk/autodesk.server";
-
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-
-const supabaseClient = getSupabaseServiceRole();
-
-const job = triggerClient.defineJob({
- id: "autodesk-upload",
- name: "Upload CAD Model to Autodesk",
- version: "0.0.1",
- trigger: eventTrigger({
- name: "autodesk.upload",
- schema: z.object({
- name: z.string(),
- modelPath: z.string(),
- fileId: z.string(),
- companyId: z.string(),
- itemId: z.union([z.string(), z.null()]),
- salesRfqLineId: z.union([z.string(), z.null()]),
- quoteLineId: z.union([z.string(), z.null()]),
- }),
- }),
- run: async (payload, io, ctx) => {
- const {
- companyId,
- modelPath,
- fileId,
- name,
- itemId,
- salesRfqLineId,
- quoteLineId,
- } = payload;
-
- try {
- const autodeskToken = await getAutodeskToken();
- if (autodeskToken.error) {
- throw new Error(
- "Failed to get Autodesk token: " + autodeskToken.error.message
- );
- }
- const token = autodeskToken.data?.token;
- const encodedFilename = modelPath.split("/").pop() as string;
-
- const [signedUrl, blob] = await Promise.all([
- getAutodeskSignedUrl(encodedFilename, token),
- supabaseClient.storage.from("private").download(modelPath),
- ]);
- if (signedUrl.error) {
- throw new Error("Failed to get signed URL: " + signedUrl.error.message);
- }
- if (blob.error) {
- throw new Error("Failed to download blob: " + blob.error.message);
- }
-
- const file = new File([blob.data], encodedFilename);
- const { uploadKey, url } = signedUrl.data;
-
- const initialUpload = await uploadToAutodesk(url, file, uploadKey);
- if (initialUpload.error) {
- throw new Error(
- "Failed to upload file: " + initialUpload.error.message
- );
- }
-
- const upload = await finalizeAutodeskUpload(
- encodedFilename,
- token,
- uploadKey
- );
- if (upload.error) {
- throw new Error("Failed to finalize upload: " + upload.error.message);
- }
-
- const { urn } = upload.data;
- const autodeskUrn = Buffer.from(urn).toString("base64");
-
- const translation = await translateFile(autodeskUrn, token);
- if (translation.error) {
- throw new Error(
- "Failed to translate file: " + translation.error.message
- );
- }
-
- const event = await triggerClient.sendEvent({
- name: "autodesk.poll",
- payload: {
- id: fileId,
- size: file.size,
- name,
- autodeskUrn,
- companyId,
- },
- });
-
- io.logger.info("Event sent", event);
- } catch (err) {
- const client = getSupabaseServiceRole();
- if (itemId) {
- await client
- .from("item")
- .update({ modelUploadId: null })
- .eq("id", itemId);
- }
- if (salesRfqLineId) {
- await client
- .from("salesRfqLine")
- .update({ modelUploadId: null })
- .eq("id", salesRfqLineId);
- }
- if (quoteLineId) {
- await client
- .from("quoteLine")
- .update({ modelUploadId: null })
- .eq("id", quoteLineId);
- }
- io.logger.error("Error uploading to Autodesk");
- }
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs.server/index.ts b/apps/carbon/app/jobs.server/index.ts
deleted file mode 100644
index a6ccfbf58a..0000000000
--- a/apps/carbon/app/jobs.server/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import autodeskPoll from "./autodesk-poll.server";
-import autodeskUpload from "./autodesk-upload.server";
-import postTransaction from "./post-transaction.server";
-import sendEmailResend from "./send-email-resend.server";
-import updateExchangeRates from "./update-exchange-rates.server";
-import updatePermissions from "./update-permissions.server";
-import userAdminServer from "./user-admin.server";
-
-export {
- autodeskPoll,
- autodeskUpload,
- postTransaction,
- sendEmailResend,
- updateExchangeRates,
- updatePermissions,
- userAdminServer,
-};
diff --git a/apps/carbon/app/jobs.server/post-transaction.server.ts b/apps/carbon/app/jobs.server/post-transaction.server.ts
deleted file mode 100644
index 8aecf77b7a..0000000000
--- a/apps/carbon/app/jobs.server/post-transaction.server.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { eventTrigger } from "@trigger.dev/sdk";
-import { z } from "zod";
-
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-import type { Result } from "~/types";
-
-const supabaseClient = getSupabaseServiceRole();
-export const postTransactionSchema = z.object({
- documentId: z.string(),
- type: z.enum(["receipt", "purchase-invoice"]),
-});
-
-const job = triggerClient.defineJob({
- id: "post-transactions",
- name: "Post Transactions",
- version: "0.0.1",
- trigger: eventTrigger({
- name: "post.transactions",
- schema: postTransactionSchema,
- }),
- run: async (payload, io, ctx) => {
- await io.logger.info(
- `🔰 User admin update ${payload.type} for ${payload.documentId}`
- );
-
- let result: Result;
-
- switch (payload.type) {
- case "receipt":
- await io.logger.info(`📫 Posting receipt ${payload.documentId}`);
- const postReceipt = await supabaseClient.functions.invoke(
- "post-receipt",
- {
- body: {
- receiptId: payload.documentId,
- },
- }
- );
-
- result = {
- success: postReceipt.error === null ? true : false,
- message: postReceipt.error?.message,
- };
-
- break;
- case "purchase-invoice":
- await io.logger.info(
- `📫 Posting purchase invoice ${payload.documentId}`
- );
- const postPurchaseInvoice = await supabaseClient.functions.invoke(
- "post-purchase-invoice",
- {
- body: {
- invoiceId: payload.documentId,
- },
- }
- );
-
- result = {
- success: postPurchaseInvoice.error === null ? true : false,
- message: postPurchaseInvoice.error?.message,
- };
-
- if (result.success) {
- await io.logger.info(
- `💵 Updating pricing from invoice ${payload.documentId}`
- );
- const priceUpdate = await supabaseClient.functions.invoke(
- "update-purchased-prices",
- {
- body: {
- invoiceId: payload.documentId,
- },
- }
- );
-
- result = {
- success: priceUpdate.error === null ? true : false,
- message: priceUpdate.error?.message,
- };
- }
-
- break;
- default:
- result = {
- success: false,
- message: `Invalid posting type: ${payload.type}`,
- };
- break;
- }
-
- if (result.success) {
- await io.logger.info(`✅ Success ${payload.documentId}`);
- } else {
- await io.logger.error(
- `❌ Admin action ${payload.type} failed for ${payload.documentId}: ${result.message}`
- );
- }
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs.server/send-email-resend.server.ts b/apps/carbon/app/jobs.server/send-email-resend.server.ts
deleted file mode 100644
index 4b7e3e61b7..0000000000
--- a/apps/carbon/app/jobs.server/send-email-resend.server.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { eventTrigger } from "@trigger.dev/sdk";
-import { nanoid } from "nanoid";
-import { Resend } from "resend";
-import { z } from "zod";
-
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-import { resendFormValidator } from "~/modules/settings";
-
-const supabaseClient = getSupabaseServiceRole();
-
-const job = triggerClient.defineJob({
- id: "send-email-resend",
- name: "Send Email with Resend",
- version: "0.0.1",
- trigger: eventTrigger({
- name: "resend.email",
- schema: z.object({
- to: z.union([z.string(), z.array(z.string())]),
- cc: z.union([z.string(), z.array(z.string())]).optional(),
- from: z.string().optional(),
- subject: z.string(),
- text: z.string(),
- html: z.string(),
- attachments: z
- .object({
- filename: z.string(),
- content: z.any(),
- })
- .array()
- .optional(),
- companyId: z.string(),
- }),
- }),
- run: async (payload, io, ctx) => {
- const integration = await supabaseClient
- .from("companyIntegration")
- .select("active, metadata")
- .eq("companyId", payload.companyId)
- .eq("id", "resend")
- .maybeSingle();
-
- // TODO: integration should include from email
- const integrationMetadata = resendFormValidator.safeParse(
- integration?.data?.metadata
- );
-
- if (!integrationMetadata.success || integration?.data?.active !== true)
- return;
-
- const resend = new Resend(integrationMetadata.data.apiKey);
-
- const email = {
- to: payload.to,
- reply_to: payload.from,
- subject: payload.subject,
- html: payload.html,
- text: payload.text,
- attachments: payload.attachments,
- headers: {
- "X-Entity-Ref-ID": nanoid(7),
- },
- };
-
- await io.logger.info(`📬 Resend Email Job`);
- await resend.emails.send(email);
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs.server/update-exchange-rates.server.ts b/apps/carbon/app/jobs.server/update-exchange-rates.server.ts
deleted file mode 100644
index fce5e7d10d..0000000000
--- a/apps/carbon/app/jobs.server/update-exchange-rates.server.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { intervalTrigger } from "@trigger.dev/sdk";
-import type { ExchangeRatesClient, Rates } from "~/lib/exchange-rates.server";
-import { getExchangeRatesClient } from "~/lib/exchange-rates.server";
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-import type { CurrencyCode } from "~/modules/accounting";
-import { exchangeRatesFormValidator } from "~/modules/settings";
-
-const supabaseClient = getSupabaseServiceRole();
-
-const job = triggerClient.defineJob({
- id: "update-exchange-rates",
- name: "Update Currency Exchange Rates",
- version: "0.0.1",
- trigger: intervalTrigger({
- seconds: 60 * 60 * 8, // thrice a day
- }),
- run: async (payload, io, ctx) => {
- let rates: Rates;
- let hasRates = false;
- let exchangeRatesClient: ExchangeRatesClient | undefined;
-
- const integrations = await supabaseClient
- .from("companyIntegration")
- .select("active, metadata, companyId")
- .eq("id", "exchange-rates-v1");
-
- if (integrations.error) {
- io.logger.error(JSON.stringify(integrations.error));
- return;
- }
-
- await io.logger.info(`💵 Exchange Rates Job: ${payload.lastTimestamp}`);
- for await (const integration of integrations.data) {
- const integrationMetadata = exchangeRatesFormValidator.safeParse(
- integration?.metadata
- );
-
- if (!integrationMetadata.success || integration?.active !== true) return;
-
- try {
- if (!hasRates) {
- exchangeRatesClient = getExchangeRatesClient(
- integrationMetadata.data.apiKey
- );
-
- if (!exchangeRatesClient) return;
- await io.logger.info(
- JSON.stringify(exchangeRatesClient.getMetaData())
- );
- rates = await exchangeRatesClient.getExchangeRates();
- await io.logger.info(JSON.stringify(rates));
- hasRates = true;
- }
- // @ts-expect-error
- if (!rates) throw new Error("No rates found");
-
- const updatedAt = new Date().toISOString();
-
- const { data } = await supabaseClient
- .from("currency")
- .select("*")
- .eq("companyId", integration.companyId);
- if (!data) return;
-
- const updates = data
- // eslint-disable-next-line no-loop-func
- .map((currency) => ({
- ...currency,
- exchangeRate: Number(
- rates[currency.code as CurrencyCode]?.toFixed(
- currency.decimalPlaces
- )
- ),
- updatedAt,
- }))
- .filter((currency) => currency.exchangeRate);
-
- if (updates?.length === 0) return;
-
- const { error } = await supabaseClient.from("currency").upsert(updates);
- if (error) {
- await io.logger.error(JSON.stringify(error));
- return;
- }
- } catch (err) {
- // TODO: notify someone
- await io.logger.error(JSON.stringify(err));
- }
- }
- io.logger.log("Success");
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs.server/update-permissions.server.ts b/apps/carbon/app/jobs.server/update-permissions.server.ts
deleted file mode 100644
index c76bd1c288..0000000000
--- a/apps/carbon/app/jobs.server/update-permissions.server.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { eventTrigger } from "@trigger.dev/sdk";
-import { z } from "zod";
-
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-import { updatePermissions } from "~/modules/users/users.server";
-
-const supabaseClient = getSupabaseServiceRole();
-export const permissionsUpdateSchema = z.object({
- id: z.string(),
- addOnly: z.boolean(),
- permissions: z.record(
- z.string(),
- z.object({
- view: z.boolean(),
- create: z.boolean(),
- update: z.boolean(),
- delete: z.boolean(),
- })
- ),
- companyId: z.string(),
-});
-
-const job = triggerClient.defineJob({
- id: "update-permissions",
- name: "Update Permissions",
- version: "0.0.1",
- trigger: eventTrigger({
- name: "update.permissions",
- schema: permissionsUpdateSchema,
- }),
- run: async (payload, io, ctx) => {
- await io.logger.info(`🔰 Permission Update for ${payload.id}`);
- const { success, message } = await updatePermissions(
- supabaseClient,
- payload
- );
- if (success) {
- await io.logger.info(`✅ Permission Update for ${payload.id}`);
- } else {
- await io.logger.error(
- `❌ Permission Update for ${payload.id}: ${message}`
- );
- }
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs.server/user-admin.server.ts b/apps/carbon/app/jobs.server/user-admin.server.ts
deleted file mode 100644
index 19c30e23da..0000000000
--- a/apps/carbon/app/jobs.server/user-admin.server.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { eventTrigger } from "@trigger.dev/sdk";
-import { z } from "zod";
-
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { triggerClient } from "~/lib/trigger.server";
-import { deactivateUser, resendInvite } from "~/modules/users/users.server";
-import type { Result } from "~/types";
-
-const supabaseClient = getSupabaseServiceRole();
-export const userAdminSchema = z.object({
- id: z.string(),
- type: z.enum(["resend", "deactivate"]),
-});
-
-const job = triggerClient.defineJob({
- id: "user-admin",
- name: "User Admin",
- version: "0.0.1",
- trigger: eventTrigger({
- name: "user.admin",
- schema: userAdminSchema,
- }),
- run: async (payload, io, ctx) => {
- await io.logger.info(
- `🔰 User admin update ${payload.type} for ${payload.id}`
- );
-
- let result: Result;
-
- switch (payload.type) {
- case "resend":
- await io.logger.info(`📫 Resending invite for ${payload.id}`);
- result = await resendInvite(supabaseClient, payload.id);
-
- break;
- case "deactivate":
- await io.logger.info(`🚭 Deactivating ${payload.id}`);
- result = await deactivateUser(supabaseClient, payload.id);
- break;
- default:
- result = {
- success: false,
- message: `Invalid user admin type: ${payload.type}`,
- };
- break;
- }
-
- if (result.success) {
- await io.logger.info(`✅ Success ${payload.id}`);
- } else {
- await io.logger.error(
- `❌ Admin action ${payload.type} failed for ${payload.id}: ${result.message}`
- );
- }
- },
-});
-
-export default job;
diff --git a/apps/carbon/app/jobs/send-email-resend.server.ts b/apps/carbon/app/jobs/send-email-resend.server.ts
index 4b7e3e61b7..15ba902322 100644
--- a/apps/carbon/app/jobs/send-email-resend.server.ts
+++ b/apps/carbon/app/jobs/send-email-resend.server.ts
@@ -33,25 +33,35 @@ const job = triggerClient.defineJob({
}),
}),
run: async (payload, io, ctx) => {
- const integration = await supabaseClient
- .from("companyIntegration")
- .select("active, metadata")
- .eq("companyId", payload.companyId)
- .eq("id", "resend")
- .maybeSingle();
+ const [company, integration] = await Promise.all([
+ supabaseClient
+ .from("company")
+ .select("name")
+ .eq("id", payload.companyId)
+ .single(),
+ supabaseClient
+ .from("companyIntegration")
+ .select("active, metadata")
+ .eq("companyId", payload.companyId)
+ .eq("id", "resend")
+ .maybeSingle(),
+ ]);
- // TODO: integration should include from email
const integrationMetadata = resendFormValidator.safeParse(
integration?.data?.metadata
);
+ io.logger.info(integrationMetadata.data?.fromEmail ?? "no email found");
+
if (!integrationMetadata.success || integration?.data?.active !== true)
return;
const resend = new Resend(integrationMetadata.data.apiKey);
const email = {
+ from: `${company.data?.name} <${
+ integrationMetadata.data.fromEmail ?? "[email protected]"
+ }>`,
to: payload.to,
reply_to: payload.from,
subject: payload.subject,
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index da8c21e641..a1a970f55c 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -263,16 +263,7 @@ export const quoteOperationValidator = z.object({
overheadRate: zfd.numeric(z.number().min(0)),
});
-export const quotationPricingValidator = z.object({
- quantity: zfd.numeric(z.number()),
- unitCost: zfd.numeric(z.number()),
- leadTime: zfd.numeric(z.number().int().nonnegative()),
- discountPercent: zfd.numeric(z.number().nonnegative()),
- markupPercent: zfd.numeric(z.number().nonnegative()),
- extendedPrice: zfd.numeric(z.number()),
-});
-
-export const quotationReleaseValidator = z
+export const quoteFinalizeValidator = z
.object({
notification: z.enum(["Email", "None"]).optional(),
customerContact: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 494a818a57..b56abc78eb 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -15,11 +15,11 @@ import type {
customerTypeValidator,
customerValidator,
getMethodValidator,
- quotationPricingValidator,
quoteLineAdditionalChargesValidator,
quoteLineValidator,
quoteMaterialValidator,
quoteOperationValidator,
+ quoteStatusType,
quoteValidator,
salesOrderLineValidator,
salesOrderPaymentValidator,
@@ -1323,6 +1323,18 @@ export async function updateQuoteOperationOrder(
return Promise.all(updatePromises);
}
+export async function updateQuoteStatus(
+ client: SupabaseClient<Database>,
+ update: {
+ id: string;
+ status: (typeof quoteStatusType)[number];
+ assignee: null | undefined;
+ updatedBy: string;
+ }
+) {
+ return client.from("quote").update(update).eq("id", update.id);
+}
+
export async function upsertMakeMethodFromQuoteLine(
client: SupabaseClient<Database>,
lineMethod: {
@@ -1397,7 +1409,20 @@ export async function upsertQuote(
})
) {
if ("createdBy" in quote) {
- return client.from("quote").insert([quote]).select("id, quoteId");
+ const insert = await client
+ .from("quote")
+ .insert([quote])
+ .select("id, quoteId");
+ if (insert.error) {
+ return insert;
+ }
+ const opportunity = await client
+ .from("opportunity")
+ .insert([{ quoteId: insert.data[0].id, companyId: quote.companyId }]);
+ if (opportunity.error) {
+ return opportunity;
+ }
+ return insert;
} else {
return client
.from("quote")
@@ -1497,20 +1522,6 @@ export async function upsertQuoteLinePrices(
.insert(pricesWithExistingDiscountsAndLeadTimes);
}
-export async function updateQuoteLinePrice(
- client: SupabaseClient<Database>,
- quoteLinePrice: z.infer<typeof quotationPricingValidator> & {
- quoteId: string;
- quoteLineId: string;
- updatedBy: string;
- }
-) {
- return client
- .from("quoteLinePrice")
- .update(sanitize(quoteLinePrice))
- .eq("quoteLineId", quoteLinePrice.quoteLineId);
-}
-
export async function upsertQuoteLineMethod(
client: SupabaseClient<Database>,
lineMethod: {
@@ -1849,7 +1860,20 @@ export async function upsertSalesRFQ(
})
) {
if ("createdBy" in rfq) {
- return client.from("salesRfq").insert([rfq]).select("id, rfqId");
+ const insert = await client
+ .from("salesRfq")
+ .insert([rfq])
+ .select("id, rfqId");
+ if (insert.error) {
+ return insert;
+ }
+ const opportunity = await client
+ .from("opportunity")
+ .insert([{ salesRfqId: insert.data[0].id, companyId: rfq.companyId }]);
+ if (opportunity.error) {
+ return opportunity;
+ }
+ return insert;
} else {
return client
.from("salesRfq")
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
new file mode 100644
index 0000000000..61b50bbb08
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
@@ -0,0 +1,108 @@
+import {
+ Button,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ VStack,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
+import { CustomerContact, SelectControlled } from "~/components/Form";
+import { useIntegrations } from "~/hooks/useIntegrations";
+import { path } from "~/utils/path";
+import { quoteFinalizeValidator } from "../../sales.models";
+import type { Quotation } from "../../types";
+
+type QuotationReleaseModalProps = {
+ onClose: () => void;
+ quote?: Quotation;
+};
+
+const QuotationReleaseModal = ({
+ quote,
+ onClose,
+}: QuotationReleaseModalProps) => {
+ const { quoteId } = useParams();
+ if (!quoteId) throw new Error("quoteId not found");
+
+ const integrations = useIntegrations();
+ const canEmail = integrations.has("resend");
+
+ const [notificationType, setNotificationType] = useState(
+ canEmail ? "Email" : "Download"
+ );
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ validator={quoteFinalizeValidator}
+ action={path.to.quoteFinalize(quoteId)}
+ onSubmit={onClose}
+ defaultValues={{
+ notification: notificationType as "Email" | "None",
+ customerContact: quote?.customerContactId ?? undefined,
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>{`Release ${quote?.quoteId}`}</ModalTitle>
+ <ModalDescription>
+ Are you sure you want to finalize the quote?
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ {canEmail && (
+ <SelectControlled
+ label="Send Via"
+ name="notification"
+ options={[
+ {
+ label: "None",
+ value: "None",
+ },
+ {
+ label: "Email",
+ value: "Email",
+ },
+ ]}
+ value={notificationType}
+ onChange={(t) => {
+ if (t) setNotificationType(t.value);
+ }}
+ />
+ )}
+ {notificationType === "Email" && (
+ <CustomerContact
+ name="customerContact"
+ customer={quote?.customerId ?? undefined}
+ />
+ )}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit">Release</Button>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default QuotationReleaseModal;
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 1fbb4686c8..f88a659751 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -21,11 +21,10 @@ import {
Hidden,
Input,
Location,
- Select,
Submit,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import { quoteStatusType, quoteValidator } from "~/modules/sales";
+import { quoteValidator } from "~/modules/sales";
type QuoteFormValues = z.infer<typeof quoteValidator>;
@@ -41,11 +40,6 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
const isEditing = initialValues.id !== undefined;
const isCustomer = permissions.is("customer");
- const statusOptions = quoteStatusType.map((status) => ({
- label: status,
- value: status,
- }));
-
return (
<Card>
<ValidatedForm
@@ -103,15 +97,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
label="Expiration Date"
isDisabled={isCustomer}
/>
- {isEditing && permissions.can("delete", "sales") && (
- <Select
- name="status"
- label="Status"
- value={initialValues.status}
- options={statusOptions}
- isReadOnly={isCustomer}
- />
- )}
+
<CustomFormFields table="quote" />
</div>
</VStack>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index 0b513af866..2c9c76cba9 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -1,20 +1,33 @@
-import { Badge, Button, HStack, Heading } from "@carbon/react";
+import { Badge, Button, HStack, Heading, useDisclosure } from "@carbon/react";
-import { useParams } from "@remix-run/react";
-import { LuCheckCheck, LuEye } from "react-icons/lu";
+import { Form, Link, useParams } from "@remix-run/react";
+import {
+ LuCheckCheck,
+ LuEye,
+ LuRefreshCw,
+ LuSend,
+ LuTrophy,
+ LuXCircle,
+} from "react-icons/lu";
import { RiProgress4Line } from "react-icons/ri";
import { Assignee, useOptimisticAssignment } from "~/components";
import { usePermissions, useRouteData } from "~/hooks";
-import type { Quotation } from "~/modules/sales";
+import type { Quotation, QuotationLine } from "~/modules/sales";
import { path } from "~/utils/path";
+import QuoteFinalizeModal from "./QuoteFinalizeModal";
+import QuoteStatus from "./QuoteStatus";
const QuoteHeader = () => {
const permissions = usePermissions();
const { quoteId } = useParams();
if (!quoteId) throw new Error("quoteId not found");
- const routeData = useRouteData<{ quote: Quotation }>(path.to.quote(quoteId));
+ const routeData = useRouteData<{ quote: Quotation; lines: QuotationLine[] }>(
+ path.to.quote(quoteId)
+ );
+
+ const finalizeModal = useDisclosure();
const optimisticAssignment = useOptimisticAssignment({
id: quoteId,
@@ -26,54 +39,134 @@ const QuoteHeader = () => {
: routeData?.quote?.assignee;
return (
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
- <HStack className="w-full justify-between">
- <HStack>
- <Heading size="h2">{routeData?.quote?.quoteId}</Heading>
- <Badge variant="secondary">
+ <>
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
+ <HStack className="w-full justify-between">
+ <HStack>
+ <Heading size="h2">{routeData?.quote?.quoteId}</Heading>
<Badge variant="secondary">
- <RiProgress4Line />
+ <Badge variant="secondary">
+ <RiProgress4Line />
+ </Badge>
</Badge>
- </Badge>
- </HStack>
- <HStack>
- <Assignee
- id={quoteId}
- table="quote"
- value={assignee ?? ""}
- className="h-8"
- isReadOnly={!permissions.can("update", "sales")}
- />
- <Button leftIcon={<LuEye />} variant="secondary" asChild>
- <a
- target="_blank"
- href={path.to.file.quote(quoteId)}
- rel="noreferrer"
- >
- Preview
- </a>
- </Button>
- {/* <DropdownMenu>
- <DropdownMenuTrigger>
- <Button rightIcon={<LuChevronDown />} variant="secondary">
- Actions
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem>Download</DropdownMenuItem>
- <DropdownMenuItem>Print</DropdownMenuItem>
- <DropdownMenuItem>Export</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu> */}
- <Button
- isDisabled={!permissions.can("update", "sales")}
- leftIcon={<LuCheckCheck />}
- >
- Send
- </Button>
+ <QuoteStatus status={routeData?.quote?.status} />
+ </HStack>
+ <HStack>
+ <Assignee
+ id={quoteId}
+ table="quote"
+ value={assignee ?? ""}
+ className="h-8"
+ isReadOnly={!permissions.can("update", "sales")}
+ />
+ <Button leftIcon={<LuEye />} variant="secondary" asChild>
+ <a
+ target="_blank"
+ href={path.to.file.quote(quoteId)}
+ rel="noreferrer"
+ >
+ Preview
+ </a>
+ </Button>
+ {routeData?.quote?.status === "Draft" && (
+ <>
+ <Form method="post" action={path.to.quoteStatus(quoteId)}>
+ <input type="hidden" name="status" value="Cancelled" />
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuXCircle />}
+ type="submit"
+ variant="destructive"
+ >
+ Cancel
+ </Button>
+ </Form>
+ <Button
+ onClick={finalizeModal.onOpen}
+ isDisabled={
+ !permissions.can("update", "sales") ||
+ !routeData?.lines?.length
+ }
+ leftIcon={<LuCheckCheck />}
+ >
+ Finalize
+ </Button>
+ </>
+ )}
+ {routeData?.quote?.status === "Sent" && (
+ <>
+ <Form method="post" action={path.to.quoteStatus(quoteId)}>
+ <input type="hidden" name="status" value="Draft" />
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuRefreshCw />}
+ type="submit"
+ variant="secondary"
+ >
+ Reopen
+ </Button>
+ </Form>
+ <Form method="post" action={path.to.quoteStatus(quoteId)}>
+ <input type="hidden" name="status" value="Lost" />
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuXCircle />}
+ type="submit"
+ variant="destructive"
+ >
+ Lost
+ </Button>
+ </Form>
+ <Button leftIcon={<LuTrophy />} variant="primary">
+ Won
+ </Button>
+ </>
+ )}
+ {["Cancelled", "Expired"].includes(
+ routeData?.quote?.status ?? ""
+ ) && (
+ <>
+ <Form method="post" action={path.to.quoteStatus(quoteId)}>
+ <input type="hidden" name="status" value="Draft" />
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuRefreshCw />}
+ type="submit"
+ variant="secondary"
+ >
+ Reopen
+ </Button>
+ </Form>
+ </>
+ )}
+ {["Ordered", "Partial"].includes(routeData?.quote?.status ?? "") &&
+ routeData?.quote?.salesOrderId && (
+ <Button
+ isDisabled={!routeData?.quote.salesOrderId}
+ leftIcon={<LuSend />}
+ variant="primary"
+ asChild
+ >
+ <Link
+ to={path.to.salesOrderDetails(
+ routeData?.quote.salesOrderId!
+ )}
+ prefetch="intent"
+ >
+ View Order
+ </Link>
+ </Button>
+ )}
+ </HStack>
</HStack>
- </HStack>
- </div>
+ </div>
+ {finalizeModal.isOpen && (
+ <QuoteFinalizeModal
+ quote={routeData?.quote}
+ onClose={finalizeModal.onClose}
+ />
+ )}
+ </>
);
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index 1361cad874..692bae3894 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -176,7 +176,8 @@ const QuoteLineForm = ({
if (customerPart.data && !itemData.customerPartId) {
newItemData.customerPartId = customerPart.data.customerPartId;
- newItemData.customerPartRevision = customerPart.data.customerPartRevision;
+ newItemData.customerPartRevision =
+ customerPart.data.customerPartRevision ?? "";
}
setItemData(newItemData);
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
index bd3c014277..80ae245122 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
@@ -20,11 +20,10 @@ import {
Hidden,
Input,
Location,
- Select,
Submit,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import { salesRFQStatusType, salesRfqValidator } from "~/modules/sales";
+import { salesRfqValidator } from "~/modules/sales";
type SalesRFQFormValues = z.infer<typeof salesRfqValidator>;
@@ -41,11 +40,6 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
const isCustomer = permissions.is("customer");
const isDraft = initialValues.status === "Draft";
- const statusOptions = salesRFQStatusType.map((status) => ({
- label: status,
- value: status,
- }));
-
return (
<Card>
<ValidatedForm
@@ -90,15 +84,6 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
label="Customer Contact"
customer={customer}
/>
- {isEditing && permissions.can("delete", "sales") && (
- <Select
- name="status"
- label="Status"
- value={initialValues.status}
- options={statusOptions}
- isReadOnly={isCustomer}
- />
- )}
<DatePicker
name="rfqDate"
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
index bc366d2384..aaa925394c 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
@@ -29,6 +29,7 @@ import { Assignee, useOptimisticAssignment } from "~/components";
import { usePermissions, useRouteData } from "~/hooks";
import type { SalesRFQ, SalesRFQLine } from "~/modules/sales";
import { path } from "~/utils/path";
+import SalesRFQStatus from "./SalesRFQStatus";
const SalesRFQHeader = () => {
const { rfqId } = useParams();
@@ -61,6 +62,7 @@ const SalesRFQHeader = () => {
<Badge variant="secondary">
<RiProgress2Line />
</Badge>
+ <SalesRFQStatus status={routeData?.rfqSummary?.status} />
</HStack>
<HStack>
<Assignee
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
index 67ad8a25bf..d932499ea4 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
@@ -164,7 +164,8 @@ const SalesRFQLineForm = ({
if (customerPart.data && !itemData.customerPartId) {
newItemData.customerPartId = customerPart.data.customerPartId;
- newItemData.customerPartRevision = customerPart.data.customerPartRevision;
+ newItemData.customerPartRevision =
+ customerPart.data.customerPartRevision ?? "";
}
setItemData(newItemData);
diff --git a/apps/carbon/app/modules/settings/integrations.models.ts b/apps/carbon/app/modules/settings/integrations.models.ts
index 72e13865af..71013e7f88 100644
--- a/apps/carbon/app/modules/settings/integrations.models.ts
+++ b/apps/carbon/app/modules/settings/integrations.models.ts
@@ -35,15 +35,22 @@ export const googlePlacesFormValidator = integration.merge(apiKey).refine(
}
);
-export const resendFormValidator = integration.merge(apiKey).refine(
- (data) => {
- if (data.active) {
- return data.apiKey.length > 0;
+export const resendFormValidator = integration
+ .merge(apiKey)
+ .merge(
+ z.object({
+ fromEmail: zfd.text(z.string().email().optional()),
+ })
+ )
+ .refine(
+ (data) => {
+ if (data.active) {
+ return data.apiKey.length > 0;
+ }
+ return true;
+ },
+ {
+ message: "API key is required when integration is active",
+ path: ["apiKey"],
}
- return true;
- },
- {
- message: "API key is required when integration is active",
- path: ["apiKey"],
- }
-);
+ );
diff --git a/apps/carbon/app/modules/settings/ui/Integrations/ResendForm.tsx b/apps/carbon/app/modules/settings/ui/Integrations/ResendForm.tsx
index 558443c4a8..6d3363fc09 100644
--- a/apps/carbon/app/modules/settings/ui/Integrations/ResendForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Integrations/ResendForm.tsx
@@ -51,6 +51,11 @@ const ResendForm = ({ initialValues, onClose }: ResendFormProps) => {
<VStack spacing={4}>
<Boolean name="active" label="Active" />
<Input name="apiKey" label="API Key" />
+ <Input
+ name="fromEmail"
+ label="From Email"
+ placeholder="[email protected]"
+ />
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
new file mode 100644
index 0000000000..2ba64a6e92
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -0,0 +1,193 @@
+import { QuoteEmail } from "@carbon/documents";
+import { validationError, validator } from "@carbon/remix-validated-form";
+import { renderAsync } from "@react-email/components";
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { triggerClient } from "~/lib/trigger.server";
+import { upsertDocument } from "~/modules/documents";
+import {
+ getCustomer,
+ getCustomerContact,
+ getQuote,
+ quoteFinalizeValidator,
+ releaseQuote,
+} from "~/modules/sales";
+import { getCompany } from "~/modules/settings";
+import { getUser } from "~/modules/users/users.server";
+import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function action(args: ActionFunctionArgs) {
+ const { request, params } = args;
+ assertIsPost(request);
+
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ role: "employee",
+ });
+
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ let file: ArrayBuffer;
+ let fileName: string;
+
+ const quote = await getQuote(client, quoteId);
+ if (quote.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(quote.error, "Failed to get quote"))
+ );
+ }
+
+ try {
+ const pdf = await pdfLoader({ ...args, params: { id: quoteId } });
+ if (pdf.headers.get("content-type") !== "application/pdf")
+ throw new Error("Failed to generate PDF");
+
+ file = await pdf.arrayBuffer();
+ fileName = `${quote.data.quoteId} - ${new Date()
+ .toISOString()
+ .slice(0, -5)}.pdf`;
+
+ const documentFilePath = `${companyId}/quote/${quoteId}/${fileName}`;
+
+ const documentFileUpload = await client.storage
+ .from("private")
+ .upload(documentFilePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ contentType: "application/pdf",
+ upsert: true,
+ });
+
+ if (documentFileUpload.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(documentFileUpload.error, "Failed to upload file")
+ )
+ );
+ }
+
+ const createDocument = await upsertDocument(client, {
+ path: documentFilePath,
+ name: fileName,
+ size: Math.round(file.byteLength / 1024),
+ sourceDocument: "Quote",
+ sourceDocumentId: quoteId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ createdBy: userId,
+ companyId,
+ });
+
+ if (createDocument.error) {
+ return redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(createDocument.error, "Failed to create document")
+ )
+ );
+ }
+
+ const release = await releaseQuote(client, quoteId, userId);
+ if (release.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(release.error, "Failed to release quote"))
+ );
+ }
+ } catch (err) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(err, "Failed to release quote"))
+ );
+ }
+
+ const validation = await validator(quoteFinalizeValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { notification, customerContact: customerContactId } = validation.data;
+
+ switch (notification) {
+ case "Email":
+ try {
+ if (!customerContactId) throw new Error("Customer contact is required");
+
+ const [company, customer, customerContact, user] = await Promise.all([
+ getCompany(client, companyId),
+ getCustomer(client, quote.data.customerId!),
+ getCustomerContact(client, customerContactId),
+ getUser(client, userId),
+ ]);
+
+ if (!company.data) throw new Error("Failed to get company");
+ if (!customer.data) throw new Error("Failed to get customer");
+ if (!customerContact.data)
+ throw new Error("Failed to get customer contact");
+ if (!user.data) throw new Error("Failed to get user");
+
+ // TODO: Update sender email
+ const emailTemplate = QuoteEmail({
+ company: company.data,
+ // @ts-ignore
+ quote: quote.data,
+ recipient: {
+ email: customerContact.data?.contact!.email!,
+ firstName: customerContact.data.contact!.firstName!,
+ lastName: customerContact.data.contact!.lastName!,
+ },
+ sender: {
+ email: user.data.email,
+ firstName: user.data.firstName,
+ lastName: user.data.lastName,
+ },
+ });
+
+ await triggerClient.sendEvent({
+ name: "resend.email",
+ payload: {
+ to: customerContact.data.contact!.email!,
+ from: user.data.email,
+ subject: `Quote ${quote.data.quoteId}`,
+ html: await renderAsync(emailTemplate),
+ text: await renderAsync(emailTemplate, { plainText: true }),
+ attachments: [
+ {
+ content: Buffer.from(file),
+ filename: fileName,
+ },
+ ],
+ companyId,
+ },
+ });
+ } catch (err) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(err, "Failed to send email"))
+ );
+ }
+
+ break;
+ case undefined:
+ case "None":
+ break;
+ default:
+ throw new Error("Invalid notification type");
+ }
+
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, success("Quote finalized successfully"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
new file mode 100644
index 0000000000..23e27109b5
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
@@ -0,0 +1,46 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "remix-typedjson";
+import { quoteStatusType, updateQuoteStatus } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { quoteId: id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const status = formData.get("status") as (typeof quoteStatusType)[number];
+
+ if (!status || !quoteStatusType.includes(status)) {
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const update = await updateQuoteStatus(client, {
+ id,
+ status,
+ assignee: ["Draft", "Sent"].includes(status) ? null : undefined,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, error(update.error, "Failed to update RFQ status"))
+ );
+ }
+
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, success("Updated RFQ status"))
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 1d5dca180c..d1dc8dd019 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -592,7 +592,8 @@ export const path = {
quoteOperationsOrder: `${x}/quote/methods/operation/order`,
quoteLineRecalculatePrice: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/${quoteId}/${lineId}/recalculate-price`),
- quoteRelease: (id: string) => generatePath(`${x}/quote/${id}/release`),
+ quoteFinalize: (id: string) => generatePath(`${x}/quote/${id}/finalize`),
+ quoteStatus: (id: string) => generatePath(`${x}/quote/${id}/status`),
quotes: `${x}/sales/quotes`,
receipt: (id: string) => generatePath(`${x}/receipt/${id}`),
receiptInvoice: (id: string) => generatePath(`${x}/receipt/${id}/invoice`),
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 90f1602510..5d926d1515 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8985,6 +8985,108 @@ export type Database = {
},
]
}
+ opportunity: {
+ Row: {
+ companyId: string
+ id: string
+ quoteId: string | null
+ salesOrderId: string | null
+ salesRfqId: string | null
+ }
+ Insert: {
+ companyId: string
+ id?: string
+ quoteId?: string | null
+ salesOrderId?: string | null
+ salesRfqId?: string | null
+ }
+ Update: {
+ companyId?: string
+ id?: string
+ quoteId?: string | null
+ salesOrderId?: string | null
+ salesRfqId?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfq"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqs"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
part: {
Row: {
approved: boolean
@@ -12490,7 +12592,6 @@ export type Database = {
quoteId: string
revisionId: number
salesPersonId: string | null
- salesRfqId: string | null
status: Database["public"]["Enums"]["quoteStatus"]
updatedAt: string | null
updatedBy: string | null
@@ -12514,7 +12615,6 @@ export type Database = {
quoteId: string
revisionId?: number
salesPersonId?: string | null
- salesRfqId?: string | null
status?: Database["public"]["Enums"]["quoteStatus"]
updatedAt?: string | null
updatedBy?: string | null
@@ -12538,7 +12638,6 @@ export type Database = {
quoteId?: string
revisionId?: number
salesPersonId?: string | null
- salesRfqId?: string | null
status?: Database["public"]["Enums"]["quoteStatus"]
updatedAt?: string | null
updatedBy?: string | null
@@ -12775,20 +12874,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfq"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfqs"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "quote_updatedBy_fkey"
columns: ["updatedBy"]
@@ -16121,88 +16206,6 @@ export type Database = {
},
]
}
- salesRfqToQuote: {
- Row: {
- companyId: string
- quoteId: string
- salesRfqId: string
- }
- Insert: {
- companyId: string
- quoteId: string
- salesRfqId: string
- }
- Update: {
- companyId?: string
- quoteId?: string
- salesRfqId?: string
- }
- Relationships: [
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quoteCustomerDetails"
- referencedColumns: ["quoteId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfq"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfqs"
- referencedColumns: ["id"]
- },
- ]
- }
search: {
Row: {
companyId: string | null
@@ -23713,6 +23716,7 @@ export type Database = {
notes: Json | null
quoteId: string | null
revisionId: number | null
+ salesOrderId: string | null
salesPersonId: string | null
salesRfqId: string | null
status: Database["public"]["Enums"]["quoteStatus"] | null
@@ -23720,6 +23724,34 @@ export type Database = {
updatedBy: string | null
}
Relationships: [
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfq"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqs"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quote_assignee_fkey"
columns: ["assignee"]
@@ -23951,20 +23983,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfq"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfqs"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "quote_updatedBy_fkey"
columns: ["updatedBy"]
@@ -24889,11 +24907,47 @@ export type Database = {
revisionId: number | null
rfqDate: string | null
rfqId: string | null
+ salesOrderId: string | null
status: Database["public"]["Enums"]["salesRfqStatus"] | null
updatedAt: string | null
updatedBy: string | null
}
Relationships: [
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfq_assigneeId_fkey"
columns: ["assignee"]
@@ -25125,27 +25179,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quoteCustomerDetails"
- referencedColumns: ["quoteId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quotes"
- referencedColumns: ["id"]
- },
]
}
services: {
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 052e0ebb82..dbdd4cf256 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -129,14 +129,11 @@ serve(async (req: Request) => {
.execute();
await trx
- .insertInto("salesRfqToQuote")
- .values([
- {
- salesRfqId: id,
- quoteId: quote.id!,
- companyId,
- },
- ])
+ .updateTable("opportunity")
+ .set({
+ quoteId: quote.id!,
+ })
+ .where("salesRfqId", "=", id)
.execute();
const customerPartToItemInserts = validLines
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 90f1602510..5d926d1515 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -8985,6 +8985,108 @@ export type Database = {
},
]
}
+ opportunity: {
+ Row: {
+ companyId: string
+ id: string
+ quoteId: string | null
+ salesOrderId: string | null
+ salesRfqId: string | null
+ }
+ Insert: {
+ companyId: string
+ id?: string
+ quoteId?: string | null
+ salesOrderId?: string | null
+ salesRfqId?: string | null
+ }
+ Update: {
+ companyId?: string
+ id?: string
+ quoteId?: string | null
+ salesOrderId?: string | null
+ salesRfqId?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "opportunity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfq"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqs"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
part: {
Row: {
approved: boolean
@@ -12490,7 +12592,6 @@ export type Database = {
quoteId: string
revisionId: number
salesPersonId: string | null
- salesRfqId: string | null
status: Database["public"]["Enums"]["quoteStatus"]
updatedAt: string | null
updatedBy: string | null
@@ -12514,7 +12615,6 @@ export type Database = {
quoteId: string
revisionId?: number
salesPersonId?: string | null
- salesRfqId?: string | null
status?: Database["public"]["Enums"]["quoteStatus"]
updatedAt?: string | null
updatedBy?: string | null
@@ -12538,7 +12638,6 @@ export type Database = {
quoteId?: string
revisionId?: number
salesPersonId?: string | null
- salesRfqId?: string | null
status?: Database["public"]["Enums"]["quoteStatus"]
updatedAt?: string | null
updatedBy?: string | null
@@ -12775,20 +12874,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfq"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfqs"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "quote_updatedBy_fkey"
columns: ["updatedBy"]
@@ -16121,88 +16206,6 @@ export type Database = {
},
]
}
- salesRfqToQuote: {
- Row: {
- companyId: string
- quoteId: string
- salesRfqId: string
- }
- Insert: {
- companyId: string
- quoteId: string
- salesRfqId: string
- }
- Update: {
- companyId?: string
- quoteId?: string
- salesRfqId?: string
- }
- Relationships: [
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quoteCustomerDetails"
- referencedColumns: ["quoteId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfq"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfqs"
- referencedColumns: ["id"]
- },
- ]
- }
search: {
Row: {
companyId: string | null
@@ -23713,6 +23716,7 @@ export type Database = {
notes: Json | null
quoteId: string | null
revisionId: number | null
+ salesOrderId: string | null
salesPersonId: string | null
salesRfqId: string | null
status: Database["public"]["Enums"]["quoteStatus"] | null
@@ -23720,6 +23724,34 @@ export type Database = {
updatedBy: string | null
}
Relationships: [
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfq"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqs"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quote_assignee_fkey"
columns: ["assignee"]
@@ -23951,20 +23983,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfq"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_salesRfqId_fkey"
- columns: ["salesRfqId"]
- isOneToOne: false
- referencedRelation: "salesRfqs"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "quote_updatedBy_fkey"
columns: ["updatedBy"]
@@ -24889,11 +24907,47 @@ export type Database = {
revisionId: number | null
rfqDate: string | null
rfqId: string | null
+ salesOrderId: string | null
status: Database["public"]["Enums"]["salesRfqStatus"] | null
updatedAt: string | null
updatedBy: string | null
}
Relationships: [
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "opportunity_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_salesOrderId_fkey"
+ columns: ["salesOrderId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfq_assigneeId_fkey"
columns: ["assignee"]
@@ -25125,27 +25179,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quoteCustomerDetails"
- referencedColumns: ["quoteId"]
- },
- {
- foreignKeyName: "salesRfqToQuote_quoteId_fkey"
- columns: ["quoteId"]
- isOneToOne: false
- referencedRelation: "quotes"
- referencedColumns: ["id"]
- },
]
}
services: {
diff --git a/packages/database/supabase/migrations/20240815020752_opportunity.sql b/packages/database/supabase/migrations/20240815020752_opportunity.sql
new file mode 100644
index 0000000000..4a7f4057c5
--- /dev/null
+++ b/packages/database/supabase/migrations/20240815020752_opportunity.sql
@@ -0,0 +1,92 @@
+DROP VIEW "salesRfqs";
+DROP VIEW "quotes";
+DROP TABLE "salesRfqToQuote";
+
+COMMIT;
+
+ALTER TABLE "quote"
+ DROP CONSTRAINT "quote_salesRfqId_fkey",
+ DROP COLUMN "salesRfqId";
+
+CREATE TABLE "opportunity" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "salesRfqId" TEXT,
+ "quoteId" TEXT,
+ "salesOrderId" TEXT,
+ "companyId" TEXT NOT NULL,
+
+ PRIMARY KEY ("id"),
+ FOREIGN KEY ("salesRfqId") REFERENCES "salesRfq" ("id") ON DELETE SET NULL,
+ FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE SET NULL,
+ FOREIGN KEY ("salesOrderId") REFERENCES "salesOrder" ("id") ON DELETE SET NULL,
+ FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "opportunity_companyId_idx" ON "opportunity" ("companyId");
+CREATE INDEX "opportunity_salesRfqId_idx" ON "opportunity" ("salesRfqId");
+CREATE INDEX "opportunity_quoteId_idx" ON "opportunity" ("quoteId");
+
+ALTER TABLE "opportunity" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with sales_view can view opportunities" ON "opportunity" FOR SELECT USING (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_create can insert opportunities" ON "opportunity" FOR INSERT WITH CHECK (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_create can update opportunities" ON "opportunity" FOR UPDATE WITH CHECK (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE OR REPLACE VIEW "salesRfqs" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ rfq.*,
+ l."name" AS "locationName",
+ opp."quoteId",
+ opp."salesOrderId",
+ EXISTS(SELECT 1 FROM "salesRfqFavorite" rf WHERE rf."rfqId" = rfq.id AND rf."userId" = auth.uid()::text) AS favorite
+ FROM "salesRfq" rfq
+ LEFT JOIN "location" l
+ ON l.id = rfq."locationId"
+ LEFT JOIN "opportunity" opp
+ ON opp."salesRfqId" = rfq.id;
+
+CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ q.*,
+ l."name" AS "locationName",
+ ql."lines",
+ ql."completedLines",
+ EXISTS(SELECT 1 FROM "quoteFavorite" pf WHERE pf."quoteId" = q.id AND pf."userId" = auth.uid()::text) AS favorite,
+ opp."salesRfqId",
+ opp."salesOrderId"
+ FROM "quote" q
+ LEFT JOIN (
+ SELECT
+ "quoteId",
+ COUNT("id") AS "lines",
+ COUNT("id") FILTER (WHERE "status" = 'Complete') AS "completedLines"
+ FROM "quoteLine"
+ GROUP BY "quoteId"
+ ) ql ON ql."quoteId" = q.id
+ LEFT JOIN "location" l
+ ON l.id = q."locationId"
+ LEFT JOIN "opportunity" opp
+ ON opp."quoteId" = q.id;
+
+CREATE POLICY "Employees with settings_update can insert company integrations." ON "companyIntegration"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ has_company_permission('settings_update', "companyId")
+ );
+
+UPDATE "integration" SET jsonschema = '{"type": "object","properties": {"apiKey": {"type": "string"}, "fromEmail": {"type": "string"}}, "required": ["apiKey"]}'::json WHERE id = 'resend';
+
+ALTER TABLE "integration" ENABLE ROW LEVEL SECURITY;
+
diff --git a/packages/documents/src/email/QuoteEmail.tsx b/packages/documents/src/email/QuoteEmail.tsx
index 3c5ef9ac18..ac552e360e 100644
--- a/packages/documents/src/email/QuoteEmail.tsx
+++ b/packages/documents/src/email/QuoteEmail.tsx
@@ -4,7 +4,6 @@ import {
Column,
Container,
Head,
- Hr,
Html,
Img,
Link,
@@ -17,16 +16,9 @@ import type { Email } from "../types";
interface QuoteEmailProps extends Email {
quote: Database["public"]["Tables"]["quote"]["Row"];
- quoteLines: Database["public"]["Tables"]["quoteLine"]["Row"][];
}
-const QuoteEmail = ({
- company,
- quote,
- quoteLines,
- recipient,
- sender,
-}: QuoteEmailProps) => {
+const QuoteEmail = ({ company, quote, recipient, sender }: QuoteEmailProps) => {
const reSubject = `Re: ${quote.quoteId} from ${company.name}`;
return (
@@ -59,7 +51,6 @@ const QuoteEmail = ({
<Section>
<Text style={subtleText}>
Hi {recipient.firstName}, please see the attached quote.
- questions.
</Text>
</Section>
<Section style={informationTable}>
@@ -68,7 +59,7 @@ const QuoteEmail = ({
<Section>
<Row>
<Column style={informationTableColumn}>
- <Text style={informationTableLabel}>Buyer</Text>
+ <Text style={informationTableLabel}>Quoter</Text>
<Link
style={{
...informationTableValue,
@@ -84,145 +75,32 @@ const QuoteEmail = ({
<Row>
<Column style={informationTableColumn}>
- <Text style={informationTableLabel}>Payment Terms</Text>
- {/* <Text style={informationTableValue}>
- {quote.paymentTermName ?? "-"}
- </Text> */}
+ <Text style={informationTableLabel}>
+ Reference Number
+ </Text>
+ <Text style={informationTableValue}>
+ {quote.customerReference ?? "-"}
+ </Text>
</Column>
</Row>
<Row>
<Column style={informationTableColumn}>
- <Text style={informationTableLabel}>Order ID</Text>
+ <Text style={informationTableLabel}>Quote ID</Text>
<Text style={informationTableValue}>{quote.quoteId}</Text>
</Column>
<Column style={informationTableColumn}>
- <Text style={informationTableLabel}>Requested Date</Text>
- {/* <Text style={informationTableValue}>
- {quote.receiptRequestedDate ?? "-"}
- </Text> */}
+ <Text style={informationTableLabel}>Expiration Date</Text>
+ <Text style={informationTableValue}>
+ {quote.expirationDate ?? "-"}
+ </Text>
</Column>
</Row>
</Section>
</Column>
- {/* <Column style={informationTableColumn} colSpan={2}>
- <Text style={informationTableLabel}>Ship To</Text>
- {dropShipment ? (
- <>
- <Text style={informationTableValue}>{customerName}</Text>
- {customerAddressLine1 && (
- <Text style={informationTableValue}>
- {customerAddressLine1}
- </Text>
- )}
- {customerAddressLine2 && (
- <Text style={informationTableValue}>
- {customerAddressLine2}
- </Text>
- )}
- <Text style={informationTableValue}>
- {formatAddress(
- customerCity,
- customerState,
- customerPostalCode
- )}
- </Text>
- <Text style={informationTableValue}>
- {customerCountryCode}
- </Text>
- </>
- ) : (
- <>
- <Text style={informationTableValue}>{company.name}</Text>
- <Text style={informationTableValue}>{deliveryName}</Text>
- {deliveryAddressLine1 && (
- <Text style={informationTableValue}>
- {deliveryAddressLine1}
- </Text>
- )}
- {deliveryAddressLine2 && (
- <Text style={informationTableValue}>
- {deliveryAddressLine2}
- </Text>
- )}
- <Text style={informationTableValue}>
- {formatAddress(
- deliveryCity,
- deliveryState,
- deliveryPostalCode
- )}
- </Text>
- <Text>{deliveryCountryCode}</Text>
- </>
- )}
- </Column> */}
- </Row>
- </Section>
- <Section style={linesHeader}>
- <Text style={{ ...informationTableLabel, paddingLeft: "20px" }}>
- Quote Lines
- </Text>
- </Section>
- <Section>
- {quoteLines.map((line) => (
- <Row key={line.id}>
- <Column>
- <Text>{line.description}</Text>
- </Column>
- </Row>
- ))}
- </Section>
- {/* <Section>
- {purchaseOrderLines.map((line) => (
- <Row key={line.id} style={lineRow}>
- <Column
- style={{
- paddingLeft: "5px",
- }}
- >
- <Text style={lineTitle}>{getLineDescription(line)}</Text>
- {getLineDescriptionDetails(line)
- ?.split("\n")
- .map((l, i) => (
- <Text key={i} style={lineDescription}>
- {l}
- </Text>
- ))}
- </Column>
- <Column style={lineValueWrapper} align="right">
- <Text style={lineValue}>
- {line.purchaseOrderLineType === "Comment"
- ? ""
- : `(${line.purchaseQuantity})`}
- </Text>
- </Column>
- <Column style={lineValueWrapper} align="right">
- <Text style={lineValue}>
- {line.purchaseOrderLineType === "Comment"
- ? "-"
- : line.unitPrice
- ? `$${line.unitPrice.toFixed(2)}`
- : "-"}
- </Text>
- </Column>
- </Row>
- ))}
- </Section> */}
- <Hr style={priceLine} />
- <Section align="right">
- <Row>
- <Column style={tableCell} align="right">
- <Text style={priceTotal}>TOTAL</Text>
- </Column>
- <Column style={priceVerticalLine}></Column>
- <Column style={priceLargeWrapper}>
- {/* <Text style={priceLarge}>
- {`$${getTotal(purchaseOrderLines)}`}
- </Text> */}
- </Column>
</Row>
</Section>
- <Hr style={priceLineBottom} />
+
<Section>
<Row>
<Column align="center" style={block}>
@@ -322,65 +200,4 @@ const informationTableValue = {
lineHeight: 1.4,
};
-const linesHeader = {
- ...informationTable,
- margin: "30px 0 15px 0",
- height: "24px",
-};
-
-// const lineTitle = { fontSize: "12px", fontWeight: "600", ...resetText };
-
-// const lineDescription = {
-// fontSize: "12px",
-// color: "rgb(102,102,102)",
-// ...resetText,
-// };
-
-// const lineRow = {
-// marginBottom: "10px",
-// paddingLeft: "20px",
-// };
-
-const priceTotal = {
- margin: "0",
- color: "rgb(102,102,102)",
- fontSize: "10px",
- fontWeight: "600",
- padding: "0px 30px 0px 0px",
- textAlign: "right" as const,
-};
-
-// const lineValue = {
-// fontSize: "12px",
-// fontWeight: "600",
-// margin: "0",
-// };
-
-// const priceLarge = {
-// margin: "0px 20px 0px 0px",
-// fontSize: "16px",
-// fontWeight: "600",
-// whiteSpace: "nowrap" as const,
-// textAlign: "right" as const,
-// };
-
-// const lineValueWrapper = {
-// display: "table-cell",
-// padding: "0px 20px 0px 0px",
-// width: "100px",
-// verticalAlign: "top",
-// };
-
-const priceLine = { margin: "30px 0 0 0" };
-
-const priceVerticalLine = {
- height: "48px",
- borderLeft: "1px solid",
- borderColor: "rgb(238,238,238)",
-};
-
-const priceLargeWrapper = { display: "table-cell", width: "90px" };
-
-const priceLineBottom = { margin: "0 0 75px 0" };
-
const block = { display: "block" };
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index 04d787c9a5..e3b70ff89b 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -67,6 +67,10 @@ const QuotePDF = ({
items={
quote.expirationDate
? [
+ {
+ label: "Ref #",
+ value: quote?.customerReference,
+ },
{
label: "Date",
value: today(getLocalTimeZone()).toString(),
@@ -81,6 +85,10 @@ const QuotePDF = ({
},
]
: [
+ {
+ label: "Ref #",
+ value: quote?.customerReference,
+ },
{
label: "Date",
value: today(getLocalTimeZone()).toString(),