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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon } from "@carbon/api/carbon.server";
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import {
Hidden,
Input,
PhoneInput,
Select,
Submit,
ValidatedForm,
validator
} from "@carbon/form";
import { useAction } from "@carbon/query";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
Heading,
HStack,
ScrollArea,
Switch,
toast,
VStack
} from "@carbon/react";
import { getStripeConnectAccountId } from "@carbon/stripe/send-sales-invoice.server";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useState } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { z } from "zod";
import { EmailRecipients, Users } from "~/components/Form";
import Country from "~/components/Form/Country";
import { useSavedToggle } from "~/hooks/useSavedToggle";
import {
accountsReceivableBillingAddressValidator,
accountsReceivableEmailValidator,
billingAddressFields,
defaultCustomerCcValidator,
invoiceAutomations,
invoiceAutomationValidator,
invoiceNotificationValidator,
settingsToggle
} from "~/modules/settings/settings.models";
import {
getAccountsReceivableBillingAddress,
getCompanySettings
} from "~/modules/settings/settings.service";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const handle: Handle = {
breadcrumb: msg`Invoicing`,
to: path.to.invoicingSettings
};
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "settings"
});
const [companySettings, arBillingAddress, stripeAccountId] =
await Promise.all([
getCompanySettings(client, companyId),
getAccountsReceivableBillingAddress(client, companyId),
getStripeConnectAccountId(getCarbonServiceRole(), companyId)
]);
if (!companySettings.data)
throw redirect(
path.to.settings,
await flash(
request,
error(companySettings.error, "Failed to get company settings")
)
);
return {
companySettings: companySettings.data,
arBillingAddress: arBillingAddress.data,
isStripeConnected: stripeAccountId !== null
};
}
// One form per card, told apart by its intent: each becomes the fields of
// `settings.invoicing.update` it saves (the operation drops `intent`).
const invoicingSettingsForm = z.discriminatedUnion("intent", [
invoiceAutomationValidator.extend({ intent: z.literal("invoiceAutomation") }),
accountsReceivableEmailValidator
.extend({ intent: z.literal("receivablesEmail") })
.transform(({ accountsReceivableEmail }) => ({
accountsReceivableEmail: accountsReceivableEmail ?? null
})),
invoiceNotificationValidator
.extend({ intent: z.literal("invoiceNotifications") })
.transform(({ invoiceNotificationGroup }) => ({
invoiceNotificationGroup: invoiceNotificationGroup ?? []
})),
settingsToggle(
"accountsReceivableAddressToggle",
"accountsReceivableAddress"
),
accountsReceivableBillingAddressValidator
.extend({ intent: z.literal("accountsReceivableBillingAddress") })
.transform((form) => ({
accountsReceivableBillingAddress: billingAddressFields(form)
})),
defaultCustomerCcValidator
.extend({ intent: z.literal("emails") })
.transform(({ defaultCustomerCc }) => ({
defaultCustomerCc: defaultCustomerCc ?? []
}))
]);
export async function action(args: ActionFunctionArgs) {
const input = await validator(invoicingSettingsForm).request(args);
if ("invalid" in input) return input.invalid;
const api = await carbon(args.request);
return api.settings.updateInvoicingSettings(input.data);
}
export default function InvoicingSettingsRoute() {
const { t } = useLingui();
const { companySettings, arBillingAddress, isStripeConnected } =
useLoaderData<typeof loader>();
const fetcher = useAction<typeof action>({
onSuccess: ({ data }) => {
if (!data) return;
if (data.invoiceAutomation)
toast.success(t`Recurring invoice setting updated`);
else if (data.accountsReceivableEmail !== undefined)
toast.success(t`Receivables email updated`);
else if (data.invoiceNotificationGroup)
toast.success(t`Invoice notification settings updated`);
else if (data.accountsReceivableBillingAddress)
toast.success(t`Accounts receivable billing address updated`);
else toast.success(t`Customer email settings updated`);
}
});
const toggleFetcher = useAction<typeof action>({
onSuccess: ({ data }) => {
if (data?.accountsReceivableAddress === undefined) return;
toast.success(
data.accountsReceivableAddress
? t`Accounts receivable billing address enabled`
: t`Accounts receivable billing address disabled`
);
}
});
const arAddressEnabled = useSavedToggle(
toggleFetcher,
"accountsReceivableAddressToggle",
companySettings.accountsReceivableAddress ?? false
);
const invoiceAutomationLabels: Record<
(typeof invoiceAutomations)[number],
string
> = {
"Draft Only": t`Draft only`,
Post: t`Post`,
"Post and Email": t`Post and email`,
"Post and Send via Stripe": t`Post and send via Stripe`
};
// Only the user's pick is state; until they pick, the saved mode shows.
const [pickedInvoiceAutomation, setInvoiceAutomation] = useState<
string | null
>(null);
const invoiceAutomation =
pickedInvoiceAutomation ??
companySettings.invoiceAutomation ??
"Post and Email";
const handleArAddressToggle = useCallback(
(checked: boolean) => {
toggleFetcher.submit(
{
intent: "accountsReceivableAddressToggle",
enabled: checked.toString()
},
{ method: "POST" }
);
},
[toggleFetcher]
);
return (
<ScrollArea className="w-full h-[calc(100dvh-var(--topbar-height)-var(--content-inset))]">
<VStack
spacing={4}
className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
>
<Heading size="h3">
<Trans>Invoicing</Trans>
</Heading>
<Card>
<ValidatedForm
method="post"
validator={invoiceAutomationValidator}
defaultValues={{
invoiceAutomation:
companySettings.invoiceAutomation ?? "Post and Email"
}}
fetcher={fetcher}
>
<Hidden name="intent" value="invoiceAutomation" />
<CardHeader>
<CardTitle>
<Trans>Recurring Invoices</Trans>
</CardTitle>
<CardDescription>
<Trans>
What happens to invoices created automatically each day from
rental agreements and contracts. Invoices with rental charges,
credits, re-bills of voided invoices or rule violations always
wait for review.
</Trans>
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-8 max-w-[400px]">
<Select
name="invoiceAutomation"
label={t`When an invoice is created`}
options={invoiceAutomations.map((mode) => ({
value: mode,
label: invoiceAutomationLabels[mode],
helper:
mode === "Post and Send via Stripe" && !isStripeConnected
? t`Connect Stripe in Integrations first`
: undefined
}))}
onChange={(selected) =>
setInvoiceAutomation(selected?.value ?? "")
}
helperText={
invoiceAutomation === "Post and Send via Stripe"
? isStripeConnected
? t`Posts the invoice and sends it through your connected Stripe account with a payment link. An invoice for a customer with no linked Stripe customer is posted and marked not sent.`
: t`Connect Stripe in Integrations first`
: undefined
}
/>
</div>
</CardContent>
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
isLoading={
fetcher.state !== "idle" &&
fetcher.formData?.get("intent") === "invoiceAutomation"
}
>
<Trans>Save</Trans>
</Submit>
</CardFooter>
</ValidatedForm>
</Card>
<Card>
<ValidatedForm
method="post"
validator={accountsReceivableEmailValidator}
defaultValues={{
accountsReceivableEmail:
companySettings.accountsReceivableEmail ?? ""
}}
fetcher={fetcher}
>
<Hidden name="intent" value="receivablesEmail" />
<CardHeader>
<CardTitle>
<Trans>Receivables Email</Trans>
</CardTitle>
<CardDescription>
<Trans>
Replies to emailed invoices go here, and it's copied on each
one.
</Trans>
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-8 max-w-[400px]">
<Input name="accountsReceivableEmail" label={t`Email`} />
</div>
</CardContent>
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
isLoading={
fetcher.state !== "idle" &&
fetcher.formData?.get("intent") === "receivablesEmail"
}
>
<Trans>Save</Trans>
</Submit>
</CardFooter>
</ValidatedForm>
</Card>
<Card>
<ValidatedForm
method="post"
validator={invoiceNotificationValidator}
defaultValues={{
invoiceNotificationGroup:
companySettings.invoiceNotificationGroup ?? []
}}
fetcher={fetcher}
>
<Hidden name="intent" value="invoiceNotifications" />
<CardHeader>
<CardTitle>
<Trans>Notifications</Trans>
</CardTitle>
<CardDescription>
<Trans>
Each rental agreement's or contract's salesperson (or its
creator) gets a daily summary of its invoices.
</Trans>
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-8 max-w-[400px]">
<Users
name="invoiceNotificationGroup"
label={t`Also notify`}
helperText={t`Gets the summary for every agreement`}
type="employee"
/>
</div>
</CardContent>
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
isLoading={
fetcher.state !== "idle" &&
fetcher.formData?.get("intent") === "invoiceNotifications"
}
>
<Trans>Save</Trans>
</Submit>
</CardFooter>
</ValidatedForm>
</Card>
<Card>
<ValidatedForm
method="post"
validator={defaultCustomerCcValidator}
defaultValues={{
defaultCustomerCc: companySettings.defaultCustomerCc ?? []
}}
fetcher={fetcher}
>
<input type="hidden" name="intent" value="emails" />
<CardHeader>
<CardTitle>
<Trans>Emails</Trans>
</CardTitle>
<CardDescription>
<Trans>
These email addresses will be automatically CC'd on all quote
emails sent to customers.
</Trans>
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-8 max-w-[400px]">
<EmailRecipients
name="defaultCustomerCc"
label={t`Default CC Recipients`}
/>
</div>
</CardContent>
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
isLoading={
fetcher.state !== "idle" &&
fetcher.formData?.get("intent") === "emails"
}
>
<Trans>Save</Trans>
</Submit>
</CardFooter>
</ValidatedForm>
</Card>
<Card>
<CardHeader>
<CardTitle>
<Trans>Centralized Billing Address</Trans>
</CardTitle>
<CardDescription>
<Trans>
Route all AR invoices to one address (e.g. corporate
headquarters) instead of individual locations.
</Trans>
</CardDescription>
</CardHeader>
<CardContent>
<HStack className="justify-between items-center">
<VStack className="items-start" spacing={1}>
<span className="font-medium">
{arAddressEnabled ? (
<Trans>Centralized billing is enabled</Trans>
) : (
<Trans>Centralized billing is disabled</Trans>
)}
</span>
<span className="text-sm text-muted-foreground">
{arAddressEnabled ? (
<Trans>
AR invoices are routed to a single billing address.
</Trans>
) : (
<Trans>
Enable to route all AR invoices to a single billing
address.
</Trans>
)}
</span>
</VStack>
<Switch
checked={arAddressEnabled}
onCheckedChange={handleArAddressToggle}
disabled={toggleFetcher.state !== "idle"}
/>
</HStack>
</CardContent>
</Card>
{arAddressEnabled && (
<Card>
<ValidatedForm
method="post"
validator={accountsReceivableBillingAddressValidator}
defaultValues={{
name: arBillingAddress?.name ?? "",
addressLine1: arBillingAddress?.addressLine1 ?? "",
addressLine2: arBillingAddress?.addressLine2 ?? "",
city: arBillingAddress?.city ?? "",
state: arBillingAddress?.state ?? "",
postalCode: arBillingAddress?.postalCode ?? "",
countryCode: arBillingAddress?.countryCode ?? "",
phone: arBillingAddress?.phone ?? "",
fax: arBillingAddress?.fax ?? "",
email: arBillingAddress?.email ?? ""
}}
fetcher={fetcher}
>
<input
type="hidden"
name="intent"
value="accountsReceivableBillingAddress"
/>
<CardHeader>
<CardTitle>
<Trans>Billing Address</Trans>
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4 w-full">
<Input name="name" label={t`Name`} />
<Input name="email" label={t`Email`} />
<Input name="addressLine1" label={t`Address Line 1`} />
<Input name="addressLine2" label={t`Address Line 2`} />
<Input name="city" label={t`City`} />
<Input name="state" label={t`State / Province`} />
<Input name="postalCode" label={t`Postal Code`} />
<Country name="countryCode" />
<PhoneInput name="phone" label={t`Phone`} />
<PhoneInput name="fax" label={t`Fax`} />
</div>
</CardContent>
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
isLoading={
fetcher.state !== "idle" &&
fetcher.formData?.get("intent") ===
"accountsReceivableBillingAddress"
}
>
<Trans>Save</Trans>
</Submit>
</CardFooter>
</ValidatedForm>
</Card>
)}
</VStack>
</ScrollArea>
);
}