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 {
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
Heading,
HStack,
Table,
Tbody,
Td,
Tr,
TruncatedTooltipText,
useViewport,
VStack
} from "@carbon/react";
import { distinctItemText, getItemReadableId } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import { motion } from "motion/react";
import { useState } from "react";
import { LuChevronRight, LuImage } from "react-icons/lu";
import { Link, useParams } from "react-router";
import {
DateTime,
MethodIcon,
RevisionSuffix,
SupplierAvatar
} from "~/components";
import { useAccounts } from "~/components/Form/Account";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { useShowRecordPanel } from "~/components/Layout/Panels";
import { SummaryLineList, SummaryLineRow } from "~/components/SummaryLineRow";
import {
useCurrencyFormatter,
usePercentFormatter,
useRouteData,
useUser
} from "~/hooks";
import { useItems } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
import { isPurchaseOrderLocked } from "../../purchasing.models";
import type {
PurchaseOrder,
PurchaseOrderDelivery,
PurchaseOrderLine,
Supplier
} from "../../types";
import { PurchaseOrderLinePromisedDate } from "./PurchaseOrderLineDates";
const LineItems = ({
currencyCode,
presentationCurrencyFormatter,
formatter,
locale,
lines,
order,
shouldConvertCurrency
}: {
currencyCode: string;
order: PurchaseOrder | undefined;
presentationCurrencyFormatter: Intl.NumberFormat;
formatter: Intl.NumberFormat;
locale: string;
lines: PurchaseOrderLine[];
shouldConvertCurrency: boolean;
}) => {
const { t } = useLingui();
const { isPhone } = useViewport();
const showRecordPanel = useShowRecordPanel();
const [items] = useItems();
const accounts = useAccounts();
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
const percentFormatter = usePercentFormatter();
const [openItems, setOpenItems] = useState<string[]>([]);
const unitOfMeasures = useUnitOfMeasure();
const toggleOpen = (id: string) => {
setOpenItems((prev) =>
prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
);
};
// Phones: the first lines as rows that open the line page; the Lines tab
// lists them all.
const phoneLineLimit = 3;
const shownLines = isPhone ? lines.slice(0, phoneLineLimit) : lines;
const rows = shownLines.map((line) => {
if (!line.id) return null;
const isGlAccount = line.purchaseOrderLineType === "G/L Account";
const isFixedAsset = line.purchaseOrderLineType === "Fixed Asset";
const isIndirect = isGlAccount || isFixedAsset;
const isReceivable = !isGlAccount && (line.purchaseQuantity ?? 0) > 0;
const quantityReceived = line.quantityReceived ?? 0;
const quantityInvoiced = line.quantityInvoiced ?? 0;
const itemReadableId = isGlAccount
? line.description || "Indirect Expense"
: isFixedAsset
? line.assetReadableId || "Fixed Asset"
: getItemReadableId(items, line.itemId);
const lineDescription = isGlAccount
? (accounts.find((a) => a.id === line.accountId)?.name ??
"Indirect Expense")
: isFixedAsset
? line.description || "Fixed Asset"
: distinctItemText(itemReadableId, line.description);
const lineTotal = (line.unitPrice ?? 0) * (line.purchaseQuantity ?? 0);
const supplierLineTotal =
(line.supplierUnitPrice ?? 0) * (line.purchaseQuantity ?? 0);
const total = lineTotal + (line.taxAmount ?? 0) + (line.shippingCost ?? 0);
const supplierTotal =
supplierLineTotal +
(line.supplierTaxAmount ?? 0) +
(line.supplierShippingCost ?? 0);
const unitOfMeasureLabel = unitOfMeasures.find(
(uom) => uom.value === line.purchaseUnitOfMeasureCode
)?.label;
// Phones: one row that opens the line page (its Edit link, the
// badges and the breakdown stay on desktop).
if (isPhone) {
return (
<SummaryLineRow
key={line.id}
to={path.to.purchaseOrderLine(orderId, line.id)}
title={itemReadableId}
value={formatter.format(total)}
description={lineDescription}
meta={
<>
{line.purchaseQuantity} × {formatter.format(line.unitPrice ?? 0)}{" "}
{unitOfMeasureLabel}
</>
}
/>
);
}
return (
<motion.div
key={line.id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, ease: "easeOut" }}
className="border-b border-input py-6 w-full"
>
<HStack spacing={4} className="items-start">
{line.thumbnailPath ? (
<img
alt={itemReadableId!}
className="w-24 h-24 shrink-0 bg-gradient-to-bl from-muted to-muted/40 rounded-lg"
src={getPrivateUrl(line.thumbnailPath)}
/>
) : (
<div className="w-24 h-24 shrink-0 bg-gradient-to-bl from-muted to-muted/40 rounded-lg p-4">
<LuImage className="w-16 h-16 text-muted-foreground" />
</div>
)}
<VStack spacing={0} className="flex-1 min-w-0">
<div
className="flex flex-col cursor-pointer w-full"
onClick={() => toggleOpen(line.id!)}
>
{/* The text column must shrink (flex-1 min-w-0) or a long
description shoves the totals out of the card, and its
children need w-full because VStack is items-start, which
sizes each child to its own content and leaves truncate
inert no matter how narrow the column gets. */}
<div className="flex items-center justify-between w-full">
<VStack spacing={0} className="flex-1 min-w-0">
<HStack spacing={2} className="flex min-w-0 w-full">
<Heading className="truncate">{itemReadableId}</Heading>
<Button
asChild
variant="link"
size="sm"
className="text-muted-foreground flex-shrink-0"
>
<Link to={path.to.purchaseOrderLine(orderId, line.id!)}>
<Trans>Edit</Trans>
</Link>
</Button>
</HStack>
{lineDescription && (
<TruncatedTooltipText
className="text-muted-foreground text-sm truncate w-full"
tooltip={lineDescription}
>
{lineDescription}
</TruncatedTooltipText>
)}
</VStack>
<VStack spacing={2} className="flex-shrink-0 items-end w-auto">
<HStack spacing={4}>
<VStack spacing={0}>
<span className="font-semibold text-xl whitespace-nowrap">
{formatter.format(total)}
</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-sm">
{presentationCurrencyFormatter.format(supplierTotal)}
</span>
)}
</VStack>
<motion.div
animate={{
rotate: openItems.includes(line.id) ? 90 : 0
}}
transition={{ duration: 0.3 }}
>
<LuChevronRight size={24} />
</motion.div>
</HStack>
<div className="flex items-center gap-2">
{!isIndirect && (
<Badge
variant="outline"
className="flex items-center gap-2"
>
{line.purchaseQuantity}
<MethodIcon
// @ts-expect-error
type={line.methodType ?? "Pull from Inventory"}
/>
</Badge>
)}
<Badge variant="green">
{formatter.format(line.unitPrice ?? 0)}{" "}
{
unitOfMeasures.find(
(uom) => uom.value === line.purchaseUnitOfMeasureCode
)?.label
}
</Badge>
{(line.taxPercent ?? 0) > 0 ? (
<Badge variant="red">
{percentFormatter.format(line.taxPercent ?? 0)} Tax
</Badge>
) : null}
</div>
{!isIndirect && (
<PurchaseOrderLinePromisedDate
line={{
id: line.id,
purchaseOrderId: orderId,
receivedComplete: line.receivedComplete ?? false,
promisedDate: line.promisedDate
}}
order={order}
/>
)}
</VStack>
</div>
</div>
</VStack>
</HStack>
<motion.div
initial="collapsed"
animate={openItems.includes(line.id) ? "open" : "collapsed"}
variants={{
open: { opacity: 1, height: "auto", marginTop: 16 },
collapsed: { opacity: 0, height: 0, marginTop: 0 }
}}
transition={{ duration: 0.3 }}
className="w-full overflow-hidden"
>
<div className="w-full">
<Table>
<Tbody>
<Tr>
<Td>Quantity</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>
{line.purchaseQuantity}{" "}
{
unitOfMeasures.find(
(uom) =>
uom.value === line.purchaseUnitOfMeasureCode
)?.label
}
</span>
{line.conversionFactor !== 1 && (
<span className="text-muted-foreground text-xs">
{(line.purchaseQuantity ?? 0) *
(line.conversionFactor ?? 1)}{" "}
{
unitOfMeasures.find(
(uom) =>
uom.value === line.inventoryUnitOfMeasureCode
)?.label
}
</span>
)}
</VStack>
</Td>
</Tr>
{isReceivable && (
<Tr>
<Td>Received</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>
{quantityReceived} of {line.purchaseQuantity}{" "}
{
unitOfMeasures.find(
(uom) =>
uom.value === line.purchaseUnitOfMeasureCode
)?.label
}
</span>
{!line.receivedComplete &&
(line.quantityToReceive ?? 0) > 0 && (
<span className="text-muted-foreground text-xs">
{line.quantityToReceive} remaining
</span>
)}
</VStack>
</Td>
</Tr>
)}
{(line.purchaseQuantity ?? 0) > 0 && (
<Tr>
<Td>Invoiced</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>
{quantityInvoiced} of {line.purchaseQuantity}{" "}
{
unitOfMeasures.find(
(uom) =>
uom.value === line.purchaseUnitOfMeasureCode
)?.label
}
</span>
{!line.invoicedComplete &&
(line.quantityToInvoice ?? 0) > 0 && (
<span className="text-muted-foreground text-xs">
{line.quantityToInvoice} remaining
</span>
)}
</VStack>
</Td>
</Tr>
)}
<Tr>
<Td>Unit Price</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>{formatter.format(line.unitPrice ?? 0)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
line.supplierUnitPrice ?? 0
)}
</span>
)}
</VStack>
</Td>
</Tr>
<Tr className="border-b border-border">
<Td>Extended Price</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>{formatter.format(lineTotal)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
supplierLineTotal
)}
</span>
)}
</VStack>
</Td>
</Tr>
<Tr key="tax">
<Td>Tax ({percentFormatter.format(line.taxPercent ?? 0)})</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>{formatter.format(line.taxAmount ?? 0)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
line.supplierTaxAmount ?? 0
)}
</span>
)}
</VStack>
</Td>
</Tr>
<Tr key="shipping" className="border-b border-border">
<Td>Shipping</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>{formatter.format(line.shippingCost ?? 0)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
line.supplierShippingCost ?? 0
)}
</span>
)}
</VStack>
</Td>
</Tr>
<Tr key="total" className="font-semibold">
<Td>Total</Td>
<Td className="text-right">
<VStack spacing={0} className="items-end">
<span>{formatter.format(total)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(supplierTotal)}
</span>
)}
</VStack>
</Td>
</Tr>
</Tbody>
</Table>
</div>
</motion.div>
</motion.div>
);
});
if (isPhone) {
return (
<SummaryLineList>
{rows}
{lines.length > phoneLineLimit ? (
<div className="w-full pt-3">
<Button
variant="secondary"
className="w-full"
onClick={() => showRecordPanel("explorer")}
>
{t`See all ${lines.length}`}
</Button>
</div>
) : null}
</SummaryLineList>
);
}
return (
<VStack spacing={8} className="w-full overflow-hidden">
{rows}
</VStack>
);
};
type PurchaseOrderSummaryProps = {
onEditShippingCost: () => void;
};
const PurchaseOrderSummary = ({
onEditShippingCost
}: PurchaseOrderSummaryProps) => {
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
const { company } = useUser();
const routeData = useRouteData<{
purchaseOrder: PurchaseOrder;
lines: PurchaseOrderLine[];
purchaseOrderDelivery: PurchaseOrderDelivery;
supplier: Supplier;
}>(path.to.purchaseOrder(orderId));
const isEditable = !isPurchaseOrderLocked(routeData?.purchaseOrder?.status);
const { locale } = useLocale();
const formatter = useCurrencyFormatter();
const presentationCurrencyFormatter = useCurrencyFormatter({
currency:
routeData?.purchaseOrder?.currencyCode ??
company?.baseCurrencyCode ??
"USD"
});
const shouldConvertCurrency =
routeData?.purchaseOrder?.currencyCode !== company?.baseCurrencyCode;
// Calculate totals
const subtotal =
routeData?.lines?.reduce((acc, line) => {
const lineTotal =
(line.unitPrice ?? 0) * (line.purchaseQuantity ?? 0) +
(line.shippingCost ?? 0);
return acc + lineTotal;
}, 0) ?? 0;
const supplierSubtotal =
routeData?.lines?.reduce((acc, line) => {
const lineTotal =
(line.supplierUnitPrice ?? 0) * (line.purchaseQuantity ?? 0) +
(line.supplierShippingCost ?? 0);
return acc + lineTotal;
}, 0) ?? 0;
const tax =
routeData?.lines?.reduce((acc, line) => {
return acc + (line.taxAmount ?? 0);
}, 0) ?? 0;
const supplierTax =
routeData?.lines?.reduce((acc, line) => {
return acc + (line.supplierTaxAmount ?? 0);
}, 0) ?? 0;
const shippingCost =
(routeData?.purchaseOrderDelivery?.supplierShippingCost ?? 0) /
(routeData?.purchaseOrder?.exchangeRate || 1);
const supplierShippingCost =
routeData?.purchaseOrderDelivery?.supplierShippingCost ?? 0;
const total = subtotal + tax + shippingCost;
const supplierTotal = supplierSubtotal + supplierTax + supplierShippingCost;
return (
<Card>
<CardHeader>
<HStack className="justify-between items-center max-md:min-w-0">
<div className="flex flex-col gap-1 max-md:hidden">
<CardTitle className="flex items-center gap-0">
<span>{routeData?.purchaseOrder.purchaseOrderId}</span>
<RevisionSuffix
revisionId={routeData?.purchaseOrder?.revisionId}
/>
</CardTitle>
<CardDescription>
<Trans>Purchase Order</Trans>
</CardDescription>
</div>
<div className="flex flex-col gap-1 items-end max-md:w-full max-md:min-w-0 max-md:items-start max-md:[&>*]:max-w-full max-md:[&_span]:truncate">
<SupplierAvatar
supplierId={routeData?.purchaseOrder.supplierId ?? null}
/>
{routeData?.purchaseOrder?.orderDate && (
<span className="text-xs text-muted-foreground tracking-tight">
Ordered{" "}
<DateTime
value={routeData?.purchaseOrder.orderDate}
variant="date"
/>
</span>
)}
</div>
</HStack>
</CardHeader>
<CardContent>
<LineItems
currencyCode={company?.baseCurrencyCode ?? "USD"}
presentationCurrencyFormatter={presentationCurrencyFormatter}
formatter={formatter}
locale={locale}
lines={routeData?.lines ?? []}
order={routeData?.purchaseOrder}
shouldConvertCurrency={shouldConvertCurrency}
/>
<VStack spacing={2} className="mt-8">
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>Subtotal:</span>
<VStack spacing={0} className="items-end">
<span>{formatter.format(subtotal)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
{presentationCurrencyFormatter.format(supplierSubtotal)}
</span>
)}
</VStack>
</HStack>
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>Tax:</span>
<VStack spacing={0} className="items-end">
<span>{formatter.format(tax)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
{presentationCurrencyFormatter.format(supplierTax)}
</span>
)}
</VStack>
</HStack>
<HStack className="justify-between text-sm text-muted-foreground w-full">
{shippingCost > 0 ? (
<>
<VStack spacing={0}>
<span>Shipping:</span>
{isEditable && (
<Button
variant="link"
size="sm"
className="text-muted-foreground"
onClick={onEditShippingCost}
>
<Trans>Edit Shipping</Trans>
</Button>
)}
</VStack>
<VStack spacing={0} className="items-end">
<span>{formatter.format(shippingCost)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
{presentationCurrencyFormatter.format(
supplierShippingCost
)}
</span>
)}
</VStack>
</>
) : isEditable ? (
<Button
variant="link"
size="sm"
className="text-primary"
onClick={onEditShippingCost}
>
<Trans>Add Shipping</Trans>
</Button>
) : null}
</HStack>
<HStack className="justify-between text-xl font-semibold w-full">
<span>Total:</span>
<VStack spacing={0} className="items-end">
<span>{formatter.format(total)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
{presentationCurrencyFormatter.format(supplierTotal)}
</span>
)}
</VStack>
</HStack>
</VStack>
</CardContent>
</Card>
);
};
export default PurchaseOrderSummary;