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 the ability to ship and receive warehouse transfers

Brad Barbin77fe45b77457
diff --git a/apps/academy/app/config.tsx b/apps/academy/app/config.tsx
index f9994df31d..15180b8be8 100644
--- a/apps/academy/app/config.tsx
+++ b/apps/academy/app/config.tsx
@@ -123,11 +123,11 @@ export const modules: Config = [
{
id: "carbon-modules",
loomUrl:
- "https://www.loom.com/share/6d0edd4106e4440a9df253a711b1fc85?sid=d84101c2-7673-495f-a97c-e662d46ed974",
+ "https://www.loom.com/share/8adc024df71a4d3297da362eb1ecec97?sid=687ef385-5393-41ba-b634-a5084e91196f",
name: "Carbon's Modules",
description:
"Learn about Carbon's modular architecture and how different modules work together to provide comprehensive business management capabilities.",
- duration: 205,
+ duration: 328,
},
{
id: "architecture-overview",
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index dad9382186..8737322994 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -112,7 +112,7 @@ export const receiptSourceDocumentType = [
"Purchase Order",
"Purchase Invoice",
// "Purchase Return Order",
- // "Inbound Transfer",
+ "Inbound Transfer",
// "Outbound Transfer",
// "Manufacturing Consumption",
// "Manufacturing Output",
@@ -149,7 +149,7 @@ export const shipmentSourceDocumentType = [
// "Purchase Invoice",
// "Purchase Return Order",
// "Inbound Transfer",
- // "Outbound Transfer",
+ "Outbound Transfer",
] as const;
export const shippingCarrierType = [
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
index 4feca76268..b75be45e78 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
@@ -27,11 +27,17 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
case "Sales Invoice":
return `invoiced ${ledgerRecord.quantity} units for sale`;
case "Transfer Shipment":
- return `shipped ${-1 * ledgerRecord.quantity} units for transfer`;
+ return `shipped ${-1 * ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ } for transfer`;
case "Transfer Receipt":
- return `received ${ledgerRecord.quantity} units from transfer`;
+ return `received ${ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""
+ } from transfer`;
case "Direct Transfer":
- return `directly transferred ${ledgerRecord.quantity} units`;
+ return `directly transferred ${ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Inventory Receipt":
return `received ${ledgerRecord.quantity} units into inventory`;
case "Inventory Shipment":
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
index 8b7bf8fa4b..b454dbc14c 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
@@ -1,10 +1,10 @@
import { useCarbon } from "@carbon/auth";
import { useParams } from "@remix-run/react";
import { useCallback, useEffect, useState } from "react";
-import { z } from "zod";
+import type { z } from "zod";
import { useUser } from "~/hooks";
-import { receiptStatusType } from "~/modules/inventory";
-import { receiptValidator } from "~/modules/inventory/inventory.models";
+import type { receiptStatusType } from "~/modules/inventory";
+import type { receiptValidator } from "~/modules/inventory/inventory.models";
import type { ReceiptSourceDocument } from "~/modules/inventory/types";
import type { ListItem } from "~/types";
@@ -65,6 +65,29 @@ export default function useReceiptForm({
);
}
});
+ break;
+
+ case "Inbound Transfer":
+ carbon
+ ?.from("warehouseTransfer")
+ .select("id, transferId")
+ .eq("companyId", user.company.id)
+ .or(
+ "status.eq.To Ship and Receive, status.eq.To Receive, status.eq.To Ship"
+ )
+ .then((response) => {
+ if (response.error) {
+ setError(response.error.message);
+ } else {
+ setSourceDocuments(
+ response.data.map((d) => ({
+ name: d.transferId,
+ id: d.id,
+ }))
+ );
+ }
+ });
+ break;
default:
setSourceDocuments([]);
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
index 0dbe445ad9..e3f018047c 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
@@ -12,6 +12,7 @@ import {
LuCreditCard,
LuQrCode,
LuShoppingCart,
+ LuTruck,
} from "react-icons/lu";
import { usePermissions, useRouteData } from "~/hooks";
@@ -117,10 +118,13 @@ function SourceDocumentLink({
sourceDocumentId?: string;
sourceDocumentReadableId?: string;
}) {
+ const permissions = usePermissions();
+
if (!sourceDocument || !sourceDocumentId || !sourceDocumentReadableId)
return null;
switch (sourceDocument) {
case "Purchase Order":
+ if (!permissions.can("view", "purchasing")) return null;
return (
<Button variant="secondary" leftIcon={<LuShoppingCart />} asChild>
<Link to={path.to.purchaseOrderDetails(sourceDocumentId!)}>
@@ -129,6 +133,7 @@ function SourceDocumentLink({
</Button>
);
case "Purchase Invoice":
+ if (!permissions.can("view", "invoicing")) return null;
return (
<Button variant="secondary" leftIcon={<LuCreditCard />} asChild>
<Link to={path.to.purchaseInvoice(sourceDocumentId!)}>
@@ -136,6 +141,15 @@ function SourceDocumentLink({
</Link>
</Button>
);
+ case "Inbound Transfer":
+ if (!permissions.can("view", "inventory")) return null;
+ return (
+ <Button variant="secondary" leftIcon={<LuTruck />} asChild>
+ <Link to={path.to.warehouseTransferDetails(sourceDocumentId!)}>
+ Warehouse Transfer
+ </Link>
+ </Button>
+ );
default:
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
index c2283ebb7b..19269417dc 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
@@ -104,6 +104,16 @@ const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
{row.original.sourceDocumentReadableId}
</Hyperlink>
);
+ case "Inbound Transfer":
+ return (
+ <Hyperlink
+ to={path.to.warehouseTransferDetails(
+ row.original.sourceDocumentId!
+ )}
+ >
+ {row.original.sourceDocumentReadableId}
+ </Hyperlink>
+ );
default:
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
index 0d563bec7b..f76179b0ee 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
@@ -64,6 +64,7 @@ export default function useShipmentForm({
);
}
});
+ break;
case "Purchase Order":
carbon
?.from("purchaseOrder")
@@ -82,6 +83,26 @@ export default function useShipmentForm({
);
}
});
+ break;
+ case "Outbound Transfer":
+ carbon
+ ?.from("warehouseTransfer")
+ .select("id, transferId")
+ .eq("companyId", user.company.id)
+ .or("status.eq.To Ship and Receive, status.eq.To Ship")
+ .then((response) => {
+ if (response.error) {
+ setError(response.error.message);
+ } else {
+ setSourceDocuments(
+ response.data.map((d) => ({
+ name: d.transferId,
+ id: d.id,
+ }))
+ );
+ }
+ });
+ break;
default:
setSourceDocuments([]);
}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
index cd1830d9a8..110fc33f95 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
@@ -20,6 +20,7 @@ import {
LuCreditCard,
LuQrCode,
LuShoppingCart,
+ LuTruck,
} from "react-icons/lu";
import { usePermissions, useRouteData } from "~/hooks";
import type { ItemTracking, Shipment, ShipmentLine } from "~/modules/inventory";
@@ -362,6 +363,15 @@ function SourceDocumentLink({
</Link>
</Button>
);
+ case "Outbound Transfer":
+ if (!permissions.can("view", "inventory")) return null;
+ return (
+ <Button variant="secondary" leftIcon={<LuTruck />} asChild>
+ <Link to={path.to.warehouseTransferDetails(sourceDocumentId!)}>
+ Warehouse Transfer
+ </Link>
+ </Button>
+ );
// case "Sales Invoice":
// return (
// <Button variant="secondary" leftIcon={<LuCreditCard />} asChild>
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
index 4b74e0606c..7b1d79a410 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
@@ -114,6 +114,16 @@ const ShipmentsTable = memo(({ data, count }: ShipmentsTableProps) => {
{row.original.sourceDocumentReadableId}
</Hyperlink>
);
+ case "Outbound Transfer":
+ return (
+ <Hyperlink
+ to={path.to.warehouseTransferDetails(
+ row.original.sourceDocumentId!
+ )}
+ >
+ {row.original.sourceDocumentReadableId}
+ </Hyperlink>
+ );
default:
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
index d2f1d5b1cf..24b5c75172 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
@@ -42,7 +42,7 @@ const WarehouseTransferForm = ({
>
<Card className="w-full">
<CardHeader>
- <CardTitle>{isEditing ? "Edit" : "New"} Transfer</CardTitle>
+ <CardTitle>{isEditing ? "Warehouse" : "New"} Transfer</CardTitle>
{!isEditing && (
<CardDescription>
A warehouse transfer is an inter-company movement of inventory
@@ -84,7 +84,7 @@ const WarehouseTransferForm = ({
<TextArea name="notes" label="Notes" />
- <Submit disabled={!canEdit}>Save Transfer</Submit>
+ <Submit disabled={!canEdit}>Save</Submit>
</VStack>
</CardContent>
</Card>
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx
index fa0a551690..eadd45fca4 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx
@@ -40,7 +40,7 @@ const WarehouseTransferHeader = ({
const permissions = usePermissions();
const statusFetcher = useFetcher<typeof statusAction>();
- const { receipts, shipments, ship, receive } =
+ const { receipts, shipments, ship, receive, hasShippedItems } =
useWarehouseTransferRelatedDocuments(warehouseTransfer.id);
return (
@@ -186,7 +186,7 @@ const WarehouseTransferHeader = ({
disabled={
!["To Receive", "To Ship and Receive"].includes(
warehouseTransfer.status ?? ""
- )
+ ) || !hasShippedItems
}
onClick={() => {
receive(warehouseTransfer);
@@ -215,12 +215,12 @@ const WarehouseTransferHeader = ({
isDisabled={
!["To Receive", "To Ship and Receive"].includes(
warehouseTransfer.status ?? ""
- )
+ ) || !hasShippedItems
}
variant={
["To Receive", "To Ship and Receive"].includes(
warehouseTransfer.status ?? ""
- )
+ ) && hasShippedItems
? "primary"
: "secondary"
}
@@ -272,6 +272,8 @@ export const useWarehouseTransferRelatedDocuments = (
Pick<Shipment, "id" | "shipmentId" | "status">[]
>([]);
+ const [hasShippedItems, setHasShippedItems] = useState(false);
+
const { carbon } = useCarbon();
const ship = useCallback((warehouseTransfer: WarehouseTransfer) => {
@@ -289,7 +291,7 @@ export const useWarehouseTransferRelatedDocuments = (
const getRelatedDocuments = useCallback(
async (warehouseTransferId: string) => {
if (!carbon || !warehouseTransferId) return;
- const [receipts, shipments] = await Promise.all([
+ const [receipts, shipments, warehouseTransferLines] = await Promise.all([
carbon
.from("receipt")
.select("id, receiptId, status")
@@ -300,6 +302,10 @@ export const useWarehouseTransferRelatedDocuments = (
.select("id, shipmentId, status")
.eq("sourceDocument", "Outbound Transfer")
.eq("sourceDocumentId", warehouseTransferId),
+ carbon
+ .from("warehouseTransferLine")
+ .select("shippedQuantity")
+ .eq("transferId", warehouseTransferId),
]);
if (receipts.error) {
@@ -313,6 +319,14 @@ export const useWarehouseTransferRelatedDocuments = (
} else {
setShipments(shipments.data);
}
+
+ // Check if any lines have been shipped
+ if (!warehouseTransferLines.error) {
+ const hasShipped = warehouseTransferLines.data.some(
+ (line) => (line.shippedQuantity ?? 0) > 0
+ );
+ setHasShippedItems(hasShipped);
+ }
},
[carbon]
);
@@ -321,5 +335,5 @@ export const useWarehouseTransferRelatedDocuments = (
getRelatedDocuments(warehouseTransferId);
}, [getRelatedDocuments, warehouseTransferId]);
- return { receipts, shipments, ship, receive };
+ return { receipts, shipments, ship, receive, hasShippedItems };
};
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx
index 2dbca284a7..e4c2f51a53 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx
@@ -83,6 +83,30 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
break;
+
+ case "Inbound Transfer":
+ const warehouseTransferReceipt = await serviceRole.functions.invoke<{
+ id: string;
+ }>("create", {
+ body: {
+ type: "receiptFromInboundTransfer",
+ companyId,
+ warehouseTransferId: data.sourceDocumentId,
+ receiptId: id,
+ userId: userId,
+ },
+ });
+ if (!warehouseTransferReceipt.data || warehouseTransferReceipt.error) {
+ throw redirect(
+ path.to.receipt(id),
+ await flash(
+ request,
+ error(warehouseTransferReceipt.error, "Failed to create receipt")
+ )
+ );
+ }
+ break;
+
default:
throw new Error("Unsupported source document");
}
@@ -129,7 +153,7 @@ export default function ReceiptDetailsRoute() {
receiptId: routeData.receipt.receiptId ?? undefined,
externalDocumentId: routeData.receipt.externalDocumentId ?? undefined,
sourceDocument: (routeData.receipt.sourceDocument ??
- "Purchase Order") as "Purchase Order",
+ "Purchase Order") as "Purchase Order" | "Inbound Transfer",
sourceDocumentId: routeData.receipt.sourceDocumentId ?? undefined,
sourceDocumentReadableId:
routeData.receipt.sourceDocumentReadableId ?? undefined,
diff --git a/apps/erp/app/routes/x+/receipt+/new.tsx b/apps/erp/app/routes/x+/receipt+/new.tsx
index 2c857d5faa..6dcd00a033 100644
--- a/apps/erp/app/routes/x+/receipt+/new.tsx
+++ b/apps/erp/app/routes/x+/receipt+/new.tsx
@@ -53,6 +53,30 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
throw redirect(path.to.receiptDetails(purchaseOrderReceipt.data.id));
+ case "Inbound Transfer":
+ const warehouseTransferReceipt = await serviceRole.functions.invoke<{
+ id: string;
+ }>("create", {
+ body: {
+ type: "receiptFromInboundTransfer",
+ companyId,
+ warehouseTransferId: sourceDocumentId,
+ receiptId: undefined,
+ userId: userId,
+ },
+ region: FunctionRegion.UsEast1,
+ });
+ if (!warehouseTransferReceipt.data || warehouseTransferReceipt.error) {
+ throw redirect(
+ path.to.warehouseTransfer(sourceDocumentId),
+ await flash(
+ request,
+ error(warehouseTransferReceipt.error, "Failed to create receipt")
+ )
+ );
+ }
+
+ throw redirect(path.to.receiptDetails(warehouseTransferReceipt.data.id));
default:
const defaultReceipt = await serviceRole.functions.invoke<{
id: string;
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
index ac296f130e..03312ceaf3 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
@@ -113,6 +113,36 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
break;
+ case "Outbound Transfer":
+ const warehouseTransferShipment = await serviceRole.functions.invoke<{
+ id: string;
+ }>("create", {
+ body: {
+ type: "shipmentFromWarehouseTransfer",
+ companyId,
+ warehouseTransferId: data.sourceDocumentId,
+ shipmentId: id,
+ userId: userId,
+ },
+ region: FunctionRegion.UsEast1,
+ });
+ if (
+ !warehouseTransferShipment.data ||
+ warehouseTransferShipment.error
+ ) {
+ console.error(warehouseTransferShipment.error);
+ throw redirect(
+ path.to.shipment(id),
+ await flash(
+ request,
+ error(
+ warehouseTransferShipment.error,
+ "Failed to create shipment"
+ )
+ )
+ );
+ }
+ break;
default:
throw new Error(`Unsupported source document: ${data.sourceDocument}`);
}
@@ -159,8 +189,10 @@ export default function ShipmentDetailsRoute() {
shipmentId: routeData.shipment.shipmentId ?? undefined,
trackingNumber: routeData.shipment.trackingNumber ?? undefined,
shippingMethodId: routeData.shipment.shippingMethodId ?? undefined,
- sourceDocument: (routeData.shipment.sourceDocument ??
- "Sales Order") as "Sales Order",
+ sourceDocument: (routeData.shipment.sourceDocument ?? "Sales Order") as
+ | "Sales Order"
+ | "Purchase Order"
+ | "Outbound Transfer",
sourceDocumentId: routeData.shipment.sourceDocumentId ?? undefined,
sourceDocumentReadableId:
routeData.shipment.sourceDocumentReadableId ?? undefined,
diff --git a/apps/erp/app/routes/x+/shipment+/new.tsx b/apps/erp/app/routes/x+/shipment+/new.tsx
index d099e3bc0b..4f3e253588 100644
--- a/apps/erp/app/routes/x+/shipment+/new.tsx
+++ b/apps/erp/app/routes/x+/shipment+/new.tsx
@@ -80,6 +80,33 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
throw redirect(path.to.shipmentDetails(purchaseOrderShipment.data.id));
+ case "Outbound Transfer":
+ const warehouseTransferShipment = await serviceRole.functions.invoke<{
+ id: string;
+ }>("create", {
+ body: {
+ type: "shipmentFromWarehouseTransfer",
+ companyId,
+ warehouseTransferId: sourceDocumentId,
+ shipmentId: undefined,
+ userId: userId,
+ },
+ region: FunctionRegion.UsEast1,
+ });
+ if (!warehouseTransferShipment.data || warehouseTransferShipment.error) {
+ console.error(warehouseTransferShipment.error);
+ throw redirect(
+ path.to.warehouseTransferDetails(sourceDocumentId),
+ await flash(
+ request,
+ error(warehouseTransferShipment.error, "Failed to create shipment")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.shipmentDetails(warehouseTransferShipment.data.id)
+ );
default:
const defaultShipment = await serviceRole.functions.invoke<{
id: string;
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx
new file mode 100644
index 0000000000..8fb78a59ab
--- /dev/null
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx
@@ -0,0 +1,16 @@
+import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { transferId } = params;
+ if (!transferId) throw new Error("transferId not found");
+
+ // Redirect to create a new receipt with the warehouse transfer as the source document
+ const url = path.to.newReceipt;
+ const searchParams = new URLSearchParams({
+ sourceDocument: "Inbound Transfer",
+ sourceDocumentId: transferId,
+ });
+
+ throw redirect(`${url}?${searchParams.toString()}`);
+}
\ No newline at end of file
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx
new file mode 100644
index 0000000000..b824d6f0a5
--- /dev/null
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx
@@ -0,0 +1,16 @@
+import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { transferId } = params;
+ if (!transferId) throw new Error("transferId not found");
+
+ // Redirect to create a new shipment with the warehouse transfer as the source document
+ const url = path.to.newShipment;
+ const searchParams = new URLSearchParams({
+ sourceDocument: "Outbound Transfer",
+ sourceDocumentId: transferId,
+ });
+
+ throw redirect(`${url}?${searchParams.toString()}`);
+}
\ No newline at end of file
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 6641cabd49..5d68a7d5d5 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -38,6 +38,20 @@ const payloadValidator = z.discriminatedUnion("type", [
companyId: z.string(),
userId: z.string(),
}),
+ z.object({
+ type: z.literal("receiptFromInboundTransfer"),
+ warehouseTransferId: z.string(),
+ receiptId: z.string().optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+ z.object({
+ type: z.literal("receiptFromWarehouseTransfer"),
+ warehouseTransferId: z.string(),
+ receiptId: z.string().optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("receiptLineSplit"),
quantity: z.number(),
@@ -61,6 +75,13 @@ const payloadValidator = z.discriminatedUnion("type", [
companyId: z.string(),
userId: z.string(),
}),
+ z.object({
+ type: z.literal("shipmentFromWarehouseTransfer"),
+ warehouseTransferId: z.string(),
+ shipmentId: z.string().optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("shipmentFromSalesOrder"),
locationId: z.string(),
@@ -971,6 +992,370 @@ serve(async (req: Request) => {
});
}
}
+ case "receiptFromInboundTransfer": {
+ const { warehouseTransferId, receiptId: existingReceiptId } = payload;
+
+ console.log({
+ function: "create",
+ type,
+ companyId,
+ warehouseTransferId,
+ existingReceiptId,
+ userId,
+ });
+
+ try {
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ companyId
+ );
+
+ const [warehouseTransfer, warehouseTransferLines, receipt] =
+ await Promise.all([
+ client
+ .from("warehouseTransfer")
+ .select("*")
+ .eq("id", warehouseTransferId)
+ .single(),
+ client
+ .from("warehouseTransferLine")
+ .select("*")
+ .eq("transferId", warehouseTransferId),
+ client
+ .from("receipt")
+ .select("*")
+ .eq("id", existingReceiptId)
+ .maybeSingle(),
+ ]);
+
+ if (!warehouseTransfer.data)
+ throw new Error("Warehouse transfer not found");
+ if (warehouseTransferLines.error)
+ throw new Error(warehouseTransferLines.error.message);
+
+ const locationId = warehouseTransfer.data.toLocationId;
+
+ const items = await client
+ .from("item")
+ .select("id, itemTrackingType")
+ .in(
+ "id",
+ warehouseTransferLines.data
+ .map((d) => d.itemId)
+ .filter(Boolean) as string[]
+ );
+ const serializedItems = new Set(
+ items.data
+ ?.filter((d) => d.itemTrackingType === "Serial")
+ .map((d) => d.id)
+ );
+ const batchItems = new Set(
+ items.data
+ ?.filter((d) => d.itemTrackingType === "Batch")
+ .map((d) => d.id)
+ );
+
+ const hasReceipt = !!receipt.data?.id;
+
+ const previouslyReceivedQuantitiesByLine = (
+ warehouseTransferLines.data ?? []
+ ).reduce<Record<string, number>>((acc, d) => {
+ if (d.id) acc[d.id] = d.receivedQuantity ?? 0;
+ return acc;
+ }, {});
+
+ const receiptLineItems = warehouseTransferLines.data.reduce<
+ ReceiptLineItem[]
+ >((acc, d) => {
+ if (!d.itemId || !d.quantity) return acc;
+
+ const serialTracking = serializedItems.has(d.itemId);
+ const batchTracking = batchItems.has(d.itemId);
+ // For unshipped lines, we want all lines where shippedQuantity < quantity
+ const quantityToReceive = Math.max(
+ 0,
+ (d.shippedQuantity ?? 0) -
+ (previouslyReceivedQuantitiesByLine[d.id] ?? 0)
+ );
+
+ if (quantityToReceive === 0) return acc;
+
+ acc.push({
+ lineId: d.id,
+ itemId: d.itemId,
+ locationId: d.toLocationId ?? locationId,
+ shelfId: d.toShelfId,
+ requiresSerialTracking: serialTracking,
+ requiresBatchTracking: batchTracking,
+ receivedQuantity: quantityToReceive,
+ outstandingQuantity: quantityToReceive,
+ unitPrice: 0, // Transfers don't have a unit price
+ conversionFactor: 1,
+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",
+ companyId,
+ createdBy: userId,
+ orderQuantity: d.quantity ?? 0,
+ });
+
+ return acc;
+ }, []);
+
+ if (receiptLineItems.length === 0) {
+ throw new Error("No lines to receive");
+ }
+
+ const result = await db.transaction().execute(async (trx) => {
+ const receiptId = await getNextSequence(trx, "receipt", companyId);
+
+ let id: string;
+ if (hasReceipt) {
+ id = receipt.data!.id;
+ await trx
+ .updateTable("receipt")
+ .set({
+ sourceDocument: "Inbound Transfer",
+ sourceDocumentId: warehouseTransferId,
+ sourceDocumentReadableId: warehouseTransfer.data.transferId,
+ locationId,
+ updatedBy: userId,
+ })
+ .where("id", "=", id)
+ .execute();
+ } else {
+ const insertReceipt = await trx
+ .insertInto("receipt")
+ .values({
+ receiptId,
+ sourceDocument: "Inbound Transfer",
+ sourceDocumentId: warehouseTransferId,
+ sourceDocumentReadableId: warehouseTransfer.data.transferId,
+ locationId,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .execute();
+
+ id = insertReceipt[0]?.id ?? "";
+ }
+
+ await trx
+ .deleteFrom("receiptLine")
+ .where("receiptId", "=", id)
+ .execute();
+
+ await trx
+ .insertInto("receiptLine")
+ .values(
+ receiptLineItems.map((lineItem) => ({
+ ...lineItem,
+ receiptId: id,
+ }))
+ )
+ .execute();
+
+ return { id };
+ });
+
+ return new Response(JSON.stringify(result, null, 2), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 201,
+ });
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+ }
+ case "receiptFromWarehouseTransfer": {
+ const { warehouseTransferId, receiptId: existingReceiptId } = payload;
+
+ console.log({
+ function: "create",
+ type,
+ companyId,
+ warehouseTransferId,
+ existingReceiptId,
+ userId,
+ });
+
+ try {
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ companyId
+ );
+
+ const [warehouseTransfer, warehouseTransferLines, receipt] =
+ await Promise.all([
+ client
+ .from("warehouseTransfer")
+ .select("*")
+ .eq("id", warehouseTransferId)
+ .single(),
+ client
+ .from("warehouseTransferLine")
+ .select("*")
+ .eq("transferId", warehouseTransferId),
+ client
+ .from("receipt")
+ .select("*")
+ .eq("id", existingReceiptId)
+ .maybeSingle(),
+ ]);
+
+ if (!warehouseTransfer.data)
+ throw new Error("Warehouse transfer not found");
+ if (warehouseTransferLines.error)
+ throw new Error(warehouseTransferLines.error.message);
+
+ const locationId = warehouseTransfer.data.toLocationId;
+
+ const items = await client
+ .from("item")
+ .select("id, itemTrackingType")
+ .in(
+ "id",
+ warehouseTransferLines.data
+ .map((d) => d.itemId)
+ .filter(Boolean) as string[]
+ );
+ const serializedItems = new Set(
+ items.data
+ ?.filter((d) => d.itemTrackingType === "Serial")
+ .map((d) => d.id)
+ );
+ const batchItems = new Set(
+ items.data
+ ?.filter((d) => d.itemTrackingType === "Batch")
+ .map((d) => d.id)
+ );
+
+ const hasReceipt = !!receipt.data?.id;
+
+ const previouslyReceivedQuantitiesByLine = (
+ warehouseTransferLines.data ?? []
+ ).reduce<Record<string, number>>((acc, d) => {
+ if (d.id) acc[d.id] = d.receivedQuantity ?? 0;
+ return acc;
+ }, {});
+
+ const receiptLineItems = warehouseTransferLines.data.reduce<
+ ReceiptLineItem[]
+ >((acc, d) => {
+ if (!d.itemId || !d.quantity) return acc;
+
+ const serialTracking = serializedItems.has(d.itemId);
+ const batchTracking = batchItems.has(d.itemId);
+ const quantityToReceive = Math.max(
+ 0,
+ (d.shippedQuantity ?? 0) -
+ (previouslyReceivedQuantitiesByLine[d.id] ?? 0)
+ );
+
+ if (quantityToReceive === 0) return acc;
+
+ acc.push({
+ lineId: d.id,
+ itemId: d.itemId,
+ locationId: d.toLocationId ?? locationId,
+ shelfId: d.toShelfId,
+ requiresSerialTracking: serialTracking,
+ requiresBatchTracking: batchTracking,
+ receivedQuantity: quantityToReceive,
+ outstandingQuantity: quantityToReceive,
+ unitPrice: 0, // Transfers don't have a unit price
+ conversionFactor: 1,
+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",
+ companyId,
+ createdBy: userId,
+ orderQuantity: d.quantity ?? 0,
+ });
+
+ return acc;
+ }, []);
+
+ if (receiptLineItems.length === 0) {
+ throw new Error("No lines to receive");
+ }
+
+ const result = await db.transaction().execute(async (trx) => {
+ const receiptId = await getNextSequence(trx, "receipt", companyId);
+
+ let id: string;
+ if (hasReceipt) {
+ id = receipt.data!.id;
+ await trx
+ .updateTable("receipt")
+ .set({
+ sourceDocument: "Inbound Transfer",
+ sourceDocumentId: warehouseTransferId,
+ sourceDocumentReadableId: warehouseTransfer.data.transferId,
+ locationId,
+ updatedBy: userId,
+ })
+ .where("id", "=", id)
+ .execute();
+ } else {
+ const insertReceipt = await trx
+ .insertInto("receipt")
+ .values({
+ receiptId,
+ sourceDocument: "Inbound Transfer",
+ sourceDocumentId: warehouseTransferId,
+ sourceDocumentReadableId: warehouseTransfer.data.transferId,
+ locationId,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .execute();
+
+ id = insertReceipt[0]?.id ?? "";
+ }
+
+ await trx
+ .insertInto("receiptLine")
+ .values(
+ receiptLineItems.map((d) => ({
+ receiptId: id,
+ lineId: d.lineId,
+ itemId: d.itemId,
+ locationId: d.locationId,
+ shelfId: d.shelfId,
+ requiresSerialTracking: d.requiresSerialTracking,
+ requiresBatchTracking: d.requiresBatchTracking,
+ receivedQuantity: d.receivedQuantity,
+ outstandingQuantity: d.outstandingQuantity,
+ unitPrice: d.unitPrice,
+ conversionFactor: d.conversionFactor,
+ unitOfMeasure: d.unitOfMeasure,
+ orderQuantity: d.orderQuantity,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+
+ return { id };
+ });
+
+ return new Response(JSON.stringify(result), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ });
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+ }
case "receiptLineSplit": {
const { receiptId, receiptLineId, quantity, locationId } = payload;
@@ -1110,6 +1495,183 @@ serve(async (req: Request) => {
});
}
}
+ case "shipmentFromWarehouseTransfer": {
+ const { warehouseTransferId, shipmentId: existingShipmentId } = payload;
+
+ console.log({
+ function: "create",
+ type,
+ companyId,
+ warehouseTransferId,
+ existingShipmentId,
+ userId,
+ });
+
+ try {
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ companyId
+ );
+
+ const [warehouseTransfer, warehouseTransferLines, shipment] =
+ await Promise.all([
+ client
+ .from("warehouseTransfer")
+ .select("*")
+ .eq("id", warehouseTransferId)
+ .single(),
+ client
+ .from("warehouseTransferLine")
+ .select("*")
+ .eq("transferId", warehouseTransferId),
+ client
+ .from("shipment")
+ .select("*")
+ .eq("id", existingShipmentId)
+ .maybeSingle(),
+ ]);
+
+ if (!warehouseTransfer.data)
+ throw new Error("Warehouse transfer not found");
+ if (warehouseTransferLines.error)
+ throw new Error(warehouseTransferLines.error.message);
+
+ const locationId = warehouseTransfer.data.toLocationId;
+
+ const items = await client
+ .from("item")
+ .select("id, itemTrackingType")
+ .in(
+ "id",
+ warehouseTransferLines.data
+ .map((d) => d.itemId)
+ .filter(Boolean) as string[]
+ );
+ const serializedItems = new Set(
+ items.data
+ ?.filter((d) => d.itemTrackingType === "Serial")
+ .map((d) => d.id)
+ );
+ const batchItems = new Set(
+ items.data
+ ?.filter((d) => d.itemTrackingType === "Batch")
+ .map((d) => d.id)
+ );
+
+ const hasShipment = !!shipment.data?.id;
+
+ const previouslyShippedQuantitiesByLine = (
+ warehouseTransferLines.data ?? []
+ ).reduce<Record<string, number>>((acc, d) => {
+ if (d.id) acc[d.id] = d.shippedQuantity ?? 0;
+ return acc;
+ }, {});
+
+ const shipmentLineItems = warehouseTransferLines.data.reduce<
+ ShipmentLineItem[]
+ >((acc, d) => {
+ if (!d.itemId || !d.quantity) return acc;
+
+ const serialTracking = serializedItems.has(d.itemId);
+ const batchTracking = batchItems.has(d.itemId);
+ // For unshipped lines, we want all lines where shippedQuantity < quantity
+ const quantityToShip = Math.max(
+ 0,
+ (d.quantity ?? 0) - (previouslyShippedQuantitiesByLine[d.id] ?? 0)
+ );
+
+ if (quantityToShip === 0) return acc;
+
+ acc.push({
+ lineId: d.id,
+ itemId: d.itemId,
+ locationId: d.fromLocationId ?? locationId,
+ shelfId: d.fromShelfId,
+ requiresSerialTracking: serialTracking,
+ requiresBatchTracking: batchTracking,
+ shippedQuantity: quantityToShip,
+ outstandingQuantity: quantityToShip,
+ unitPrice: 0, // Transfers don't have a unit price
+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",
+ companyId,
+ createdBy: userId,
+ orderQuantity: d.quantity ?? 0,
+ });
+
+ return acc;
+ }, []);
+
+ if (shipmentLineItems.length === 0) {
+ throw new Error("No lines to ship");
+ }
+
+ const result = await db.transaction().execute(async (trx) => {
+ const shipmentId = await getNextSequence(trx, "shipment", companyId);
+
+ let id: string;
+ if (hasShipment) {
+ id = shipment.data!.id;
+ await trx
+ .updateTable("shipment")
+ .set({
+ sourceDocument: "Outbound Transfer",
+ sourceDocumentId: warehouseTransferId,
+ sourceDocumentReadableId: warehouseTransfer.data.transferId,
+ locationId,
+ updatedBy: userId,
+ })
+ .where("id", "=", id)
+ .execute();
+ } else {
+ const insertShipment = await trx
+ .insertInto("shipment")
+ .values({
+ shipmentId,
+ sourceDocument: "Outbound Transfer",
+ sourceDocumentId: warehouseTransferId,
+ sourceDocumentReadableId: warehouseTransfer.data.transferId,
+ locationId,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .execute();
+
+ id = insertShipment[0]?.id ?? "";
+ }
+
+ await trx
+ .deleteFrom("shipmentLine")
+ .where("shipmentId", "=", id)
+ .execute();
+
+ await trx
+ .insertInto("shipmentLine")
+ .values(
+ shipmentLineItems.map((lineItem) => ({
+ ...lineItem,
+ shipmentId: id,
+ }))
+ )
+ .execute();
+
+ return { id };
+ });
+
+ return new Response(JSON.stringify(result, null, 2), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 201,
+ });
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+ }
case "shipmentFromPurchaseOrder": {
const {
purchaseOrderId,
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 98892a0185..471fe17a36 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -1163,7 +1163,8 @@ serve(async (req: Request) => {
if (warehouseTransferLines.error)
throw new Error("Failed to fetch warehouse transfer lines");
- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] = [];
+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
+ [];
const warehouseTransferLineUpdates: Record<
string,
Database["public"]["Tables"]["warehouseTransferLine"]["Update"]
@@ -1180,7 +1181,7 @@ serve(async (req: Request) => {
const shippedQuantity = shipmentLine.shippedQuantity ?? 0;
// Update warehouse transfer line shipped quantity
- const newShippedQuantity =
+ const newShippedQuantity =
(warehouseTransferLine.shippedQuantity ?? 0) + shippedQuantity;
warehouseTransferLineUpdates[warehouseTransferLine.id] = {
@@ -1198,7 +1199,8 @@ serve(async (req: Request) => {
entryType: "Transfer",
documentType: "Transfer Shipment",
documentId: warehouseTransfer.data?.transferId,
- externalDocumentId: shipment.data?.externalDocumentId ?? undefined,
+ externalDocumentId:
+ shipment.data?.externalDocumentId ?? undefined,
createdBy: userId,
companyId,
});
@@ -1206,20 +1208,25 @@ serve(async (req: Request) => {
}
// Check if all lines are fully shipped
- const allLinesFullyShipped = warehouseTransferLines.data.every((line) => {
- const updates = warehouseTransferLineUpdates[line.id];
- const shippedQty = updates?.shippedQuantity ?? line.shippedQuantity ?? 0;
- return shippedQty >= (line.quantity ?? 0);
- });
+ const allLinesFullyShipped = warehouseTransferLines.data.every(
+ (line) => {
+ const updates = warehouseTransferLineUpdates[line.id];
+ const shippedQty =
+ updates?.shippedQuantity ?? line.shippedQuantity ?? 0;
+ return shippedQty >= (line.quantity ?? 0);
+ }
+ );
// Check if all lines are fully received
- const allLinesFullyReceived = warehouseTransferLines.data.every((line) => {
- const receivedQty = line.receivedQuantity ?? 0;
- return receivedQty >= (line.quantity ?? 0);
- });
+ const allLinesFullyReceived = warehouseTransferLines.data.every(
+ (line) => {
+ const receivedQty = line.receivedQuantity ?? 0;
+ return receivedQty >= (line.quantity ?? 0);
+ }
+ );
// Determine new warehouse transfer status
- let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =
+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =
warehouseTransfer.data.status;
if (allLinesFullyShipped && allLinesFullyReceived) {
@@ -1247,6 +1254,7 @@ serve(async (req: Request) => {
.updateTable("warehouseTransfer")
.set({
status: newStatus,
+ transferDate: today,
updatedBy: userId,
})
.where("id", "=", warehouseTransfer.data.id)
@@ -1274,6 +1282,7 @@ serve(async (req: Request) => {
break;
}
+
default: {
throw new Error(
`Invalid source document type: ${shipment.data.sourceDocument}`