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: sales rfq form

Brad Barbin18e39b7a2169
diff --git a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
index a190718d6e..96e76e8a63 100644
--- a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
@@ -3,6 +3,7 @@ import { Search } from "~/components/Search";
import { usePermissions } from "~/hooks";
import AvatarMenu from "./AvatarMenu";
import Breadcrumbs from "./Breadcrumbs";
+import CreateMenu from "./CreateMenu";
import HelpMenu from "./HelpMenu";
import ModeSwitcher from "./ModeSwitcher";
@@ -13,7 +14,7 @@ const Topbar = () => {
<Breadcrumbs />
{permissions.is("employee") ? <Search /> : <div />}
<HStack spacing={1} className="justify-end py-2">
- {/* <CreateMenu /> */}
+ <CreateMenu />
<HelpMenu />
<ModeSwitcher />
<AvatarMenu />
diff --git a/apps/carbon/app/components/Layout/Topbar/useCreate.tsx b/apps/carbon/app/components/Layout/Topbar/useCreate.tsx
index 2fa6de87e2..e928d559f6 100644
--- a/apps/carbon/app/components/Layout/Topbar/useCreate.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useCreate.tsx
@@ -2,12 +2,15 @@ import { useMemo } from "react";
import {
LuComponent,
LuContainer,
- LuPenSquare,
- LuReceipt,
LuShoppingCart,
LuUserSquare,
LuUsers,
} from "react-icons/lu";
+import {
+ RiProgress2Line,
+ RiProgress4Line,
+ RiProgress8Line,
+} from "react-icons/ri";
import { usePermissions } from "~/hooks";
import type { Route } from "~/types";
@@ -46,17 +49,22 @@ export default function useCreate(): Route[] {
links.push({
name: "Customer",
to: path.to.newCustomer,
- icon: <LuUsers />,
+ icon: <LuUserSquare />,
});
links.push({
- name: "Quotation",
+ name: "RFQ",
+ to: path.to.newSalesRFQ,
+ icon: <RiProgress2Line />,
+ });
+ links.push({
+ name: "Quote",
to: path.to.newQuote,
- icon: <LuPenSquare />,
+ icon: <RiProgress4Line />,
});
links.push({
name: "Sales Order",
to: path.to.newSalesOrder,
- icon: <LuReceipt />,
+ icon: <RiProgress8Line />,
});
}
@@ -64,7 +72,7 @@ export default function useCreate(): Route[] {
links.push({
name: "Employee",
to: path.to.newEmployee,
- icon: <LuUserSquare />,
+ icon: <LuUsers />,
});
}
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index e90957c979..ee42ab37de 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -302,3 +302,17 @@ export const salesOrderReleaseValidator = z
path: ["customerContact"], // path of error
}
);
+
+export const salesRfqValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ rfqId: zfd.text(z.string().optional()),
+ customerContactId: zfd.text(z.string().optional()),
+ customerId: z.string().min(36, { message: "Customer is required" }),
+ customerReference: zfd.text(z.string().optional()),
+ employeeId: z.string().min(36, { message: "Quoter is required" }),
+ expirationDate: zfd.text(z.string().optional()),
+ externalNotes: zfd.text(z.string().optional()),
+ internalNotes: zfd.text(z.string().optional()),
+ rfqDate: z.string().min(1, { message: "Order Date is required" }),
+ status: z.enum(salesRFQStatusType).optional(),
+});
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index afec16b445..352b622743 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -23,6 +23,7 @@ import type {
salesOrderPaymentValidator,
salesOrderShipmentValidator,
salesOrderValidator,
+ salesRfqValidator,
} from "./sales.models";
export async function closeSalesOrder(
@@ -467,6 +468,26 @@ export async function getQuoteCustomerDetails(
.single();
}
+export async function getSalesOrderExternalDocuments(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ salesOrderId: string
+) {
+ return client.storage
+ .from("private")
+ .list(`${companyId}/sales/external/${salesOrderId}`);
+}
+
+/*export async function getSalesOrderInternalDocuments(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ salesOrderId: string
+) {
+ return client.storage
+ .from("private")
+ .list(`${companyId}/sales/internal/${salesOrderId}`);
+}*/
+
export async function getQuoteLinePrice(
client: SupabaseClient<Database>,
quoteLineId: string
@@ -544,6 +565,129 @@ export async function getQuoteOperations(
return client.from("quoteOperation").select("*").eq("quoteId", quoteId);
}
+export async function getSalesOrder(
+ client: SupabaseClient<Database>,
+ salesOrderId: string
+) {
+ return client.from("salesOrders").select("*").eq("id", salesOrderId).single();
+}
+
+export async function getSalesOrders(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ status: string | null;
+ customerId: string | null;
+ }
+) {
+ let query = client
+ .from("salesOrders")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args.search) {
+ query = query.or(
+ `salesOrderId.ilike.%${args.search}%,customerReference.ilike.%${args.search}%`
+ );
+ }
+
+ if (args.customerId) {
+ query = query.eq("customerId", args.customerId);
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "favorite", ascending: false },
+ { column: "salesOrderId", ascending: false },
+ ]);
+
+ return query;
+}
+
+export async function getSalesOrderShipment(
+ client: SupabaseClient<Database>,
+ salesOrderId: string
+) {
+ return client
+ .from("salesOrderShipment")
+ .select("*")
+ .eq("id", salesOrderId)
+ .single();
+}
+
+/*export async function getSalesOrderLocations(
+ client: SupabaseClient<Database>,
+ salesOrderId: string
+) {
+ return client
+ .from("salesOrderLocations")
+ .select("*")
+ .eq("id", salesOrderId)
+ .single();
+}*/
+
+/*export async function getSalesOrderPayment(
+ client: SupabaseClient<Database>,
+ salesOrderId: string
+) {
+ return client
+ .from("salesOrderPayment")
+ .select("*")
+ .eq("id", salesOrderId)
+ .single();
+}*/
+
+export async function getSalesOrderCustomers(client: SupabaseClient<Database>) {
+ return client.from("salesOrderCustomers").select("id, name");
+}
+
+export async function getSalesOrderLines(
+ client: SupabaseClient<Database>,
+ salesOrderId: string
+) {
+ return client
+ .from("salesOrderLines")
+ .select("*")
+ .eq("salesOrderId", salesOrderId)
+ .order("createdAt", { ascending: true });
+}
+
+export async function getSalesOrderLine(
+ client: SupabaseClient<Database>,
+ salesOrderLineId: string
+) {
+ return client
+ .from("salesOrderLine")
+ .select("*")
+ .eq("id", salesOrderLineId)
+ .single();
+}
+
+export async function getSalesRFQs(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client
+ .from("salesRfqs")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args.search) {
+ query = query.or(
+ `rfqId.ilike.%${args.search}%,name.ilike.%${args.search}%,customerReference.ilike%${args.search}%`
+ );
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "favorite", ascending: false },
+ { column: "id", ascending: false },
+ ]);
+ return query;
+}
+
export async function insertCustomerContact(
client: SupabaseClient<Database>,
customerContact: {
@@ -670,6 +814,18 @@ export async function insertQuoteLinePrice(
]);
}
+export async function insertSalesOrderLines(
+ client: SupabaseClient<Database>,
+ salesOrderLines:
+ | (Omit<z.infer<typeof salesOrderLineValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })[]
+) {
+ return client.from("salesOrderLine").insert(salesOrderLines).select("id");
+}
+
export async function releaseQuote(
client: SupabaseClient<Database>,
quoteId: string,
@@ -699,6 +855,21 @@ export async function releaseQuote(
.eq("quoteId", quoteId);
}
+export async function releaseSalesOrder(
+ client: SupabaseClient<Database>,
+ salesOrderId: string,
+ userId: string
+) {
+ return client
+ .from("salesOrder")
+ .update({
+ status: "Confirmed",
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", salesOrderId);
+}
+
export async function upsertCustomer(
client: SupabaseClient<Database>,
customer:
@@ -1068,176 +1239,6 @@ export async function upsertQuoteOperation(
.single();
}
-export async function getSalesOrderExternalDocuments(
- client: SupabaseClient<Database>,
- companyId: string,
- salesOrderId: string
-) {
- return client.storage
- .from("private")
- .list(`${companyId}/sales/external/${salesOrderId}`);
-}
-
-/*export async function getSalesOrderInternalDocuments(
- client: SupabaseClient<Database>,
- companyId: string,
- salesOrderId: string
-) {
- return client.storage
- .from("private")
- .list(`${companyId}/sales/internal/${salesOrderId}`);
-}*/
-
-export async function getSalesOrder(
- client: SupabaseClient<Database>,
- salesOrderId: string
-) {
- return client.from("salesOrders").select("*").eq("id", salesOrderId).single();
-}
-
-export async function getSalesOrders(
- client: SupabaseClient<Database>,
- companyId: string,
- args: GenericQueryFilters & {
- search: string | null;
- status: string | null;
- customerId: string | null;
- }
-) {
- let query = client
- .from("salesOrders")
- .select("*", { count: "exact" })
- .eq("companyId", companyId);
-
- if (args.search) {
- query = query.or(
- `salesOrderId.ilike.%${args.search}%,customerReference.ilike.%${args.search}%`
- );
- }
-
- if (args.customerId) {
- query = query.eq("customerId", args.customerId);
- }
-
- query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
- { column: "salesOrderId", ascending: false },
- ]);
-
- return query;
-}
-
-export async function getSalesOrderShipment(
- client: SupabaseClient<Database>,
- salesOrderId: string
-) {
- return client
- .from("salesOrderShipment")
- .select("*")
- .eq("id", salesOrderId)
- .single();
-}
-
-/*export async function getSalesOrderLocations(
- client: SupabaseClient<Database>,
- salesOrderId: string
-) {
- return client
- .from("salesOrderLocations")
- .select("*")
- .eq("id", salesOrderId)
- .single();
-}*/
-
-/*export async function getSalesOrderPayment(
- client: SupabaseClient<Database>,
- salesOrderId: string
-) {
- return client
- .from("salesOrderPayment")
- .select("*")
- .eq("id", salesOrderId)
- .single();
-}*/
-
-export async function getSalesOrderCustomers(client: SupabaseClient<Database>) {
- return client.from("salesOrderCustomers").select("id, name");
-}
-
-export async function getSalesOrderLines(
- client: SupabaseClient<Database>,
- salesOrderId: string
-) {
- return client
- .from("salesOrderLines")
- .select("*")
- .eq("salesOrderId", salesOrderId)
- .order("createdAt", { ascending: true });
-}
-
-export async function getSalesOrderLine(
- client: SupabaseClient<Database>,
- salesOrderLineId: string
-) {
- return client
- .from("salesOrderLine")
- .select("*")
- .eq("id", salesOrderLineId)
- .single();
-}
-
-export async function getSalesRFQs(
- client: SupabaseClient<Database>,
- companyId: string,
- args: GenericQueryFilters & {
- search: string | null;
- }
-) {
- let query = client
- .from("salesRfqs")
- .select("*", { count: "exact" })
- .eq("companyId", companyId);
-
- if (args.search) {
- query = query.or(
- `rfqId.ilike.%${args.search}%,name.ilike.%${args.search}%,customerReference.ilike%${args.search}%`
- );
- }
-
- query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
- { column: "id", ascending: false },
- ]);
- return query;
-}
-
-export async function insertSalesOrderLines(
- client: SupabaseClient<Database>,
- salesOrderLines:
- | (Omit<z.infer<typeof salesOrderLineValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- customFields?: Json;
- })[]
-) {
- return client.from("salesOrderLine").insert(salesOrderLines).select("id");
-}
-
-export async function releaseSalesOrder(
- client: SupabaseClient<Database>,
- salesOrderId: string,
- userId: string
-) {
- return client
- .from("salesOrder")
- .update({
- status: "Confirmed",
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", salesOrderId);
-}
-
export async function updateSalesOrderFavorite(
client: SupabaseClient<Database>,
args: {
@@ -1433,3 +1434,32 @@ export async function upsertSalesOrderPayment(
.select("id")
.single();
}
+
+export async function upsertSalesRFQ(
+ client: SupabaseClient<Database>,
+ rfq:
+ | (Omit<z.infer<typeof salesRfqValidator>, "id" | "rfqId"> & {
+ rfqId: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof salesRfqValidator>, "id" | "rfqId"> & {
+ id: string;
+ rfqId: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in rfq) {
+ return client.from("salesRfq").insert([rfq]).select("id, rfqId");
+ } else {
+ return client
+ .from("salesRfq")
+ .update({
+ ...sanitize(rfq),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", rfq.id);
+ }
+}
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index b5add09eff..24a03e94e6 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -92,3 +92,5 @@ export type SalesOrderTransactionType =
export type SalesRFQ = NonNullable<
Awaited<ReturnType<typeof getSalesRFQs>>["data"]
>[number];
+
+export type SalesRFQStatus = Database["public"]["Enums"]["salesRfqStatus"];
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
new file mode 100644
index 0000000000..fea2e36041
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
@@ -0,0 +1,130 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ VStack,
+ cn,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useState } from "react";
+import type { z } from "zod";
+import {
+ CustomFormFields,
+ Customer,
+ CustomerContact,
+ DatePicker,
+ Employee,
+ Hidden,
+ Input,
+ Location,
+ Select,
+ Submit,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { salesRFQStatusType, salesRfqValidator } from "~/modules/sales";
+
+type SalesRFQFormValues = z.infer<typeof salesRfqValidator>;
+
+type SalesRFQFormProps = {
+ initialValues: SalesRFQFormValues;
+};
+
+const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
+ const permissions = usePermissions();
+ const [customer, setCustomer] = useState<string | undefined>(
+ initialValues.customerId
+ );
+ const isEditing = initialValues.id !== undefined;
+ const isCustomer = permissions.is("customer");
+
+ const statusOptions = salesRFQStatusType.map((status) => ({
+ label: status,
+ value: status,
+ }));
+
+ return (
+ <ValidatedForm
+ method="post"
+ validator={salesRfqValidator}
+ defaultValues={initialValues}
+ >
+ <Card>
+ <CardHeader>
+ <CardTitle>{isEditing ? "RFQ" : "New RFQ"}</CardTitle>
+ {!isEditing && (
+ <CardDescription>
+ A sales request for quote (RFQ) is an inquiry for pricing on a set
+ of parts and quantities.
+ </CardDescription>
+ )}
+ </CardHeader>
+ <CardContent>
+ <Hidden name="rfqId" />
+ <VStack>
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-4",
+ isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-2"
+ )}
+ >
+ <Customer
+ autoFocus={!isEditing}
+ name="customerId"
+ label="Customer"
+ onChange={(newValue) =>
+ setCustomer(newValue?.value as string | undefined)
+ }
+ />
+ <Input name="customerReference" label="Customer Order Number" />
+ {isEditing && permissions.can("delete", "sales") && (
+ <Select
+ name="status"
+ label="Status"
+ value={initialValues.status}
+ options={statusOptions}
+ isReadOnly={isCustomer}
+ />
+ )}
+
+ <CustomerContact
+ name="customerContactId"
+ label="Customer Contact"
+ customer={customer}
+ />
+ <Employee name="employeeId" label="Quoter" />
+
+ <DatePicker
+ name="rfqDate"
+ label="RFQ Date"
+ isDisabled={isCustomer}
+ />
+ <DatePicker
+ name="expirateDate"
+ label="Expiration Date"
+ isDisabled={isCustomer}
+ />
+ <Location name="locationId" label="Location" />
+ <CustomFormFields table="salesRfq" />
+ </div>
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={
+ isEditing
+ ? !permissions.can("update", "sales")
+ : !permissions.can("create", "sales")
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ );
+};
+
+export default SalesRFQForm;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts b/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts
index 76dcc7028f..a249161709 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts
@@ -1,3 +1,4 @@
+import SalesRFQForm from "./SalesRFQForm";
import SalesRFQStatus from "./SalesRFQStatus";
-export { SalesRFQStatus };
+export { SalesRFQForm, SalesRFQStatus };
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx
index 1e07dc6725..7f4968ff79 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx
@@ -72,7 +72,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
{row.original.favorite ? (
<fetcher.Form
method="post"
- action={path.to.salesRFQFavorite}
+ action={path.to.salesRfqFavorite}
className="flex items-center"
>
<input type="hidden" name="id" value={row.original.id!} />
@@ -87,7 +87,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
) : (
<fetcher.Form
method="post"
- action={path.to.salesRFQFavorite}
+ action={path.to.salesRfqFavorite}
className="flex items-center"
>
<input type="hidden" name="id" value={row.original.id!} />
@@ -100,7 +100,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
</button>
</fetcher.Form>
)}
- <Hyperlink to={path.to.salesRFQDetails(row.original.id!)}>
+ <Hyperlink to={path.to.salesRfqDetails(row.original.id!)}>
{row.original.rfqId}
</Hyperlink>
</HStack>
@@ -256,7 +256,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
// eslint-disable-next-line react/display-name
return (row: SalesRFQ) => (
<>
- <MenuItem onClick={() => navigate(path.to.salesRFQDetails(row.id!))}>
+ <MenuItem onClick={() => navigate(path.to.salesRfqDetails(row.id!))}>
<MenuIcon icon={<LuPencil />} />
Edit
</MenuItem>
@@ -291,7 +291,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
}}
primaryAction={
permissions.can("create", "sales") && (
- <New label="Quote" to={path.to.newQuote} />
+ <New label="RFQ" to={path.to.newSalesRFQ} />
)
}
withColumnOrdering
@@ -299,7 +299,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
/>
{selectedSalesRFQ && selectedSalesRFQ.id && (
<ConfirmDelete
- action={path.to.deleteQuote(selectedSalesRFQ.id)}
+ action={path.to.deleteSalesRfq(selectedSalesRFQ.id)}
isOpen={deleteSalesRFQModal.isOpen}
name={selectedSalesRFQ.rfqId!}
text={`Are you sure you want to delete ${selectedSalesRFQ.rfqId!}? This cannot be undone.`}
@@ -324,7 +324,7 @@ export default SalesRFQsTable;
function useOptimisticFavorite() {
const fetchers = useFetchers();
const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.salesRFQFavorite
+ (f) => f.formAction === path.to.salesRfqFavorite
);
if (favoriteFetcher && favoriteFetcher.formData) {
diff --git a/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx b/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx
index 7a11f9fba2..a630746623 100644
--- a/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx
+++ b/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx
@@ -19,7 +19,7 @@ const salesRoutes: AuthenticatedRouteGroup[] = [
},
{
name: "RFQs",
- to: path.to.salesRFQs,
+ to: path.to.salesRfqs,
icon: <RiProgress2Line />,
},
{
diff --git a/apps/carbon/app/routes/x+/sales+/rfqs.tsx b/apps/carbon/app/routes/x+/sales+/rfqs.tsx
index 8c6d997a0d..a9e93138cd 100644
--- a/apps/carbon/app/routes/x+/sales+/rfqs.tsx
+++ b/apps/carbon/app/routes/x+/sales+/rfqs.tsx
@@ -12,7 +12,7 @@ import { error } from "~/utils/result";
export const handle: Handle = {
breadcrumb: "RFQs",
- to: path.to.salesRFQs,
+ to: path.to.salesRfqs,
};
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/new.tsx b/apps/carbon/app/routes/x+/sales-rfq+/new.tsx
new file mode 100644
index 0000000000..41b7c623bc
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-rfq+/new.tsx
@@ -0,0 +1,88 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useUrlParams, useUser } from "~/hooks";
+import type { SalesRFQStatus } from "~/modules/sales";
+import {
+ SalesRFQForm,
+ salesRfqValidator,
+ upsertSalesRFQ,
+} from "~/modules/sales";
+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(salesRfqValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const nextSequence = await getNextSequence(client, "salesRfq", companyId);
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.newSalesRFQ,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ const createSalesRFQ = await upsertSalesRFQ(client, {
+ ...validation.data,
+ rfqId: nextSequence.data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createSalesRFQ.error || !createSalesRFQ.data?.[0]) {
+ // TODO: this should be done as a transaction
+ await rollbackNextSequence(client, "salesRfq", companyId);
+ throw redirect(
+ path.to.salesRfqs,
+ await flash(request, error(createSalesRFQ.error, "Failed to insert RFQ"))
+ );
+ }
+
+ const order = createSalesRFQ.data?.[0];
+
+ throw redirect(path.to.salesRfq(order.id!));
+}
+
+export default function SalesRFQNewRoute() {
+ const { id, defaults } = useUser();
+ const [params] = useUrlParams();
+ const customerId = params.get("customerId");
+ const initialValues = {
+ customerContactId: "",
+ customerId: customerId ?? "",
+ customerReference: "",
+ employeeId: id,
+ expirateDate: "",
+ id: undefined,
+ locationId: defaults?.locationId ?? "",
+ rfqDate: today(getLocalTimeZone()).toString(),
+ rfqId: undefined,
+ status: "Draft" as SalesRFQStatus,
+ };
+
+ return (
+ <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <SalesRFQForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 54745e5c73..b3f6736e26 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -246,6 +246,7 @@ export const path = {
generatePath(`${x}/sales-order/delete/${id}`),
deleteSalesOrderLine: (orderId: string, lineId: string) =>
generatePath(`${x}/sales-order/${orderId}/lines/delete/${lineId}`),
+ deleteSalesRfq: (id: string) => generatePath(`${x}/sales-rfq/delete/${id}`),
deleteShift: (id: string) =>
generatePath(`${x}/resources/shifts/delete/${id}`),
deleteShippingMethod: (id: string) =>
@@ -463,6 +464,8 @@ export const path = {
newSalesOrder: `${x}/sales-order/new`,
newSalesOrderLine: (id: string) =>
generatePath(`${x}/sales-order/${id}/lines/new`),
+ newSalesRFQ: `${x}/sales-rfq/new`,
+ newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),
newShift: `${x}/resources/shifts/new`,
newShippingMethod: `${x}/inventory/shipping-methods/new`,
newService: `${x}/service/new`,
@@ -617,9 +620,10 @@ export const path = {
salesOrderRelease: (id: string) =>
generatePath(`${x}/sales-order/${id}/release`),
salesOrders: `${x}/sales/orders`,
- salesRFQDetails: (id: string) => generatePath(`${x}/sales-rfq/${id}`),
- salesRFQFavorite: `${x}/sales/rfqs/favorite`,
- salesRFQs: `${x}/sales/rfqs`,
+ salesRfq: (id: string) => generatePath(`${x}/sales-rfq/${id}`),
+ salesRfqDetails: (id: string) => generatePath(`${x}/sales-rfq/${id}`),
+ salesRfqFavorite: `${x}/sales/rfqs/favorite`,
+ salesRfqs: `${x}/sales/rfqs`,
scheduling: `${x}/scheduling`,
service: (id: string) => generatePath(`${x}/service/${id}`),
services: `${x}/items/services`,
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index 0a155386f8..f1b933920c 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -2059,6 +2059,15 @@ export const sequences = [
size: 6,
step: 1,
},
+ {
+ table: "salesRfq",
+ name: "RFQ (Sales)",
+ prefix: "RFQ",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ },
{
table: "salesOrder",
name: "Sales Order",
diff --git a/packages/database/supabase/migrations/20230525025310_sequences.sql b/packages/database/supabase/migrations/20230525025310_sequences.sql
index e97c6a028f..71fa118379 100644
--- a/packages/database/supabase/migrations/20230525025310_sequences.sql
+++ b/packages/database/supabase/migrations/20230525025310_sequences.sql
@@ -22,7 +22,7 @@ CREATE TABLE "sequence" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
"updatedBy" TEXT,
- CONSTRAINT "sequence_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "sequence_pkey" PRIMARY KEY ("id", "companyId"), -- this is replaced with "table", "companyId"
CONSTRAINT "sequence_next_check" CHECK ("next" >= 0),
CONSTRAINT "sequence_size_check" CHECK ("size" >= 1),
CONSTRAINT "sequence_step_check" CHECK ("step" >= 1),
@@ -32,3 +32,5 @@ CREATE TABLE "sequence" (
CREATE INDEX "sequence_companyId_idx" ON "sequence" ("companyId");
+
+
diff --git a/packages/database/supabase/migrations/20240704105128_rfq.sql b/packages/database/supabase/migrations/20240704105128_rfq.sql
index 4b53b6456e..9629273df5 100644
--- a/packages/database/supabase/migrations/20240704105128_rfq.sql
+++ b/packages/database/supabase/migrations/20240704105128_rfq.sql
@@ -100,4 +100,31 @@ CREATE OR REPLACE VIEW "salesRfqs" WITH(SECURITY_INVOKER=true) AS
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";
\ No newline at end of file
+ ON l.id = rfq."locationId";
+
+
+ALTER TABLE "sequence" DROP CONSTRAINT "sequence_pkey";
+ALTER TABLE "sequence" ADD CONSTRAINT "sequence_pkey" PRIMARY KEY ("table", "companyId");
+
+-- salesRfq sequence for existing companies
+INSERT INTO "sequence" (
+ "table",
+ "name",
+ "prefix",
+ "suffix",
+ "next",
+ "size",
+ "step",
+ "companyId"
+)
+SELECT
+ 'salesRfq',
+ 'RFQ (Sales)',
+ 'RFQ',
+ null,
+ 0,
+ 6,
+ 1,
+ id
+FROM "company"
+ON CONFLICT DO NOTHING;
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index 9024ac7713..d71c8e1150 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -15,7 +15,7 @@ export const buttonVariants = cva(
primary:
"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm",
active:
- "bg-primary/10 text-primary hover:bg-primary/20 dark:shadow-inner",
+ "bg-primary/10 text-primary hover:bg-primary/5 dark:shadow-inner",
secondary:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
solid: "bg-primary/25 text-accent-foreground hover:bg-primary/35",