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 printing kanban labels
Brad Barbinc59b0682f62a
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 6f86762597..968d8e0346 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -126,6 +126,9 @@ export const kanbanValidator = z.object({),locationId: z.string().min(1, { message: "Location is required" }),shelfId: zfd.text(z.string().optional()),+ supplierId: zfd.text(z.string().optional()),+ purchaseUnitOfMeasureCode: zfd.text(z.string().optional()),+ conversionFactor: zfd.numeric(z.number().min(0).default(1)),});export const receiptValidator = z.object({diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 53d51b8e38..8cd84fbe14 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -231,11 +231,7 @@ export async function getKanban(client: SupabaseClient<Database>,kanbanId: string) {- return client- .from("kanban")- .select("*, item!itemId(*), location!locationId(*)")- .eq("id", kanbanId)- .single();+ return client.from("kanbans").select("*").eq("id", kanbanId).single();}export async function getReceipts(diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsxindex f026dd36f2..335f15b490 100644--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx@@ -13,14 +13,21 @@ import {toast,VStack,} from "@carbon/react";-import { useFetcher } from "@remix-run/react";import { useState } from "react";import type { z } from "zod";import { Enumerable } from "~/components/Enumerable";-import { Item, Location, Number, Shelf, Submit } from "~/components/Form";+import {+ ConversionFactor,+ Item,+ Location,+ Number,+ Shelf,+ Submit,+ Supplier,+ UnitOfMeasure,+} from "~/components/Form";import { useUser } from "~/hooks";import type { MethodItemType } from "~/modules/shared/types";-import { path } from "~/utils/path";import {kanbanValidator,replenishmentSystemTypes,@@ -35,8 +42,6 @@ type KanbanFormProps = {};const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {- const fetcher = useFetcher<{ success: boolean; message: string }>();-const [selectedReplenishmentSystem, setSelectedReplenishmentSystem] =useState<string>(initialValues.replenishmentSystem || "Buy");@@ -46,19 +51,31 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {initialValues.shelfId || null);const [itemType, setItemType] = useState<MethodItemType | "Item">("Item");- const onTypeChange = (type: MethodItemType) => {- setItemType(type);- };+ const [itemId, setItemId] = useState<string>(initialValues.itemId || "");++ const [supplierId, setSupplierId] = useState<string>(+ initialValues.supplierId || ""+ );+ const [purchaseUnitOfMeasureCode, setPurchaseUnitOfMeasureCode] =+ useState<string>(initialValues.purchaseUnitOfMeasureCode || "");+ const [inventoryUnitOfMeasureCode, setInventoryUnitOfMeasureCode] =+ useState<string>("");+ const [conversionFactor, setConversionFactor] = useState<number>(+ initialValues.conversionFactor || 1+ );const { carbon } = useCarbon();const { company } = useUser();const onItemChange = async (value: { value: string } | null) => {if (!carbon || !value) return;++ setItemId(value.value);+const [item, shelf] = await Promise.all([carbon.from("item")- .select("replenishmentSystem")+ .select("replenishmentSystem, unitOfMeasureCode").eq("id", value.value).single(),carbon@@ -77,6 +94,62 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {if (shelf.data?.defaultShelfId) {setShelfId(shelf.data.defaultShelfId);}++ // Set inventory unit of measure from item+ const itemUnitOfMeasure = item.data?.unitOfMeasureCode || "";+ setInventoryUnitOfMeasureCode(itemUnitOfMeasure);++ // If there's no supplier selected, set purchase unit to match inventory unit+ if (!supplierId) {+ setPurchaseUnitOfMeasureCode(itemUnitOfMeasure);+ setConversionFactor(1);+ } else {+ // If there's a supplier, look up supplier part for this item/supplier combo+ const supplierPart = await carbon+ .from("supplierPart")+ .select("supplierUnitOfMeasureCode, conversionFactor")+ .eq("itemId", value.value)+ .eq("supplierId", supplierId)+ .eq("companyId", company.id)+ .maybeSingle();++ if (supplierPart.data) {+ setPurchaseUnitOfMeasureCode(+ supplierPart.data.supplierUnitOfMeasureCode || itemUnitOfMeasure+ );+ setConversionFactor(supplierPart.data.conversionFactor || 1);+ } else {+ setPurchaseUnitOfMeasureCode(itemUnitOfMeasure);+ setConversionFactor(1);+ }+ }+ };++ const onSupplierChange = async (value: { value: string } | null) => {+ setSupplierId(value?.value || "");++ // If we have both item and supplier, look up supplier part+ if (carbon && value?.value && itemId) {+ const supplierPart = await carbon+ .from("supplierPart")+ .select("supplierUnitOfMeasureCode, conversionFactor")+ .eq("itemId", itemId)+ .eq("supplierId", value.value)+ .eq("companyId", company.id)+ .maybeSingle();++ if (supplierPart.data) {+ setPurchaseUnitOfMeasureCode(+ supplierPart.data.supplierUnitOfMeasureCode ||+ inventoryUnitOfMeasureCode+ );+ setConversionFactor(supplierPart.data.conversionFactor || 1);+ }+ } else if (!value?.value) {+ // If supplier is cleared, reset to inventory unit of measure+ setPurchaseUnitOfMeasureCode(inventoryUnitOfMeasureCode);+ setConversionFactor(1);+ }};const [locationId, setLocationId] = useState<string>(@@ -91,14 +164,9 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {<Drawer open onOpenChange={onClose}><DrawerContent><ValidatedForm- fetcher={fetcher}method="post"- action={- isEditing ? path.to.kanban(initialValues.id!) : path.to.newKanban- }validator={kanbanValidator}defaultValues={initialValues}- onSubmit={onClose}className="flex flex-col h-full"><DrawerHeader>@@ -121,10 +189,8 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {<Itemname="itemId"label="Item"- type="Item"- itemType={itemType}- // @ts-ignore- onTypeChange={onTypeChange}+ type={itemType}+ onTypeChange={(t) => setItemType(t as MethodItemType)}onChange={onItemChange}isReadOnly={isEditing}/>@@ -141,7 +207,9 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {name="replenishmentSystem"label="Replenishment System"onChange={(value) => {- console.log(value);+ if (value) {+ setSelectedReplenishmentSystem(value.value);+ }}}options={replenishmentSystemTypes.filter((type) => type !== "Buy and Make")@@ -151,6 +219,44 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {}))}/>+ {selectedReplenishmentSystem === "Buy" && (+ <>+ <Supplier+ name="supplierId"+ label="Supplier"+ value={supplierId}+ onChange={onSupplierChange}+ />++ <UnitOfMeasure+ name="purchaseUnitOfMeasureCode"+ label="Purchase Unit of Measure"+ value={purchaseUnitOfMeasureCode}+ onChange={(value) => {+ if (+ value &&+ typeof value === "object" &&+ "value" in value+ ) {+ setPurchaseUnitOfMeasureCode(value.value);+ } else {+ setPurchaseUnitOfMeasureCode("");+ }+ }}+ />++ <ConversionFactor+ name="conversionFactor"+ label="Conversion Factor"+ inventoryCode={inventoryUnitOfMeasureCode}+ purchasingCode={purchaseUnitOfMeasureCode}+ value={conversionFactor}+ onChange={setConversionFactor}+ helperText="Number of inventory units per purchase unit"+ />+ </>+ )}+<Locationname="locationId"label="Location"diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsxindex 49d6d13a49..81b62967fa 100644--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx@@ -1,12 +1,20 @@import {Combobox,Copy,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,HStack,IconButton,MenuItem,- Popover,- PopoverContent,- PopoverTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,VStack,} from "@carbon/react";import { Link } from "@remix-run/react";@@ -14,20 +22,30 @@ import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";import {LuCalendar,+ LuContainer,LuHash,LuLink,LuMapPin,LuPackage,LuPencil,+ LuPrinter,LuQrCode,LuRefreshCw,+ LuTag,LuTrash,LuUser,} from "react-icons/lu";-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";+import {+ EmployeeAvatar,+ Hyperlink,+ New,+ SupplierAvatar,+ Table,+} from "~/components";import { Enumerable } from "~/components/Enumerable";import { useLocations } from "~/components/Form/Location";import { usePermissions, useUrlParams } from "~/hooks";+import { useSuppliers } from "~/stores";import { useItems } from "~/stores/items";import { usePeople } from "~/stores/people";import { path } from "~/utils/path";@@ -41,6 +59,7 @@ type KanbansTableProps = {const defaultColumnVisibility = {createdBy: false,+ supplierName: false,createdAt: false,updatedBy: false,updatedAt: false,@@ -52,6 +71,7 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {const permissions = usePermissions();const [people] = usePeople();const [items] = useItems();+ const [suppliers] = useSuppliers();const locations = useLocations();const columns = useMemo<ColumnDef<Kanban>[]>(@@ -87,15 +107,32 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {header: "",cell: ({ row }) => (<HStack>- <Popover>- <PopoverTrigger>+ <Tooltip>+ <TooltipTrigger>+ <IconButton+ aria-label="Labels"+ variant="secondary"+ icon={<LuTag />}+ onClick={() => {+ window.open(+ path.to.file.kanbanLabelsPdf([row.original.id!]),+ "_blank"+ );+ }}+ />+ </TooltipTrigger>+ <TooltipContent>Print Label</TooltipContent>+ </Tooltip>++ <HoverCard>+ <HoverCardTrigger><IconButtonaria-label="QR Code"variant="secondary"icon={<LuQrCode />}/>- </PopoverTrigger>- <PopoverContent+ </HoverCardTrigger>+ <HoverCardContentalign="center"className="size-[236px] overflow-hidden z-[100] bg-white p-4">@@ -106,8 +143,8 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {height="198"src={path.to.file.kanbanQrCode(row.original.id!)}/>- </PopoverContent>- </Popover>+ </HoverCardContent>+ </HoverCard><Copytext={`${typeof window === "undefined" ? "" : window.location.origin@@ -121,7 +158,17 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {{accessorKey: "quantity",header: "Reorder Qty.",- cell: ({ row }) => row.original.quantity,+ cell: ({ row }) => {+ const { quantity, purchaseUnitOfMeasureCode } = row.original;+ const baseQuantity = quantity || 0;++ return (+ <span>+ {baseQuantity}+ {purchaseUnitOfMeasureCode && ` ${purchaseUnitOfMeasureCode}`}+ </span>+ );+ },meta: {icon: <LuHash />,},@@ -144,11 +191,26 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {},},{- accessorKey: "locationName",- header: "Location",+ accessorKey: "supplierId",+ header: "Supplier",cell: ({ row }) => (- <Enumerable value={row.original.locationName || ""} />+ <SupplierAvatar supplierId={row.original.supplierId} />),+ meta: {+ icon: <LuContainer />,+ filter: {+ type: "static",+ options: suppliers.map((supplier) => ({+ value: supplier.id,+ label: supplier.name,+ })),+ },+ },+ },+ {+ accessorKey: "shelfName",+ header: "Shelf",+ cell: ({ row }) => row.original.shelfName || "",meta: {icon: <LuMapPin />,},@@ -211,7 +273,7 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {},},],- [items, params, people]+ [items, params, people, suppliers]);const renderContextMenu = useCallback(@@ -243,6 +305,30 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {[params, permissions]);+ const renderActions = useCallback((selectedRows: typeof data) => {+ const handlePrintLabels = () => {+ const selectedIds = selectedRows+ .map((row) => row.id)+ .filter(Boolean) as string[];+ if (selectedIds.length > 0) {+ window.open(path.to.file.kanbanLabelsPdf(selectedIds), "_blank");+ }+ };++ return (+ <DropdownMenuContent align="end" className="min-w-[200px]">+ <DropdownMenuLabel>Actions</DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem onClick={handlePrintLabels}>+ <LuPrinter className="mr-2 h-4 w-4" />+ Print Labels ({selectedRows.length})+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ );+ }, []);+return (<Table<Kanban>count={count}@@ -266,10 +352,12 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {)}</div>}+ renderActions={renderActions}renderContextMenu={renderContextMenu}title="Kanbans"table="kanban"withSavedView+ withSelectableRows/>);});diff --git a/apps/erp/app/routes/api+/kanban.$id.ts b/apps/erp/app/routes/api+/kanban.$id.tsnew file mode 100644index 0000000000..6b168789e3--- /dev/null+++ b/apps/erp/app/routes/api+/kanban.$id.ts@@ -0,0 +1,33 @@+import { badRequest, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { redirect, type LoaderFunctionArgs } from "@vercel/remix";++import { getKanban } from "~/modules/inventory";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ const { id } = params;+ if (!id) throw notFound("id not found");++ const kanban = await getKanban(client, id);++ if (kanban.error || !kanban.data) {+ throw notFound("Kanban is not active");+ }++ if (kanban.data.companyId !== companyId) {+ throw notFound("Kanban is not active");+ }++ if (kanban.data.replenishmentSystem === "Make") {+ console.log("Make");+ } else if (kanban.data.replenishmentSystem === "Buy") {+ console.log("Buy");+ } else {+ throw badRequest(`${kanban.data.replenishmentSystem} is not supported`);+ }++ throw redirect(path.to.authenticatedRoot);+}diff --git a/apps/erp/app/routes/file+/kanban+/labels[.]pdf.tsx b/apps/erp/app/routes/file+/kanban+/labels[.]pdf.tsxnew file mode 100644index 0000000000..850572b8a2--- /dev/null+++ b/apps/erp/app/routes/file+/kanban+/labels[.]pdf.tsx@@ -0,0 +1,116 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { KanbanLabelPDF } from "@carbon/documents/pdf";+import { renderToStream } from "@react-pdf/renderer";+import { type LoaderFunctionArgs } from "@vercel/remix";+import { getBase64ImageFromSupabase } from "~/modules/shared";++export const config = { runtime: "nodejs" };++export async function loader({ request }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "inventory",+ });++ // Get kanban IDs from search params+ const url = new URL(request.url);+ const idsParam = url.searchParams.get("ids");++ if (!idsParam) {+ return new Response("No kanban IDs provided", { status: 400 });+ }++ // Parse comma-separated IDs+ const kanbanIds = idsParam.split(",").map((id) => id.trim());++ if (kanbanIds.length === 0) {+ return new Response("No valid kanban IDs provided", { status: 400 });+ }++ // Fetch all kanban records in parallel+ const kanbanPromises = kanbanIds.map((id) =>+ client.from("kanbans").select("*").eq("id", id).single()+ );+ const kanbanResults = await Promise.all(kanbanPromises);++ // Collect all thumbnails paths first+ const thumbnailPaths: Record<string, string> = {};+ const validKanbans: typeof kanbanResults = [];++ for (const result of kanbanResults) {+ if (!result.error && result.data) {+ validKanbans.push(result);+ if (result.data.thumbnailPath && result.data.id) {+ thumbnailPaths[result.data.id] = result.data.thumbnailPath;+ }+ }+ }++ // Fetch all thumbnails in parallel+ const thumbnails: Record<string, string | null> = {};+ if (Object.keys(thumbnailPaths).length > 0) {+ const thumbnailPromises = Object.entries(thumbnailPaths).map(+ async ([id, path]) => {+ const base64 = await getBase64ImageFromSupabase(client, path);+ return { id, data: base64 };+ }+ );++ const thumbnailResults = await Promise.all(thumbnailPromises);+ for (const thumbnail of thumbnailResults) {+ if (thumbnail.data) {+ thumbnails[thumbnail.id] = thumbnail.data;+ }+ }+ }++ // Transform to label format+ const labels = [];++ for (const result of validKanbans) {+ if (!result.error && result.data) {+ const kanban = result.data;++ // Prepare label data+ const labelData = {+ id: kanban.id!,+ itemId: kanban.itemId!,+ itemName: kanban.name || "",+ itemReadableId: kanban.readableIdWithRevision || kanban.itemId!,+ locationName: kanban.locationName || "",+ shelfId: kanban.shelfId,+ shelfName: kanban.shelfName,+ supplierName: kanban.supplierName,+ quantity: kanban.quantity ?? 0,+ unitOfMeasureCode: kanban.purchaseUnitOfMeasureCode,+ thumbnail: thumbnails[kanban.id!] || null,+ };++ labels.push(labelData);+ }+ }++ if (labels.length === 0) {+ return new Response("No valid kanbans found", { status: 404 });+ }++ // Generate PDF+ const stream = await renderToStream(<KanbanLabelPDF labels={labels} />);++ 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="Kanban Labels.pdf"`,+ });++ return new Response(body, { status: 200, headers });+}diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsxindex 0ca0b10590..d9d14e6c02 100644--- a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx+++ b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx@@ -74,6 +74,10 @@ export default function EditKanbanRoute() {quantity: kanban?.quantity ?? 1,replenishmentSystem: kanban?.replenishmentSystem ?? "Buy",locationId: kanban?.locationId ?? "",+ shelfId: kanban?.shelfId ?? "",+ supplierId: kanban?.supplierId ?? "",+ purchaseUnitOfMeasureCode: kanban?.purchaseUnitOfMeasureCode ?? "",+ conversionFactor: kanban?.conversionFactor ?? 1,};return (diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.new.tsxindex b718dc5d4a..f89a212a6a 100644--- a/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx+++ b/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx@@ -24,7 +24,6 @@ export async function action({ request }: ActionFunctionArgs) {});const formData = await request.formData();- const modal = formData.get("type") === "modal";const validation = await validator(kanbanValidator).validate(formData);@@ -39,6 +38,7 @@ export async function action({ request }: ActionFunctionArgs) {companyId,createdBy: userId,});+if (createKanban.error) {return json({},@@ -46,12 +46,10 @@ export async function action({ request }: ActionFunctionArgs) {);}- return modal- ? json(createKanban, { status: 201 })- : redirect(- `${path.to.kanbans}?${getParams(request)}`,- await flash(request, success("Kanban created"))- );+ throw redirect(+ `${path.to.kanbans}?${getParams(request)}`,+ await flash(request, success("Kanban created"))+ );}export default function NewKanbanRoute() {@@ -66,6 +64,7 @@ export default function NewKanbanRoute() {quantity: 1,replenishmentSystem: "Buy" as const,locationId,+ conversionFactor: 1,};return (diff --git a/llm/cache/kanban-system.md b/llm/cache/kanban-system.mdnew file mode 100644index 0000000000..4126e9b602--- /dev/null+++ b/llm/cache/kanban-system.md@@ -0,0 +1,197 @@+# Kanban System++## Overview++Carbon's kanban system manages replenishment cards for inventory items across different locations and shelves. It supports both "Buy" and "Make" replenishment systems for streamlined inventory management.++## Database Structure++### Table: `kanban`++Created in migration `20250909012102_kanban.sql`:++**Fields:**++- `id`: TEXT (PRIMARY KEY, default: id('kb')) - Unique kanban identifier+- `itemId`: TEXT (FOREIGN KEY to item.id) - Associated item+- `replenishmentSystem`: itemReplenishmentSystem ENUM (default: 'Buy') - "Buy", "Make", or "Buy and Make"+- `quantity`: INTEGER - Kanban quantity+- `locationId`: TEXT (FOREIGN KEY to location.id) - Storage location+- `shelfId`: TEXT (FOREIGN KEY to shelf.id, optional) - Specific shelf location+- `companyId`: TEXT (FOREIGN KEY to company.id) - Company association+- `createdAt`: TIMESTAMP WITH TIME ZONE (default: NOW())+- `createdBy`: TEXT (FOREIGN KEY to user.id) - Creator+- `updatedAt`: TIMESTAMP WITH TIME ZONE+- `updatedBy`: TEXT (FOREIGN KEY to user.id) - Last updater++**Indexes:**++- `kanban_itemId_idx` on `itemId`+- `kanban_locationId_idx` on `(companyId, locationId)`+- `kanban_companyId_idx` on `companyId`++**Row Level Security:**++- SELECT: Company employees with any role+- INSERT: Requires `inventory_create` permission+- UPDATE: Requires `inventory_update` permission+- DELETE: Requires `inventory_delete` permission++### View: `kanbans`++A security-invoker view that joins kanban data with item and location information:++```sql+SELECT+ k.*,+ i.name,+ i.readableIdWithRevision,+ l.name as locationName+FROM kanban k+JOIN item i ON k.itemId = i.id+JOIN location l ON k.locationId = l.id+```++## TypeScript Types and Validation++### Zod Validator (`kanbanValidator`)++Located in `/apps/erp/app/modules/inventory/inventory.models.ts`:++```typescript+const kanbanValidator = z.object({+ id: zfd.text(z.string().optional()),+ itemId: z.string().min(1, { message: "Item is required" }),+ replenishmentSystem: z.enum(replenishmentSystemTypes).default("Buy"),+ quantity: zfd.numeric(+ z.number().int().min(1, { message: "Quantity must be at least 1" })+ ),+ locationId: z.string().min(1, { message: "Location is required" }),+ shelfId: zfd.text(z.string().optional()),+});+```++### TypeScript Types++- `Kanban` type defined in `/apps/erp/app/modules/inventory/types.ts`+- Type generated from `getKanbans` service function return data++## Service Functions++### Core Functions++Located in `/apps/erp/app/modules/inventory/inventory.service.ts`:++- **`getKanbans(client, locationId, companyId, args)`** - Get paginated kanbans for location with search+- **`getKanban(client, kanbanId)`** - Get single kanban with item and location details+- **`upsertKanban(client, kanban)`** - Create or update kanban record+- **`deleteKanban(client, kanbanId)`** - Delete kanban record++### Service Features++- Search functionality across item name and readable ID with revision+- Generic query filters support (pagination, sorting, filtering)+- Joins with item and location data for enriched views++## UI Components++### KanbanForm++Located at `/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx`:++- Form for creating/editing kanbans+- Supports item selection, location/shelf assignment+- Replenishment system selection (Buy/Make/Buy and Make)+- Quantity input validation++### KanbansTable++Located at `/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx`:++- Table view of kanbans with search and filtering+- Column visibility controls+- Action buttons for edit/delete/QR code generation+- Location filtering support++## Routes and API++### Frontend Routes++- `/x/inventory/kanbans` - Main kanbans list page+- `/x/inventory/kanbans/new` - Create new kanban+- `/x/inventory/kanbans/:id` - View/edit kanban details+- `/x/inventory/kanbans/delete/:id` - Delete kanban confirmation++### API Routes++- `/api/kanban/:id` - Kanban API endpoint (handles replenishment logic)+- `/file/kanban/:id.png` - QR code generation for kanban++## QR Code Integration++### QR Code Generation++- Route: `/file/kanban/:id.png`+- Generates QR code pointing to `/api/kanban/:id`+- Uses `@carbon/documents/qr` package+- 36px size with PNG format+- Cached with max-age headers++### QR Code Usage++- Available as action in KanbansTable+- Generates scannable codes for physical kanban cards+- Links to API endpoint for replenishment processing++## Replenishment System Integration++### API Handler (`/api/kanban/:id`)++- Validates kanban access and company association+- Routes based on replenishment system:+ - **"Make"** - Production order creation logic (placeholder)+ - **"Buy"** - Purchase order creation logic (placeholder)+ - **"Buy and Make"** - Not yet supported (throws error)+- Currently redirects to authenticated root after processing++### Replenishment Types++Defined in `replenishmentSystemTypes`:++- `"Buy"` - Purchase-based replenishment+- `"Make"` - Production-based replenishment+- `"Buy and Make"` - Hybrid approach (not implemented)++## Path Configuration++Kanban-related paths defined in `/apps/erp/app/utils/path.ts`:++```typescript+api: {+ kanban: (id: string) => `/api/kanban/${id}`+}+file: {+ kanbanQrCode: (id: string) => `/file/kanban/${id}.png`+}+to: {+ kanbans: '/x/inventory/kanbans',+ kanban: (id: string) => `/x/inventory/kanbans/${id}`,+ newKanban: '/x/inventory/kanbans/new',+ deleteKanban: (id: string) => `/x/inventory/kanbans/delete/${id}`+}+```++## Integration Points++### Inventory Module++- Part of the inventory module structure+- Integrated with location and shelf management+- Connected to item management system+- Uses company-based multi-tenancy++### Permissions++- Requires inventory permissions for CRUD operations+- Uses RLS policies for data security+- Integrates with user/company permission systemdiff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex efcb8a307b..c49b3b560b 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -14316,6 +14316,15 @@ export default {{$ref: "#/parameters/rowFilter.kanbans.shelfId",},+ {+ $ref: "#/parameters/rowFilter.kanbans.supplierId",+ },+ {+ $ref: "#/parameters/rowFilter.kanbans.purchaseUnitOfMeasureCode",+ },+ {+ $ref: "#/parameters/rowFilter.kanbans.conversionFactor",+ },{$ref: "#/parameters/rowFilter.kanbans.companyId",},@@ -14340,6 +14349,12 @@ export default {{$ref: "#/parameters/rowFilter.kanbans.locationName",},+ {+ $ref: "#/parameters/rowFilter.kanbans.shelfName",+ },+ {+ $ref: "#/parameters/rowFilter.kanbans.thumbnailPath",+ },{$ref: "#/parameters/select",},@@ -54819,6 +54834,15 @@ export default {{$ref: "#/parameters/rowFilter.kanban.shelfId",},+ {+ $ref: "#/parameters/rowFilter.kanban.supplierId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.purchaseUnitOfMeasureCode",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.conversionFactor",+ },{$ref: "#/parameters/rowFilter.kanban.companyId",},@@ -54911,6 +54935,15 @@ export default {{$ref: "#/parameters/rowFilter.kanban.shelfId",},+ {+ $ref: "#/parameters/rowFilter.kanban.supplierId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.purchaseUnitOfMeasureCode",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.conversionFactor",+ },{$ref: "#/parameters/rowFilter.kanban.companyId",},@@ -54957,6 +54990,15 @@ export default {{$ref: "#/parameters/rowFilter.kanban.shelfId",},+ {+ $ref: "#/parameters/rowFilter.kanban.supplierId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.purchaseUnitOfMeasureCode",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.conversionFactor",+ },{$ref: "#/parameters/rowFilter.kanban.companyId",},@@ -67030,6 +67072,20 @@ export default {format: "text",type: "string",},+ supplierId: {+ description:+ "Note:\nThis is a Foreign Key to `supplier.id`.<fk table='supplier' column='id'/>",+ format: "text",+ type: "string",+ },+ purchaseUnitOfMeasureCode: {+ format: "text",+ type: "string",+ },+ conversionFactor: {+ format: "numeric",+ type: "number",+ },companyId: {description:"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",@@ -67068,6 +67124,14 @@ export default {format: "text",type: "string",},+ shelfName: {+ format: "text",+ type: "string",+ },+ thumbnailPath: {+ format: "text",+ type: "string",+ },},type: "object",},@@ -86041,6 +86105,7 @@ export default {"replenishmentSystem","quantity","locationId",+ "conversionFactor","companyId","createdAt","createdBy",@@ -86080,6 +86145,21 @@ export default {format: "text",type: "string",},+ supplierId: {+ description:+ "Note:\nThis is a Foreign Key to `supplier.id`.<fk table='supplier' column='id'/>",+ format: "text",+ type: "string",+ },+ purchaseUnitOfMeasureCode: {+ format: "text",+ type: "string",+ },+ conversionFactor: {+ default: 1,+ format: "numeric",+ type: "number",+ },companyId: {description:"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",@@ -93792,6 +93872,24 @@ export default {in: "query",type: "string",},+ "rowFilter.kanbans.supplierId": {+ name: "supplierId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanbans.purchaseUnitOfMeasureCode": {+ name: "purchaseUnitOfMeasureCode",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanbans.conversionFactor": {+ name: "conversionFactor",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.kanbans.companyId": {name: "companyId",required: false,@@ -93840,6 +93938,18 @@ export default {in: "query",type: "string",},+ "rowFilter.kanbans.shelfName": {+ name: "shelfName",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanbans.thumbnailPath": {+ name: "thumbnailPath",+ required: false,+ in: "query",+ type: "string",+ },"body.companies": {name: "companies",description: "companies",@@ -115257,6 +115367,24 @@ export default {in: "query",type: "string",},+ "rowFilter.kanban.supplierId": {+ name: "supplierId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.purchaseUnitOfMeasureCode": {+ name: "purchaseUnitOfMeasureCode",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.conversionFactor": {+ name: "conversionFactor",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.kanban.companyId": {name: "companyId",required: false,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 9c53d050c5..18f6eddd1f 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -11630,40 +11630,49 @@ export type Database = {kanban: {Row: {companyId: string+ conversionFactor: numbercreatedAt: stringcreatedBy: stringid: stringitemId: stringlocationId: string+ purchaseUnitOfMeasureCode: string | nullquantity: numberreplenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]shelfId: string | null+ supplierId: string | nullupdatedAt: string | nullupdatedBy: string | null}Insert: {companyId: string+ conversionFactor?: numbercreatedAt?: stringcreatedBy: stringid?: stringitemId: stringlocationId: string+ purchaseUnitOfMeasureCode?: string | nullquantity: numberreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]shelfId?: string | null+ supplierId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}Update: {companyId?: string+ conversionFactor?: numbercreatedAt?: stringcreatedBy?: stringid?: stringitemId?: stringlocationId?: string+ purchaseUnitOfMeasureCode?: string | nullquantity?: numberreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]shelfId?: string | null+ supplierId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}@@ -11773,6 +11782,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_purchaseUnitOfMeasureCode_fkey"+ columns: ["purchaseUnitOfMeasureCode", "companyId"]+ isOneToOne: false+ referencedRelation: "unitOfMeasure"+ referencedColumns: ["code", "companyId"]+ },{foreignKeyName: "kanban_shelfId_fkey"columns: ["shelfId"]@@ -11780,6 +11796,41 @@ export type Database = {referencedRelation: "shelf"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },{foreignKeyName: "kanban_updatedBy_fkey"columns: ["updatedBy"]@@ -39326,6 +39377,7 @@ export type Database = {kanbans: {Row: {companyId: string | null+ conversionFactor: number | nullcreatedAt: string | nullcreatedBy: string | nullid: string | null@@ -39333,12 +39385,17 @@ export type Database = {locationId: string | nulllocationName: string | nullname: string | null+ purchaseUnitOfMeasureCode: string | nullquantity: number | nullreadableIdWithRevision: string | nullreplenishmentSystem:| Database["public"]["Enums"]["itemReplenishmentSystem"]| nullshelfId: string | null+ shelfName: string | null+ supplierId: string | null+ supplierName: string | null+ thumbnailPath: string | nullupdatedAt: string | nullupdatedBy: string | null}@@ -39448,6 +39505,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_purchaseUnitOfMeasureCode_fkey"+ columns: ["purchaseUnitOfMeasureCode", "companyId"]+ isOneToOne: false+ referencedRelation: "unitOfMeasure"+ referencedColumns: ["code", "companyId"]+ },{foreignKeyName: "kanban_shelfId_fkey"columns: ["shelfId"]@@ -39455,6 +39519,41 @@ export type Database = {referencedRelation: "shelf"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },{foreignKeyName: "kanban_updatedBy_fkey"columns: ["updatedBy"]@@ -40469,14 +40568,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -44273,14 +44372,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -44816,14 +44915,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 9c53d050c5..18f6eddd1f 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -11630,40 +11630,49 @@ export type Database = {kanban: {Row: {companyId: string+ conversionFactor: numbercreatedAt: stringcreatedBy: stringid: stringitemId: stringlocationId: string+ purchaseUnitOfMeasureCode: string | nullquantity: numberreplenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]shelfId: string | null+ supplierId: string | nullupdatedAt: string | nullupdatedBy: string | null}Insert: {companyId: string+ conversionFactor?: numbercreatedAt?: stringcreatedBy: stringid?: stringitemId: stringlocationId: string+ purchaseUnitOfMeasureCode?: string | nullquantity: numberreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]shelfId?: string | null+ supplierId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}Update: {companyId?: string+ conversionFactor?: numbercreatedAt?: stringcreatedBy?: stringid?: stringitemId?: stringlocationId?: string+ purchaseUnitOfMeasureCode?: string | nullquantity?: numberreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]shelfId?: string | null+ supplierId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}@@ -11773,6 +11782,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_purchaseUnitOfMeasureCode_fkey"+ columns: ["purchaseUnitOfMeasureCode", "companyId"]+ isOneToOne: false+ referencedRelation: "unitOfMeasure"+ referencedColumns: ["code", "companyId"]+ },{foreignKeyName: "kanban_shelfId_fkey"columns: ["shelfId"]@@ -11780,6 +11796,41 @@ export type Database = {referencedRelation: "shelf"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },{foreignKeyName: "kanban_updatedBy_fkey"columns: ["updatedBy"]@@ -39326,6 +39377,7 @@ export type Database = {kanbans: {Row: {companyId: string | null+ conversionFactor: number | nullcreatedAt: string | nullcreatedBy: string | nullid: string | null@@ -39333,12 +39385,17 @@ export type Database = {locationId: string | nulllocationName: string | nullname: string | null+ purchaseUnitOfMeasureCode: string | nullquantity: number | nullreadableIdWithRevision: string | nullreplenishmentSystem:| Database["public"]["Enums"]["itemReplenishmentSystem"]| nullshelfId: string | null+ shelfName: string | null+ supplierId: string | null+ supplierName: string | null+ thumbnailPath: string | nullupdatedAt: string | nullupdatedBy: string | null}@@ -39448,6 +39505,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_purchaseUnitOfMeasureCode_fkey"+ columns: ["purchaseUnitOfMeasureCode", "companyId"]+ isOneToOne: false+ referencedRelation: "unitOfMeasure"+ referencedColumns: ["code", "companyId"]+ },{foreignKeyName: "kanban_shelfId_fkey"columns: ["shelfId"]@@ -39455,6 +39519,41 @@ export type Database = {referencedRelation: "shelf"referencedColumns: ["id"]},+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },{foreignKeyName: "kanban_updatedBy_fkey"columns: ["updatedBy"]@@ -40469,14 +40568,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -44273,14 +44372,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -44816,14 +44915,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/migrations/20250909012102_kanban.sql b/packages/database/supabase/migrations/20250909012102_kanban.sqlindex 5fbf374c4d..f231f82b9d 100644--- a/packages/database/supabase/migrations/20250909012102_kanban.sql+++ b/packages/database/supabase/migrations/20250909012102_kanban.sql@@ -5,6 +5,9 @@ CREATE TABLE "kanban" ("quantity" INTEGER NOT NULL,"locationId" TEXT NOT NULL,"shelfId" TEXT,+ "supplierId" TEXT,+ "purchaseUnitOfMeasureCode" TEXT,+ "conversionFactor" NUMERIC NOT NULL DEFAULT 1,"companyId" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,@@ -15,6 +18,8 @@ CREATE TABLE "kanban" (CONSTRAINT "kanban_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,CONSTRAINT "kanban_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,CONSTRAINT "kanban_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE CASCADE,+ CONSTRAINT "kanban_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE,+ CONSTRAINT "kanban_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchaseUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE CASCADE,CONSTRAINT "kanban_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,CONSTRAINT "kanban_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE,CONSTRAINT "kanban_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE@@ -72,7 +77,16 @@ SELECTk.*,i.name,i."readableIdWithRevision",- l.name as "locationName"+ l.name as "locationName",+ s.name as "shelfName",+ su.name as "supplierName",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath"FROM "kanban" kJOIN "item" i ON k."itemId" = i."id"-JOIN "location" l ON k."locationId" = l."id";\ No newline at end of file+LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+JOIN "location" l ON k."locationId" = l."id"+LEFT JOIN "shelf" s ON k."shelfId" = s."id"+LEFT JOIN "supplier" su ON k."supplierId" = su."id";\ No newline at end of filediff --git a/packages/documents/src/pdf/KanbanLabelPDF.tsx b/packages/documents/src/pdf/KanbanLabelPDF.tsxnew file mode 100644index 0000000000..49f3388469--- /dev/null+++ b/packages/documents/src/pdf/KanbanLabelPDF.tsx@@ -0,0 +1,205 @@+import { Document, Image, Page, Text, View } from "@react-pdf/renderer";+import { createTw } from "react-pdf-tailwind";+import { generateQRCode } from "../qr/qr-code";++interface KanbanLabel {+ id: string;+ itemId: string;+ itemName: string;+ itemReadableId: string;+ locationName: string;+ supplierName?: string | null;+ shelfId?: string | null;+ shelfName?: string | null;+ quantity: number;+ unitOfMeasureCode?: string | null;+ thumbnail?: string | null;+}++interface KanbanLabelPDFProps {+ labels: KanbanLabel[];+}++// Initialize tailwind-styled-components+const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Helvetica", "Arial", "sans-serif"],+ },+ extend: {+ colors: {+ gray: {+ 500: "#7d7d7d",+ },+ },+ },+ },+});++const KanbanLabelPDF = ({ labels }: KanbanLabelPDFProps) => {+ // Fixed 2x3 layout (6 labels per page)+ const rows = 3;+ const columns = 2;++ // Standard letter size paper (8.5 x 11 inches in points)+ const LETTER_WIDTH = 8.5 * 72;+ const LETTER_HEIGHT = 11 * 72;++ // Calculate label dimensions for 2x3 layout with margins+ const margin = 36; // 0.5 inch margins+ const labelWidth = (LETTER_WIDTH - 2 * margin) / columns;+ const labelHeight = (LETTER_HEIGHT - 2 * margin) / rows;++ // Calculate how many pages we need+ const labelsPerPage = rows * columns;+ const pageCount = Math.ceil(labels.length / labelsPerPage);++ // QR code size - make it prominent+ const qrCodeSize = Math.min(labelHeight * 0.35, labelWidth * 0.4);++ return (+ <Document>+ {Array.from({ length: pageCount }).map((_, pageIndex) => (+ <Page+ key={pageIndex}+ size={[LETTER_WIDTH, LETTER_HEIGHT]}+ style={tw("p-0")}+ >+ <View style={{ margin: margin }}>+ {Array.from({ length: rows }).map((_, rowIndex) => (+ <View+ key={`row-${rowIndex}`}+ style={{+ flexDirection: "row",+ }}+ >+ {Array.from({ length: columns }).map((_, colIndex) => {+ const itemIndex =+ pageIndex * labelsPerPage + rowIndex * columns + colIndex;+ const label = labels[itemIndex];++ if (!label)+ return (+ <View+ key={`empty-${colIndex}`}+ style={{ width: labelWidth, height: labelHeight }}+ />+ );++ return (+ <View+ key={`label-${itemIndex}`}+ style={{+ ...tw(+ "relative p-4 flex flex-col border border-gray-300"+ ),+ width: labelWidth,+ height: labelHeight,+ }}+ >+ {/* QR Code at the top */}+ <View style={tw("flex items-center justify-center mb-3")}>+ <Image+ src={generateQRCode(label.id, qrCodeSize / 72)}+ style={{+ width: qrCodeSize,+ height: qrCodeSize,+ objectFit: "contain",+ }}+ />+ </View>++ {/* Item Information */}+ <View style={tw("flex-1 flex flex-col justify-center")}>+ {/* Item Name - Main Title */}+ <Text+ style={{+ ...tw("text-center mb-2"),+ fontSize: "14pt",+ fontWeight: "bold",+ }}+ >+ {label.itemName}+ </Text>++ {/* Item ID */}+ <Text+ style={{+ ...tw("text-center mb-1"),+ fontSize: "10pt",+ }}+ >+ {label.itemReadableId}+ </Text>++ {/* Thumbnail if available */}+ {label.thumbnail && (+ <View style={tw("flex items-center mb-2")}>+ <Image+ src={label.thumbnail}+ style={{+ width: labelWidth * 0.3,+ height: labelHeight * 0.15,+ objectFit: "contain",+ }}+ />+ </View>+ )}++ {/* Location and Shelf */}+ <View+ style={tw(+ "border-t border-gray-300 pt-2 mt-2 flex flex-col items-center text-center text-[14pt]"+ )}+ >+ {label.shelfName ? (+ <Text>{label.shelfName}</Text>+ ) : (+ <Text>{label.locationName}</Text>+ )}+ </View>++ {/* Quantity */}+ <View+ style={tw(+ "border-t border-gray-300 pt-2 mt-2 flex items-center"+ )}+ >+ <Text+ style={{+ ...tw("text-center"),+ fontSize: "16pt",+ fontWeight: "bold",+ }}+ >+ QTY: {label.quantity}+ {label.unitOfMeasureCode+ ? ` ${label.unitOfMeasureCode}`+ : ""}+ </Text>+ </View>+ </View>++ {/* Kanban ID at bottom */}+ <Text+ style={{+ ...tw("text-center"),+ fontSize: "12pt",+ color: "#7d7d7d",+ }}+ >+ {label.supplierName}+ </Text>+ </View>+ );+ })}+ </View>+ ))}+ </View>+ </Page>+ ))}+ </Document>+ );+};++export default KanbanLabelPDF;diff --git a/packages/documents/src/pdf/index.ts b/packages/documents/src/pdf/index.tsindex 54ec1f5d75..d39e710cb3 100644--- a/packages/documents/src/pdf/index.ts+++ b/packages/documents/src/pdf/index.ts@@ -10,6 +10,7 @@ import SalesOrderPDF from "./SalesOrderPDF";export {IssuePDF,JobTravelerPDF,+ KanbanLabelPDF,PackingSlipPDF,ProductLabelPDF,PurchaseOrderPDF,