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: convert order to job

Brad Barbin3dbff4de8150
diff --git a/apps/carbon/app/components/Empty.tsx b/apps/carbon/app/components/Empty.tsx
index 4c482b46b3..e56d76bf21 100644
--- a/apps/carbon/app/components/Empty.tsx
+++ b/apps/carbon/app/components/Empty.tsx
@@ -1,10 +1,17 @@
-import { VStack } from "@carbon/react";
-import type { ReactNode } from "react";
+import { cn, VStack } from "@carbon/react";
+import type { ComponentProps } from "react";
import { LuGhost } from "react-icons/lu";
-export default function Empty({ children }: { children: ReactNode }) {
+export default function Empty({
+ className,
+ children,
+ ...props
+}: ComponentProps<"div">) {
return (
- <VStack className="w-full h-full justify-center items-center">
+ <VStack
+ className={cn("w-full h-full justify-center items-center", className)}
+ {...props}
+ >
<LuGhost className="w-12 h-12" />
<h3 className="text-base">Pretty empty around here</h3>
{children}
diff --git a/apps/carbon/app/components/Grid/Grid.tsx b/apps/carbon/app/components/Grid/Grid.tsx
index dd83bcd734..f28e821dab 100644
--- a/apps/carbon/app/components/Grid/Grid.tsx
+++ b/apps/carbon/app/components/Grid/Grid.tsx
@@ -330,7 +330,7 @@ const Grid = <T extends object>({
ref={tableContainerRef}
onKeyDown={onKeyDown}
>
- <Table className="absolute">
+ <Table full={contained} className="absolute border">
<Thead className="sticky top-0 z-10">
{table.getHeaderGroups().map((headerGroup) => (
<Tr key={headerGroup.id} className="h-10">
@@ -417,7 +417,7 @@ const Grid = <T extends object>({
{onNewRow && (
<Tr
onClick={onNewRow}
- className="cursor-pointer h-10 hover:bg-muted/50"
+ className="cursor-pointer h-10 hover:bg-muted/50 border-t"
>
<Td colSpan={24}>
<HStack className="items-start h-6">
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 7fda6218c6..fc700536d7 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -580,7 +580,7 @@ const Table = <T extends object>({
{rows.length === 0 ? (
isLoading ? (
<div className="flex h-full w-full items-start justify-center">
- <TableBase className="w-full">
+ <TableBase full className="w-full">
<Thead>
<Tr>
{Array.from({ length: 7 }).map((_, colIndex) => (
@@ -635,6 +635,7 @@ const Table = <T extends object>({
) : (
<TableBase
ref={tableRef}
+ full
className="relative border-collapse border-spacing-0"
>
<Thead className="sticky top-0 z-10">
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index 7e0b1cec33..ee286e2b0c 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -24,23 +24,46 @@ export const jobStatus = [
"Cancelled",
] as const;
-export const jobValidator = z
- .object({
- id: zfd.text(z.string().optional()),
- jobId: zfd.text(z.string().optional()),
- itemId: z.string().min(1, { message: "Item is required" }),
- customerId: zfd.text(z.string().optional()),
- dueDate: zfd.text(z.string().optional()),
- deadlineType: z.enum(deadlineTypes, {
- errorMap: () => ({ message: "Deadline type is required" }),
- }),
- locationId: z.string().min(1, { message: "Location is required" }),
- quantity: zfd.numeric(z.number().min(0)),
- scrapQuantity: zfd.numeric(z.number().min(0)),
- unitOfMeasureCode: z
- .string()
- .min(1, { message: "Unit of measure is required" }),
- modelUploadId: zfd.text(z.string().optional()),
+const baseJobValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ jobId: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ customerId: zfd.text(z.string().optional()),
+ dueDate: zfd.text(z.string().optional()),
+ deadlineType: z.enum(deadlineTypes, {
+ errorMap: () => ({ message: "Deadline type is required" }),
+ }),
+ locationId: z.string().min(1, { message: "Location is required" }),
+ quantity: zfd.numeric(z.number().min(0)),
+ scrapQuantity: zfd.numeric(z.number().min(0)),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of measure is required" }),
+ modelUploadId: zfd.text(z.string().optional()),
+});
+
+export const jobValidator = baseJobValidator.refine(
+ (data) => {
+ if (
+ ["Hard Deadline", "Soft Deadline"].includes(data.deadlineType) &&
+ !data.dueDate
+ ) {
+ return false;
+ }
+ return true;
+ },
+ {
+ message: "Due date is required",
+ path: ["dueDate"],
+ }
+);
+
+export const salesOrderToJobValidator = baseJobValidator
+ .extend({
+ quoteId: zfd.text(z.string().optional()),
+ quoteLineId: zfd.text(z.string().optional()),
+ salesOrderId: zfd.text(z.string()),
+ salesOrderLineId: zfd.text(z.string()),
})
.refine(
(data) => {
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index 4ca6ca512d..34c4bbf8e3 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -93,6 +93,17 @@ export async function getJobs(
return query;
}
+export async function getJobsBySalesOrderLine(
+ client: SupabaseClient<Database>,
+ salesOrderLineId: string
+) {
+ return client
+ .from("jobs")
+ .select("*")
+ .eq("salesOrderLineId", salesOrderLineId)
+ .order("createdAt", { ascending: true });
+}
+
export async function getJobsList(
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
index e7230d6eac..dd12ee2ed0 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -21,6 +21,7 @@ import {
LuSettings,
LuTable,
} from "react-icons/lu";
+import { RiProgress8Line } from "react-icons/ri";
import { Assignee, Copy, useOptimisticAssignment } from "~/components";
import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
import { path } from "~/utils/path";
@@ -71,7 +72,6 @@ const JobHeader = () => {
const currentValue = getOptionFromPath();
return (
-
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
<HStack>
<Link to={path.to.jobDetails(jobId)}>
@@ -91,6 +91,19 @@ const JobHeader = () => {
className="h-8"
isReadOnly={!permissions.can("update", "production")}
/>
+ {routeData?.job?.salesOrderId && routeData?.job.salesOrderLineId && (
+ <Button leftIcon={<RiProgress8Line />} variant="secondary" asChild>
+ <Link
+ to={path.to.salesOrderLine(
+ routeData?.job?.salesOrderId,
+ routeData?.job?.salesOrderLineId
+ )}
+ >
+ View Order
+ </Link>
+ </Button>
+ )}
+
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
index f98911a423..6dc770721d 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -117,13 +117,17 @@ const JobsTable = memo(({ data, count, locations }: JobsTableProps) => {
{
accessorKey: "salesOrderReadableId",
header: "Sales Order",
- cell: ({ row }) => (
- <Hyperlink
- to={path.to.salesOrderDetails(row.original.salesOrderLineId!)}
- >
- {row.original?.salesOrderReadableId}
- </Hyperlink>
- ),
+ cell: ({ row }) =>
+ row.original.salesOrderId && row.original.salesOrderLineId ? (
+ <Hyperlink
+ to={path.to.salesOrderLine(
+ row.original.salesOrderId,
+ row.original.salesOrderLineId!
+ )}
+ >
+ {row.original?.salesOrderReadableId}
+ </Hyperlink>
+ ) : null,
},
{
accessorKey: "status",
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index e3f809ba15..6930e19128 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -114,6 +114,7 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
<Button
isDisabled={isDisabled}
leftIcon={<LuPlus />}
+ variant="secondary"
onClick={newQuoteLineDisclosure.onOpen}
>
Add Line Item
@@ -130,6 +131,7 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
className="w-full"
isDisabled={isDisabled || !permissions.can("update", "sales")}
leftIcon={<LuPlus />}
+ variant="secondary"
onClick={newQuoteLineDisclosure.onOpen}
>
Add Line Item
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
index f8fef5c9ff..107f03ebf6 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
@@ -39,8 +39,6 @@ export function useLineCosts({
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
- console.log({ originalMethodTree });
-
// TODO: instead of walking the tree twice (once for the quantities/operations and once for the effects)
// we could do it all in one pass
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index d78b16956a..180ad28edb 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -102,6 +102,7 @@ export default function SalesOrderExplorer() {
<Button
isDisabled={isDisabled}
leftIcon={<LuPlus />}
+ variant="secondary"
onClick={newSalesOrderLineDisclosure.onOpen}
>
Add Line Item
@@ -118,6 +119,7 @@ export default function SalesOrderExplorer() {
className="w-full"
isDisabled={isDisabled || !permissions.can("update", "sales")}
leftIcon={<LuPlus />}
+ variant="secondary"
onClick={newSalesOrderLineDisclosure.onOpen}
>
Add Line Item
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
new file mode 100644
index 0000000000..c4702f3090
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
@@ -0,0 +1,249 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+ useDisclosure,
+} from "@carbon/react";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
+import { LuHardHat, LuPlus } from "react-icons/lu";
+import { Assignee, Empty, Hyperlink } from "~/components";
+import {
+ DatePicker,
+ Hidden,
+ Location,
+ NumberControlled,
+ Select,
+ SequenceOrCustomId,
+ Submit,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import {
+ deadlineTypes,
+ JobStatus,
+ salesOrderToJobValidator,
+ type Job,
+} from "~/modules/production";
+import { path } from "~/utils/path";
+import type { Opportunity, SalesOrder, SalesOrderLine } from "../../types";
+
+type SalesOrderLineJobsProps = {
+ salesOrder: SalesOrder;
+ line: SalesOrderLine;
+ opportunity: Opportunity;
+ jobs: Job[];
+ itemReplenishment: { lotSize: number | null; scrapPercentage: number | null };
+};
+
+export function SalesOrderLineJobs({
+ salesOrder,
+ line,
+ opportunity,
+ jobs,
+ itemReplenishment,
+}: SalesOrderLineJobsProps) {
+ const permissions = usePermissions();
+ const { orderId, lineId } = useParams();
+ if (!orderId) throw new Error("orderId not found");
+ if (!lineId) throw new Error("lineId not found");
+
+ const newJobDisclosure = useDisclosure();
+ const hasJobs = jobs.length > 0;
+
+ const scrapPercentage = itemReplenishment.scrapPercentage ?? 0;
+ const totalJobQuantity = jobs.reduce(
+ (sum, job) => sum + (job.quantity ?? 0),
+ 0
+ );
+ const quantityRequired = (line.saleQuantity ?? 0) - totalJobQuantity;
+ const [quantities, setQuantities] = useState<{
+ quantity: number;
+ scrapQuantity: number;
+ }>(() => {
+ const quantity = itemReplenishment.lotSize
+ ? Math.min(quantityRequired, itemReplenishment.lotSize)
+ : quantityRequired;
+ return {
+ quantity,
+ scrapQuantity: Math.ceil(quantity * (scrapPercentage / 100)),
+ };
+ });
+
+ return (
+ <>
+ <Card>
+ <HStack className="w-full justify-between">
+ <CardHeader>
+ <CardTitle>Jobs</CardTitle>
+ </CardHeader>
+ <CardAction>
+ {hasJobs && (
+ <Button
+ leftIcon={<LuHardHat />}
+ onClick={newJobDisclosure.onOpen}
+ >
+ Make to Order
+ </Button>
+ )}
+ </CardAction>
+ </HStack>
+
+ <CardContent>
+ {jobs.length > 0 ? (
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Job ID</Th>
+ <Th>Status</Th>
+ <Th>Quantity Complete</Th>
+ <Th>Assignee</Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {jobs.map((job) => (
+ <Tr key={job.id}>
+ <Td>
+ <Hyperlink to={path.to.job(job.id!)}>
+ {job.jobId}
+ </Hyperlink>
+ </Td>
+ <Td>
+ <JobStatus status={job.status} />
+ </Td>
+ <Td>{job.quantityComplete}</Td>
+ <Td>
+ <Assignee
+ id={job.id!}
+ table="job"
+ value={job.assignee ?? ""}
+ isReadOnly={!permissions.can("update", "production")}
+ />
+ </Td>
+ </Tr>
+ ))}
+ </Tbody>
+ </Table>
+ ) : (
+ <Empty className="pb-12">
+ <Button leftIcon={<LuPlus />} onClick={newJobDisclosure.onOpen}>
+ Make to Order
+ </Button>
+ </Empty>
+ )}
+ </CardContent>
+ </Card>
+ {newJobDisclosure.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) newJobDisclosure.onClose();
+ }}
+ >
+ <ModalContent size="large">
+ <ValidatedForm
+ validator={salesOrderToJobValidator}
+ method="post"
+ action={path.to.salesOrderLineToJob(orderId, lineId)}
+ defaultValues={{
+ customerId: salesOrder.customerId ?? undefined,
+ dueDate: line.promisedDate ?? "",
+ deadlineType: "Hard Deadline",
+ itemId: line.itemId ?? undefined,
+ locationId: line.locationId ?? "",
+ modelUploadId: line.modelUploadId ?? undefined,
+ quantity: line.saleQuantity ?? undefined,
+ quoteId: opportunity.quoteId ?? undefined,
+ quoteLineId: opportunity.quoteId ? lineId : undefined,
+ salesOrderId: opportunity.salesOrderId ?? undefined,
+ salesOrderLineId: lineId,
+ scrapQuantity: 0,
+ unitOfMeasureCode: line.unitOfMeasureCode ?? undefined,
+ }}
+ className="flex flex-col h-full"
+ onSubmit={newJobDisclosure.onClose}
+ >
+ <ModalHeader>
+ <ModalTitle>Convert Line to Job</ModalTitle>
+ <ModalDescription>
+ Create a new production job to fulfill the sales order
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="modelUploadId" />
+ <Hidden name="customerId" />
+ <Hidden name="itemId" />
+ <Hidden name="salesOrderId" />
+ <Hidden name="salesOrderLineId" />
+ <Hidden name="quoteId" />
+ <Hidden name="quoteLineId" />
+ <Hidden name="unitOfMeasureCode" />
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 md:grid-cols-2">
+ <SequenceOrCustomId name="jobId" label="Job ID" table="job" />
+ <Location name="locationId" label="Location" />
+ <NumberControlled
+ name="quantity"
+ label="Quantity"
+ value={quantities.quantity}
+ onChange={(value) => {
+ setQuantities((prev) => ({
+ ...prev,
+ quantity: value,
+ scrapQuantity: Math.ceil(value * scrapPercentage),
+ }));
+ }}
+ minValue={0}
+ />
+ <NumberControlled
+ name="scrapQuantity"
+ label="Scrap Quantity"
+ value={quantities.scrapQuantity}
+ onChange={(value) =>
+ setQuantities((prev) => ({
+ ...prev,
+ scrapQuantity: value,
+ }))
+ }
+ minValue={0}
+ />
+ <DatePicker name="dueDate" label="Due Date" />
+ <Select
+ name="deadlineType"
+ label="Deadline Type"
+ options={deadlineTypes.map((d) => ({
+ value: d,
+ label: d,
+ }))}
+ />
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={newJobDisclosure.onClose}>
+ Cancel
+ </Button>
+ <Submit>Create</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ );
+}
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts b/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts
index de4495c299..558bfdb88f 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts
@@ -9,6 +9,7 @@ import SalesOrderLineForm from "./SalesOrderLineForm";
import SalesOrderLines from "./SalesOrderLines";
import SalesOrderPaymentForm from "./SalesOrderPaymentForm";
+import { SalesOrderLineJobs } from "./SalesOrderLineJobs";
import SalesStatus from "./SalesStatus";
import { useSalesOrderTotals } from "./useSalesOrderTotals";
@@ -20,6 +21,7 @@ export {
SalesOrderForm,
SalesOrderHeader,
SalesOrderLineForm,
+ SalesOrderLineJobs,
SalesOrderLines,
SalesOrderPaymentForm,
SalesOrderShipmentForm,
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index a89b6b305d..8bf27247a3 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -119,6 +119,7 @@ export default function SalesRFQExplorer() {
<Button
leftIcon={<LuPlus />}
isDisabled={isDisabled}
+ variant="secondary"
onClick={newSalesRFQLineDisclosure.onOpen}
>
Add Line Item
@@ -153,6 +154,7 @@ export default function SalesRFQExplorer() {
className="w-full"
isDisabled={isDisabled || !permissions.can("update", "sales")}
leftIcon={<LuPlus />}
+ variant="secondary"
onClick={newSalesRFQLineDisclosure.onOpen}
>
Add Line Item
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx
index 659cfca398..e3def6a2ad 100644
--- a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx
@@ -117,7 +117,7 @@ export default function ItemInventoryRoute() {
defaultSize={50}
maxSize={70}
minSize={25}
- className="bg-background"
+ className="bg-muted"
>
<ScrollArea className="h-[calc(100vh-49px)]">
<InventoryItemHeader itemReadableId={item.readableId} />
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
index 59e9dd3592..0fa554da50 100644
--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
@@ -1,13 +1,22 @@
import { validationError, validator } from "@carbon/form";
-import { Outlet, useLoaderData, useParams } from "@remix-run/react";
+import { Card, CardHeader, CardTitle } from "@carbon/react";
+import { Await, Outlet, useLoaderData, useParams } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
+import { defer, redirect } from "@vercel/remix";
+import { Suspense } from "react";
import { CadModel } from "~/components";
-import { usePermissions } from "~/hooks";
-import type { SalesOrderLineType } from "~/modules/sales";
+import { usePermissions, useRouteData } from "~/hooks";
+import { getItemReplenishment } from "~/modules/items";
+import { getJobsBySalesOrderLine } from "~/modules/production";
+import type {
+ Opportunity,
+ SalesOrder,
+ SalesOrderLineType,
+} from "~/modules/sales";
import {
OpportunityLineDocuments,
SalesOrderLineForm,
+ SalesOrderLineJobs,
getOpportunityLineDocuments,
getSalesOrderLine,
salesOrderLineValidator,
@@ -26,17 +35,31 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
role: "employee",
});
- const { lineId } = params;
+ const { orderId, lineId } = params;
+ if (!orderId) throw notFound("orderId not found");
if (!lineId) throw notFound("lineId not found");
- const [line, files] = await Promise.all([
+ const [line, jobs, files] = await Promise.all([
getSalesOrderLine(client, lineId),
+ getJobsBySalesOrderLine(client, lineId),
getOpportunityLineDocuments(client, companyId, lineId),
]);
- return json({
+ if (line.error) {
+ throw redirect(
+ path.to.salesOrder(orderId),
+ await flash(request, error(line.error, "Failed to load sales order line"))
+ );
+ }
+
+ return defer({
line: line?.data ?? null,
+ itemReplenishment:
+ line.data.itemId && line.data.methodType === "Make"
+ ? getItemReplenishment(client, line.data.itemId, companyId)
+ : Promise.resolve({ data: null }),
files: files?.data ?? [],
+ jobs: jobs?.data ?? [],
});
}
@@ -94,12 +117,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function EditSalesOrderLineRoute() {
- const { line, files } = useLoaderData<typeof loader>();
+ const { line, jobs, itemReplenishment, files } =
+ useLoaderData<typeof loader>();
const permissions = usePermissions();
const { orderId, lineId } = useParams();
if (!orderId) throw new Error("orderId not found");
if (!lineId) throw new Error("lineId not found");
+ const orderData = useRouteData<{
+ salesOrder: SalesOrder;
+ opportunity: Opportunity;
+ }>(path.to.salesOrder(orderId));
+
+ if (!orderData?.opportunity) throw new Error("Failed to load opportunity");
+ if (!orderData?.salesOrder) throw new Error("Failed to load sales order");
+
const initialValues = {
id: line?.id ?? undefined,
salesOrderId: line?.salesOrderId ?? "",
@@ -128,7 +160,37 @@ export default function EditSalesOrderLineRoute() {
key={initialValues.id}
initialValues={initialValues}
/>
-
+ {line.methodType === "Make" && (
+ <Suspense
+ fallback={
+ <Card className="min-h-[264px]">
+ <CardHeader>
+ <CardTitle>Jobs</CardTitle>
+ </CardHeader>
+ </Card>
+ }
+ >
+ <Await
+ resolve={itemReplenishment}
+ errorElement={<div>Error loading make method</div>}
+ >
+ {(resolvedItemReplenishment) => (
+ <SalesOrderLineJobs
+ salesOrder={orderData.salesOrder}
+ line={line}
+ opportunity={orderData.opportunity}
+ jobs={jobs}
+ itemReplenishment={
+ resolvedItemReplenishment.data ?? {
+ lotSize: 0,
+ scrapPercentage: 0,
+ }
+ }
+ />
+ )}
+ </Await>
+ </Suspense>
+ )}
<div className="grid grid-cols-1 xl:grid-cols-2 w-full flex-grow gap-2 ">
<CadModel
autodeskUrn={line?.autodeskUrn ?? null}
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
new file mode 100644
index 0000000000..f226033931
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
@@ -0,0 +1,125 @@
+import { validationError, validator } from "@carbon/form";
+import { tasks } from "@trigger.dev/sdk/v3";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import {
+ salesOrderToJobValidator,
+ upsertJob,
+ upsertJobMethod,
+} from "~/modules/production";
+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { recalculateTask } from "~/trigger/recalculate";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export const config = { runtime: "nodejs" };
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+
+ const { orderId, lineId } = params;
+ if (!orderId || !lineId) {
+ throw new Error("Invalid orderId or lineId");
+ }
+
+ const { companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+ const serviceRole = getSupabaseServiceRole();
+
+ const formData = await request.formData();
+ const validation = await validator(salesOrderToJobValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ let jobId = validation.data.jobId;
+ const useNextSequence = !jobId;
+ if (useNextSequence) {
+ const nextSequence = await getNextSequence(serviceRole, "job", companyId);
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.newJob,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+ jobId = nextSequence.data;
+ }
+
+ if (!jobId) throw new Error("jobId is not defined");
+ const { id: _id, ...data } = validation.data;
+
+ const createJob = await upsertJob(serviceRole, {
+ ...data,
+ jobId,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ const id = createJob.data?.id!;
+ if (createJob.error || !jobId) {
+ // TODO: this should be done as a transaction
+ await rollbackNextSequence(serviceRole, "job", companyId);
+ throw redirect(
+ path.to.salesOrderLine(orderId, lineId),
+ await flash(request, error(createJob.error, "Failed to insert job"))
+ );
+ }
+
+ if (validation.data.quoteId && validation.data.quoteLineId) {
+ const upsertMethod = await upsertJobMethod(serviceRole, "quoteLineToJob", {
+ sourceId: `${data.quoteId}:${data.quoteLineId}`,
+ targetId: id,
+ companyId,
+ userId,
+ });
+
+ if (upsertMethod.error) {
+ throw redirect(
+ path.to.salesOrderLine(orderId, lineId),
+ await flash(
+ request,
+ error(upsertMethod.error, "Failed to create job method.")
+ )
+ );
+ }
+ } else {
+ const upsertMethod = await upsertJobMethod(serviceRole, "itemToJob", {
+ sourceId: data.itemId,
+ targetId: id,
+ companyId,
+ userId,
+ });
+
+ if (upsertMethod.error) {
+ throw redirect(
+ path.to.salesOrderLine(orderId, lineId),
+ await flash(
+ request,
+ error(upsertMethod.error, "Failed to create job method.")
+ )
+ );
+ }
+ }
+
+ await tasks.trigger<typeof recalculateTask>("recalculate", {
+ type: "jobRequirements",
+ id,
+ companyId,
+ userId,
+ });
+
+ throw redirect(path.to.salesOrderLine(orderId, lineId));
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 6d6549b0ff..0a98ed9a0c 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -686,6 +686,8 @@ export const path = {
generatePath(`${x}/sales-order/${id}/internal`),
salesOrderLine: (orderId: string, id: string) =>
generatePath(`${x}/sales-order/${orderId}/${id}/details`),
+ salesOrderLineToJob: (orderId: string, lineId: string) =>
+ generatePath(`${x}/sales-order/${orderId}/${lineId}/job`),
salesOrderPayment: (id: string) =>
generatePath(`${x}/sales-order/${id}/payment`),
salesOrderRelease: (id: string) =>
diff --git a/packages/database/supabase/migrations/20240924002936_sales-order-jobs.sql b/packages/database/supabase/migrations/20240924002936_sales-order-jobs.sql
new file mode 100644
index 0000000000..2e314bf889
--- /dev/null
+++ b/packages/database/supabase/migrations/20240924002936_sales-order-jobs.sql
@@ -0,0 +1,15 @@
+-- Add index on job table for salesOrderLineId
+CREATE INDEX IF NOT EXISTS idx_job_sales_order_line_id ON "job" ("salesOrderLineId");
+
+
+ALTER TABLE "itemReplenishment"
+DROP CONSTRAINT IF EXISTS "itemReplenishment_pkey";
+
+ALTER TABLE "itemReplenishment"
+ADD CONSTRAINT "itemReplenishment_pkey" PRIMARY KEY ("itemId");
+
+UPDATE "itemReplenishment" SET
+"lotSize" = COALESCE("lotSize", 0);
+
+ALTER TABLE "itemReplenishment"
+ALTER COLUMN "lotSize" SET DEFAULT 0;
\ No newline at end of file
diff --git a/packages/react/src/Table.tsx b/packages/react/src/Table.tsx
index a950f74809..6a17aba554 100644
--- a/packages/react/src/Table.tsx
+++ b/packages/react/src/Table.tsx
@@ -3,8 +3,11 @@ import { forwardRef } from "react";
import { cn } from "./utils/cn";
-const Table = forwardRef<HTMLTableElement, HTMLAttributes<HTMLTableElement>>(
- ({ className, ...props }, ref) => (
+const Table = forwardRef<
+ HTMLTableElement,
+ HTMLAttributes<HTMLTableElement> & { full?: boolean }
+>(({ className, full = false, ...props }, ref) =>
+ full ? (
<div className="w-full">
<table
ref={ref}
@@ -15,6 +18,16 @@ const Table = forwardRef<HTMLTableElement, HTMLAttributes<HTMLTableElement>>(
{...props}
/>
</div>
+ ) : (
+ <div className="rounded-md border overflow-hidden">
+ <div className="relative w-full overflow-auto">
+ <table
+ ref={ref}
+ className={cn("w-full caption-bottom text-sm", className)}
+ {...props}
+ />
+ </div>
+ </div>
)
);
Table.displayName = "Table";
@@ -56,7 +69,7 @@ const Tr = forwardRef<HTMLTableRowElement, HTMLAttributes<HTMLTableRowElement>>(
<tr
ref={ref}
className={cn(
- "group border-b transition-colors data-[state=selected]:bg-muted",
+ "group transition-colors data-[state=selected]:bg-muted",
className
)}
{...props}
@@ -72,7 +85,7 @@ const Th = forwardRef<
<th
ref={ref}
className={cn(
- "group-hover:bg-primary/5 h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-muted-foreground [&:has([role=checkbox])]:pr-0",
+ "group-hover:bg-primary/5 h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
@@ -87,7 +100,7 @@ const Td = forwardRef<
<td
ref={ref}
className={cn(
- "group-hover:bg-primary/5 text-muted-foreground px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",
+ "group-hover:bg-primary/5 text-foreground/80 px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",
className
)}
{...props}