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: quote permissions

Brad Barbin1f450672a0a7
diff --git a/apps/carbon/app/components/Assignee.tsx b/apps/carbon/app/components/Assignee.tsx
index fe47d579c1..44d3cd9c21 100644
--- a/apps/carbon/app/components/Assignee.tsx
+++ b/apps/carbon/app/components/Assignee.tsx
@@ -89,8 +89,10 @@ const Assign = forwardRef<HTMLButtonElement, ComboboxProps>(
)}
role="combobox"
aria-expanded={open}
+ aria-controls="assignee-options"
ref={ref}
onClick={() => setOpen(true)}
+ disabled={isReadOnly}
{...props}
>
{value ? (
@@ -101,7 +103,7 @@ const Assign = forwardRef<HTMLButtonElement, ComboboxProps>(
</button>
</PopoverTrigger>
<PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
- <Command>
+ <Command id="assignee-options">
<CommandInput placeholder="Search..." className="h-9" />
<CommandEmpty>No option found.</CommandEmpty>
<CommandGroup>
diff --git a/apps/carbon/app/modules/items/ui/Item/CadModel.tsx b/apps/carbon/app/modules/items/ui/Item/CadModel.tsx
index e72cf3062b..7ba2d31740 100644
--- a/apps/carbon/app/modules/items/ui/Item/CadModel.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/CadModel.tsx
@@ -19,10 +19,12 @@ type CadModelProps = {
title?: string;
uploadClassName?: string;
viewerClassName?: string;
+ isReadOnly?: boolean;
};
const CadModel = ({
autodeskUrn,
+ isReadOnly,
metadata,
modelPath,
title,
@@ -103,7 +105,7 @@ const CadModel = ({
showDefaultToolbar
urn={autodeskUrn}
/>
- ) : (
+ ) : isReadOnly ? null : (
<CadModelUpload
className={uploadClassName}
file={file}
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx
index c18b55d5ca..1a2db7ff31 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx
@@ -2,7 +2,7 @@ import { File, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { LuUpload } from "react-icons/lu";
-import { useUser } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
@@ -14,6 +14,7 @@ const QuoteDocumentForm = ({ id }: QuoteDocumentFormProps) => {
const submit = useSubmit();
const { company } = useUser();
const { supabase } = useSupabase();
+ const permissions = usePermissions();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase && company) {
@@ -64,7 +65,11 @@ const QuoteDocumentForm = ({ id }: QuoteDocumentFormProps) => {
};
return (
- <File leftIcon={<LuUpload />} onChange={uploadFile}>
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFile}
+ >
New
</File>
);
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index e4b84f4010..974739481a 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -5,11 +5,12 @@ import { LuCheckCheck, LuEye } from "react-icons/lu";
import { RiProgress4Line } from "react-icons/ri";
import { Assignee, useOptimisticAssignment } from "~/components";
-import { useRouteData } from "~/hooks";
+import { usePermissions, useRouteData } from "~/hooks";
import type { Quotation } from "~/modules/sales";
import { path } from "~/utils/path";
const QuoteHeader = () => {
+ const permissions = usePermissions();
const { quoteId } = useParams();
if (!quoteId) throw new Error("quoteId not found");
@@ -38,6 +39,7 @@ const QuoteHeader = () => {
<HStack>
<Assignee
id={quoteId}
+ isReadOnly={!permissions.can("update", "sales")}
table="quote"
value={assignee ?? ""}
className="h-8"
@@ -63,7 +65,12 @@ const QuoteHeader = () => {
<DropdownMenuItem>Export</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu> */}
- <Button leftIcon={<LuCheckCheck />}>Send</Button>
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuCheckCheck />}
+ >
+ Send
+ </Button>
</HStack>
</HStack>
</div>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx
index 29f0e302e7..d4cca85f0c 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx
@@ -1,16 +1,11 @@
-import type { Json } from "@carbon/database";
import {
Badge,
- Button,
Card,
CardContent,
CardHeader,
CardTitle,
Enumerable,
HStack,
- Input,
- NumberField,
- NumberInput,
Table,
Tbody,
Td,
@@ -24,30 +19,24 @@ import {
VStack,
} from "@carbon/react";
import { useLocale } from "@react-aria/i18n";
-import { useFetcher, useParams } from "@remix-run/react";
-import { useCallback, useMemo } from "react";
-import { LuInfo, LuPlus, LuTrash } from "react-icons/lu";
-import type { z } from "zod";
+import { useParams } from "@remix-run/react";
+import { useMemo } from "react";
+import { LuInfo } from "react-icons/lu";
import { MethodItemTypeIcon } from "~/modules/shared";
-import { path } from "~/utils/path";
-import { quoteLineAdditionalChargesValidator } from "../../sales.models";
import type { Costs } from "../../types";
const QuoteLineCosting = ({
quantities,
- additionalCharges: additionalChargesJson,
getLineCosts,
}: {
quantities: number[];
- additionalCharges?: Json;
+
getLineCosts: (quantity: number) => Costs;
}) => {
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
- const fetcher = useFetcher<{ id: string }>();
-
const quantityCosts = quantities.map((quantity) => ({
quantity,
costs: getLineCosts(quantity),
@@ -60,77 +49,6 @@ const QuoteLineCosting = ({
[locale]
);
- const additionalCharges = useMemo(() => {
- if (fetcher.formAction === path.to.quoteLineCost(quoteId, lineId)) {
- // get the optimistic update
- return JSON.parse(
- (fetcher.formData?.get("additionalCharges") as string) ?? "{}"
- ) as z.infer<typeof quoteLineAdditionalChargesValidator>;
- }
- const parsedAdditionalCharges =
- quoteLineAdditionalChargesValidator.safeParse(additionalChargesJson);
-
- return parsedAdditionalCharges.success ? parsedAdditionalCharges.data : {};
- }, [
- additionalChargesJson,
- fetcher.formAction,
- fetcher.formData,
- lineId,
- quoteId,
- ]);
-
- const additionalChargesByQuantity = quantities.map((quantity) => {
- const charges = Object.values(additionalCharges).reduce((acc, charge) => {
- const amount = charge.amounts?.[quantity] ?? 0;
- return acc + amount;
- }, 0);
- return charges;
- });
-
- const onUpdateChargeDescription = useCallback(
- (chargeId: string, description: string) => {
- const updatedCharges = {
- ...additionalCharges,
- [chargeId]: {
- ...additionalCharges[chargeId],
- description,
- },
- };
-
- const formData = new FormData();
-
- formData.set("additionalCharges", JSON.stringify(updatedCharges));
- fetcher.submit(formData, {
- method: "post",
- action: path.to.quoteLineCost(quoteId, lineId),
- });
- },
- [additionalCharges, fetcher, lineId, quoteId]
- );
-
- const onUpdateChargeAmount = useCallback(
- (chargeId: string, quantity: number, amount: number) => {
- const updatedCharges = {
- ...additionalCharges,
- [chargeId]: {
- ...additionalCharges[chargeId],
- amounts: {
- ...additionalCharges[chargeId].amounts,
- [quantity]: amount,
- },
- },
- };
-
- const formData = new FormData();
- formData.set("additionalCharges", JSON.stringify(updatedCharges));
- fetcher.submit(formData, {
- method: "post",
- action: path.to.quoteLineCost(quoteId, lineId),
- });
- },
- [additionalCharges, fetcher, lineId, quoteId]
- );
-
return (
<Card>
<CardHeader>
@@ -147,8 +65,8 @@ const QuoteLineCosting = ({
</Tr>
</Thead>
<Tbody>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border ">
<HStack className="w-full justify-between ">
<span>Total Material Cost</span>
<Enumerable value="Material" />
@@ -164,10 +82,7 @@ const QuoteLineCosting = ({
costs.serviceCost;
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{totalMaterialCost
@@ -184,8 +99,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border pl-10 group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border pl-10 ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap flex items-center justify-start gap-2">
Part Cost{" "}
@@ -205,10 +120,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.partCost
@@ -225,8 +137,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border pl-10 group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border pl-10 ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap">Material Cost</span>
<Badge variant="secondary">
@@ -236,10 +148,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.materialCost
@@ -256,8 +165,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border pl-10 group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border pl-10 ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap">Tooling Cost</span>
<Badge variant="secondary">
@@ -267,10 +176,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.toolCost
@@ -287,8 +193,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border pl-10 group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border pl-10 ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap">Fixture Cost</span>
<Badge variant="secondary">
@@ -298,10 +204,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.fixtureCost
@@ -318,8 +221,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border pl-10 group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border pl-10 ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap">Consumable Cost</span>
<Badge variant="secondary">
@@ -329,10 +232,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.consumableCost
@@ -349,8 +249,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border pl-10 group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border pl-10 ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap">Service Cost</span>
<Badge variant="secondary">
@@ -360,10 +260,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.serviceCost
@@ -380,8 +277,8 @@ const QuoteLineCosting = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border group-hover:bg-muted/50">
+ <Tr>
+ <Td className="border-r border-border ">
<HStack className="w-full justify-between ">
<span className="whitespace-nowrap">
Total Labor &amp; Overhead
@@ -391,10 +288,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{costs.overheadCost
@@ -416,7 +310,7 @@ const QuoteLineCosting = ({
})}
</Tr>
{/* <Tr>
- <Td className="border-r border-border group-hover:bg-muted/50">
+ <Td className="border-r border-border ">
<HStack className="w-full justify-between ">
<span>Total Outside Processing</span>
<Enumerable value="Subcontract" />
@@ -424,7 +318,7 @@ const QuoteLineCosting = ({
</Td>
{quantityCosts.map(({ quantity, costs }) => {
return (
- <Td key={quantity.toString()} className="group-hover:bg-muted/50" >
+ <Td key={quantity.toString()} >
<VStack spacing={0}>
<span>
{costs.outsideCost
@@ -441,130 +335,15 @@ const QuoteLineCosting = ({
);
})}
</Tr> */}
- {Object.entries(additionalCharges).map(([chargeId, charge]) => {
- const isDeleting =
- fetcher.state === "loading" &&
- fetcher.formAction ===
- path.to.deleteQuoteLineCost(quoteId, lineId) &&
- fetcher.formData?.get("id") === chargeId;
- return (
- <Tr key={chargeId}>
- <Td className="border-r border-border">
- <HStack className="w-full justify-between ">
- <Input
- defaultValue={charge.description}
- size="sm"
- className="border-0 -ml-3 shadow-none"
- onBlur={(e) => {
- if (
- e.target.value &&
- e.target.value !== charge.description
- ) {
- onUpdateChargeDescription(chargeId, e.target.value);
- }
- }}
- />
- <HStack spacing={1}>
- <fetcher.Form
- method="post"
- action={path.to.deleteQuoteLineCost(quoteId, lineId)}
- >
- <input type="hidden" name="id" value={chargeId} />
- <input
- type="hidden"
- name="additionalCharges"
- value={JSON.stringify(additionalCharges ?? {})}
- />
- <Button
- type="submit"
- aria-label="Delete"
- size="sm"
- variant="secondary"
- isDisabled={isDeleting}
- isLoading={isDeleting}
- >
- <LuTrash className="w-3 h-3" />
- </Button>
- </fetcher.Form>
- <Enumerable value="Extra" />
- </HStack>
- </HStack>
- </Td>
- {quantityCosts.map(({ quantity }) => {
- const amount = charge.amounts?.[quantity] ?? 0;
- return (
- <Td key={quantity.toString()}>
- <VStack spacing={0}>
- <NumberField
- defaultValue={amount}
- formatOptions={{
- style: "currency",
- currency: "USD",
- }}
- onChange={(value) => {
- if (value && value !== amount) {
- onUpdateChargeAmount(chargeId, quantity, value);
- }
- }}
- >
- <NumberInput
- className="border-0 -ml-3 shadow-none"
- size="sm"
- min={0}
- />
- </NumberField>
- </VStack>
- </Td>
- );
- })}
- </Tr>
- );
- })}
- <Tr>
- <Td className="border-r border-border">
- <HStack className="w-full justify-between ">
- <fetcher.Form
- method="post"
- action={path.to.newQuoteLineCost(quoteId, lineId)}
- >
- <input
- type="hidden"
- name="additionalCharges"
- value={JSON.stringify(additionalCharges ?? {})}
- />
- <Button
- className="-ml-3"
- type="submit"
- rightIcon={<LuPlus />}
- variant="ghost"
- isLoading={
- fetcher.formAction ===
- path.to.newQuoteLineCost(quoteId, lineId) &&
- fetcher.state === "loading"
- }
- isDisabled={
- fetcher.formAction ===
- path.to.newQuoteLineCost(quoteId, lineId) &&
- fetcher.state === "loading"
- }
- >
- Add
- </Button>
- </fetcher.Form>
- </HStack>
- </Td>
- {quantityCosts.map(({ quantity }) => {
- return <Td key={quantity.toString()}></Td>;
- })}
- </Tr>
- <Tr className="font-bold [&>td]:bg-muted/60">
- <Td className="border-r border-border group-hover:bg-muted/50">
+
+ <Tr className="font-bold ">
+ <Td className="border-r border-border ">
<HStack className="w-full justify-between ">
<span>Total Estimated Cost</span>
<Enumerable value="Total" />
</HStack>
</Td>
- {quantityCosts.map(({ quantity, costs }, index) => {
+ {quantityCosts.map(({ quantity, costs }) => {
const totalCost =
costs.materialCost +
costs.partCost +
@@ -574,13 +353,9 @@ const QuoteLineCosting = ({
costs.serviceCost +
costs.laborCost +
costs.overheadCost +
- costs.outsideCost +
- additionalChargesByQuantity[index];
+ costs.outsideCost;
return (
- <Td
- key={quantity.toString()}
- className="group-hover:bg-muted/50"
- >
+ <Td key={quantity.toString()}>
<VStack spacing={0}>
<span>
{totalCost
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx
index 4d3466efbe..01761a75fe 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx
@@ -49,6 +49,7 @@ const useQuoteLineDocuments = ({
const { company } = useUser();
const canDelete = permissions.can("delete", "sales");
+ const canUpdate = permissions.can("update", "sales");
const getPath = useCallback(
(file: ItemFile) => {
return `${company.id}/quote-line/${quoteLineId}/${file.name}`;
@@ -130,6 +131,7 @@ const useQuoteLineDocuments = ({
return {
canDelete,
+ canUpdate,
deleteFile,
deleteModel,
download,
@@ -313,6 +315,7 @@ const QuoteLineDocumentForm = ({
const submit = useSubmit();
const { company } = useUser();
const { supabase } = useSupabase();
+ const permissions = usePermissions();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase && company) {
@@ -363,7 +366,11 @@ const QuoteLineDocumentForm = ({
};
return (
- <File leftIcon={<LuUpload />} onChange={uploadFile}>
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFile}
+ >
New
</File>
);
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index af4a1608c7..ff19a64bc1 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -148,7 +148,7 @@ const QuoteLineForm = ({
: "A quote line contains pricing and lead times for a particular part"}
</ModalCardDescription>
</ModalCardHeader>
- {isEditing && (
+ {isEditing && permissions.can("update", "sales") && (
<CardAction>
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index 1b80f7aa66..ecd382862c 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -6,11 +6,13 @@ import {
CardContent,
CardHeader,
CardTitle,
+ cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
HStack,
+ Input,
NumberField,
NumberInput,
Table,
@@ -26,10 +28,16 @@ import {
} from "@carbon/react";
import { useLocale } from "@react-aria/i18n";
import { useFetcher, useParams } from "@remix-run/react";
-import { useEffect, useMemo, useState } from "react";
-import { LuChevronDown, LuInfo, LuRefreshCcw } from "react-icons/lu";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ LuChevronDown,
+ LuInfo,
+ LuPlus,
+ LuRefreshCcw,
+ LuTrash,
+} from "react-icons/lu";
import type { z } from "zod";
-import { useUser } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
import { quoteLineAdditionalChargesValidator } from "../../sales.models";
@@ -46,6 +54,9 @@ const QuoteLinePricing = ({
pricesByQuantity: Record<number, QuotationPrice>;
getLineCosts: (quantity: number) => Costs;
}) => {
+ const permissions = usePermissions();
+ const canEdit = permissions.can("update", "sales");
+
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
@@ -93,6 +104,50 @@ const QuoteLinePricing = ({
return charges;
});
+ const onUpdateChargeDescription = useCallback(
+ (chargeId: string, description: string) => {
+ const updatedCharges = {
+ ...additionalCharges,
+ [chargeId]: {
+ ...additionalCharges[chargeId],
+ description,
+ },
+ };
+
+ const formData = new FormData();
+
+ formData.set("additionalCharges", JSON.stringify(updatedCharges));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.quoteLineCost(quoteId, lineId),
+ });
+ },
+ [additionalCharges, fetcher, lineId, quoteId]
+ );
+
+ const onUpdateChargeAmount = useCallback(
+ (chargeId: string, quantity: number, amount: number) => {
+ const updatedCharges = {
+ ...additionalCharges,
+ [chargeId]: {
+ ...additionalCharges[chargeId],
+ amounts: {
+ ...additionalCharges[chargeId].amounts,
+ [quantity]: amount,
+ },
+ },
+ };
+
+ const formData = new FormData();
+ formData.set("additionalCharges", JSON.stringify(updatedCharges));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.quoteLineCost(quoteId, lineId),
+ });
+ },
+ [additionalCharges, fetcher, lineId, quoteId]
+ );
+
const unitCostsByQuantity = quantities.map((quantity, index) => {
const costs = getLineCosts(quantity);
const totalCost =
@@ -104,8 +159,7 @@ const QuoteLinePricing = ({
costs.serviceCost +
costs.laborCost +
costs.overheadCost +
- costs.outsideCost +
- additionalChargesByQuantity[index]) /
+ costs.outsideCost) /
quantity;
return totalCost;
});
@@ -128,7 +182,7 @@ const QuoteLinePricing = ({
});
};
- const onUpdate = async (
+ const onUpdatePrice = async (
key: "leadTime" | "unitPrice" | "discountPercent",
quantity: number,
value: number
@@ -179,46 +233,48 @@ const QuoteLinePricing = ({
<CardHeader>
<CardTitle>Pricing</CardTitle>
</CardHeader>
- <CardAction>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="secondary"
- leftIcon={<LuRefreshCcw />}
- rightIcon={<LuChevronDown />}
- isLoading={
- fetcher.state === "loading" &&
- fetcher.formAction ===
- path.to.quoteLineRecalculatePrice(quoteId, lineId)
- }
- isDisabled={
- fetcher.state === "loading" &&
- fetcher.formAction ===
- path.to.quoteLineRecalculatePrice(quoteId, lineId)
- }
- >
- Recalculate
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => onRecalculate(0)}>
- 0% Markup
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onRecalculate(10)}>
- 10% Markup
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onRecalculate(15)}>
- 15% Markup
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onRecalculate(20)}>
- 20% Markup
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onRecalculate(30)}>
- 30% Markup
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </CardAction>
+ {permissions.can("update", "sales") && (
+ <CardAction>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ leftIcon={<LuRefreshCcw />}
+ rightIcon={<LuChevronDown />}
+ isLoading={
+ fetcher.state === "loading" &&
+ fetcher.formAction ===
+ path.to.quoteLineRecalculatePrice(quoteId, lineId)
+ }
+ isDisabled={
+ fetcher.state === "loading" &&
+ fetcher.formAction ===
+ path.to.quoteLineRecalculatePrice(quoteId, lineId)
+ }
+ >
+ Recalculate
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => onRecalculate(0)}>
+ 0% Markup
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onRecalculate(10)}>
+ 10% Markup
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onRecalculate(15)}>
+ 15% Markup
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onRecalculate(20)}>
+ 20% Markup
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onRecalculate(30)}>
+ 30% Markup
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ )}
</HStack>
<CardContent>
<Table>
@@ -252,15 +308,15 @@ const QuoteLinePricing = ({
unitDisplay: "long",
}}
minValue={0}
- isDisabled
onChange={(value) => {
if (Number.isFinite(value) && value !== leadTime) {
- onUpdate("leadTime", quantity, value);
+ onUpdatePrice("leadTime", quantity, value);
}
}}
>
<NumberInput
- className="border-0 -ml-3 shadow-none"
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!canEdit}
size="sm"
min={0}
/>
@@ -304,12 +360,13 @@ const QuoteLinePricing = ({
minValue={0}
onChange={(value) => {
if (Number.isFinite(value) && value !== price) {
- onUpdate("unitPrice", quantity, value);
+ onUpdatePrice("unitPrice", quantity, value);
}
}}
>
<NumberInput
- className="border-0 -ml-3 shadow-none"
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!canEdit}
size="sm"
min={0}
/>
@@ -318,7 +375,54 @@ const QuoteLinePricing = ({
);
})}
</Tr>
+ <Tr>
+ <Td className="border-r border-border">
+ <HStack className="w-full justify-between ">
+ <span className="flex items-center justify-start gap-2">
+ Markup Percent
+ <Tooltip>
+ <TooltipTrigger>
+ <LuInfo className="w-4 h-4" />
+ </TooltipTrigger>
+ <TooltipContent>(Price - Cost) / Cost</TooltipContent>
+ </Tooltip>
+ </span>
+ </HStack>
+ </Td>
+ {quantities.map((quantity, index) => {
+ const price = prices[quantity]?.unitPrice ?? 0;
+ const cost = unitCostsByQuantity[index];
+
+ const markup = price ? (price - cost) / cost : 0;
+ return (
+ <Td key={quantity.toString()}>
+ <NumberField
+ value={markup}
+ formatOptions={{
+ style: "percent",
+ }}
+ onChange={(value) => {
+ if (Number.isFinite(value) && value !== price) {
+ onUpdatePrice(
+ "unitPrice",
+ quantity,
+ cost * (1 + value)
+ );
+ }
+ }}
+ >
+ <NumberInput
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!canEdit}
+ size="sm"
+ min={0}
+ />
+ </NumberField>
+ </Td>
+ );
+ })}
+ </Tr>
<Tr>
<Td className="border-r border-border">
<HStack className="w-full justify-between ">
@@ -334,18 +438,18 @@ const QuoteLinePricing = ({
value={discount}
formatOptions={{
style: "percent",
- currency: "USD",
}}
minValue={0}
maxValue={1}
onChange={(value) => {
if (Number.isFinite(value) && value !== discount) {
- onUpdate("discountPercent", quantity, value);
+ onUpdatePrice("discountPercent", quantity, value);
}
}}
>
<NumberInput
- className="border-0 -ml-3 shadow-none"
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!canEdit}
size="sm"
/>
</NumberField>
@@ -369,36 +473,7 @@ const QuoteLinePricing = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border group-hover:bg-muted/50">
- <HStack className="w-full justify-between ">
- <span className="flex items-center justify-start gap-2">
- Markup Percent
- <Tooltip>
- <TooltipTrigger>
- <LuInfo className="w-4 h-4" />
- </TooltipTrigger>
- <TooltipContent>(Price - Cost) / Cost</TooltipContent>
- </Tooltip>
- </span>
- </HStack>
- </Td>
- {netPricesByQuantity.map((price, index) => {
- const cost = unitCostsByQuantity[index];
- const markup = ((price - cost) / cost) * 100;
- return (
- <Td key={index} className="group-hover:bg-muted/50">
- <VStack spacing={0}>
- {Number.isFinite(markup) ? (
- <span>{(markup ?? 0).toFixed(2)}%</span>
- ) : (
- <span>-</span>
- )}
- </VStack>
- </Td>
- );
- })}
- </Tr>
+
<Tr className="[&>td]:bg-muted/60">
<Td className="border-r border-border group-hover:bg-muted/50">
<HStack className="w-full justify-between ">
@@ -420,7 +495,9 @@ const QuoteLinePricing = ({
<Td key={index} className="group-hover:bg-muted/50">
<VStack spacing={0}>
{Number.isFinite(profit) ? (
- <span>{profit.toFixed(2)}%</span>
+ <span className={cn(profit < -0.01 && "text-red-500")}>
+ {profit.toFixed(2)}%
+ </span>
) : (
<span>-</span>
)}
@@ -443,12 +520,155 @@ const QuoteLinePricing = ({
return (
<Td key={index} className="group-hover:bg-muted/50">
<VStack spacing={0}>
- <span>{formatter.format(profit)}</span>
+ {price ? (
+ <span className={cn(profit < -0.01 && "text-red-500")}>
+ {formatter.format(profit)}
+ </span>
+ ) : (
+ <span>-</span>
+ )}
</VStack>
</Td>
);
})}
</Tr>
+ {Object.entries(additionalCharges)
+ .sort((a, b) => {
+ return a[1].description.localeCompare(b[1].description);
+ })
+ .map(([chargeId, charge]) => {
+ const isDeleting =
+ fetcher.state === "loading" &&
+ fetcher.formAction ===
+ path.to.deleteQuoteLineCost(quoteId, lineId) &&
+ fetcher.formData?.get("id") === chargeId;
+ return (
+ <Tr key={chargeId}>
+ <Td className="border-r border-border">
+ <HStack className="w-full justify-between ">
+ <Input
+ defaultValue={charge.description}
+ size="sm"
+ className="border-0 -ml-3 shadow-none"
+ onBlur={(e) => {
+ if (
+ e.target.value &&
+ e.target.value !== charge.description
+ ) {
+ onUpdateChargeDescription(
+ chargeId,
+ e.target.value
+ );
+ }
+ }}
+ />
+ <HStack spacing={1}>
+ <fetcher.Form
+ method="post"
+ action={path.to.deleteQuoteLineCost(
+ quoteId,
+ lineId
+ )}
+ >
+ <input type="hidden" name="id" value={chargeId} />
+ <input
+ type="hidden"
+ name="additionalCharges"
+ value={JSON.stringify(additionalCharges ?? {})}
+ />
+ <Button
+ type="submit"
+ aria-label="Delete"
+ size="sm"
+ variant="secondary"
+ isDisabled={
+ !permissions.can("update", "sales") ||
+ isDeleting
+ }
+ isLoading={isDeleting}
+ >
+ <LuTrash className="w-3 h-3" />
+ </Button>
+ </fetcher.Form>
+ </HStack>
+ </HStack>
+ </Td>
+ {quantities.map((quantity) => {
+ const amount = charge.amounts?.[quantity] ?? 0;
+ return (
+ <Td key={quantity.toString()}>
+ <VStack spacing={0}>
+ <NumberField
+ defaultValue={amount}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(value) => {
+ if (
+ Number.isFinite(value) &&
+ value !== amount
+ ) {
+ onUpdateChargeAmount(
+ chargeId,
+ quantity,
+ value
+ );
+ }
+ }}
+ >
+ <NumberInput
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ size="sm"
+ isDisabled={!canEdit}
+ min={0}
+ />
+ </NumberField>
+ </VStack>
+ </Td>
+ );
+ })}
+ </Tr>
+ );
+ })}
+ <Tr>
+ <Td className="border-r border-border">
+ <HStack className="w-full justify-between ">
+ <fetcher.Form
+ method="post"
+ action={path.to.newQuoteLineCost(quoteId, lineId)}
+ >
+ <input
+ type="hidden"
+ name="additionalCharges"
+ value={JSON.stringify(additionalCharges ?? {})}
+ />
+ <Button
+ className="-ml-3"
+ type="submit"
+ rightIcon={<LuPlus />}
+ variant="ghost"
+ isLoading={
+ fetcher.formAction ===
+ path.to.newQuoteLineCost(quoteId, lineId) &&
+ fetcher.state === "loading"
+ }
+ isDisabled={
+ !canEdit ||
+ (fetcher.formAction ===
+ path.to.newQuoteLineCost(quoteId, lineId) &&
+ fetcher.state === "loading")
+ }
+ >
+ Add
+ </Button>
+ </fetcher.Form>
+ </HStack>
+ </Td>
+ {quantities.map((quantity) => {
+ return <Td key={quantity.toString()}></Td>;
+ })}
+ </Tr>
<Tr className="font-bold [&>td]:bg-muted/60">
<Td className="border-r border-border group-hover:bg-muted/50">
<HStack className="w-full justify-between ">
@@ -456,11 +676,13 @@ const QuoteLinePricing = ({
</HStack>
</Td>
{quantities.map((quantity, index) => {
- const price = netPricesByQuantity[index];
+ const price =
+ netPricesByQuantity[index] * quantity +
+ additionalChargesByQuantity[index];
return (
<Td key={index} className="group-hover:bg-muted/50">
<VStack spacing={0}>
- <span>{formatter.format(price * quantity)}</span>
+ <span>{formatter.format(price)}</span>
</VStack>
</Td>
);
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx
index 150a856fd9..52a8d59375 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx
@@ -44,6 +44,7 @@ const useSalesRFQLineDocuments = ({
const { company } = useUser();
const canDelete = permissions.can("delete", "sales");
+ const canUpdate = permissions.can("update", "sales");
const getPath = useCallback(
(file: ItemFile) => {
return `${company.id}/sales-rfq/${rfqId}/${salesRfqLineId}/${file.name}`;
@@ -125,6 +126,7 @@ const useSalesRFQLineDocuments = ({
return {
canDelete,
+ canUpdate,
deleteFile,
deleteModel,
download,
@@ -302,6 +304,7 @@ const SalesRFQLineDocumentForm = ({
const submit = useSubmit();
const { company } = useUser();
const { supabase } = useSupabase();
+ const permissions = usePermissions();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase && company) {
@@ -352,7 +355,11 @@ const SalesRFQLineDocumentForm = ({
};
return (
- <File leftIcon={<LuUpload />} onChange={uploadFile}>
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFile}
+ >
New
</File>
);
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
index df27d4dc56..0cf68ef684 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
@@ -12,6 +12,7 @@ import {
HStack,
VStack,
cn,
+ generateHTML,
toast,
useDebounce,
useMount,
@@ -41,7 +42,7 @@ import type {
SortableItemRenderProps,
} from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
-import { useUser } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type { ModelUpload } from "~/modules/items";
import { CadModel } from "~/modules/items";
@@ -147,6 +148,7 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
const fetcher = useFetcher<{}>();
const { supabase } = useSupabase();
+ const permissions = usePermissions();
const {
company: { id: companyId },
id: userId,
@@ -163,11 +165,13 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
}, [files]);
const onToggleItem = (id: string) => {
- setItems((prevItems) =>
- prevItems.map((item) =>
- item.id === id ? { ...item, checked: !item.checked } : item
- )
- );
+ if (permissions.can("delete", "sales")) {
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === id ? { ...item, checked: !item.checked } : item
+ )
+ );
+ }
};
useMount(() => {
@@ -378,6 +382,7 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
>
<CadModel
autodeskUrn={item.data.autodeskUrn ?? null}
+ isReadOnly={!permissions.can("update", "sales")}
metadata={{
salesRfqLineId: item.id,
}}
@@ -430,12 +435,23 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
delay: 0.15,
}}
>
- <Editor
- className="min-h-[300px]"
- initialValue={item.data.internalNotes}
- onUpload={onUploadImage}
- onChange={onUpdateInternalNotes}
- />
+ {permissions.can("update", "sales") ? (
+ <Editor
+ className="min-h-[300px]"
+ initialValue={item.data.internalNotes}
+ onUpload={onUploadImage}
+ onChange={onUpdateInternalNotes}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert py-4"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ item.data.internalNotes as JSONContent
+ ),
+ }}
+ />
+ )}
</motion.div>
</div>
),
@@ -456,12 +472,23 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
delay: 0.15,
}}
>
- <Editor
- className="min-h-[300px]"
- initialValue={item.data.externalNotes ?? ({} as JSONContent)}
- onUpload={onUploadImage}
- onChange={onUpdateExternalNotes}
- />
+ {permissions.can("update", "sales") ? (
+ <Editor
+ className="min-h-[300px]"
+ initialValue={item.data.externalNotes}
+ onUpload={onUploadImage}
+ onChange={onUpdateExternalNotes}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert py-4"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ item.data.externalNotes as JSONContent
+ ),
+ }}
+ />
+ )}
</motion.div>
</div>
),
@@ -589,7 +616,9 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
<CardAction>
<Button
variant="secondary"
- isDisabled={selectedLineId !== null}
+ isDisabled={
+ !permissions.can("update", "sales") || selectedLineId !== null
+ }
onClick={onAddItem}
>
Add Line
@@ -622,6 +651,7 @@ function SalesRFQLineForm({
}) {
const { supabase } = useSupabase();
const salesRfqLineFetcher = useFetcher<{ id: string }>();
+ const permissions = usePermissions();
const { company } = useUser();
@@ -770,7 +800,7 @@ function SalesRFQLineForm({
}}
>
<motion.div layout className="ml-auto mr-1 pt-2">
- <Submit>Save</Submit>
+ <Submit disabled={!permissions.can("update", "sales")}>Save</Submit>
</motion.div>
</motion.div>
</VStack>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
index 9f664c59bf..d60950d85f 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
@@ -17,7 +17,7 @@ import {
CustomerAvatar,
useOptimisticAssignment,
} from "~/components";
-import { useRouteData } from "~/hooks";
+import { usePermissions, useRouteData } from "~/hooks";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import type { SalesRFQ } from "../../types";
@@ -27,6 +27,7 @@ const SalesRFQProperties = () => {
const { rfqId } = useParams();
if (!rfqId) throw new Error("rfqId not found");
+ const permissions = usePermissions();
const sharedData = useRouteData<{ locations: ListItem[] }>(
path.to.salesRfqRoot
);
@@ -112,7 +113,12 @@ const SalesRFQProperties = () => {
<VStack spacing={2}>
<h3 className="text-xs text-muted-foreground">Assignee</h3>
- <Assignee id={rfqId} table="salesRfq" value={assignee ?? ""} />
+ <Assignee
+ id={rfqId}
+ isReadOnly={!permissions.can("update", "sales")}
+ table="salesRfq"
+ value={assignee ?? ""}
+ />
</VStack>
<VStack spacing={2}>
diff --git a/apps/carbon/app/modules/shared/shared.service.ts b/apps/carbon/app/modules/shared/shared.service.ts
index d0400b88ba..6eb402ae80 100644
--- a/apps/carbon/app/modules/shared/shared.service.ts
+++ b/apps/carbon/app/modules/shared/shared.service.ts
@@ -8,6 +8,25 @@ export async function deleteNote(
return client.from("note").update({ active: false }).eq("id", noteId);
}
+export async function getBase64ImageFromSupabase(
+ client: SupabaseClient<Database>,
+ path: string
+) {
+ function arrayBufferToBase64(buffer: ArrayBuffer): string {
+ const binary = String.fromCharCode(...new Uint8Array(buffer));
+ return btoa(binary);
+ }
+
+ const { data, error } = await client.storage.from("private").download(path);
+ if (error) {
+ return null;
+ }
+
+ const arrayBuffer = await data.arrayBuffer();
+ const base64String = arrayBufferToBase64(arrayBuffer);
+ return `data:image/png;base64,${base64String}`;
+}
+
export async function getNotes(
client: SupabaseClient<Database>,
documentId: string
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index d0a00de103..71c0c5021c 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -853,6 +853,7 @@ export async function updatePermissions(
? {}
: claims.data
) as Record<string, string[]>;
+ delete updatedPermissions["role"];
// add any missing claims to the current claims
Object.keys(permissions).forEach((name) => {
diff --git a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
index 5cfa613810..155f6a131b 100644
--- a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
@@ -9,6 +9,7 @@ import {
getQuoteLines,
} from "~/modules/sales";
import { getCompany } from "~/modules/settings";
+import { getBase64ImageFromSupabase } from "~/modules/shared";
import { requirePermissions } from "~/services/auth/auth.server";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -52,6 +53,37 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Failed to load quote");
}
+ const thumbnailPaths = quoteLines.data?.reduce<Record<string, string | null>>(
+ (acc, line) => {
+ if (line.thumbnailPath) {
+ acc[line.id!] = line.thumbnailPath;
+ }
+ return acc;
+ },
+ {}
+ );
+
+ const thumbnails: Record<string, string | null> =
+ (thumbnailPaths
+ ? await Promise.all(
+ Object.entries(thumbnailPaths).map(([id, path]) => {
+ if (!path) {
+ return null;
+ }
+ return getBase64ImageFromSupabase(client, path).then((data) => ({
+ id,
+ data,
+ }));
+ })
+ )
+ : []
+ )?.reduce<Record<string, string | null>>((acc, thumbnail) => {
+ if (thumbnail) {
+ acc[thumbnail.id] = thumbnail.data;
+ }
+ return acc;
+ }, {}) ?? {};
+
const stream = await renderToStream(
<QuotePDF
company={company.data}
@@ -59,6 +91,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
quoteLines={quoteLines.data ?? []}
quoteLinePrices={quoteLinePrices.data ?? []}
quoteCustomerDetails={quoteLocations.data}
+ thumbnails={thumbnails}
/>
);
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.details.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.details.tsx
index d4cedea082..a6aa41cf1f 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.details.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.details.tsx
@@ -95,6 +95,7 @@ export default function FixtureDetailsRoute() {
<div className="grid grid-cols-1 md:grid-cols-2 w-full flex-grow gap-2">
<CadModel
autodeskUrn={fixtureData?.fixtureSummary?.autodeskUrn ?? null}
+ isReadOnly={!permissions.can("update", "items")}
metadata={{
itemId,
}}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.details.tsx b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
index 483b83c64a..e9364382c6 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
@@ -86,6 +86,7 @@ export default function PartDetailsRoute() {
<div className="grid grid-cols-1 md:grid-cols-2 w-full flex-grow gap-2">
<CadModel
autodeskUrn={partData?.partSummary?.autodeskUrn ?? null}
+ isReadOnly={!permissions.can("update", "items")}
metadata={{ itemId }}
modelPath={partData?.partSummary?.modelPath ?? null}
title="CAD Model"
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index 1659488e8d..d45b5e2834 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -155,6 +155,7 @@ export default function QuoteLine() {
<div className="grid grid-cols-1 xl:grid-cols-2 w-full flex-grow gap-2 ">
<CadModel
autodeskUrn={line?.autodeskUrn ?? null}
+ isReadOnly={!permissions.can("update", "sales")}
metadata={{ quoteLineId: line.id ?? undefined }}
modelPath={line?.modelPath ?? null}
title="CAD Model"
@@ -172,7 +173,6 @@ export default function QuoteLine() {
{line.methodType === "Make" && (
<QuoteLineCosting
quantities={line.quantity ?? [1]}
- additionalCharges={line.additionalCharges ?? {}}
getLineCosts={getLineCosts}
/>
)}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
index 9abdfa86d2..a556ebbf73 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
@@ -5,6 +5,7 @@ import {
CardHeader,
CardTitle,
Editor,
+ generateHTML,
toast,
useDebounce,
} from "@carbon/react";
@@ -14,7 +15,7 @@ import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
-import { useRouteData, useUser } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type { Quotation } from "~/modules/sales";
import {
@@ -108,6 +109,7 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
company: { id: companyId },
} = useUser();
const { supabase } = useSupabase();
+ const permissions = usePermissions();
const onUploadImage = async (file: File) => {
const fileName = `${companyId}/quote/${quote.id}/${encodeURIComponent(
@@ -129,9 +131,9 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
return `/file/preview/private/${result.data.path}`;
};
- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {
+ const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {
await supabase
- ?.from("quoteLine")
+ ?.from("quote")
.update({
notes: content,
updatedAt: today(getLocalTimeZone()).toString(),
@@ -146,11 +148,20 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
<CardTitle>External Notes</CardTitle>
</CardHeader>
<CardContent>
- <Editor
- initialValue={(quote.notes ?? {}) as JSONContent}
- onUpload={onUploadImage}
- onChange={onUpdateInternalNotes}
- />
+ {permissions.can("update", "sales") ? (
+ <Editor
+ initialValue={(quote.notes ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={onUpdateExternalNotes}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(quote.notes as JSONContent),
+ }}
+ />
+ )}
</CardContent>
</Card>
);
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
index 9ec33afbec..b41c91dd85 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
@@ -8,23 +8,34 @@ import {
DropdownMenuTrigger,
HStack,
IconButton,
+ Kbd,
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
ScrollArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
useDisclosure,
+ useKeyboardShortcuts,
useMount,
VStack,
} from "@carbon/react";
+import { prettifyKeyboardShortcut } from "@carbon/utils";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useNavigate, useParams } from "@remix-run/react";
-import { useState } from "react";
+import { useRef, useState } from "react";
import { LuChevronsUpDown, LuGhost, LuImage, LuPlus } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import type { Tree } from "~/components/TreeView";
import { flattenTree } from "~/components/TreeView";
-import { useOptimisticLocation, useRouteData, useUser } from "~/hooks";
+import {
+ useOptimisticLocation,
+ usePermissions,
+ useRouteData,
+ useUser,
+} from "~/hooks";
import type { QuotationLine, QuoteMethod } from "~/modules/sales";
import {
DeleteQuoteLine,
@@ -130,7 +141,7 @@ function QuoteExplorer() {
const quoteData = useRouteData<{ lines: QuotationLine[] }>(
path.to.quote(quoteId)
);
-
+ const permissions = usePermissions();
const { id: userId } = useUser();
const quoteLineInitialValues = {
quoteId,
@@ -158,6 +169,14 @@ function QuoteExplorer() {
deleteLineDisclosure.onClose();
};
+ const newButtonRef = useRef<HTMLButtonElement>(null);
+ useKeyboardShortcuts({
+ "Command+Shift+l": (event: KeyboardEvent) => {
+ event.stopPropagation();
+ newButtonRef.current?.click();
+ },
+ });
+
return (
<>
<VStack className="w-full h-[calc(100vh-99px)] justify-between">
@@ -175,13 +194,25 @@ function QuoteExplorer() {
)}
</VStack>
<div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Button
- className="w-full"
- leftIcon={<LuPlus />}
- onClick={newQuoteLineDisclosure.onOpen}
- >
- Add Line Item
- </Button>
+ <Tooltip>
+ <TooltipTrigger className="w-full">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuPlus />}
+ onClick={newQuoteLineDisclosure.onOpen}
+ >
+ Add Line Item
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>New Line Item</span>
+ <Kbd>{prettifyKeyboardShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
</div>
</VStack>
{newQuoteLineDisclosure.isOpen && (
@@ -199,13 +230,16 @@ function QuoteExplorer() {
}
function EmptyQuote({ onAdd }: { onAdd: () => void }) {
+ const permissions = usePermissions();
return (
<VStack className="w-full h-full justify-center items-center">
<LuGhost className="w-12 h-12" />
<h3 className="text-base">Pretty empty around here</h3>
- <Button leftIcon={<LuPlus />} onClick={onAdd}>
- Add Line Item
- </Button>
+ {permissions.can("update", "sales") && (
+ <Button leftIcon={<LuPlus />} onClick={onAdd}>
+ Add Line Item
+ </Button>
+ )}
</VStack>
);
}
@@ -218,7 +252,7 @@ type QuoteLineItemProps = {
function QuoteLineItem({ line, onDelete }: QuoteLineItemProps) {
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
-
+ const permissions = usePermissions();
const navigate = useNavigate();
const disclosure = useDisclosure();
const location = useOptimisticLocation();
@@ -292,7 +326,7 @@ function QuoteLineItem({ line, onDelete }: QuoteLineItemProps) {
</VStack>
</HStack>
<HStack spacing={0}>
- {line.methodType === "Make" && (
+ {line.methodType === "Make" && permissions.can("update", "sales") && (
<IconButton
aria-label={disclosure.isOpen ? "Hide" : "Show"}
icon={<LuChevronsUpDown />}
@@ -314,6 +348,7 @@ function QuoteLineItem({ line, onDelete }: QuoteLineItemProps) {
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
+ disabled={!permissions.can("update", "sales")}
onClick={(e) => {
e.stopPropagation();
onDelete(line);
@@ -325,7 +360,7 @@ function QuoteLineItem({ line, onDelete }: QuoteLineItemProps) {
</DropdownMenu>
</HStack>
</HStack>
- {disclosure.isOpen && (
+ {disclosure.isOpen && permissions.can("update", "sales") && (
<VStack className="border-b border-border">
<QuoteBoMExplorer methods={methods} />
</VStack>
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index 4e80b14566..04d787c9a5 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -1,6 +1,6 @@
import type { Database } from "@carbon/database";
import { getLocalTimeZone, today } from "@internationalized/date";
-import { StyleSheet, Text, View } from "@react-pdf/renderer";
+import { Image, StyleSheet, Text, View } from "@react-pdf/renderer";
import type { PDF } from "../types";
import { getLineDescription, getLineDescriptionDetails } from "../utils/quote";
@@ -12,6 +12,7 @@ interface QuotePDFProps extends PDF {
quoteLines: Database["public"]["Views"]["quoteLines"]["Row"][];
quoteCustomerDetails: Database["public"]["Views"]["quoteCustomerDetails"]["Row"];
quoteLinePrices: Database["public"]["Tables"]["quoteLinePrice"]["Row"][];
+ thumbnails: Record<string, string | null>;
}
// TODO: format currency based on settings
@@ -27,6 +28,7 @@ const QuotePDF = ({
quoteLines,
quoteLinePrices,
quoteCustomerDetails,
+ thumbnails,
title = "Quote",
}: QuotePDFProps) => {
const {
@@ -106,56 +108,117 @@ const QuotePDF = ({
<View style={styles.table}>
<View style={styles.thead}>
- <View style={styles.rowThird}>
- <Text style={styles.tableCol1}>Description</Text>
+ <View style={styles.rowForty}>
+ <Text>Description</Text>
</View>
- <View style={styles.rowTwoThirds}>
- <Text style={styles.tableCol2}>Qty</Text>
- <Text style={styles.tableCol3}>Unit Price</Text>
- <Text style={styles.tableCol3}>Lead Time</Text>
- <Text style={styles.tableCol4}>Extended Price</Text>
+ <View style={styles.rowSixty}>
+ <Text style={styles.cell15}>Qty</Text>
+ <Text style={styles.cell20}>Unit Price</Text>
+ <Text style={styles.cell20}>Add-Ons</Text>
+ <Text style={styles.cell20}>Lead Time</Text>
+ <Text style={styles.cell25}>Extended Price</Text>
</View>
</View>
- {quoteLines.map((line) => (
- <View style={styles.tr} key={line.id}>
- <View style={styles.rowThird}>
- <View style={styles.tableCol1}>
- <Text style={{ ...styles.bold, marginBottom: 4 }}>
- {getLineDescription(line)}
- </Text>
- <Text style={{ fontSize: 9, opacity: 0.8 }}>
- {getLineDescriptionDetails(line)}
- </Text>
- </View>
- </View>
- <View style={styles.colTwoThirds}>
- {line.quantity.map((quantity) => {
- const prices = pricesByLine[line.id] ?? [];
- const price = prices.find(
- (price) => price.quantity === quantity
- );
- const netPrice =
- price?.unitPrice *
- (1 - (price?.discountPercent ?? 0) / 100);
+ {quoteLines.map((line) => {
+ const additionalCharges = line.additionalCharges ?? {};
+ const additionalChargesByQuantity = line.quantity.map(
+ (quantity) => {
+ const charges = Object.values(additionalCharges).reduce(
+ (acc, charge) => {
+ const amount = charge.amounts?.[quantity] ?? 0;
+ return acc + amount;
+ },
+ 0
+ );
+ return charges;
+ }
+ );
- return (
- <View key={quantity} style={styles.row}>
- <Text style={styles.tableCol2}>{quantity}</Text>
- <Text style={styles.tableCol3}>
- {netPrice ? formatter.format(netPrice) : "-"}
- </Text>
- <Text style={styles.tableCol3}>
- {price ? `${price.leadTime} days` : "-"}
- </Text>
- <Text style={styles.tableCol4}>
- {netPrice ? formatter.format(netPrice * quantity) : "-"}
+ return (
+ <View style={styles.tr} key={line.id}>
+ <View style={styles.colForty}>
+ <View style={styles.col}>
+ <Text style={{ ...styles.bold, marginBottom: 4 }}>
+ {getLineDescription(line)}
+ </Text>
+ <Text style={{ fontSize: 9, opacity: 0.8 }}>
+ {getLineDescriptionDetails(line)}
+ </Text>
+ </View>
+
+ {thumbnails && line.id in thumbnails && (
+ <View style={styles.row}>
+ <Image
+ src={thumbnails[line.id]!}
+ style={{ width: "100%", height: "auto" }}
+ />
+ </View>
+ )}
+
+ {Object.keys(additionalCharges).length > 0 && (
+ <View style={styles.col}>
+ <Text style={{ fontSize: 9, fontWeight: 700 }}>
+ Additional Charges:
</Text>
+ {Object.values(additionalCharges)
+ .sort((a, b) =>
+ a.description.localeCompare(b.description)
+ )
+ .map((charge) => {
+ return charge.description ? (
+ <Text
+ key={charge.description}
+ style={{ fontSize: 9, opacity: 0.8 }}
+ >
+ - {charge.description}
+ </Text>
+ ) : null;
+ })}
</View>
- );
- })}
+ )}
+ </View>
+ <View style={styles.colSixty}>
+ {line.quantity.map((quantity) => {
+ const prices = pricesByLine[line.id] ?? [];
+ const price = prices.find(
+ (price) => price.quantity === quantity
+ );
+ const netPrice =
+ price?.unitPrice *
+ (1 - (price?.discountPercent ?? 0) / 100);
+
+ const additionalCharge =
+ additionalChargesByQuantity[quantity] ?? 0;
+
+ return (
+ <View key={quantity} style={styles.row}>
+ <Text style={styles.cell15}>{quantity}</Text>
+ <Text style={styles.cell20}>
+ {netPrice ? formatter.format(netPrice) : "-"}
+ </Text>
+ <Text style={styles.cell20}>
+ {additionalCharge
+ ? formatter.format(additionalCharge)
+ : "-"}
+ </Text>
+ <Text style={styles.cell20}>
+ {price ? `${price.leadTime} days` : "-"}
+ </Text>
+
+ <Text style={styles.cell25}>
+ {netPrice
+ ? formatter.format(
+ netPrice * quantity + additionalCharge
+ )
+ : "-"}
+ </Text>
+ </View>
+ );
+ })}
+ </View>
</View>
- </View>
- ))}
+ );
+ })}
</View>
</View>
</Template>
@@ -176,20 +239,25 @@ const styles = StyleSheet.create({
marginBottom: 20,
width: "100%",
},
-
- rowThird: {
+ rowForty: {
display: "flex",
flexDirection: "row",
columnGap: 3,
- width: "33%",
+ width: "40%",
},
- rowTwoThirds: {
+ rowSixty: {
display: "flex",
flexDirection: "row",
columnGap: 3,
- width: "66%",
+ width: "60%",
},
- colTwoThirds: {
+ colForty: {
+ display: "flex",
+ flexDirection: "column",
+ rowGap: 3,
+ width: "40%",
+ },
+ colSixty: {
display: "flex",
flexDirection: "column",
columnGap: 3,
@@ -256,20 +324,22 @@ const styles = StyleSheet.create({
color: "#7d7d7d",
textTransform: "uppercase",
},
- tableCol1: {
- width: "50%",
- textAlign: "left",
+ col: {
+ display: "flex",
+ flexDirection: "column",
+ width: "100%",
+ rowGap: 3,
+ },
+ cell15: {
+ width: "15%",
+ textAlign: "right",
},
- tableCol2: {
+ cell20: {
width: "20%",
textAlign: "right",
},
- tableCol3: {
+ cell25: {
width: "25%",
textAlign: "right",
},
- tableCol4: {
- width: "30%",
- textAlign: "right",
- },
});
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 780fce6ccf..f7a265722a 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -115,7 +115,8 @@ import { Heading } from "./Heading";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "./HoverCard";
import { RichText, useRichText } from "./RichText";
-import { generateHTML } from "@tiptap/react";
+import { generateHTML as DefaultGenerateHTML } from "@tiptap/react";
+import { defaultExtensions } from "./Editor/extensions";
import { IconButton } from "./IconButton";
import type { InputProps } from "./Input";
import {
@@ -242,6 +243,14 @@ import {
import { VStack } from "./VStack";
import { cn } from "./utils/cn";
import { getValidChildren, reactNodeToString } from "./utils/react";
+
+const generateHTML = (content: JSONContent) => {
+ if (typeof window === "undefined") {
+ return "";
+ }
+ return DefaultGenerateHTML(content, defaultExtensions);
+};
+
export * from "./hooks";
export {
Accordion,