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
feat: add pdf for stock transfer
Brad Barbinc947a84420c7
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsxindex 173db43a3e..5844019b1a 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx@@ -150,11 +150,13 @@ const WarehouseTransferLineForm = ({<Shelfname="fromShelfId"label="From Shelf"+ itemId={itemId ?? undefined}locationId={warehouseTransfer.fromLocationId}/><Shelfname="toShelfId"label="To Shelf"+ itemId={itemId ?? undefined}locationId={warehouseTransfer.toLocationId}/><TextArea name="notes" label="Notes" rows={3} />diff --git a/apps/erp/app/routes/api+/stock-transfer+/$lineId+/pick.tsx b/apps/erp/app/routes/api+/stock-transfer+/$lineId+/pick.tsxnew file mode 100644index 0000000000..f16bcb729a--- /dev/null+++ b/apps/erp/app/routes/api+/stock-transfer+/$lineId+/pick.tsx@@ -0,0 +1,30 @@+import { assertIsPost, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "inventory",+ });++ const { lineId } = params;+ if (!lineId) throw notFound("lineId not found");++ // TODO: Implement pick functionality+ // This would typically:+ // 1. Get the stock transfer line+ // 2. Update the pickedQuantity+ // 3. Create inventory transactions+ // 4. Update stock transfer status if needed++ return json(+ {+ success: true,+ message: "Pick functionality not yet implemented",+ },+ await flash(request, success("Pick operation completed"))+ );+}diff --git a/apps/erp/app/routes/api+/stock-transfer+/$lineId+/unpick.tsx b/apps/erp/app/routes/api+/stock-transfer+/$lineId+/unpick.tsxnew file mode 100644index 0000000000..350fd2dc56--- /dev/null+++ b/apps/erp/app/routes/api+/stock-transfer+/$lineId+/unpick.tsx@@ -0,0 +1,30 @@+import { assertIsPost, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "inventory",+ });++ const { lineId } = params;+ if (!lineId) throw notFound("lineId not found");++ // TODO: Implement unpick functionality+ // This would typically:+ // 1. Get the stock transfer line+ // 2. Decrease the pickedQuantity+ // 3. Reverse inventory transactions+ // 4. Update stock transfer status if needed++ return json(+ {+ success: true,+ message: "Unpick functionality not yet implemented",+ },+ await flash(request, success("Unpick operation completed"))+ );+}diff --git a/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsxnew file mode 100644index 0000000000..d41af45000--- /dev/null+++ b/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx@@ -0,0 +1,125 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { StockTransferPDF } from "@carbon/documents/pdf";+import { renderToStream } from "@react-pdf/renderer";+import { type LoaderFunctionArgs } from "@vercel/remix";+import { getStockTransfer, getStockTransferLines } from "~/modules/inventory";+import { getCompany } from "~/modules/settings";+import { getBase64ImageFromSupabase } from "~/modules/shared";+import { getLocale } from "~/utils/request";++export const config = { runtime: "nodejs" };++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "inventory",+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const [company, stockTransfer, stockTransferLines] = await Promise.all([+ getCompany(client, companyId),+ getStockTransfer(client, id),+ getStockTransferLines(client, id),+ ]);++ if (company.error) {+ console.error(company.error);+ }++ if (stockTransfer.error) {+ console.error(stockTransfer.error);+ }++ if (stockTransferLines.error) {+ console.error(stockTransferLines.error);+ }++ if (+ company.error ||+ stockTransfer.error ||+ stockTransferLines.error ||+ stockTransfer.data.companyId !== companyId+ ) {+ throw new Error("Failed to load stock transfer");+ }++ // Get location information+ const location = await client+ .from("location")+ .select("*")+ .eq("id", stockTransfer.data.locationId)+ .single();++ if (location.error) {+ console.error(location.error);+ throw new Error("Failed to load location");+ }++ const locale = getLocale(request);++ // Get thumbnails for items+ const thumbnailPaths = stockTransferLines.data?.reduce<+ Record<string, string | null>+ >((acc, line) => {+ if (line.thumbnailPath) {+ acc[line.id!] = line.thumbnailPath;+ }+ return acc;+ }, {});++ const thumbnails: Record<string, string | null> =+ (thumbnailPaths+ ? await Promise.all(+ Object.entries(thumbnailPaths).map(([id, path]) => {+ if (!path) {+ return null;+ }+ return getBase64ImageFromSupabase(client, path).then((data) => ({+ id,+ data,+ }));+ })+ )+ : []+ )?.reduce<Record<string, string | null>>((acc, thumbnail) => {+ if (thumbnail) {+ acc[thumbnail.id] = thumbnail.data;+ }+ return acc;+ }, {}) ?? {};++ const stream = await renderToStream(+ <StockTransferPDF+ company={company.data}+ stockTransfer={stockTransfer.data}+ stockTransferLines={stockTransferLines.data ?? []}+ location={location.data}+ locale={locale}+ meta={{+ author: "Carbon",+ keywords: "stock transfer",+ subject: "Stock Transfer",+ }}+ title="Stock Transfer"+ thumbnails={thumbnails}+ />+ );++ const body: Buffer = await new Promise((resolve, reject) => {+ const buffers: Uint8Array[] = [];+ stream.on("data", (data) => {+ buffers.push(data);+ });+ stream.on("end", () => {+ resolve(Buffer.concat(buffers));+ });+ stream.on("error", reject);+ });++ const headers = new Headers({+ "Content-Type": "application/pdf",+ "Content-Disposition": `inline; filename="${stockTransfer.data.stockTransferId}.pdf"`,+ });+ return new Response(body, { status: 200, headers });+}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 013604b756..c0e913c3df 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -47050,6 +47050,7 @@ export type Database = {fromShelfId: string | nullfromShelfName: string | nullid: string | null+ itemDescription: string | nullitemId: string | nullitemReadableId: string | nulljobId: string | nulldiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 013604b756..c0e913c3df 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -47050,6 +47050,7 @@ export type Database = {fromShelfId: string | nullfromShelfName: string | nullid: string | null+ itemDescription: string | nullitemId: string | nullitemReadableId: string | nulljobId: string | nulldiff --git a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql b/packages/database/supabase/migrations/20251007014240_stock-transfers.sqlindex 6380afb1e5..e095a83c2b 100644--- a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql+++ b/packages/database/supabase/migrations/20251007014240_stock-transfers.sql@@ -240,6 +240,7 @@ SELECTELSE i."thumbnailPath"END AS "thumbnailPath",i."readableIdWithRevision" as "itemReadableId",+ i."name" as "itemDescription",uom."name" AS "unitOfMeasure",sf."name" AS "fromShelfName",st."name" AS "toShelfName"@@ -271,7 +272,7 @@ BEGINELSE-- All lines are fully picked, set status to CompletedUPDATE "stockTransfer"- SET "status" = 'Completed'+ SET "status" = 'Completed', "completedAt" = NOW()WHERE "id" = NEW."stockTransferId";END IF;END IF;diff --git a/packages/documents/src/pdf/StockTransferPDF.tsx b/packages/documents/src/pdf/StockTransferPDF.tsxnew file mode 100644index 0000000000..8a226a6590--- /dev/null+++ b/packages/documents/src/pdf/StockTransferPDF.tsx@@ -0,0 +1,189 @@+import bwipjs from "@bwip-js/node";+import { getAppUrl } from "@carbon/auth";+import type { Database } from "@carbon/database";+import { Image, Text, View } from "@react-pdf/renderer";+import { createTw } from "react-pdf-tailwind";+import { generateQRCode } from "../qr/qr-code";+import type { PDF } from "../types";+import { Header, Summary, Template } from "./components";++interface StockTransferPDFProps extends PDF {+ stockTransfer: Database["public"]["Tables"]["stockTransfer"]["Row"];+ stockTransferLines: Database["public"]["Views"]["stockTransferLines"]["Row"][];+ location: Database["public"]["Tables"]["location"]["Row"];+ thumbnails?: Record<string, string | null>;+}++// Initialize tailwind-styled-components+const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Helvetica", "Arial", "sans-serif"],+ },+ extend: {+ colors: {+ gray: {+ 500: "#7d7d7d",+ },+ },+ },+ },+});++const StockTransferPDF = ({+ company,+ stockTransfer,+ stockTransferLines,+ location,+ title = "Stock Transfer",+ thumbnails,+}: StockTransferPDFProps) => {+ const details = [+ {+ label: "Date",+ value: stockTransfer?.createdAt+ ? new Date(stockTransfer.createdAt).toLocaleDateString()+ : "",+ },+ {+ label: "Stock Transfer",+ value: stockTransfer?.stockTransferId,+ },+ {+ label: "Location",+ value: location?.name,+ },+ ];++ if (stockTransfer?.assignee) {+ details.push({+ label: "Assignee",+ value: stockTransfer.assignee,+ });+ }++ return (+ <Template+ title={title}+ meta={{+ author: "Carbon",+ keywords: "stock transfer",+ subject: "Stock Transfer",+ }}+ >+ <View style={tw("flex flex-col")}>+ {/* Header Section - Always at the top */}+ <View style={tw("mb-4")}>+ <Header title={title} company={company} />+ <Summary company={company} items={details} />+ </View>++ {/* Line Items Section */}+ <View style={tw("mb-6 text-xs")}>+ <View+ style={tw(+ "flex flex-row justify-between items-center mt-5 py-3 px-[6px] border-t border-b border-gray-300 font-bold uppercase page-break-inside-avoid"+ )}+ >+ <Text style={tw("w-2/5 text-left")}>Description</Text>+ <Text style={tw("w-1/4 text-center")}>Transfer</Text>+ <Text style={tw("w-1/6 text-center")}>Qty</Text>+ <Text style={tw("w-1/8 text-center")}>Pick</Text>+ </View>++ {stockTransferLines+ .sort((a, b) => {+ const shelfA = a.fromShelfName || "Any";+ const shelfB = b.fromShelfName || "Any";+ return shelfA.localeCompare(shelfB);+ })+ .map((line) => {+ const barcodeDataUrl = generateBarcode(line.itemReadableId);+ const pickUrl = `${getAppUrl()}/api/stock-transfer/${+ line.id+ }/pick`;+ const pickQRCode = generateQRCode(pickUrl, 4);++ return (+ <View+ style={tw(+ "flex flex-row justify-between py-3 px-[6px] border-b border-gray-300 page-break-inside-avoid"+ )}+ key={line.id}+ >+ <View style={tw("w-2/5")}>+ <Text style={tw("font-bold mb-1")}>+ {getLineDescription(line)}+ </Text>+ <Text style={tw("text-[9px] opacity-80 mb-2")}>+ {getLineDescriptionDetails(line)}+ </Text>++ {thumbnails &&+ line.id in thumbnails &&+ thumbnails[line.id] && (+ <View style={tw("mt-2 mb-2")}>+ <Image+ src={thumbnails[line.id]!}+ style={tw("w-1/4 h-auto max-w-[25%]")}+ />+ </View>+ )}++ <Image src={barcodeDataUrl} style={tw("max-w-[50%]")} />+ </View>++ <View style={tw("w-1/4 text-center")}>+ <Text style={tw("text-xs")}>+ {line.fromShelfName || "Any"} →{" "}+ {line.toShelfName || "Any"}+ </Text>+ </View>++ <Text style={tw("w-1/6 text-center")}>+ {getLineQuantity(line)}+ </Text>++ <View style={tw("w-1/8 flex flex-col items-center")}>+ <Image src={pickQRCode} style={tw("h-16 w-16")} />+ </View>+ </View>+ );+ })}+ </View>+ </View>+ </Template>+ );+};++function getLineQuantity(+ line: Database["public"]["Views"]["stockTransferLines"]["Row"]+) {+ return `${line.quantity} ${line.unitOfMeasure}`;+}++function getLineDescription(+ line: Database["public"]["Views"]["stockTransferLines"]["Row"]+) {+ return line.itemDescription;+}++function getLineDescriptionDetails(+ line: Database["public"]["Views"]["stockTransferLines"]["Row"]+) {+ return line.itemReadableId;+}++async function generateBarcode(text: string): Promise<string> {+ const buffer = await bwipjs.toBuffer({+ bcid: "code128", // Barcode type+ text: text, // Text to encode+ scale: 3, // 3x scaling factor+ height: 5, // Bar height, in millimeters+ includetext: true, // Show human-readable text+ textxalign: "center", // Always good to set this+ });+ return `data:image/png;base64,${buffer.toString("base64")}`;+}++export default StockTransferPDF;diff --git a/packages/documents/src/pdf/index.ts b/packages/documents/src/pdf/index.tsindex d39e710cb3..ebef1a40a2 100644--- a/packages/documents/src/pdf/index.ts+++ b/packages/documents/src/pdf/index.ts@@ -7,6 +7,7 @@ import PurchaseOrderPDF from "./PurchaseOrderPDF";import QuotePDF from "./QuotePDF";import SalesInvoicePDF from "./SalesInvoicePDF";import SalesOrderPDF from "./SalesOrderPDF";+import StockTransferPDF from "./StockTransferPDF";export {IssuePDF,JobTravelerPDF,@@ -17,4 +18,5 @@ export {QuotePDF,SalesInvoicePDF,SalesOrderPDF,+ StockTransferPDF,};