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: use different logo variants

Brad Barbinf938b550690e
diff --git a/apps/carbon/app/components/Copy.tsx b/apps/carbon/app/components/Copy.tsx
index b639754d1a..bb1fd47432 100644
--- a/apps/carbon/app/components/Copy.tsx
+++ b/apps/carbon/app/components/Copy.tsx
@@ -5,11 +5,20 @@ import {
TooltipContent,
TooltipTrigger,
} from "@carbon/react";
+import type { ReactNode } from "react";
import { useState } from "react";
import { LuCheck, LuCopy } from "react-icons/lu";
import { copyToClipboard } from "~/utils/string";
-const Copy = ({ text, className }: { text: string; className?: string }) => {
+const Copy = ({
+ text,
+ icon,
+ className,
+}: {
+ text: string;
+ icon?: ReactNode;
+ className?: string;
+}) => {
const [isCopied, setIsCopied] = useState(false);
const handleCopy = () => {
@@ -35,7 +44,7 @@ const Copy = ({ text, className }: { text: string; className?: string }) => {
{isCopied ? (
<LuCheck className="w-3 h-3" />
) : (
- <LuCopy className="w-3 h-3" />
+ icon ?? <LuCopy className="w-3 h-3" />
)}
</Button>
</TooltipTrigger>
diff --git a/apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx
index a938b7f955..c03ceac753 100644
--- a/apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -4,6 +4,7 @@ import { forwardRef, type AnchorHTMLAttributes } from "react";
import { BsFillHexagonFill } from "react-icons/bs";
import { z } from "zod";
import { useOptimisticLocation, useUser } from "~/hooks";
+import { useMode } from "~/hooks/useMode";
import type { Authenticated, NavItem } from "~/types";
import { useModules } from "./useModules";
@@ -13,6 +14,8 @@ export const ModuleHandle = z.object({
const PrimaryNavigation = () => {
const { company } = useUser();
+ const mode = useMode();
+ const logo = mode === "dark" ? company?.logoDarkIcon : company?.logoLightIcon;
const navigationPanel = useDisclosure();
const location = useOptimisticLocation();
@@ -49,9 +52,9 @@ const PrimaryNavigation = () => {
<VStack spacing={1}>
<Button isIcon asChild variant="ghost" size="lg">
<Link to="/">
- {company?.logo ? (
+ {logo ? (
<img
- src={company.logo}
+ src={logo}
alt={`${company.name} logo`}
className="w-full h-auto rounded"
/>
diff --git a/apps/carbon/app/components/Modals/Confirm/Confirm.tsx b/apps/carbon/app/components/Modals/Confirm/Confirm.tsx
index d4aac2ddc9..11d70839e1 100644
--- a/apps/carbon/app/components/Modals/Confirm/Confirm.tsx
+++ b/apps/carbon/app/components/Modals/Confirm/Confirm.tsx
@@ -7,6 +7,7 @@ import {
ModalHeader,
ModalOverlay,
ModalTitle,
+ toast,
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useRef } from "react";
@@ -14,8 +15,9 @@ import { useEffect, useRef } from "react";
type ConfirmProps = {
action?: string;
isOpen?: boolean;
- name: string;
+ title: string;
text: string;
+ confirmText: string;
onCancel: () => void;
onSubmit?: () => void;
};
@@ -23,12 +25,13 @@ type ConfirmProps = {
const Confirm = ({
action,
isOpen = true,
- name,
+ title,
text,
+ confirmText = "Confirm",
onCancel,
onSubmit,
}: ConfirmProps) => {
- const fetcher = useFetcher<{}>();
+ const fetcher = useFetcher<{ success: boolean; message: string }>();
const submitted = useRef(false);
useEffect(() => {
@@ -38,6 +41,16 @@ const Confirm = ({
}
}, [fetcher.state, onSubmit]);
+ useEffect(() => {
+ if (fetcher.data?.success === true && fetcher?.data?.message) {
+ toast.success(fetcher.data.message);
+ }
+
+ if (fetcher.data?.success === false && fetcher?.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+ }, [fetcher.data?.message, fetcher.data?.success]);
+
return (
<Modal
open={isOpen}
@@ -48,7 +61,7 @@ const Confirm = ({
<ModalOverlay />
<ModalContent>
<ModalHeader>
- <ModalTitle>{name}</ModalTitle>
+ <ModalTitle>{title}</ModalTitle>
</ModalHeader>
<ModalBody>{text}</ModalBody>
<ModalFooter>
@@ -65,7 +78,7 @@ const Confirm = ({
isDisabled={fetcher.state !== "idle"}
type="submit"
>
- Confirm
+ {confirmText}
</Button>
</fetcher.Form>
</ModalFooter>
diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsx
index 04427569d5..7a185118c1 100644
--- a/apps/carbon/app/hooks/useUser.tsx
+++ b/apps/carbon/app/hooks/useUser.tsx
@@ -13,7 +13,10 @@ type PersonalData = {
type Company = {
id: string;
name: string;
- logo: string | null;
+ logoDarkIcon: string | null;
+ logoLightIcon: string | null;
+ logoDark: string | null;
+ logoLight: string | null;
countryCode: string | null;
baseCurrencyCode: string;
};
@@ -64,7 +67,10 @@ function isCompany(value: any): value is Company {
return (
typeof value.id === "string" &&
typeof value.name === "string" &&
- (typeof value.logo === "string" || value.logo === null) &&
+ (typeof value.logoDarkIcon === "string" || value.logoDarkIcon === null) &&
+ (typeof value.logoLightIcon === "string" || value.logoLightIcon === null) &&
+ (typeof value.logoDark === "string" || value.logoDark === null) &&
+ (typeof value.logoLight === "string" || value.logoLight === null) &&
(typeof value.countryCode === "string" || value.countryCode === null) &&
typeof value.baseCurrencyCode === "string"
);
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 836296ddf5..5aa3e9fb4e 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -133,15 +133,17 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
<CustomerLocation
name="customerLocationId"
label="Customer Location"
+ isOptional
customer={customer.id}
/>
<CustomerContact
name="customerContactId"
label="Customer Contact"
+ isOptional
customer={customer.id}
/>
- <Employee name="salesPersonId" label="Sales Person" />
- <Employee name="estimatorId" label="Estimator" />
+ <Employee name="salesPersonId" label="Sales Person" isOptional />
+ <Employee name="estimatorId" label="Estimator" isOptional />
<Location name="locationId" label="Quote Location" />
<DatePicker
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index becf13e965..b90e90a74a 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -1,9 +1,22 @@
-import { Button, HStack, Heading, useDisclosure } from "@carbon/react";
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ Heading,
+ useDisclosure,
+} from "@carbon/react";
import { Link, useFetcher, useParams } from "@remix-run/react";
import {
LuCheckCheck,
+ LuChevronDown,
+ LuExternalLink,
LuEye,
+ LuFile,
LuRefreshCw,
LuSend,
LuStopCircle,
@@ -77,15 +90,39 @@ const QuoteHeader = () => {
className="h-8"
isReadOnly={!permissions.can("update", "sales")}
/>
- <Button leftIcon={<LuEye />} variant="secondary" asChild>
- <a
- target="_blank"
- href={path.to.file.quote(quoteId)}
- rel="noreferrer"
- >
- Preview
- </a>
- </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuEye />}
+ variant="secondary"
+ rightIcon={<LuChevronDown />}
+ >
+ Preview
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem asChild>
+ <a
+ target="_blank"
+ href={path.to.file.quote(quoteId)}
+ rel="noreferrer"
+ >
+ <DropdownMenuIcon icon={<LuFile />} />
+ PDF
+ </a>
+ </DropdownMenuItem>
+ {routeData?.quote.externalLinkId && (
+ <DropdownMenuItem asChild>
+ <Link
+ to={path.to.externalQuote(routeData.quote.externalLinkId)}
+ >
+ <DropdownMenuIcon icon={<LuExternalLink />} />
+ Digital Quote
+ </Link>
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
{routeData?.quote?.status === "Draft" && (
<>
<statusFetcher.Form
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteStatus.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteStatus.tsx
index 75a2a5d14f..d4dc4b47a4 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteStatus.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteStatus.tsx
@@ -10,14 +10,15 @@ const QuoteStatus = ({ status }: QuoteStatusProps) => {
case "Draft":
return <Status color="gray">{status}</Status>;
case "Sent":
- return <Status color="green">{status}</Status>;
+ return <Status color="yellow">{status}</Status>;
case "Ordered":
case "Partial":
- return <Status color="blue">{status}</Status>;
+ return <Status color="green">{status}</Status>;
case "Lost":
+ return <Status color="red">{status}</Status>;
case "Cancelled":
case "Expired":
- return <Status color="red">{status}</Status>;
+ return <Status color="orange">{status}</Status>;
default:
return null;
}
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.ts
index 9dc28cfe16..d3b5b7d1b4 100644
--- a/apps/carbon/app/modules/settings/settings.models.ts
+++ b/apps/carbon/app/modules/settings/settings.models.ts
@@ -66,6 +66,10 @@ export const customFieldValidator = z
return true;
});
+export const digitalQuoteValidator = z.object({
+ digitalQuoteEnabled: zfd.checkbox(),
+});
+
export const sequenceValidator = z.object({
table: z.string().min(1, { message: "Table is required" }),
prefix: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index 6a35c097aa..716df09f1a 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -83,8 +83,17 @@ export async function getCompanies(
return {
data: companies.data.map((company) => ({
...company,
- logo: company.logo
- ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logo}`
+ logoLightIcon: company.logoLightIcon
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoLightIcon}`
+ : null,
+ logoDarkIcon: company.logoDarkIcon
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoDarkIcon}`
+ : null,
+ logoDark: company.logoDark
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoDark}`
+ : null,
+ logoLight: company.logoLight
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoLight}`
: null,
})),
error: null,
@@ -107,8 +116,17 @@ export async function getCompany(
return {
data: {
...company.data,
- logo: company.data.logo
- ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.data.logo}`
+ logoLightIcon: company.data.logoLightIcon
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.data.logoLightIcon}`
+ : null,
+ logoDarkIcon: company.data.logoDarkIcon
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.data.logoDarkIcon}`
+ : null,
+ logoDark: company.data.logoDark
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.data.logoDark}`
+ : null,
+ logoLight: company.data.logoLight
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.data.logoLight}`
: null,
},
error: null,
@@ -378,21 +396,65 @@ export async function upsertIntegration(
return client.from("companyIntegration").upsert([update]);
}
-export async function updateLogo(
+export async function updateDigitalQuoteSetting(
client: SupabaseClient<Database>,
companyId: string,
- logo: string | null
+ digitalQuoteEnabled: boolean
+) {
+ return client
+ .from("company")
+ .update(sanitize({ digitalQuoteEnabled }))
+ .eq("id", companyId);
+}
+
+export async function updateLogoDark(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ logoDark: string | null
) {
return client
.from("company")
.update(
sanitize({
- logo,
+ logoDark,
})
)
.eq("id", companyId);
}
+export async function updateLogoLight(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ logoLight: string | null
+) {
+ return client
+ .from("company")
+ .update(sanitize({ logoLight }))
+ .eq("id", companyId);
+}
+
+export async function updateLogoDarkIcon(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ logoDarkIcon: string | null
+) {
+ return client
+ .from("company")
+ .update(sanitize({ logoDarkIcon }))
+ .eq("id", companyId);
+}
+
+export async function updateLogoLightIcon(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ logoLightIcon: string | null
+) {
+ return client
+ .from("company")
+ .update(sanitize({ logoLightIcon }))
+ .eq("id", companyId);
+}
+
export async function updateSequence(
client: SupabaseClient<Database>,
table: string,
diff --git a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
index 26f0ae6aab..9c716d654a 100644
--- a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
@@ -1,30 +1,93 @@
-import { useCarbon } from "@carbon/auth";
-import { Avatar, Button, File, VStack, toast } from "@carbon/react";
+import { SUPABASE_API_URL, useCarbon } from "@carbon/auth";
+import {
+ Avatar,
+ Button,
+ File as FileUpload,
+ HStack,
+ VStack,
+ cn,
+ toast,
+} from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import { type ChangeEvent } from "react";
import type { Company } from "~/modules/settings";
import { path } from "~/utils/path";
-type CompanyLogoFormProps = {
+interface CompanyLogoFormProps {
company: Company;
-};
+ mode: "dark" | "light";
+ icon?: boolean;
+}
-const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
+const CompanyLogoForm = ({
+ company,
+ mode,
+ icon = false,
+}: CompanyLogoFormProps) => {
const { carbon } = useCarbon();
const submit = useSubmit();
- const logoPath = company?.logo
- ? company.logo.substring(company.logo.lastIndexOf("/") + 1)
- : null;
+ const getLogoPath = () => {
+ const prefix = `${company.id}/logo`;
+ const modeSuffix = mode === "dark" ? "-dark" : "-light";
+ const iconSuffix = icon ? "-icon" : "";
+ const fullPath = `${prefix}${modeSuffix}${iconSuffix}.png`;
+
+ return fullPath;
+ };
+
+ const getCurrentLogoPath = () => {
+ const logos = {
+ dark: company.logoDark,
+ light: company.logoLight,
+ "dark-icon": company.logoDarkIcon,
+ "light-icon": company.logoLightIcon,
+ };
+
+ const key = `${mode}${icon ? "-icon" : ""}` as keyof typeof logos;
+ return logos[key] || null;
+ };
+
+ const currentLogoPath = getCurrentLogoPath();
const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && carbon) {
- const logo = e.target.files[0];
- const fileExtension = logo.name.substring(logo.name.lastIndexOf(".") + 1);
+ let logo = e.target.files[0];
+
+ const formData = new FormData();
+ formData.append("file", logo);
+ formData.append("height", "128");
+
+ try {
+ const response = await fetch(
+ `${SUPABASE_API_URL}/functions/v1/image-resizer`,
+ {
+ method: "POST",
+ body: formData,
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to resize image");
+ }
+
+ const blob = await response.blob();
+ const resizedFile = new File([blob], "logo.png", {
+ type: "image/png",
+ });
+
+ logo = resizedFile;
+ } catch (error) {
+ console.error(error);
+ toast.error("Failed to resize image");
+ return;
+ }
+
+ const logoPath = getLogoPath();
const imageUpload = await carbon.storage
.from("public")
- .upload(`${company.id}/logo.${fileExtension}`, logo, {
+ .upload(logoPath, logo, {
cacheControl: "0",
upsert: true,
});
@@ -40,10 +103,10 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
};
const deleteImage = async () => {
- if (carbon && logoPath) {
+ if (carbon && currentLogoPath) {
const imageDelete = await carbon.storage
.from("public")
- .remove([logoPath]);
+ .remove([currentLogoPath]);
if (imageDelete.error) {
toast.error("Failed to remove image");
@@ -55,37 +118,84 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
const submitLogoUrl = (logoUrl: string | null) => {
const formData = new FormData();
- formData.append("intent", "logo");
+
+ formData.append("mode", mode);
+ formData.append("icon", String(icon));
if (logoUrl) formData.append("path", logoUrl);
submit(formData, {
method: "post",
- action: path.to.company,
+ action: path.to.logos,
});
};
- return (
- <VStack className="items-center p-4">
- {company?.logo ? (
- <img
- alt={`${company.name} Logo`}
- width="128"
- height="auto"
- src={company.logo}
- className="rounded-lg"
- />
- ) : (
- <Avatar name={company?.name ?? undefined} size="2xl" />
- )}
-
- <File accept="image/*" onChange={uploadImage}>
- {company.logo ? "Change" : "Upload"}
- </File>
-
- {company.logo && (
- <Button variant="secondary" onClick={deleteImage}>
- Remove
- </Button>
- )}
+ const getLogoTitle = () => {
+ const modeText = mode === "dark" ? "Dark Mode" : "Light Mode";
+ const typeText = icon ? "Icon" : "Logo";
+ return `${company.name} ${modeText} ${typeText}`;
+ };
+
+ return icon ? (
+ <VStack className="items-center py-4" spacing={4}>
+ <div
+ className={cn(
+ "flex items-center justify-center h-[156px] w-[156px] rounded-lg",
+ mode === "dark" ? "bg-black text-white" : "bg-white text-black"
+ )}
+ >
+ {currentLogoPath ? (
+ <img
+ alt={getLogoTitle()}
+ src={currentLogoPath}
+ className="h-32 w-auto mx-auto"
+ />
+ ) : (
+ <Avatar name={company?.name ?? undefined} size="2xl" />
+ )}
+ </div>
+
+ <HStack spacing={2}>
+ <FileUpload accept="image/*" onChange={uploadImage}>
+ {currentLogoPath ? "Change" : "Upload"}
+ </FileUpload>
+
+ {currentLogoPath && (
+ <Button variant="secondary" onClick={deleteImage}>
+ Remove
+ </Button>
+ )}
+ </HStack>
+ </VStack>
+ ) : (
+ <VStack className="items-center py-4" spacing={4}>
+ <div
+ className={cn(
+ "flex items-center justify-center w-full h-[156px] rounded-lg",
+ mode === "dark" ? "bg-black text-white" : "bg-white text-black"
+ )}
+ >
+ {currentLogoPath ? (
+ <img
+ alt={getLogoTitle()}
+ width="auto"
+ height="128"
+ src={currentLogoPath}
+ className="rounded-lg"
+ />
+ ) : (
+ <p className="font-mono uppercase text-sm">No logo uploaded</p>
+ )}
+ </div>
+ <HStack spacing={2}>
+ <FileUpload accept="image/*" onChange={uploadImage}>
+ {currentLogoPath ? "Change" : "Upload"}
+ </FileUpload>
+
+ {currentLogoPath && (
+ <Button variant="secondary" onClick={deleteImage}>
+ Remove
+ </Button>
+ )}
+ </HStack>
</VStack>
);
};
diff --git a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
index 768e4ee0b1..218cd9ddfd 100644
--- a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -2,6 +2,7 @@ import {
LuCrown,
LuFactory,
LuFileText,
+ LuImage,
LuSheet,
LuWorkflow,
} from "react-icons/lu";
@@ -21,11 +22,12 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
icon: <LuFactory />,
},
{
- name: "Sales",
- to: path.to.salesSettings,
+ name: "Logos",
+ to: path.to.logos,
role: "employee",
- icon: <LuCrown />,
+ icon: <LuImage />,
},
+
{
name: "Standard Terms",
to: path.to.terms,
@@ -34,6 +36,17 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
},
],
},
+ {
+ name: "Modules",
+ routes: [
+ {
+ name: "Sales",
+ to: path.to.salesSettings,
+ role: "employee",
+ icon: <LuCrown />,
+ },
+ ],
+ },
{
name: "System",
routes: [
diff --git a/apps/carbon/app/routes/external+/quote.$id.tsx b/apps/carbon/app/routes/external+/quote.$id.tsx
index afd0444d74..83efe06455 100644
--- a/apps/carbon/app/routes/external+/quote.$id.tsx
+++ b/apps/carbon/app/routes/external+/quote.$id.tsx
@@ -1,4 +1,4 @@
-import { getCarbonServiceRole } from "@carbon/auth";
+import { assertIsPost, getCarbonServiceRole, notFound } from "@carbon/auth";
import type { JSONContent } from "@carbon/react";
import {
Button,
@@ -9,6 +9,13 @@ import {
generateHTML,
Heading,
HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
RadioGroup,
RadioGroupItem,
Separator,
@@ -17,28 +24,44 @@ import {
Td,
Th,
Thead,
+ toast,
Tr,
+ useDisclosure,
VStack,
} from "@carbon/react";
+import { formatCityStatePostalCode, formatDate } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
-import { useLoaderData } from "@remix-run/react";
-import { json, type LoaderFunctionArgs } from "@vercel/remix";
+import { useFetcher, useLoaderData, useParams } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
import { motion } from "framer-motion";
+import MotionNumber from "motion-number";
import type { Dispatch, SetStateAction } from "react";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { LuChevronDown, LuCreditCard, LuImage, LuTruck } from "react-icons/lu";
+import { useMode } from "~/hooks/useMode";
import { getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
-import type { QuotationLine, QuotationPrice } from "~/modules/sales";
+import type {
+ QuotationLine,
+ QuotationPrice,
+ SalesOrderLine,
+} from "~/modules/sales";
import {
+ convertQuoteToOrder,
+ getOpportunityByQuote,
getQuoteByExternalId,
getQuoteCustomerDetails,
getQuoteLinePricesByQuoteId,
getQuoteLines,
getQuotePayment,
getQuoteShipment,
+ getSalesOrderLines,
getSalesTerms,
+ selectedLinesValidator,
} from "~/modules/sales";
+import QuoteStatus from "~/modules/sales/ui/Quotes/QuoteStatus";
import { getCompany } from "~/modules/settings";
import { getBase64ImageFromSupabase } from "~/modules/shared";
@@ -91,6 +114,7 @@ export async function loader({ params }: LoaderFunctionArgs) {
paymentTerms,
terms,
shippingMethods,
+ opportunity,
] = await Promise.all([
getCompany(serviceRole, quote.data.companyId),
getQuoteLines(serviceRole, quote.data.id),
@@ -101,8 +125,17 @@ export async function loader({ params }: LoaderFunctionArgs) {
getPaymentTermsList(serviceRole, quote.data.companyId),
getSalesTerms(serviceRole, quote.data.companyId),
getShippingMethodsList(serviceRole, quote.data.companyId),
+ getOpportunityByQuote(serviceRole, quote.data.id),
]);
+ let salesOrderLines: PostgrestResponse<SalesOrderLine> | null = null;
+ if (opportunity.data?.salesOrderId) {
+ salesOrderLines = await getSalesOrderLines(
+ serviceRole,
+ opportunity.data.salesOrderId
+ );
+ }
+
const thumbnailPaths = quoteLines.data?.reduce<Record<string, string | null>>(
(acc, line) => {
if (line.thumbnailPath) {
@@ -154,10 +187,64 @@ export async function loader({ params }: LoaderFunctionArgs) {
shippingMethod: shippingMethods.data?.find(
(method) => method.id === quoteShipment.data?.shippingMethodId
)?.name,
+ salesOrderLines: salesOrderLines?.data ?? null,
},
});
}
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const formData = await request.formData();
+ const selectedLinesRaw = formData.get("selectedLines") ?? "{}";
+
+ if (typeof selectedLinesRaw !== "string") {
+ return json({ success: false, message: "Invalid selected lines data" });
+ }
+
+ const parseResult = selectedLinesValidator.safeParse(
+ JSON.parse(selectedLinesRaw)
+ );
+
+ if (!parseResult.success) {
+ console.error("Validation error:", parseResult.error);
+ return json({ success: false, message: "Invalid selected lines data" });
+ }
+
+ const selectedLines = parseResult.data;
+
+ const serviceRole = getCarbonServiceRole();
+ const quote = await getQuoteByExternalId(serviceRole, id);
+
+ if (quote.error) {
+ return json({
+ success: false,
+ message: "Quote not found",
+ });
+ }
+ const convert = await convertQuoteToOrder(serviceRole, {
+ id: quote.data.id,
+ companyId: quote.data.companyId,
+ userId: quote.data.createdBy,
+ selectedLines,
+ });
+
+ if (convert.error) {
+ return json({
+ success: false,
+ message: "Failed to convert quote to order",
+ });
+ }
+
+ return json({
+ success: true,
+ message: "Quote accepted!",
+ });
+}
+
const Header = ({
company,
quote,
@@ -167,19 +254,50 @@ const Header = ({
quote: QuoteData["quote"];
customer: QuoteData["customerDetails"];
}) => (
- <CardHeader className="flex flex-col sm:flex-row items-start sm:items-start justify-between space-y-4 sm:space-y-0 pb-7">
+ <CardHeader className="flex flex-col sm:flex-row items-start sm:items-start justify-between space-y-4 sm:space-y-2 pb-7">
<div className="flex items-center space-x-4">
<div>
<CardTitle className="text-3xl">{company?.name ?? ""}</CardTitle>
-
{quote?.quoteId && (
<p className="text-lg text-muted-foreground">{quote.quoteId}</p>
)}
+ {quote?.expirationDate && (
+ <p className="text-lg text-muted-foreground">
+ Expires {formatDate(quote.expirationDate)}
+ </p>
+ )}
</div>
</div>
- <div className="flex flex-col items-end justify-start">
+ <div className="flex flex-col gap-2 items-end justify-start">
<p className="text-xl font-medium">{customer?.customerName ?? ""}</p>
- <p className="text-lg text-muted-foreground">{customer?.email ?? ""}</p>
+ {customer?.contactName && (
+ <p className="text-base text-muted-foreground">
+ {customer.contactName ?? ""}
+ </p>
+ )}
+ {customer?.customerAddressLine1 && (
+ <div className="text-right">
+ <p className="text-xs text-muted-foreground">
+ {customer.customerAddressLine1}
+ </p>
+
+ {customer?.customerAddressLine2 && (
+ <p className="text-xs text-muted-foreground">
+ {customer.customerAddressLine2}
+ </p>
+ )}
+ <p className="text-xs text-muted-foreground">
+ {formatCityStatePostalCode(
+ customer?.customerCity ?? "",
+ customer?.customerStateProvince ?? "",
+ customer?.customerPostalCode ?? ""
+ )}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {customer?.customerCountryName ?? ""}
+ </p>
+ </div>
+ )}
</div>
</CardHeader>
);
@@ -212,11 +330,15 @@ const deselectedLine: Omit<QuotationPrice, "id" | "quoteLineId"> = {
};
const LineItems = ({
+ currencyCode,
formatter,
+ locale,
selectedLines,
setSelectedLines,
}: {
+ currencyCode: string;
formatter: Intl.NumberFormat;
+ locale: string;
selectedLines: Record<string, SelectedLine>;
setSelectedLines: Dispatch<SetStateAction<Record<string, SelectedLine>>>;
}) => {
@@ -287,14 +409,28 @@ const LineItems = ({
<div className="flex items-center gap-x-4 justify-between flex-grow">
<Heading>{line.itemReadableId}</Heading>
<HStack spacing={4}>
- <span className="font-medium text-xl">
+ {/* <span className="font-medium text-xl">
{formatter.format(
(selectedLines[line.id!]?.convertedNetUnitPrice ??
0) *
(selectedLines[line.id!]?.quantity ?? 0) +
(selectedLines[line.id!]?.convertedAddOn ?? 0)
)}
- </span>
+ </span> */}
+ <MotionNumber
+ className="font-bold text-xl"
+ value={
+ (selectedLines[line.id!]?.convertedNetUnitPrice ??
+ 0) *
+ (selectedLines[line.id!]?.quantity ?? 0) +
+ (selectedLines[line.id!]?.convertedAddOn ?? 0)
+ }
+ format={{
+ style: "currency",
+ currency: currencyCode,
+ }}
+ locales={locale}
+ />
<motion.div
animate={{
rotate: openItems.includes(line.id) ? 180 : 0,
@@ -335,6 +471,7 @@ const LineItems = ({
quoteCurrency={quote.currencyCode ?? "USD"}
quoteExchangeRate={quote.exchangeRate ?? 1}
shouldConvertCurrency={shouldConvertCurrency}
+ locale={locale}
selectedLine={selectedLines[line.id!]}
setSelectedLines={setSelectedLines}
/>
@@ -352,6 +489,7 @@ type LinePricingOptionsProps = {
quoteCurrency: string;
shouldConvertCurrency: boolean;
quoteExchangeRate: number;
+ locale: string;
formatter: Intl.NumberFormat;
selectedLine: SelectedLine;
setSelectedLines: Dispatch<SetStateAction<Record<string, SelectedLine>>>;
@@ -363,10 +501,12 @@ const LinePricingOptions = ({
quoteCurrency,
shouldConvertCurrency,
quoteExchangeRate,
+ locale,
formatter,
selectedLine,
setSelectedLines,
}: LinePricingOptionsProps) => {
+ const { quote } = useLoaderData<typeof loader>().data!;
const [selectedValue, setSelectedValue] = useState(
selectedLine.quantity.toString()
);
@@ -397,11 +537,22 @@ const LinePricingOptions = ({
{ 0: 0 }
);
+ const additionalCharges: { name: string; amount: number }[] = [];
+ Object.entries(line.additionalCharges ?? {}).forEach(([name, charge]) => {
+ additionalCharges.push({
+ name: charge.description ?? "Additional Charge",
+ amount: charge.amounts?.[selectedLine.quantity] ?? 0,
+ });
+ });
+
return (
- <VStack spacing={2}>
+ <VStack spacing={4}>
<RadioGroup
className="w-full"
value={selectedValue}
+ disabled={["Ordered", "Partial", "Expired", "Cancelled"].includes(
+ quote.status
+ )}
onValueChange={(value) => {
const selectedOption =
value === "0"
@@ -491,6 +642,33 @@ const LinePricingOptions = ({
</Tbody>
</Table>
</RadioGroup>
+
+ {selectedLine.quantity !== 0 && additionalCharges.length > 0 && (
+ <div className="w-full">
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Additional Charge</Th>
+ <Th>Amount</Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {additionalCharges.map((charge) => (
+ <Tr key={charge.name}>
+ <Td>{charge.name}</Td>
+ <Td>
+ <MotionNumber
+ value={charge.amount}
+ format={{ style: "currency", currency: quoteCurrency }}
+ locales={locale}
+ />
+ </Td>
+ </Tr>
+ ))}
+ </Tbody>
+ </Table>
+ </div>
+ )}
</VStack>
);
};
@@ -503,6 +681,7 @@ const Quote = ({ data }: { data: QuoteData }) => {
quote,
quoteLines,
quoteLinePrices,
+ salesOrderLines,
shippingMethod,
terms,
} = data;
@@ -517,14 +696,46 @@ const Quote = ({ data }: { data: QuoteData }) => {
[locale, quote.currencyCode]
);
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find external quote id");
+ const confirmQuoteModal = useDisclosure();
+ const fetcher = useFetcher<typeof action>();
+ const submitted = useRef<boolean>(false);
+ const mode = useMode();
+ const logo = mode === "dark" ? company?.logoDark : company?.logoLight;
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && submitted.current) {
+ confirmQuoteModal.onClose();
+ submitted.current = false;
+ }
+ }, [confirmQuoteModal, fetcher.state]);
+
+ useEffect(() => {
+ if (fetcher.data?.success === true && fetcher?.data?.message) {
+ toast.success(fetcher.data.message);
+ }
+
+ if (fetcher.data?.success === false && fetcher?.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+ }, [fetcher.data?.message, fetcher.data?.success]);
+
const [selectedLines, setSelectedLines] = useState<
Record<string, SelectedLine>
>(() => {
return (
quoteLines?.reduce<Record<string, SelectedLine>>((acc, line) => {
- const price = quoteLinePrices?.find(
- (price) => price.quoteLineId === line.id
+ const salesOrderLine = salesOrderLines?.find(
+ (salesOrderLine) => salesOrderLine.id === line.id
);
+ const price = salesOrderLine
+ ? quoteLinePrices?.find(
+ (price) =>
+ price.quoteLineId === salesOrderLine.id &&
+ price.quantity === salesOrderLine.saleQuantity
+ )
+ : quoteLinePrices?.find((price) => price.quoteLineId === line.id);
if (!line.id || !price) {
return acc;
}
@@ -573,24 +784,28 @@ const Quote = ({ data }: { data: QuoteData }) => {
const total = subtotal + tax;
const termsHTML = generateHTML(terms as JSONContent);
- console.log({ termsHTML });
return (
<VStack spacing={8} className="w-full items-center p-2 md:p-8">
- {company?.logo && (
+ {logo && (
<img
- src={company.logo}
- alt={company.name}
- className="h-24 w-auto mx-auto rounded-lg"
+ src={logo}
+ alt={company?.name ?? ""}
+ className="h-32 w-auto mx-auto"
/>
)}
<Card className="w-full max-w-5xl mx-auto">
+ <div className="w-full text-center">
+ {quote?.status !== "Sent" && <QuoteStatus status={quote.status} />}
+ </div>
<Header company={company} quote={quote} customer={customerDetails} />
<CardContent>
<LineItems
+ currencyCode={quote.currencyCode ?? "USD"}
+ locale={locale}
+ formatter={formatter}
selectedLines={selectedLines}
setSelectedLines={setSelectedLines}
- formatter={formatter}
/>
<VStack spacing={2} className="mt-8">
@@ -618,7 +833,14 @@ const Quote = ({ data }: { data: QuoteData }) => {
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>Subtotal:</span>
- <span>{formatter.format(subtotal)}</span>
+ <MotionNumber
+ value={subtotal}
+ format={{
+ style: "currency",
+ currency: quote.currencyCode ?? "USD",
+ }}
+ locales={locale}
+ />
</HStack>
{/* <HStack className="justify-between text-sm text-muted-foreground w-full">
<span>Tax:</span>
@@ -627,11 +849,23 @@ const Quote = ({ data }: { data: QuoteData }) => {
<Separator />
<HStack className="justify-between text-xl font-bold w-full">
<span>Total:</span>
- <span>{formatter.format(total)}</span>
+ <MotionNumber
+ value={total}
+ format={{
+ style: "currency",
+ currency: quote.currencyCode ?? "USD",
+ }}
+ locales={locale}
+ />
</HStack>
</VStack>
- {company?.digitalQuoteEnabled && (
- <Button size="lg" className="w-full mt-8 text-lg">
+ {company?.digitalQuoteEnabled && quote?.status === "Sent" && (
+ <Button
+ onClick={confirmQuoteModal.onOpen}
+ size="lg"
+ isDisabled={total === 0}
+ className="w-full mt-8 text-lg"
+ >
Accept Quote
</Button>
)}
@@ -645,6 +879,46 @@ const Quote = ({ data }: { data: QuoteData }) => {
}}
/>
)}
+ {confirmQuoteModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) confirmQuoteModal.onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <fetcher.Form
+ method="post"
+ onSubmit={() => (submitted.current = true)}
+ >
+ <ModalHeader>
+ <ModalTitle>Accept Quote</ModalTitle>
+ </ModalHeader>
+ <ModalBody>{`Are you sure you want to accept quote ${
+ quote.quoteId
+ } for ${formatter.format(total)}?`}</ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={confirmQuoteModal.onClose}>
+ Cancel
+ </Button>
+ <input
+ type="hidden"
+ name="selectedLines"
+ value={JSON.stringify(selectedLines)}
+ />
+ <Button
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ type="submit"
+ >
+ Yes, Accept
+ </Button>
+ </ModalFooter>
+ </fetcher.Form>
+ </ModalContent>
+ </Modal>
+ )}
</VStack>
);
};
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
index 33343eaf37..bb0c4a6017 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
@@ -93,6 +93,7 @@ export default function QuoteDetailsRoute() {
const initialValues = {
id: quoteData?.quote?.id ?? "",
customerId: quoteData?.quote?.customerId ?? "",
+ customerLocationId: quoteData?.quote?.customerLocationId ?? "",
customerContactId: quoteData?.quote?.customerContactId ?? "",
customerReference: quoteData?.quote?.customerReference ?? "",
dueDate: quoteData?.quote?.dueDate ?? "",
diff --git a/apps/carbon/app/routes/x+/settings+/_layout.tsx b/apps/carbon/app/routes/x+/settings+/_layout.tsx
index 432f464e33..44e65bfc5a 100644
--- a/apps/carbon/app/routes/x+/settings+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/settings+/_layout.tsx
@@ -23,7 +23,7 @@ export default function SettingsRoute() {
const { groups } = useSettingsSubmodules();
if (permissions.can("update", "users") && permissions.is("employee")) {
- groups?.[1]?.routes.unshift({
+ groups?.[2]?.routes.unshift({
name: "API Keys",
to: path.to.apiKeys,
role: "employee",
diff --git a/apps/carbon/app/routes/x+/settings+/company.tsx b/apps/carbon/app/routes/x+/settings+/company.tsx
index 022f75aae6..e60e2bd670 100644
--- a/apps/carbon/app/routes/x+/settings+/company.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.tsx
@@ -11,15 +11,13 @@ import {
VStack,
} from "@carbon/react";
import type { ActionFunctionArgs } from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
+import { json } from "@vercel/remix";
import { useRouteData } from "~/hooks";
import type { Company as CompanyType } from "~/modules/settings";
import {
CompanyForm,
- CompanyLogoForm,
companyValidator,
updateCompany,
- updateLogo,
} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -36,58 +34,23 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- if (formData.get("intent") === "about") {
- const validation = await validator(companyValidator).validate(formData);
+ const validation = await validator(companyValidator).validate(formData);
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const update = await updateCompany(client, companyId, {
- ...validation.data,
- updatedBy: userId,
- });
- if (update.error)
- return json(
- {},
- await flash(request, error(update.error, "Failed to update company"))
- );
-
- return json({}, await flash(request, success("Updated company")));
+ if (validation.error) {
+ return validationError(validation.error);
}
- if (formData.get("intent") === "logo") {
- const logoPath = formData.get("path");
- if (logoPath === null || typeof logoPath === "string") {
- const logoUpdate = await updateLogo(client, companyId, logoPath);
-
- if (logoUpdate.error) {
- throw redirect(
- path.to.company,
- await flash(request, error(logoUpdate.error, "Failed to update logo"))
- );
- }
-
- throw redirect(
- path.to.company,
- await flash(
- request,
- success(
- logoPath === null
- ? "Removed logo. Please refresh the page"
- : "Updated logo"
- )
- )
- );
- } else {
- throw redirect(
- path.to.company,
- await flash(request, error(null, "Invalid logo path"))
- );
- }
- }
+ const update = await updateCompany(client, companyId, {
+ ...validation.data,
+ updatedBy: userId,
+ });
+ if (update.error)
+ return json(
+ {},
+ await flash(request, error(update.error, "Failed to update company"))
+ );
- return null;
+ return json({}, await flash(request, success("Updated company")));
}
export default function Company() {
@@ -123,11 +86,8 @@ export default function Company() {
</CardDescription>
</CardHeader>
<CardContent>
- <div className="grid grid-cols-1 md:grid-cols-[1fr_auto] gap-4 w-full">
- {/* @ts-ignore */}
- <CompanyForm company={initialValues} />
- <CompanyLogoForm company={company} />
- </div>
+ {/* @ts-ignore */}
+ <CompanyForm company={initialValues} />
</CardContent>
</Card>
</VStack>
diff --git a/apps/carbon/app/routes/x+/settings+/logos.tsx b/apps/carbon/app/routes/x+/settings+/logos.tsx
new file mode 100644
index 0000000000..c2dfb745cb
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/logos.tsx
@@ -0,0 +1,120 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ ScrollArea,
+ VStack,
+} from "@carbon/react";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import type { Company } from "~/modules/settings";
+import {
+ CompanyLogoForm,
+ updateLogoDark,
+ updateLogoDarkIcon,
+ updateLogoLight,
+ updateLogoLightIcon,
+} from "~/modules/settings";
+
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { LuMoon, LuSun } from "react-icons/lu";
+import { useRouteData } from "~/hooks";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Logos",
+ to: path.to.logos,
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const formData = await request.formData();
+ const mode = formData.get("mode");
+ const icon = formData.get("icon");
+ const path = formData.get("path") as string | null;
+
+ if (typeof mode !== "string" || typeof icon !== "string") {
+ return json({ error: "Invalid form data" }, { status: 400 });
+ }
+
+ if (mode === "light" && icon === "false") {
+ const { error } = await updateLogoLight(client, companyId, path);
+ if (error) return json({ error: "Failed to update logo" }, { status: 500 });
+ }
+ if (mode === "dark" && icon === "false") {
+ const { error } = await updateLogoDark(client, companyId, path);
+ if (error) return json({ error: "Failed to update logo" }, { status: 500 });
+ }
+ if (mode === "light" && icon === "true") {
+ const { error } = await updateLogoLightIcon(client, companyId, path);
+ if (error) return json({ error: "Failed to update logo" }, { status: 500 });
+ }
+ if (mode === "dark" && icon === "true") {
+ const { error } = await updateLogoDarkIcon(client, companyId, path);
+ if (error) return json({ error: "Failed to update logo" }, { status: 500 });
+ }
+
+ return json({ success: true });
+}
+
+export default function LogosRoute() {
+ const routeData = useRouteData<{ company: Company }>(
+ path.to.authenticatedRoot
+ );
+
+ const company = routeData?.company;
+ if (!company) throw new Error("Company not found");
+
+ return (
+ <ScrollArea className="w-full h-[calc(100vh-49px)]">
+ <VStack spacing={2} className="p-2 h-full">
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <LuSun /> Horizontal Light Mode
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <CompanyLogoForm company={company} mode="light" icon={false} />
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <LuMoon /> Horizontal Dark Mode
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <CompanyLogoForm company={company} mode="dark" icon={false} />
+ </CardContent>
+ </Card>
+ <div className="grid grid-cols-2 gap-2 w-full">
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <LuSun /> Icon Light Mode
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <CompanyLogoForm company={company} mode="light" icon />
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <LuMoon /> Icon Dark Mode
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <CompanyLogoForm company={company} mode="dark" icon />
+ </CardContent>
+ </Card>
+ </div>
+ </VStack>
+ </ScrollArea>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/settings+/sales.tsx b/apps/carbon/app/routes/x+/settings+/sales.tsx
new file mode 100644
index 0000000000..2f77d2fa8e
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/sales.tsx
@@ -0,0 +1,112 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ ScrollArea,
+ toast,
+ VStack,
+} from "@carbon/react";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+
+import type { Company } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";
+import { useFetcher } from "@remix-run/react";
+import { useEffect } from "react";
+import { useRouteData } from "~/hooks";
+import {
+ digitalQuoteValidator,
+ updateDigitalQuoteSetting,
+} from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Sales",
+ to: path.to.salesSettings,
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ switch (intent) {
+ case "digitalQuote":
+ const validation = await validator(digitalQuoteValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return json({ success: false, message: "Invalid form data" });
+ }
+
+ const { error } = await updateDigitalQuoteSetting(
+ client,
+ companyId,
+ validation.data.digitalQuoteEnabled
+ );
+ if (error) return json({ success: false, message: error.message });
+ }
+
+ return json({ success: true, message: "Digital quote setting updated" });
+}
+
+export default function SalesSettingsRoute() {
+ const fetcher = useFetcher<typeof action>();
+ const routeData = useRouteData<{ company: Company }>(
+ path.to.authenticatedRoot
+ );
+
+ const company = routeData?.company;
+ if (!company) throw new Error("Company not found");
+
+ useEffect(() => {
+ if (fetcher.data?.success === true && fetcher?.data?.message) {
+ toast.success(fetcher.data.message);
+ }
+
+ if (fetcher.data?.success === false && fetcher?.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+ }, [fetcher.data?.message, fetcher.data?.success]);
+
+ return (
+ <ScrollArea className="w-full h-[calc(100vh-49px)]">
+ <VStack spacing={2} className="p-2 h-full">
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={digitalQuoteValidator}
+ defaultValues={{ digitalQuoteEnabled: company.digitalQuoteEnabled }}
+ fetcher={fetcher}
+ >
+ <input type="hidden" name="intent" value="digitalQuote" />
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Digital Quote
+ </CardTitle>
+ <CardDescription>
+ Enable digital quotes for your company. This will allow you to
+ send digital quotes to your customers, and allow them to accept
+ them online.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Boolean name="digitalQuoteEnabled" description="Enabled" />
+ </CardContent>
+ <CardFooter>
+ <Submit>Save</Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ </VStack>
+ </ScrollArea>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index a6be847766..d42601a080 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -324,6 +324,7 @@ export const path = {
employeeType: (id: string) =>
generatePath(`${x}/users/employee-types/${id}`),
employeeTypes: `${x}/users/employee-types`,
+ externalQuote: (id: string) => generatePath(`/external/quote/${id}`),
feedback: `${x}/feedback`,
fiscalYears: `${x}/accounting/years`,
fixture: (id: string) => generatePath(`${x}/fixture/${id}`),
@@ -418,6 +419,7 @@ export const path = {
locations: `${x}/resources/locations`,
login: "/login",
logout: "/logout",
+ logos: `${x}/settings/logos`,
makeMethodGet: `${x}/items/methods/get`,
makeMethodSave: `${x}/items/methods/save`,
material: (id: string) => generatePath(`${x}/material/${id}`),
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 7dd86b2778..ed5201ecb3 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -55,11 +55,12 @@
"localforage": "^1.10.0",
"lodash.debounce": "^4.0.8",
"lodash.words": "^4.2.0",
- "papaparse": "5.3.2",
+ "motion-number": "0.1.7",
"nanoid": "5.0.4",
"nanostores": "^0.9.3",
"non.geist": "~1.0.3",
"nprogress": "0.2.0",
+ "papaparse": "5.3.2",
"performant-array-to-tree": "1.11.0",
"posthog-js": "^1.116.6",
"react": "^18.3.1",
diff --git a/package-lock.json b/package-lock.json
index 987aac7158..5a47643d6a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -86,6 +86,7 @@
"localforage": "^1.10.0",
"lodash.debounce": "^4.0.8",
"lodash.words": "^4.2.0",
+ "motion-number": "0.1.7",
"nanoid": "5.0.4",
"nanostores": "^0.9.3",
"non.geist": "~1.0.3",
@@ -22661,6 +22662,16 @@
"node": ">= 0.8"
}
},
+ "node_modules/motion-number": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/motion-number/-/motion-number-0.1.7.tgz",
+ "integrity": "sha512-WOqZSqimX/OTNoFsz6Hk67r1omeUmtC2jH2x6Zy7/gNVnh98AOTrkINygXLR2xoef8k7iVDoKwk4PUcrxI+bog==",
+ "peerDependencies": {
+ "framer-motion": "^11.3.19",
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0"
+ }
+ },
"node_modules/mri": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
diff --git a/packages/auth/src/services/users.ts b/packages/auth/src/services/users.ts
index 67ce5301bb..504a51e32b 100644
--- a/packages/auth/src/services/users.ts
+++ b/packages/auth/src/services/users.ts
@@ -32,8 +32,17 @@ export async function getCompanies(
return {
data: companies.data.map((company) => ({
...company,
- logo: company.logo
- ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logo}`
+ logoLightIcon: company.logoLightIcon
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoLightIcon}`
+ : null,
+ logoDarkIcon: company.logoDarkIcon
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoDarkIcon}`
+ : null,
+ logoLight: company.logoLight
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoLight}`
+ : null,
+ logoDark: company.logoDark
+ ? `${SUPABASE_API_URL}/storage/v1/object/public/public/${company.logoDark}`
: null,
})),
error: null,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 88f5b986cf..e8b7768c2f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1919,7 +1919,10 @@ export type Database = {
email: string | null
fax: string | null
id: string
- logo: string | null
+ logoDark: string | null
+ logoDarkIcon: string | null
+ logoLight: string | null
+ logoLightIcon: string | null
name: string
phone: string | null
postalCode: string | null
@@ -1938,7 +1941,10 @@ export type Database = {
email?: string | null
fax?: string | null
id?: string
- logo?: string | null
+ logoDark?: string | null
+ logoDarkIcon?: string | null
+ logoLight?: string | null
+ logoLightIcon?: string | null
name: string
phone?: string | null
postalCode?: string | null
@@ -1957,7 +1963,10 @@ export type Database = {
email?: string | null
fax?: string | null
id?: string
- logo?: string | null
+ logoDark?: string | null
+ logoDarkIcon?: string | null
+ logoLight?: string | null
+ logoLightIcon?: string | null
name?: string
phone?: string | null
postalCode?: string | null
@@ -22627,11 +22636,15 @@ export type Database = {
city: string | null
companyId: string | null
countryCode: string | null
+ digitalQuoteEnabled: boolean | null
email: string | null
employeeType: string | null
fax: string | null
id: string | null
- logo: string | null
+ logoDark: string | null
+ logoDarkIcon: string | null
+ logoLight: string | null
+ logoLightIcon: string | null
name: string | null
phone: string | null
postalCode: string | null
@@ -26185,6 +26198,8 @@ export type Database = {
}
quoteCustomerDetails: {
Row: {
+ contactEmail: string | null
+ contactName: string | null
customerAddressLine1: string | null
customerAddressLine2: string | null
customerCity: string | null
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 344bbecd41..f97ab2b164 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -89,6 +89,15 @@ serve(async (req: Request) => {
companyId
);
+ // Check if any selected lines have quantity 0
+ const hasZeroQuantityLines = quoteLines.data.some(
+ (line) =>
+ line.id &&
+ selectedLines &&
+ line.id in selectedLines &&
+ selectedLines[line.id].quantity === 0
+ );
+
const salesOrder = await trx
.insertInto("salesOrder")
.values([
@@ -101,7 +110,7 @@ serve(async (req: Request) => {
customerLocationId: quote.data.customerLocationId,
customerReference: quote.data.customerReference,
locationId: quote.data.locationId,
- status: "Draft",
+ status: "Confirmed",
createdBy: userId,
companyId: companyId,
currencyCode:
@@ -142,7 +151,11 @@ serve(async (req: Request) => {
const salesOrderLineInserts: Database["public"]["Tables"]["salesOrderLine"]["Insert"][] =
quoteLines.data
.filter(
- (line) => line.id && selectedLines && line.id in selectedLines
+ (line) =>
+ line.id &&
+ selectedLines &&
+ line.id in selectedLines &&
+ selectedLines[line.id].quantity > 0
)
.map((line) => {
return {
@@ -189,10 +202,9 @@ serve(async (req: Request) => {
.execute();
}
- const newQuoteStatus: "Ordered" | "Partial" =
- quoteLines.data.length === salesOrderLineInserts.length
- ? "Ordered"
- : "Partial";
+ const newQuoteStatus: "Ordered" | "Partial" = hasZeroQuantityLines
+ ? "Partial"
+ : "Ordered";
await trx
.updateTable("quote")
.set({ status: newQuoteStatus })
diff --git a/packages/database/supabase/functions/image-resizer/index.ts b/packages/database/supabase/functions/image-resizer/index.ts
index 6e7688698a..8185f620d5 100644
--- a/packages/database/supabase/functions/image-resizer/index.ts
+++ b/packages/database/supabase/functions/image-resizer/index.ts
@@ -27,6 +27,8 @@ serve(async (req: Request) => {
const formData = await req.formData();
const file = formData.get("file") as File;
+ const targetHeight = formData.get("height") as string | null;
+
if (!file) {
throw new Error("No file provided");
}
@@ -38,18 +40,26 @@ serve(async (req: Request) => {
const width = img.width;
const height = img.height;
- // Calculate the size for cropping
- const size = Math.min(width, height);
+ if (targetHeight) {
+ const targetHeightInt = parseInt(targetHeight, 10);
+
+ const ratio = img.width / img.height;
+ const targetWidthInt = Math.round(targetHeightInt * ratio);
+ img.resize(targetWidthInt, targetHeightInt);
+ } else {
+ // Calculate the size for cropping
+ const size = Math.min(width, height);
- // Calculate offsets for centering the crop
- const x = Math.floor((width - size) / 2);
- const y = Math.floor((height - size) / 2);
+ // Calculate offsets for centering the crop
+ const x = Math.floor((width - size) / 2);
+ const y = Math.floor((height - size) / 2);
- // Crop to square
- img.crop(new MagickGeometry(x, y, size, size));
+ // Crop to square
+ img.crop(new MagickGeometry(x, y, size, size));
- // Resize to 400x400
- img.resize(300, 300);
+ // Resize to 400x400
+ img.resize(300, 300);
+ }
return img.write((data) => data);
});
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 88f5b986cf..e8b7768c2f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1919,7 +1919,10 @@ export type Database = {
email: string | null
fax: string | null
id: string
- logo: string | null
+ logoDark: string | null
+ logoDarkIcon: string | null
+ logoLight: string | null
+ logoLightIcon: string | null
name: string
phone: string | null
postalCode: string | null
@@ -1938,7 +1941,10 @@ export type Database = {
email?: string | null
fax?: string | null
id?: string
- logo?: string | null
+ logoDark?: string | null
+ logoDarkIcon?: string | null
+ logoLight?: string | null
+ logoLightIcon?: string | null
name: string
phone?: string | null
postalCode?: string | null
@@ -1957,7 +1963,10 @@ export type Database = {
email?: string | null
fax?: string | null
id?: string
- logo?: string | null
+ logoDark?: string | null
+ logoDarkIcon?: string | null
+ logoLight?: string | null
+ logoLightIcon?: string | null
name?: string
phone?: string | null
postalCode?: string | null
@@ -22627,11 +22636,15 @@ export type Database = {
city: string | null
companyId: string | null
countryCode: string | null
+ digitalQuoteEnabled: boolean | null
email: string | null
employeeType: string | null
fax: string | null
id: string | null
- logo: string | null
+ logoDark: string | null
+ logoDarkIcon: string | null
+ logoLight: string | null
+ logoLightIcon: string | null
name: string | null
phone: string | null
postalCode: string | null
@@ -26185,6 +26198,8 @@ export type Database = {
}
quoteCustomerDetails: {
Row: {
+ contactEmail: string | null
+ contactName: string | null
customerAddressLine1: string | null
customerAddressLine2: string | null
customerCity: string | null
diff --git a/packages/database/supabase/migrations/20241030005037_external-links.sql b/packages/database/supabase/migrations/20241030005037_external-links.sql
index c534119143..461372389b 100644
--- a/packages/database/supabase/migrations/20241030005037_external-links.sql
+++ b/packages/database/supabase/migrations/20241030005037_external-links.sql
@@ -107,4 +107,28 @@ CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) AS
LEFT JOIN "location" l
ON l.id = q."locationId"
LEFT JOIN "opportunity" opp
- ON opp."quoteId" = q.id;
\ No newline at end of file
+ ON opp."quoteId" = q.id;
+
+
+DROP VIEW IF EXISTS "quoteCustomerDetails";
+CREATE OR REPLACE VIEW "quoteCustomerDetails" WITH(SECURITY_INVOKER=true) AS
+SELECT
+ q.id as "quoteId",
+ c.name as "customerName",
+ contact."fullName" as "contactName",
+ contact."email" as "contactEmail",
+ ca."addressLine1" AS "customerAddressLine1",
+ ca."addressLine2" AS "customerAddressLine2",
+ ca."city" AS "customerCity",
+ ca."stateProvince" AS "customerStateProvince",
+ ca."postalCode" AS "customerPostalCode",
+ ca."countryCode" AS "customerCountryCode",
+ country."name" AS "customerCountryName"
+
+FROM "quote" q
+INNER JOIN "customer" c ON c."id" = q."customerId"
+LEFT JOIN "customerContact" cc ON cc."id" = q."customerContactId"
+LEFT JOIN "contact" contact ON contact.id = cc."contactId"
+LEFT JOIN "customerLocation" cl ON cl."id" = q."customerLocationId"
+LEFT JOIN "address" ca ON ca."id" = cl."addressId"
+LEFT OUTER JOIN "country" country ON country.alpha2 = ca."countryCode";
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20241103015447_logos.sql b/packages/database/supabase/migrations/20241103015447_logos.sql
new file mode 100644
index 0000000000..1d23e1fc9c
--- /dev/null
+++ b/packages/database/supabase/migrations/20241103015447_logos.sql
@@ -0,0 +1,31 @@
+ALTER TABLE "company"
+ ADD COLUMN "logoDarkIcon" text,
+ ADD COLUMN "logoLightIcon" text,
+ ADD COLUMN "logoDark" text,
+ ADD COLUMN "logoLight" text;
+
+UPDATE "company"
+SET "logoDarkIcon" = "logo",
+ "logoLightIcon" = "logo",
+ "logoDark" = "logo",
+ "logoLight" = "logo";
+
+DROP VIEW "companies";
+COMMIT;
+
+ALTER TABLE "company"
+ DROP COLUMN "logo";
+
+DROP VIEW IF EXISTS "companies";
+CREATE OR REPLACE VIEW "companies" WITH(SECURITY_INVOKER=true) AS
+ SELECT DISTINCT
+ c.*,
+ uc.*,
+ et.name AS "employeeType"
+ FROM "userToCompany" uc
+ INNER JOIN "company" c
+ ON c.id = uc."companyId"
+ LEFT JOIN "employee" e
+ ON e.id = uc."userId" AND e."companyId" = uc."companyId"
+ LEFT JOIN "employeeType" et
+ ON et.id = e."employeeTypeId";
\ No newline at end of file
diff --git a/packages/documents/src/email/PurchaseOrderEmail.tsx b/packages/documents/src/email/PurchaseOrderEmail.tsx
index 01d02886d8..7f00d4c2c5 100644
--- a/packages/documents/src/email/PurchaseOrderEmail.tsx
+++ b/packages/documents/src/email/PurchaseOrderEmail.tsx
@@ -66,9 +66,9 @@ const PurchaseOrderEmail = ({
<Section>
<Row>
<Column>
- {company.logo ? (
+ {company.logoLightIcon ? (
<Img
- src={company.logo}
+ src={company.logoLightIcon}
width="auto"
height="42"
alt={`${company.name} Logo`}
@@ -238,9 +238,9 @@ const PurchaseOrderEmail = ({
<Section>
<Row>
<Column className="text-center">
- {company.logo ? (
+ {company.logoLightIcon ? (
<Img
- src={company.logo}
+ src={company.logoLightIcon}
width="60"
height="auto"
alt={`${company.name} Logo`}
diff --git a/packages/documents/src/email/QuoteEmail.tsx b/packages/documents/src/email/QuoteEmail.tsx
index 4ce95f0a1c..8fde77d7c9 100644
--- a/packages/documents/src/email/QuoteEmail.tsx
+++ b/packages/documents/src/email/QuoteEmail.tsx
@@ -33,9 +33,9 @@ const QuoteEmail = ({ company, quote, recipient, sender }: QuoteEmailProps) => {
<Section>
<Row>
<Column>
- {company.logo ? (
+ {company.logoLightIcon ? (
<Img
- src={company.logo}
+ src={company.logoLightIcon}
width="auto"
height="42"
alt={`${company.name} Logo`}
@@ -110,9 +110,9 @@ const QuoteEmail = ({ company, quote, recipient, sender }: QuoteEmailProps) => {
<Section>
<Row>
<Column className="text-center">
- {company.logo ? (
+ {company.logoLightIcon ? (
<Img
- src={company.logo}
+ src={company.logoLightIcon}
width="60"
height="auto"
alt={`${company.name} Logo`}
diff --git a/packages/documents/src/email/SalesOrderEmail.tsx b/packages/documents/src/email/SalesOrderEmail.tsx
index 6d841cf039..4b5e581994 100644
--- a/packages/documents/src/email/SalesOrderEmail.tsx
+++ b/packages/documents/src/email/SalesOrderEmail.tsx
@@ -59,6 +59,8 @@ const SalesOrderEmail = ({
const reSubject = `Re: ${salesOrder.salesOrderId} from ${company.name}`;
const formatter = getCurrencyFormatter(company.baseCurrencyCode, locale);
+ const shouldConvertCurrency =
+ company.baseCurrencyCode !== salesOrder.currencyCode;
return (
<Html>
@@ -70,9 +72,9 @@ const SalesOrderEmail = ({
<Section>
<Row>
<Column>
- {company.logo ? (
+ {company.logoLightIcon ? (
<Img
- src={company.logo}
+ src={company.logoLightIcon}
width="auto"
height="42"
alt={`${company.name} Logo`}
@@ -194,7 +196,9 @@ const SalesOrderEmail = ({
<Text className="text-xs font-semibold">
{line.salesOrderLineType === "Comment"
? "-"
- : formatter.format(getLineTotal(line))}
+ : formatter.format(
+ getLineTotal(line, shouldConvertCurrency)
+ )}
</Text>
</Column>
</Row>
@@ -211,7 +215,9 @@ const SalesOrderEmail = ({
<Column className="border-l border-gray-200 h-12"></Column>
<Column className="w-[90px] pr-5">
<Text className="text-base font-semibold whitespace-nowrap">
- {formatter.format(getTotal(salesOrderLines))}
+ {formatter.format(
+ getTotal(salesOrderLines, shouldConvertCurrency)
+ )}
</Text>
</Column>
</Row>
@@ -220,9 +226,9 @@ const SalesOrderEmail = ({
<Section>
<Row>
<Column className="text-center">
- {company.logo ? (
+ {company.logoLightIcon ? (
<Img
- src={company.logo}
+ src={company.logoLightIcon}
width="60"
height="auto"
alt={`${company.name} Logo`}
diff --git a/packages/documents/src/pdf/components/Header.tsx b/packages/documents/src/pdf/components/Header.tsx
index 63aa71bbd8..cc75a4581f 100644
--- a/packages/documents/src/pdf/components/Header.tsx
+++ b/packages/documents/src/pdf/components/Header.tsx
@@ -30,9 +30,9 @@ const Header = ({ title, company }: HeaderProps) => {
return (
<View style={styles.header}>
<View>
- {company.logo && (
+ {company.logoLightIcon && (
<View>
- <Image src={company.logo} style={styles.logo} />
+ <Image src={company.logoLightIcon} style={styles.logo} />
</View>
)}
</View>