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 : Add CC to Sales and Supplier Quotes (#452)

Gaurav Bhatt997b969a5793
diff --git a/apps/erp/app/components/Form/EmailRecipients.tsx b/apps/erp/app/components/Form/EmailRecipients.tsx
new file mode 100644
index 0000000000..eabc524c11
--- /dev/null
+++ b/apps/erp/app/components/Form/EmailRecipients.tsx
@@ -0,0 +1,368 @@
+import { useField } from "@carbon/form";
+import {
+ Badge,
+ BadgeCloseButton,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandList,
+ cn,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ useMount
+} from "@carbon/react";
+import {
+ type KeyboardEvent,
+ useCallback,
+ useMemo,
+ useRef,
+ useState
+} from "react";
+import { LuUsers } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import type { Group } from "~/modules/users";
+import { isValidEmail } from "~/utils/form";
+import { path } from "~/utils/path";
+
+type EmailRecipientsProps = {
+ name: string;
+ label?: string;
+ helperText?: string;
+ type?: "employee" | "supplier" | "customer";
+};
+
+type UserOption = {
+ type: "user";
+ id: string;
+ name: string;
+ email: string;
+};
+
+type GroupOption = {
+ type: "group";
+ id: string;
+ name: string;
+ emails: string[];
+ memberCount: number;
+};
+
+type Option = UserOption | GroupOption;
+
+const useEmailOptions = (type: "employee" | "supplier" | "customer") => {
+ const groupsFetcher = useFetcher<{ groups: Group[] }>();
+
+ useMount(() => {
+ groupsFetcher.load(path.to.api.groupsByType(type));
+ });
+
+ const options = useMemo<Option[]>(() => {
+ if (!groupsFetcher.data?.groups) return [];
+
+ const opts: Option[] = [];
+ const seenGroupIds = new Set<string>();
+
+ const collectGroupEmails = (group: Group): string[] => {
+ const groupEmails: string[] = [];
+ group.data.users?.forEach((user) => {
+ if (user.email) groupEmails.push(user.email);
+ });
+ group.children?.forEach((child) => {
+ groupEmails.push(...collectGroupEmails(child));
+ });
+ return groupEmails;
+ };
+
+ const processGroup = (group: Group) => {
+ if (seenGroupIds.has(group.data.id)) return;
+ seenGroupIds.add(group.data.id);
+
+ const groupEmails = [...new Set(collectGroupEmails(group))];
+ if (groupEmails.length > 0) {
+ opts.push({
+ type: "group",
+ id: group.data.id,
+ name: group.data.name,
+ emails: groupEmails,
+ memberCount: groupEmails.length
+ });
+ }
+
+ group.data.users?.forEach((user) => {
+ if (user.email) {
+ opts.push({
+ type: "user",
+ id: user.id,
+ name: user.fullName,
+ email: user.email
+ });
+ }
+ });
+ };
+
+ groupsFetcher.data.groups.forEach(processGroup);
+
+ const seenEmails = new Set<string>();
+ return opts.filter((opt) => {
+ if (opt.type === "group") return true;
+ if (seenEmails.has(opt.email)) return false;
+ seenEmails.add(opt.email);
+ return true;
+ });
+ }, [groupsFetcher.data]);
+
+ return options;
+};
+
+export default function EmailRecipients({
+ name,
+ label,
+ helperText,
+ type = "employee"
+}: EmailRecipientsProps) {
+ const { error, defaultValue, validate } = useField(name);
+ const [emails, setEmails] = useState<string[]>(defaultValue ?? []);
+ const [inputValue, setInputValue] = useState("");
+ const [inputError, setInputError] = useState(false);
+ const [open, setOpen] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const options = useEmailOptions(type);
+
+ // Filter options based on search
+ const filteredOptions = useMemo(() => {
+ if (!inputValue.trim()) return options;
+ const search = inputValue.toLowerCase();
+ return options.filter((opt) => {
+ if (opt.type === "user") {
+ return (
+ opt.name.toLowerCase().includes(search) ||
+ opt.email.toLowerCase().includes(search)
+ );
+ }
+ return opt.name.toLowerCase().includes(search);
+ });
+ }, [options, inputValue]);
+
+ const addEmail = useCallback(
+ (email: string) => {
+ const trimmed = email.trim().toLowerCase();
+ if (trimmed && !emails.includes(trimmed)) {
+ setEmails((prev) => [...prev, trimmed]);
+ validate();
+ }
+ },
+ [emails, validate]
+ );
+
+ const addEmails = useCallback(
+ (newEmails: string[]) => {
+ const toAdd = newEmails
+ .map((e) => e.trim().toLowerCase())
+ .filter((e) => e && !emails.includes(e));
+ if (toAdd.length > 0) {
+ setEmails((prev) => [...prev, ...toAdd]);
+ validate();
+ }
+ },
+ [emails, validate]
+ );
+
+ const removeEmail = useCallback(
+ (email: string) => {
+ setEmails((prev) => prev.filter((e) => e !== email));
+ validate();
+ },
+ [validate]
+ );
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const value = inputValue.trim();
+ if (value) {
+ if (isValidEmail(value)) {
+ addEmail(value);
+ setInputValue("");
+ setOpen(false);
+ setInputError(false);
+ } else {
+ setInputError(true);
+ }
+ }
+ } else if (e.key === "Escape") {
+ setOpen(false);
+ inputRef.current?.blur();
+ } else if (e.key === "Backspace" && !inputValue && emails.length > 0) {
+ removeEmail(emails[emails.length - 1]);
+ } else if (e.key === "ArrowDown" && filteredOptions.length > 0) {
+ e.preventDefault();
+ setOpen(true);
+ }
+ };
+
+ const handleSelect = (option: Option) => {
+ if (option.type === "user") {
+ addEmail(option.email);
+ } else {
+ addEmails(option.emails);
+ }
+ setInputValue("");
+ setOpen(false);
+ inputRef.current?.focus();
+ };
+
+ return (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {emails.map((email, index) => (
+ <input
+ key={email}
+ type="hidden"
+ name={`${name}[${index}]`}
+ value={email}
+ />
+ ))}
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <div
+ className={cn(
+ "flex flex-wrap gap-1 min-h-10 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 cursor-text",
+ inputError ? "border-destructive" : "border-input"
+ )}
+ onClick={(e) => {
+ // Prevent popover toggle, just focus input
+ e.preventDefault();
+ inputRef.current?.focus();
+ }}
+ >
+ {emails.map((email) => (
+ <Badge
+ key={email}
+ variant="secondary"
+ className="border border-card shadow-sm"
+ >
+ {email}
+ <BadgeCloseButton
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ removeEmail(email);
+ }}
+ />
+ </Badge>
+ ))}
+ <input
+ ref={inputRef}
+ value={inputValue}
+ onChange={(e) => {
+ setInputValue(e.target.value);
+ setInputError(false);
+ setOpen(true);
+ }}
+ onFocus={() => setOpen(true)}
+ onBlur={(e) => {
+ // Delay close to allow click on popover items
+ const relatedTarget = e.relatedTarget as HTMLElement;
+ if (
+ !relatedTarget?.closest("[data-radix-popper-content-wrapper]")
+ ) {
+ setTimeout(() => setOpen(false), 150);
+ }
+ }}
+ onKeyDown={handleKeyDown}
+ placeholder={
+ emails.length === 0 ? "Search or enter email..." : ""
+ }
+ className="flex-1 min-w-[120px] bg-transparent outline-none placeholder:text-muted-foreground"
+ />
+ </div>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-[--radix-popover-trigger-width] p-0"
+ align="start"
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ onPointerDownOutside={(e) => {
+ // Don't close if clicking inside the trigger
+ const target = e.target as HTMLElement;
+ if (target.closest("[data-radix-popper-content-wrapper]")) {
+ e.preventDefault();
+ }
+ }}
+ >
+ <Command shouldFilter={false}>
+ <CommandList>
+ <CommandEmpty>
+ {inputValue ? (
+ <span
+ className={cn(
+ "text-sm",
+ inputError ? "text-destructive" : "text-muted-foreground"
+ )}
+ >
+ {isValidEmail(inputValue)
+ ? "Press Enter to add this email"
+ : "Enter a valid email address"}
+ </span>
+ ) : (
+ <span className="text-muted-foreground text-sm">
+ Search users or type an email
+ </span>
+ )}
+ </CommandEmpty>
+ {filteredOptions.length > 0 && (
+ <CommandGroup>
+ {filteredOptions.map((option) => (
+ <CommandItem
+ key={
+ option.type === "user"
+ ? `user-${option.id}`
+ : `group-${option.id}`
+ }
+ value={
+ option.type === "user"
+ ? `${option.name} ${option.email}`
+ : option.name
+ }
+ onSelect={() => handleSelect(option)}
+ className="cursor-pointer"
+ >
+ {option.type === "group" ? (
+ <div className="flex items-center gap-2">
+ <LuUsers className="h-4 w-4 text-muted-foreground" />
+ <div className="flex flex-col">
+ <span>{option.name}</span>
+ <span className="text-xs text-muted-foreground">
+ {option.memberCount} member
+ {option.memberCount !== 1 ? "s" : ""}
+ </span>
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col">
+ <span>{option.name}</span>
+ <span className="text-xs text-muted-foreground">
+ {option.email}
+ </span>
+ </div>
+ )}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ )}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ {helperText && <FormHelperText>{helperText}</FormHelperText>}
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ </FormControl>
+ );
+}
diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.ts
index c43372f2a0..8abf7eff21 100644
--- a/apps/erp/app/components/Form/index.ts
+++ b/apps/erp/app/components/Form/index.ts
@@ -45,6 +45,7 @@ import CustomerType from "./CustomerType";
import CustomFormFields from "./CustomFormFields";
import DefaultMethodType from "./DefaultMethodType";
import Department from "./Department";
+import EmailRecipients from "./EmailRecipients";
import EmojiPicker from "./EmojiPicker";
import Employee from "./Employee";
import Employees from "./Employees";
@@ -106,6 +107,7 @@ export {
DefaultDisabledSubmit,
DefaultMethodType,
Department,
+ EmailRecipients,
Employee,
Employees,
EmojiPicker,
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index dbe956cb63..c39f801cf4 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -109,7 +109,8 @@ export const supplierQuoteFinalizeValidator = z
.object({
notification: z.enum(["Email", "Share"]).optional(),
supplierContact: zfd.text(z.string().optional()),
- sendAttachments: zfd.checkbox()
+ sendAttachments: zfd.checkbox(),
+ cc: z.array(z.string()).optional()
})
.refine(
(data) => (data.notification === "Email" ? data.supplierContact : true),
@@ -267,7 +268,8 @@ export const supplierValidator = z.object({
currencyCode: zfd.text(z.string().optional()),
purchasingContactId: zfd.text(z.string().optional()),
invoicingContactId: zfd.text(z.string().optional()),
- website: zfd.text(z.string().url().optional())
+ website: zfd.text(z.string().optional()),
+ defaultCc: z.array(z.string().email()).default([])
});
export const supplierContactValidator = z.object({
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
index c3e806cb00..1d58be7b80 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
@@ -19,6 +19,7 @@ import type { z } from "zod";
import {
Currency,
CustomFormFields,
+ EmailRecipients,
Employee,
Hidden,
Input,
@@ -100,25 +101,19 @@ const SupplierForm = ({
)}
>
<Input autoFocus={!isEditing} name="name" label="Name" />
-
<SupplierStatus
name="supplierStatusId"
label="Supplier Status"
placeholder="Select Supplier Status"
/>
-
<SupplierType
name="supplierTypeId"
label="Supplier Type"
placeholder="Select Supplier Type"
/>
-
<Employee name="accountManagerId" label="Account Manager" />
-
<Currency name="currencyCode" label="Currency" />
-
<Input name="website" label="Website" />
-
{isEditing && (
<>
<SupplierContact
@@ -133,7 +128,7 @@ const SupplierForm = ({
/>
</>
)}
-
+ <EmailRecipients name="defaultCc" label="Default CC" />
<CustomFormFields table="supplier" />
</div>
</ModalCardBody>
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
index 5c96ce40a5..82114363b0 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
@@ -309,6 +309,7 @@ const SupplierQuoteHeader = () => {
onClose={sendModal.onClose}
fetcher={sendFetcher}
externalLinkId={routeData?.quote?.externalLinkId ?? ""}
+ defaultCc={routeData?.defaultCc ?? []}
/>
)}
<ShareQuoteModal
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSendModal.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSendModal.tsx
index 5b886fc59f..d458d3c340 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSendModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSendModal.tsx
@@ -19,7 +19,11 @@ import {
} from "@carbon/react";
import { useState } from "react";
import type { FetcherWithComponents } from "react-router";
-import { SelectControlled, SupplierContact } from "~/components/Form";
+import {
+ EmailRecipients,
+ SelectControlled,
+ SupplierContact
+} from "~/components/Form";
import { useIntegrations } from "~/hooks/useIntegrations";
import { path } from "~/utils/path";
import { supplierQuoteFinalizeValidator } from "../../purchasing.models";
@@ -30,13 +34,15 @@ type SupplierQuoteSendModalProps = {
quote?: SupplierQuote;
fetcher: FetcherWithComponents<{}>;
externalLinkId?: string;
+ defaultCc?: string[];
};
const SupplierQuoteSendModal = ({
quote,
onClose,
fetcher,
- externalLinkId
+ externalLinkId,
+ defaultCc = []
}: SupplierQuoteSendModalProps) => {
const integrations = useIntegrations();
const canEmail = integrations.has("resend");
@@ -106,7 +112,8 @@ const SupplierQuoteSendModal = ({
defaultValues={{
notification: notificationType as "Email" | "Share",
supplierContact: quote?.supplierContactId ?? undefined,
- sendAttachments: sendAttachments
+ sendAttachments: sendAttachments,
+ cc: defaultCc
}}
fetcher={fetcher}
>
@@ -163,6 +170,7 @@ const SupplierQuoteSendModal = ({
name="supplierContact"
supplier={quote?.supplierId ?? undefined}
/>
+ <EmailRecipients name="cc" label="CC" type="employee" />
<HStack spacing={2}>
<Checkbox
id="sendAttachments"
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index d8815b4f51..732543dc41 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -74,7 +74,8 @@ export const customerValidator = z.object({
),
salesContactId: zfd.text(z.string().optional()),
invoicingContactId: zfd.text(z.string().optional()),
- website: zfd.text(z.string().url().optional())
+ website: zfd.text(z.string().optional()),
+ defaultCc: z.array(z.string().email()).default([])
});
export const customerPaymentValidator = z.object({
@@ -485,7 +486,8 @@ export const quoteOperationValidator = z
export const quoteFinalizeValidator = z
.object({
notification: z.enum(["Email", "None"]).optional(),
- customerContact: zfd.text(z.string().optional())
+ customerContact: zfd.text(z.string().optional()),
+ cc: z.array(z.string()).optional()
})
.refine(
(data) => (data.notification === "Email" ? data.customerContact : true),
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
index 1143b44f61..3af3b3b9cc 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
@@ -22,6 +22,7 @@ import {
CustomerStatus,
CustomerType,
CustomFormFields,
+ EmailRecipients,
Employee,
Hidden,
Input,
@@ -146,6 +147,7 @@ const CustomerForm = ({
/>
</>
)}
+ <EmailRecipients name="defaultCc" label="Default CC" />
<CustomFormFields table="customer" />
</div>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
index 74a0ce1528..e5f8b0433b 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
@@ -19,7 +19,11 @@ import { useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import type { FetcherWithComponents } from "react-router";
import { useParams } from "react-router";
-import { CustomerContact, SelectControlled } from "~/components/Form";
+import {
+ CustomerContact,
+ EmailRecipients,
+ SelectControlled
+} from "~/components/Form";
import { useIntegrations } from "~/hooks/useIntegrations";
import { path } from "~/utils/path";
import { quoteFinalizeValidator } from "../../sales.models";
@@ -41,6 +45,7 @@ type QuotationFinalizeModalProps = {
pricing: QuotationPrice[];
shipment: QuotationShipment | null;
fetcher: FetcherWithComponents<{}>;
+ defaultCc?: string[];
};
const QuotationFinalizeModal = ({
@@ -48,6 +53,7 @@ const QuotationFinalizeModal = ({
onClose,
fetcher,
shipment,
+ defaultCc = [],
pricing
}: QuotationFinalizeModalProps) => {
const { quoteId } = useParams();
@@ -136,7 +142,8 @@ const QuotationFinalizeModal = ({
onSubmit={onClose}
defaultValues={{
notification: notificationType as "Email" | "None",
- customerContact: quote?.customerContactId ?? undefined
+ customerContact: quote?.customerContactId ?? undefined,
+ cc: defaultCc
}}
fetcher={fetcher}
>
@@ -194,10 +201,13 @@ const QuotationFinalizeModal = ({
/>
)}
{notificationType === "Email" && (
- <CustomerContact
- name="customerContact"
- customer={quote?.customerId ?? undefined}
- />
+ <>
+ <CustomerContact
+ name="customerContact"
+ customer={quote?.customerId ?? undefined}
+ />
+ <EmailRecipients name="cc" label="CC" type="employee" />
+ </>
)}
</VStack>
</ModalBody>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index 2221b622fb..c40b459838 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -353,6 +353,7 @@ const QuoteHeader = () => {
shipment={routeData?.shipment ?? null}
onClose={finalizeModal.onClose}
fetcher={finalizeFetcher}
+ defaultCc={routeData?.defaultCc ?? []}
/>
)}
{createRevisionModal.isOpen && (
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 6ba8c94694..3fe3da1d7b 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -151,6 +151,14 @@ export const supplierQuoteNotificationValidator = z.object({
.optional()
});
+export const defaultSupplierCcValidator = z.object({
+ defaultSupplierCc: z.array(z.string().email()).optional()
+});
+
+export const defaultCustomerCcValidator = z.object({
+ defaultCustomerCc: z.array(z.string().email()).optional()
+});
+
export const sequenceValidator = z.object({
table: z.string().min(1, { message: "Table is required" }),
prefix: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 9fe36882b3..72bc7d6e20 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -626,6 +626,28 @@ export async function updatePurchasePriceUpdateTimingSetting(
.eq("id", companyId);
}
+export async function updateDefaultSupplierCc(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ defaultSupplierCc: string[]
+) {
+ return client
+ .from("companySettings")
+ .update(sanitize({ defaultSupplierCc }))
+ .eq("id", companyId);
+}
+
+export async function updateDefaultCustomerCc(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ defaultCustomerCc: string[]
+) {
+ return client
+ .from("companySettings")
+ .update(sanitize({ defaultCustomerCc }))
+ .eq("id", companyId);
+}
+
export async function updateSequence(
client: SupabaseClient<Database>,
table: string,
diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.ts
index c33b7ef444..eb53030d3a 100644
--- a/apps/erp/app/modules/users/users.service.ts
+++ b/apps/erp/app/modules/users/users.service.ts
@@ -49,7 +49,7 @@ export async function getCustomers(
let query = client
.from("customerAccount")
.select(
- `active, user!inner(id, fullName, firstName, lastName, email, avatarUrl),
+ `active, user!inner(id, fullName, firstName, lastName, email, avatarUrl),
customer!inner(name, customerType!left(name))`,
{ count: "exact" }
)
@@ -187,6 +187,21 @@ export async function getGroups(
return query;
}
+export async function getGroupEmails(
+ client: SupabaseClient<Database>,
+ groupIds: string[]
+): Promise<string[]> {
+ if (!groupIds || groupIds.length === 0) return [];
+
+ const userIdsResult = (await client.rpc("users_for_groups", {
+ groups: groupIds
+ })) as { data: string[]; error: unknown };
+
+ if (userIdsResult.error || !Array.isArray(userIdsResult.data)) return [];
+
+ return getUserEmails(client, userIdsResult.data);
+}
+
export async function getPermissionsByEmployeeType(
client: SupabaseClient<Database>,
employeeTypeId: string
@@ -208,7 +223,7 @@ export async function getSuppliers(
let query = client
.from("supplierAccount")
.select(
- `active, user!inner(id, fullName, firstName, lastName, email, avatarUrl),
+ `active, user!inner(id, fullName, firstName, lastName, email, avatarUrl),
supplier!inner(name, supplierType!left(name))`,
{ count: "exact" }
)
@@ -233,6 +248,25 @@ export async function getUsers(client: SupabaseClient<Database>) {
);
}
+export async function getUserEmails(
+ client: SupabaseClient<Database>,
+ userIds: string[]
+): Promise<string[]> {
+ if (!userIds || userIds.length === 0) return [];
+
+ const result = await client
+ .from("user")
+ .select("email")
+ .in("id", userIds)
+ .eq("active", true);
+
+ if (result.error || !result.data) return [];
+
+ return result.data
+ .map((u) => u.email)
+ .filter((email): email is string => !!email);
+}
+
export async function insertEmployeeType(
client: SupabaseClient<Database>,
employeeType: { name: string; companyId: string }
diff --git a/apps/erp/app/routes/x+/customer+/$customerId.details.tsx b/apps/erp/app/routes/x+/customer+/$customerId.details.tsx
index d87c5d6d2e..34f630b72f 100644
--- a/apps/erp/app/routes/x+/customer+/$customerId.details.tsx
+++ b/apps/erp/app/routes/x+/customer+/$customerId.details.tsx
@@ -71,6 +71,7 @@ export default function CustomerEditRoute() {
website: routeData?.customer?.website ?? "",
salesContactId: routeData?.customer?.salesContactId ?? undefined,
invoicingContactId: routeData?.customer?.invoicingContactId ?? undefined,
+ defaultCc: routeData?.customer?.defaultCc ?? [],
...getCustomFields(routeData?.customer?.customFields)
};
diff --git a/apps/erp/app/routes/x+/customer+/new.tsx b/apps/erp/app/routes/x+/customer+/new.tsx
index c07f475715..447fa4ce18 100644
--- a/apps/erp/app/routes/x+/customer+/new.tsx
+++ b/apps/erp/app/routes/x+/customer+/new.tsx
@@ -73,7 +73,8 @@ export default function CustomersNewRoute() {
phone: "",
fax: "",
website: "",
- taxPercent: 0
+ taxPercent: 0,
+ defaultCC: []
};
return (
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
index 72ab7e0067..59b54f580f 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -142,7 +142,11 @@ export async function action(args: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { notification, customerContact: customerContactId } = validation.data;
+ const {
+ notification,
+ customerContact: customerContactId,
+ cc: ccSelections
+ } = validation.data;
switch (notification) {
case "Email":
@@ -188,6 +192,7 @@ export async function action(args: ActionFunctionArgs) {
await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
to: [user.data.email, customerContact.data.contact!.email!],
+ cc: ccSelections?.length ? ccSelections : undefined,
from: user.data.email,
subject: `Quote ${quote.data.quoteId}`,
html,
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsx
index 410e9de676..5af6929841 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.tsx
@@ -35,6 +35,7 @@ import {
QuoteProperties
} from "~/modules/sales/ui/Quotes";
import { useOptimisticDocumentDrag } from "~/modules/sales/ui/Quotes/QuoteExplorer";
+import { getCompanySettings } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -74,7 +75,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
prices,
opportunity,
methods,
- opportunityDocuments
+ opportunityDocuments,
+ companySettings
] = await Promise.all([
getCustomer(client, quote.data?.customerId ?? ""),
getQuoteShipment(client, quoteId),
@@ -83,7 +85,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getQuoteLinePricesByQuoteId(client, quoteId),
getOpportunity(client, quote.data?.opportunityId),
getQuoteMethodTrees(client, quoteId),
- getOpportunityDocuments(client, companyId, quote.data?.opportunityId ?? "")
+ getOpportunityDocuments(client, companyId, quote.data?.opportunityId ?? ""),
+ getCompanySettings(client, companyId)
]);
if (!opportunity.data) throw new Error("Failed to get opportunity record");
@@ -132,6 +135,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ const defaultCc =
+ customer.data?.defaultCc?.length > 0
+ ? customer.data.defaultCc
+ : (companySettings.data?.defaultCustomerCc ?? []);
+
return {
quote: quote.data,
customer: customer.data,
@@ -143,7 +151,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
payment: payment.data,
opportunity: opportunity.data,
exchangeRate,
- salesOrderLines: salesOrderLines?.data ?? null
+ salesOrderLines: salesOrderLines?.data ?? null,
+ defaultCc
};
}
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsx
index 72a262cfa9..34beda28b4 100644
--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx
@@ -27,14 +27,16 @@ import { useEffect, useState } from "react";
import { LuCircleCheck } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
-import { Users } from "~/components/Form";
+import { EmailRecipients, Users } from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
import {
+ defaultSupplierCcValidator,
getCompanySettings,
getTerms,
purchasePriceUpdateTimingTypes,
purchasePriceUpdateTimingValidator,
supplierQuoteNotificationValidator,
+ updateDefaultSupplierCc,
updatePurchasePriceUpdateTimingSetting,
updateSupplierQuoteNotificationSetting
} from "~/modules/settings";
@@ -135,6 +137,33 @@ export async function action({ request }: ActionFunctionArgs) {
success: true,
message: "Supplier quote notification setting updated"
};
+
+ case "defaultSupplierCc":
+ const defaultSupplierCcValidation = await validator(
+ defaultSupplierCcValidator
+ ).validate(formData);
+
+ if (defaultSupplierCcValidation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const defaultSupplierCcResult = await updateDefaultSupplierCc(
+ client,
+ companyId,
+ defaultSupplierCcValidation.data.defaultSupplierCc ?? []
+ );
+
+ if (defaultSupplierCcResult.error) {
+ return {
+ success: false,
+ message: defaultSupplierCcResult.error.message
+ };
+ }
+
+ return {
+ success: true,
+ message: "Default supplier CC updated"
+ };
}
return { success: false, message: "Unknown intent" };
@@ -295,6 +324,44 @@ export default function PurchasingSettingsRoute() {
</CardFooter>
</ValidatedForm>
</Card>
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={defaultSupplierCcValidator}
+ defaultValues={{
+ defaultSupplierCc: companySettings.defaultSupplierCc ?? []
+ }}
+ fetcher={fetcher}
+ >
+ <input type="hidden" name="intent" value="defaultSupplierCc" />
+ <CardHeader>
+ <CardTitle>Default CC for Supplier Emails</CardTitle>
+ <CardDescription>
+ These email addresses will be automatically CC'd on all emails
+ sent to suppliers (quotes, purchase orders, etc.).
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-8 max-w-[400px]">
+ <EmailRecipients
+ name="defaultSupplierCc"
+ label="Default CC Recipients"
+ />
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "defaultSupplierCc"
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
<Card>
<HStack className="justify-between items-start">
<CardHeader>
diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsx
index 2b4217b513..85b74c5c1b 100644
--- a/apps/erp/app/routes/x+/settings+/sales.tsx
+++ b/apps/erp/app/routes/x+/settings+/sales.tsx
@@ -28,13 +28,15 @@ import { useEffect, useState } from "react";
import { LuCircleCheck } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
-import { Users } from "~/components/Form";
+import { EmailRecipients, Users } from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
import {
+ defaultCustomerCcValidator,
digitalQuoteValidator,
getCompanySettings,
getTerms,
rfqReadyValidator,
+ updateDefaultCustomerCc,
updateDigitalQuoteSetting,
updateRfqReadySetting
} from "~/modules/settings";
@@ -110,6 +112,35 @@ export async function action({ request }: ActionFunctionArgs) {
if (rfqSettings.error)
return { success: false, message: rfqSettings.error.message };
+
+ return { success: true, message: "RFQ setting updated" };
+
+ case "defaultCustomerCc":
+ const defaultCustomerCcValidation = await validator(
+ defaultCustomerCcValidator
+ ).validate(formData);
+
+ if (defaultCustomerCcValidation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const defaultCustomerCcResult = await updateDefaultCustomerCc(
+ client,
+ companyId,
+ defaultCustomerCcValidation.data.defaultCustomerCc ?? []
+ );
+
+ if (defaultCustomerCcResult.error) {
+ return {
+ success: false,
+ message: defaultCustomerCcResult.error.message
+ };
+ }
+
+ return {
+ success: true,
+ message: "Default customer CC updated"
+ };
}
return { success: true, message: "Digital quote setting updated" };
@@ -283,6 +314,44 @@ export default function SalesSettingsRoute() {
</CardFooter>
</ValidatedForm>
</Card>
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={defaultCustomerCcValidator}
+ defaultValues={{
+ defaultCustomerCc: companySettings.defaultCustomerCc ?? []
+ }}
+ fetcher={fetcher}
+ >
+ <input type="hidden" name="intent" value="defaultCustomerCc" />
+ <CardHeader>
+ <CardTitle>Default CC for Customer Emails</CardTitle>
+ <CardDescription>
+ These email addresses will be automatically CC'd on all quote
+ emails sent to customers.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-8 max-w-[400px]">
+ <EmailRecipients
+ name="defaultCustomerCc"
+ label="Default CC Recipients"
+ />
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "defaultCustomerCc"
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
<Card>
<HStack className="justify-between items-start">
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
index d695b120d9..822bc4aefd 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
@@ -69,6 +69,7 @@ export default function SupplierEditRoute() {
website: routeData?.supplier?.website ?? "",
purchasingContactId: routeData?.supplier?.purchasingContactId ?? undefined,
invoicingContactId: routeData?.supplier?.invoicingContactId ?? undefined,
+ defaultCc: routeData?.supplier?.defaultCc ?? [],
...getCustomFields(routeData?.supplier?.customFields)
};
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
index c74677848f..4b933c05af 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
@@ -87,7 +87,8 @@ export async function action(args: ActionFunctionArgs) {
const {
notification,
supplierContact: supplierContactId,
- sendAttachments
+ sendAttachments,
+ cc: ccSelections
} = validation.data;
switch (notification) {
@@ -153,11 +154,14 @@ export async function action(args: ActionFunctionArgs) {
const emailSubject = `Supplier Quote ${supplierQuote.data.supplierQuoteId} from ${company.data.name}`;
- const emailBody = `Hey ${supplierContact.data.contact.firstName || "there"},\n\nPlease provide pricing and lead time(s) for the linked quote:`;
+ const emailBody = `Hey ${
+ supplierContact.data.contact.firstName || "there"
+ },\n\nPlease provide pricing and lead time(s) for the linked quote:`;
const emailSignature = `Thanks,\n${user.data.firstName} ${user.data.lastName}\n${company.data.name}`;
await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
to: [user.data.email, supplierContact.data.contact?.email ?? ""],
+ cc: ccSelections?.length ? ccSelections : undefined,
from: user.data.email,
subject: emailSubject,
html: `${emailBody.replace(
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.tsx
index e1d47db362..657e51bc89 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.tsx
@@ -7,6 +7,7 @@ import { Outlet, redirect, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
import { getCurrencyByCode } from "~/modules/accounting";
import {
+ getSupplier,
getSupplierInteraction,
getSupplierInteractionDocuments,
getSupplierQuote,
@@ -18,6 +19,7 @@ import {
SupplierQuoteProperties
} from "~/modules/purchasing/ui/SupplierQuote";
import SupplierQuoteExplorer from "~/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer";
+import { getCompanySettings } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -49,10 +51,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const [supplierInteraction, presentationCurrency] = await Promise.all([
- getSupplierInteraction(serviceRole, quote.data.supplierInteractionId!),
- getCurrencyByCode(serviceRole, companyId, quote.data.currencyCode!)
- ]);
+ const [supplierInteraction, presentationCurrency, supplier, companySettings] =
+ await Promise.all([
+ getSupplierInteraction(serviceRole, quote.data.supplierInteractionId!),
+ getCurrencyByCode(serviceRole, companyId, quote.data.currencyCode!),
+ getSupplier(serviceRole, quote.data.supplierId!),
+ getCompanySettings(serviceRole, companyId)
+ ]);
if (supplierInteraction.error) {
throw redirect(
@@ -72,6 +77,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
exchangeRate = presentationCurrency.data.exchangeRate;
}
+ // Compute default CC: use supplier's if set, otherwise company's
+ const defaultCc =
+ supplier.data?.defaultCc?.length > 0
+ ? supplier.data.defaultCc
+ : (companySettings.data?.defaultSupplierCc ?? []);
+
return {
quote: quote.data,
lines: lines.data ?? [],
@@ -82,7 +93,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
quote.data.supplierInteractionId!
),
interaction: supplierInteraction.data,
- exchangeRate
+ exchangeRate,
+ defaultCc
};
}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index edb170f99f..182a9d5c75 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -13122,6 +13122,9 @@ export default {
{
$ref: "#/parameters/rowFilter.customers.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.customers.defaultCc",
+ },
{
$ref: "#/parameters/rowFilter.customers.type",
},
@@ -29124,6 +29127,9 @@ export default {
{
$ref: "#/parameters/rowFilter.suppliers.embedding",
},
+ {
+ $ref: "#/parameters/rowFilter.suppliers.defaultCc",
+ },
{
$ref: "#/parameters/rowFilter.suppliers.type",
},
@@ -37269,6 +37275,9 @@ export default {
{
$ref: "#/parameters/rowFilter.customer.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.customer.defaultCc",
+ },
{
$ref: "#/parameters/select",
},
@@ -37400,6 +37409,9 @@ export default {
{
$ref: "#/parameters/rowFilter.customer.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.customer.defaultCc",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -37485,6 +37497,9 @@ export default {
{
$ref: "#/parameters/rowFilter.customer.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.customer.defaultCc",
+ },
{
$ref: "#/parameters/body.customer",
},
@@ -53049,6 +53064,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.supplier.defaultCc",
+ },
{
$ref: "#/parameters/select",
},
@@ -53180,6 +53198,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.supplier.defaultCc",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -53265,6 +53286,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.invoicingContactId",
},
+ {
+ $ref: "#/parameters/rowFilter.supplier.defaultCc",
+ },
{
$ref: "#/parameters/body.supplier",
},
@@ -59619,6 +59643,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.otherDispatchNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.defaultSupplierCc",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companySettings.defaultCustomerCc",
+ },
{
$ref: "#/parameters/select",
},
@@ -59741,6 +59771,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.otherDispatchNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.defaultSupplierCc",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companySettings.defaultCustomerCc",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -59817,6 +59853,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.otherDispatchNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.defaultSupplierCc",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companySettings.defaultCustomerCc",
+ },
{
$ref: "#/parameters/body.companySettings",
},
@@ -71232,6 +71274,13 @@ export default {
format: "text",
type: "string",
},
+ defaultCc: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
type: {
format: "text",
type: "string",
@@ -78505,6 +78554,13 @@ export default {
format: "extensions.halfvec(384)",
type: "string",
},
+ defaultCc: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
type: {
format: "text",
type: "string",
@@ -82261,6 +82317,13 @@ export default {
format: "text",
type: "string",
},
+ defaultCc: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
},
type: "object",
},
@@ -90161,6 +90224,13 @@ export default {
format: "text",
type: "string",
},
+ defaultCc: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
},
type: "object",
},
@@ -93450,6 +93520,20 @@ export default {
},
type: "array",
},
+ defaultSupplierCc: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ defaultCustomerCc: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
},
type: "object",
},
@@ -100974,6 +101058,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.customers.defaultCc": {
+ name: "defaultCc",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.customers.type": {
name: "type",
required: false,
@@ -109061,6 +109151,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.suppliers.defaultCc": {
+ name: "defaultCc",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.suppliers.type": {
name: "type",
required: false,
@@ -113319,6 +113415,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.customer.defaultCc": {
+ name: "defaultCc",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.purchaseOrder": {
name: "purchaseOrder",
description: "purchaseOrder",
@@ -122315,6 +122417,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.supplier.defaultCc": {
+ name: "defaultCc",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.stockTransfer": {
name: "stockTransfer",
description: "stockTransfer",
@@ -125924,6 +126032,18 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.companySettings.defaultSupplierCc": {
+ name: "defaultSupplierCc",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.companySettings.defaultCustomerCc": {
+ name: "defaultCustomerCc",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a9070c56ea..b78b185884 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2250,6 +2250,8 @@ export type Database = {
}
companySettings: {
Row: {
+ defaultCustomerCc: string[] | null
+ defaultSupplierCc: string[] | null
digitalQuoteEnabled: boolean
digitalQuoteIncludesPurchaseOrders: boolean
digitalQuoteNotificationGroup: string[]
@@ -2273,6 +2275,8 @@ export type Database = {
useMetric: boolean
}
Insert: {
+ defaultCustomerCc?: string[] | null
+ defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
digitalQuoteIncludesPurchaseOrders?: boolean
digitalQuoteNotificationGroup?: string[]
@@ -2296,6 +2300,8 @@ export type Database = {
useMetric?: boolean
}
Update: {
+ defaultCustomerCc?: string[] | null
+ defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
digitalQuoteIncludesPurchaseOrders?: boolean
digitalQuoteNotificationGroup?: string[]
@@ -3611,6 +3617,7 @@ export type Database = {
customerStatusId: string | null
customerTypeId: string | null
customFields: Json | null
+ defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
@@ -3637,6 +3644,7 @@ export type Database = {
customerStatusId?: string | null
customerTypeId?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -3663,6 +3671,7 @@ export type Database = {
customerStatusId?: string | null
customerTypeId?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -33591,6 +33600,7 @@ export type Database = {
createdBy: string | null
currencyCode: string | null
customFields: Json | null
+ defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
@@ -33617,6 +33627,7 @@ export type Database = {
createdBy?: string | null
currencyCode?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -33643,6 +33654,7 @@ export type Database = {
createdBy?: string | null
currencyCode?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -41430,6 +41442,7 @@ export type Database = {
customerStatusId: string | null
customerTypeId: string | null
customFields: Json | null
+ defaultCc: string[] | null
fax: string | null
id: string | null
invoicingContactId: string | null
@@ -51984,6 +51997,7 @@ export type Database = {
createdBy: string | null
currencyCode: string | null
customFields: Json | null
+ defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a9070c56ea..b78b185884 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2250,6 +2250,8 @@ export type Database = {
}
companySettings: {
Row: {
+ defaultCustomerCc: string[] | null
+ defaultSupplierCc: string[] | null
digitalQuoteEnabled: boolean
digitalQuoteIncludesPurchaseOrders: boolean
digitalQuoteNotificationGroup: string[]
@@ -2273,6 +2275,8 @@ export type Database = {
useMetric: boolean
}
Insert: {
+ defaultCustomerCc?: string[] | null
+ defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
digitalQuoteIncludesPurchaseOrders?: boolean
digitalQuoteNotificationGroup?: string[]
@@ -2296,6 +2300,8 @@ export type Database = {
useMetric?: boolean
}
Update: {
+ defaultCustomerCc?: string[] | null
+ defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
digitalQuoteIncludesPurchaseOrders?: boolean
digitalQuoteNotificationGroup?: string[]
@@ -3611,6 +3617,7 @@ export type Database = {
customerStatusId: string | null
customerTypeId: string | null
customFields: Json | null
+ defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
@@ -3637,6 +3644,7 @@ export type Database = {
customerStatusId?: string | null
customerTypeId?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -3663,6 +3671,7 @@ export type Database = {
customerStatusId?: string | null
customerTypeId?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -33591,6 +33600,7 @@ export type Database = {
createdBy: string | null
currencyCode: string | null
customFields: Json | null
+ defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
@@ -33617,6 +33627,7 @@ export type Database = {
createdBy?: string | null
currencyCode?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -33643,6 +33654,7 @@ export type Database = {
createdBy?: string | null
currencyCode?: string | null
customFields?: Json | null
+ defaultCc?: string[] | null
embedding?: unknown
externalId?: Json | null
fax?: string | null
@@ -41430,6 +41442,7 @@ export type Database = {
customerStatusId: string | null
customerTypeId: string | null
customFields: Json | null
+ defaultCc: string[] | null
fax: string | null
id: string | null
invoicingContactId: string | null
@@ -51984,6 +51997,7 @@ export type Database = {
createdBy: string | null
currencyCode: string | null
customFields: Json | null
+ defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
diff --git a/packages/database/supabase/migrations/20260127130101_default_cc_settings.sql b/packages/database/supabase/migrations/20260127130101_default_cc_settings.sql
new file mode 100644
index 0000000000..2f7204da03
--- /dev/null
+++ b/packages/database/supabase/migrations/20260127130101_default_cc_settings.sql
@@ -0,0 +1,125 @@
+-- Add default CC settings at company level
+ALTER TABLE "companySettings"
+ADD COLUMN IF NOT EXISTS "defaultSupplierCc" TEXT[] DEFAULT '{}',
+ADD COLUMN IF NOT EXISTS "defaultCustomerCc" TEXT[] DEFAULT '{}';
+
+-- Add default CC at supplier level
+ALTER TABLE "supplier"
+ADD COLUMN IF NOT EXISTS "defaultCc" TEXT[] DEFAULT '{}';
+
+-- Add default CC at customer level
+ALTER TABLE "customer"
+ADD COLUMN IF NOT EXISTS "defaultCc" TEXT[] DEFAULT '{}';
+
+-- Recreate customers view to include defaultCc
+DROP VIEW IF EXISTS "customers";
+
+CREATE OR REPLACE VIEW "customers" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ c.id,
+ c.name,
+ c."customerTypeId",
+ c."customerStatusId",
+ c."taxId",
+ c."accountManagerId",
+ c.logo,
+ c.assignee,
+ c."taxPercent",
+ c.website,
+ c."companyId",
+ c."createdAt",
+ c."createdBy",
+ c."updatedAt",
+ c."updatedBy",
+ c."customFields",
+ c."currencyCode",
+ c."salesContactId",
+ c."invoicingContactId",
+ c."defaultCc",
+ ct.name AS "type",
+ cs.name AS "status",
+ so.count AS "orderCount",
+ pc."workPhone" AS "phone",
+ pc."fax" AS "fax"
+ FROM "customer" c
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"
+ LEFT JOIN (
+ SELECT
+ "customerId",
+ COUNT(*) AS "count"
+ FROM "salesOrder"
+ GROUP BY "customerId"
+ ) so ON so."customerId" = c.id
+ LEFT JOIN (
+ SELECT DISTINCT ON (cc."customerId")
+ cc."customerId",
+ co."workPhone",
+ co."fax"
+ FROM "customerContact" cc
+ INNER JOIN "contact" co ON co.id = cc."contactId"
+ ORDER BY cc."customerId"
+ ) pc ON pc."customerId" = c.id;
+
+-- Recreate suppliers view to include defaultCc
+DROP VIEW IF EXISTS "suppliers";
+
+CREATE OR REPLACE VIEW "suppliers" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ s.id,
+ s.name,
+ s."supplierTypeId",
+ s."supplierStatusId",
+ s."taxId",
+ s."accountManagerId",
+ s.logo,
+ s.assignee,
+ s."companyId",
+ s."createdAt",
+ s."createdBy",
+ s."updatedAt",
+ s."updatedBy",
+ s."customFields",
+ s."currencyCode",
+ s.website,
+ s."externalId",
+ s.tags,
+ s."taxPercent",
+ s."purchasingContactId",
+ s."invoicingContactId",
+ s.embedding,
+ s."defaultCc",
+ st.name AS "type",
+ ss.name AS "status",
+ po.count AS "orderCount",
+ p.count AS "partCount",
+ pc."workPhone" AS "phone",
+ pc.fax AS "fax"
+ FROM "supplier" s
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "purchaseOrder"
+ GROUP BY "supplierId"
+ ) po ON po."supplierId" = s.id
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "supplierPart"
+ GROUP BY "supplierId"
+ ) p ON p."supplierId" = s.id
+ LEFT JOIN (
+ SELECT DISTINCT ON (sc."supplierId")
+ sc."supplierId" AS id,
+ co."workPhone",
+ co."fax"
+ FROM "supplierContact" sc
+ JOIN "contact" co
+ ON co.id = sc."contactId"
+ ORDER BY sc."supplierId", sc.id
+ ) pc
+ ON pc.id = s.id;
diff --git a/packages/jobs/trigger/send-email-resend.ts b/packages/jobs/trigger/send-email-resend.ts
index 8dd91ec679..1cdeb872ab 100644
--- a/packages/jobs/trigger/send-email-resend.ts
+++ b/packages/jobs/trigger/send-email-resend.ts
@@ -32,7 +32,7 @@ export const sendEmailResendTask = task({
]);
const integrationMetadata = ResendConfig.schema.safeParse(
- integration?.data?.metadata
+ integration?.data?.metadata,
);
console.info(integrationMetadata.data?.fromEmail ?? "No email found");
@@ -48,6 +48,7 @@ export const sendEmailResendTask = task({
integrationMetadata.data.fromEmail ?? "[email protected]"
}>`,
to: payload.to,
+ cc: payload.cc,
reply_to: payload.from,
subject: payload.subject,
html: payload.html,