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 kanban crud
Brad Barbind7946d233f54
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 69a3ace2a2..defc34972d 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -231,3 +231,19 @@ export const warehouseTransferLineValidator = zmessage: "From and To locations must be different",path: ["toLocationId"],});++export const replenishmentSystemTypes = [+ "Buy",+ "Make",+ "Buy and Make",+] as const;++export 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" }),+});diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex e571e88df4..53d51b8e38 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -11,6 +11,7 @@ import type {batchPropertyOrderValidator,batchPropertyValidator,inventoryAdjustmentValidator,+ kanbanValidator,receiptValidator,shelfValidator,shipmentValidator,@@ -25,6 +26,27 @@ export async function deleteBatchProperty(return client.from("batchProperty").delete().eq("id", id);}+export async function deleteWarehouseTransfer(+ client: SupabaseClient<Database>,+ transferId: string+) {+ return client.from("warehouseTransfer").delete().eq("id", transferId);+}++export async function deleteWarehouseTransferLine(+ client: SupabaseClient<Database>,+ transferLineId: string+) {+ return client.from("warehouseTransferLine").delete().eq("id", transferLineId);+}++export async function deleteKanban(+ client: SupabaseClient<Database>,+ kanbanId: string+) {+ return client.from("kanban").delete().eq("id", kanbanId);+}+export async function deleteReceipt(client: SupabaseClient<Database>,receiptId: string@@ -177,6 +199,45 @@ export async function getInventoryItemsCount(return query;}+export async function getKanbans(+ client: SupabaseClient<Database>,+ locationId: string,+ companyId: string,+ args: GenericQueryFilters & {+ search: string | null;+ }+) {+ let query = client+ .from("kanbans")+ .select("*", {+ count: "exact",+ })+ .eq("companyId", companyId)+ .eq("locationId", locationId);++ if (args.search) {+ query = query.or(+ `name.ilike.%${args.search}%,readableIdWithRevision.ilike.%${args.search}%`+ );+ }++ query = setGenericQueryFilters(query, args, [+ { column: "readableIdWithRevision", ascending: false },+ ]);+ return query;+}++export async function getKanban(+ client: SupabaseClient<Database>,+ kanbanId: string+) {+ return client+ .from("kanban")+ .select("*, item!itemId(*), location!locationId(*)")+ .eq("id", kanbanId)+ .single();+}+export async function getReceipts(client: SupabaseClient<Database>,companyId: string,@@ -637,6 +698,76 @@ export async function getTrackedEntitiesByOperationId(jobOperation.data.jobMakeMethodId);}++export async function getWarehouseTransfers(+ client: SupabaseClient<Database>,+ companyId: string,+ args: GenericQueryFilters & {+ search: string | null;+ }+) {+ let query = client+ .from("warehouseTransfer")+ .select(+ "*, fromLocation:location!fromLocationId(name), toLocation:location!toLocationId(name)",+ {+ count: "exact",+ }+ )+ .eq("companyId", companyId);++ if (args.search) {+ query = query.or(+ `transferId.ilike.%${args.search}%,reference.ilike.%${args.search}%`+ );+ }++ query = setGenericQueryFilters(query, args, [+ { column: "transferId", ascending: false },+ ]);+ return query;+}++export async function getWarehouseTransfer(+ client: SupabaseClient<Database>,+ transferId: string+) {+ return client+ .from("warehouseTransfer")+ .select(+ "*, fromLocation:location!fromLocationId(*), toLocation:location!toLocationId(*)"+ )+ .eq("id", transferId)+ .single();+}++export async function getWarehouseTransferLine(+ client: SupabaseClient<Database>,+ transferId: string,+ lineId: string+) {+ return client+ .from("warehouseTransferLine")+ .select(+ "*, warehouseTransfer(*, fromLocation:location!fromLocationId(name), toLocation:location!toLocationId(name))"+ )+ .eq("id", lineId)+ .eq("transferId", transferId)+ .single();+}++export async function getWarehouseTransferLines(+ client: SupabaseClient<Database>,+ transferId: string+) {+ return client+ .from("warehouseTransferLine")+ .select(+ "*, item(*), fromShelf:shelf!fromShelfId(name), toShelf:shelf!toShelfId(name)"+ )+ .eq("transferId", transferId);+}+export async function insertManualInventoryAdjustment(client: SupabaseClient<Database>,inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {@@ -907,90 +1038,39 @@ export async function upsertShipment(.single();}-// Warehouse Transfer functions-export async function getWarehouseTransfers(+export async function upsertKanban(client: SupabaseClient<Database>,- companyId: string,- args: GenericQueryFilters & {- search: string | null;- }+ kanban:+ | (Omit<z.infer<typeof kanbanValidator>, "id"> & {+ companyId: string;+ createdBy: string;+ customFields?: Json;+ })+ | (Omit<z.infer<typeof kanbanValidator>, "id"> & {+ id: string;+ updatedBy: string;+ customFields?: Json;+ })) {- let query = client- .from("warehouseTransfer")- .select(- "*, fromLocation:location!fromLocationId(name), toLocation:location!toLocationId(name)",- {- count: "exact",- }- )- .eq("companyId", companyId);-- if (args.search) {- query = query.or(- `transferId.ilike.%${args.search}%,reference.ilike.%${args.search}%`- );+ if ("createdBy" in kanban) {+ return client+ .from("kanban")+ .insert({+ ...kanban,+ })+ .select("id")+ .single();}-- query = setGenericQueryFilters(query, args, [- { column: "transferId", ascending: false },- ]);- return query;-}--export async function getWarehouseTransfer(- client: SupabaseClient<Database>,- transferId: string-) {return client- .from("warehouseTransfer")- .select(- "*, fromLocation:location!fromLocationId(*), toLocation:location!toLocationId(*)"- )- .eq("id", transferId)- .single();-}--export async function getWarehouseTransferLine(- client: SupabaseClient<Database>,- transferId: string,- lineId: string-) {- return client- .from("warehouseTransferLine")- .select(- "*, warehouseTransfer(*, fromLocation:location!fromLocationId(name), toLocation:location!toLocationId(name))"- )- .eq("id", lineId)- .eq("transferId", transferId)+ .from("kanban")+ .update({+ ...sanitize(kanban),+ updatedAt: today(getLocalTimeZone()).toString(),+ })+ .eq("id", kanban.id)+ .select("id").single();}--export async function getWarehouseTransferLines(- client: SupabaseClient<Database>,- transferId: string-) {- return client- .from("warehouseTransferLine")- .select(- "*, item(*), fromShelf:shelf!fromShelfId(name), toShelf:shelf!toShelfId(name)"- )- .eq("transferId", transferId);-}--export async function deleteWarehouseTransfer(- client: SupabaseClient<Database>,- transferId: string-) {- return client.from("warehouseTransfer").delete().eq("id", transferId);-}--export async function deleteWarehouseTransferLine(- client: SupabaseClient<Database>,- transferLineId: string-) {- return client.from("warehouseTransferLine").delete().eq("id", transferLineId);-}-export async function upsertWarehouseTransfer(client: SupabaseClient<Database>,transfer:diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.tsindex 63bd49fc72..c5651bdc06 100644--- a/apps/erp/app/modules/inventory/types.ts+++ b/apps/erp/app/modules/inventory/types.ts@@ -3,22 +3,27 @@ import type {getBatchProperties,getInventoryItems,getItemLedgerPage,+ getKanbans,getReceiptLines,getReceiptTracking,getReceipts,- getShipments,getShipmentLines,- getShippingMethods,getShipmentTracking,+ getShipments,+ getShippingMethods,getTrackedEntities,- getWarehouseTransfers,getWarehouseTransferLines,+ getWarehouseTransfers,} from "./inventory.service";export type BatchProperty = NonNullable<Awaited<ReturnType<typeof getBatchProperties>>["data"]>[number];+export type Kanban = NonNullable<+ Awaited<ReturnType<typeof getKanbans>>["data"]+>[number];+export type InventoryItem = NonNullable<Awaited<ReturnType<typeof getInventoryItems>>["data"]>[number];diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsxnew file mode 100644index 0000000000..0207061898--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx@@ -0,0 +1,153 @@+import { useCarbon } from "@carbon/auth";+import { SelectControlled, ValidatedForm } from "@carbon/form";+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerDescription,+ DrawerFooter,+ DrawerHeader,+ DrawerTitle,+ HStack,+ 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, Submit } from "~/components/Form";+import type { MethodItemType } from "~/modules/shared/types";+import { path } from "~/utils/path";+import {+ kanbanValidator,+ replenishmentSystemTypes,+} from "../../inventory.models";++type KanbanFormValues = z.infer<typeof kanbanValidator>;++type KanbanFormProps = {+ initialValues: KanbanFormValues;+ locationId?: string;+ onClose: () => void;+};++const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {+ const fetcher = useFetcher<{ success: boolean; message: string }>();++ const [selectedReplenishmentSystem, setSelectedReplenishmentSystem] =+ useState<string>(initialValues.replenishmentSystem || "Buy");++ const isEditing = Boolean(initialValues.id);++ const [itemType, setItemType] = useState<MethodItemType | "Item">("Item");+ const onTypeChange = (type: MethodItemType) => {+ setItemType(type);+ };++ const { carbon } = useCarbon();++ const onItemChange = async (value: { value: string } | null) => {+ if (!carbon || !value) return;+ const item = await carbon+ .from("item")+ .select("replenishmentSystem")+ .eq("id", value.value)+ .single();+ if (item.error) {+ toast.error("Failed to load item details");+ return;+ }+ setSelectedReplenishmentSystem(item.data?.replenishmentSystem || "Buy");+ };++ return (+ <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>+ <DrawerTitle>+ {isEditing ? "Edit Kanban" : "New Kanban"}+ </DrawerTitle>+ <DrawerDescription>+ {isEditing+ ? "Update the kanban information for scan-based replenishment."+ : "Create a new kanban card for scan-based replenishment."}+ </DrawerDescription>+ </DrawerHeader>+ <DrawerBody>+ <VStack spacing={4}>+ {isEditing && (+ <input type="hidden" name="id" value={initialValues.id} />+ )}++ <div className="grid grid-cols-1 gap-4 w-full">+ <Item+ name="itemId"+ label="Item"+ type="Item"+ itemType={itemType}+ // @ts-ignore+ onTypeChange={onTypeChange}+ onChange={onItemChange}+ isReadOnly={isEditing}+ />++ <Number+ name="quantity"+ label="Quantity"+ minValue={1}+ helperText="The quantity of the item to be reordered on scan-based replenishment."+ />++ <SelectControlled+ value={selectedReplenishmentSystem}+ name="replenishmentSystem"+ label="Replenishment System"+ onChange={(value) => {+ console.log(value);+ }}+ options={replenishmentSystemTypes+ .filter((type) => type !== "Buy and Make")+ .map((type) => ({+ value: type,+ label: <Enumerable value={type} />,+ }))}+ />++ <Location+ name="locationId"+ label="Location"+ isReadOnly={isEditing}+ />+ </div>+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ <Button type="button" variant="ghost" onClick={onClose}>+ Cancel+ </Button>+ <Submit withBlocker={false}>+ {isEditing ? "Update" : "Create"} Kanban+ </Submit>+ </HStack>+ </DrawerFooter>+ </ValidatedForm>+ </DrawerContent>+ </Drawer>+ );+};++export default KanbanForm;diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsxnew file mode 100644index 0000000000..459018bd85--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx@@ -0,0 +1,235 @@+import { Combobox, HStack, MenuItem, VStack } from "@carbon/react";+import { Link } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import {+ LuCalendar,+ LuHash,+ LuMapPin,+ LuPackage,+ LuPencil,+ LuRefreshCw,+ LuTrash,+ LuUser,+} from "react-icons/lu";+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { useLocations } from "~/components/Form/Location";+import { usePermissions, useUrlParams } from "~/hooks";+import { useItems } from "~/stores/items";+import { usePeople } from "~/stores/people";+import { path } from "~/utils/path";+import type { Kanban } from "../../types";++type KanbansTableProps = {+ data: Kanban[];+ count: number;+ locationId: string;+};++const defaultColumnVisibility = {+ createdBy: false,+ createdAt: false,+ updatedBy: false,+ updatedAt: false,+};++const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {+ const [params] = useUrlParams();++ const permissions = usePermissions();+ const [people] = usePeople();+ const [items] = useItems();+ const locations = useLocations();++ const columns = useMemo<ColumnDef<Kanban>[]>(+ () => [+ {+ accessorKey: "itemId",+ header: "Item",+ cell: ({ row }) => (+ <HStack className="py-1">+ <Hyperlink to={`${path.to.kanban(row.original.id!)}?${params}`}>+ <VStack spacing={0}>+ {row.original.name}+ <div className="text-muted-foreground text-xs">+ {row.original.readableIdWithRevision}+ </div>+ </VStack>+ </Hyperlink>+ </HStack>+ ),+ meta: {+ filter: {+ type: "static",+ options: items?.map((item) => ({+ value: item.id,+ label: item.readableIdWithRevision,+ })),+ },+ icon: <LuPackage />,+ },+ },+ {+ accessorKey: "quantity",+ header: "Reorder Qty.",+ cell: ({ row }) => row.original.quantity,+ meta: {+ icon: <LuHash />,+ },+ },+ {+ accessorKey: "replenishmentSystem",+ header: "Replenishment",+ cell: ({ row }) => (+ <Enumerable value={row.original.replenishmentSystem} />+ ),+ meta: {+ filter: {+ type: "static",+ options: ["Buy", "Make"].map((type) => ({+ value: type,+ label: <Enumerable value={type} />,+ })),+ },+ icon: <LuRefreshCw />,+ },+ },+ {+ accessorKey: "locationName",+ header: "Location",+ cell: ({ row }) => (+ <Enumerable value={row.original.locationName || ""} />+ ),+ meta: {+ icon: <LuMapPin />,+ },+ },++ {+ accessorKey: "createdBy",+ header: "Created By",+ cell: ({ row }) => (+ <EmployeeAvatar employeeId={row.original.createdBy} />+ ),+ meta: {+ filter: {+ type: "static",+ options: people.map((employee) => ({+ value: employee.id,+ label: <Enumerable value={employee.name} />,+ })),+ },+ icon: <LuUser />,+ },+ },+ {+ accessorKey: "createdAt",+ header: "Created At",+ cell: ({ row }) =>+ row.original.createdAt+ ? new Date(row.original.createdAt).toLocaleDateString()+ : "",+ meta: {+ icon: <LuCalendar />,+ },+ },+ {+ accessorKey: "updatedBy",+ header: "Updated By",+ cell: ({ row }) => (+ <EmployeeAvatar employeeId={row.original.updatedBy} />+ ),+ meta: {+ filter: {+ type: "static",+ options: people.map((employee) => ({+ value: employee.id,+ label: <Enumerable value={employee.name} />,+ })),+ },+ icon: <LuUser />,+ },+ },+ {+ accessorKey: "updatedAt",+ header: "Updated At",+ cell: ({ row }) =>+ row.original.updatedAt+ ? new Date(row.original.updatedAt).toLocaleDateString()+ : "",+ meta: {+ icon: <LuCalendar />,+ },+ },+ ],+ [items, params, people]+ );++ const renderContextMenu = useCallback(+ (row: Kanban) => {+ const canUpdate = permissions.can("update", "inventory");+ const canDelete = permissions.can("delete", "inventory");++ return (+ <>+ {canUpdate && (+ <MenuItem asChild>+ <Link to={`${path.to.kanban(row.id!)}?${params}`}>+ <LuPencil className="mr-2 h-4 w-4" />+ Edit+ </Link>+ </MenuItem>+ )}+ {canDelete && (+ <MenuItem destructive asChild>+ <Link to={`${path.to.deleteKanban(row.id!)}?${params}`}>+ <LuTrash className="mr-2 h-4 w-4" />+ Delete+ </Link>+ </MenuItem>+ )}+ </>+ );+ },+ [params, permissions]+ );++ return (+ <Table<Kanban>+ count={count}+ columns={columns}+ data={data}+ defaultColumnVisibility={defaultColumnVisibility}+ primaryAction={+ <div className="flex items-center gap-2">+ <Combobox+ asButton+ size="sm"+ value={locationId}+ options={locations}+ onChange={(selected) => {+ // hard refresh because initialValues update has no effect otherwise+ window.location.href = getLocationPath(selected);+ }}+ />+ {permissions.can("create", "inventory") && (+ <New label="Kanban" to={path.to.newKanban} />+ )}+ </div>+ }+ renderContextMenu={renderContextMenu}+ title="Kanbans"+ table="kanban"+ withSavedView+ />+ );+});++KanbansTable.displayName = "KanbansTable";++export default KanbansTable;++function getLocationPath(locationId: string) {+ return `${path.to.kanbans}?location=${locationId}`;+}diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/index.ts b/apps/erp/app/modules/inventory/ui/Kanbans/index.tsnew file mode 100644index 0000000000..a3e020fc55--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Kanbans/index.ts@@ -0,0 +1,2 @@+export { default as KanbanForm } from "./KanbanForm";+export { default as KanbansTable } from "./KanbansTable";\ No newline at end of filediff --git a/apps/erp/app/modules/inventory/ui/index.ts b/apps/erp/app/modules/inventory/ui/index.tsindex 2a312d9047..9615c279aa 100644--- a/apps/erp/app/modules/inventory/ui/index.ts+++ b/apps/erp/app/modules/inventory/ui/index.ts@@ -1,5 +1,6 @@import useInventorySubmodules from "./useInventorySubmodules";export * from "./Inventory";+export * from "./Kanbans";export * from "./Receipts";export * from "./Shelves";export * from "./ShippingMethods";diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsxindex e7821fa165..4101274f92 100644--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx@@ -1,5 +1,6 @@import {LuArrowRightLeft,+ LuFolderKanban,LuHandCoins,LuNetwork,LuQrCode,@@ -63,6 +64,12 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [{name: "Configure",routes: [+ {+ name: "Kanbans",+ to: path.to.kanbans,+ role: "employee",+ icon: <LuFolderKanban />,+ },{name: "Shelves",to: path.to.shelves,diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsxnew file mode 100644index 0000000000..0ca0b10590--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx@@ -0,0 +1,87 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { useLoaderData, useNavigate } from "@remix-run/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import {+ KanbanForm,+ getKanban,+ kanbanValidator,+ upsertKanban,+} from "~/modules/inventory";+import { getParams, path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "inventory",+ role: "employee",+ });++ const { id } = params;+ if (!id) throw notFound("id not found");++ const kanban = await getKanban(client, id);++ return json({+ kanban: kanban?.data ?? null,+ });+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "inventory",+ });++ const formData = await request.formData();+ const validation = await validator(kanbanValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;+ if (!id) throw new Error("id not found");++ const updateKanban = await upsertKanban(client, {+ id,+ ...data,+ updatedBy: userId,+ });++ if (updateKanban.error) {+ return json(+ {},+ await flash(request, error(updateKanban.error, "Failed to update kanban"))+ );+ }++ throw redirect(+ `${path.to.kanbans}?${getParams(request)}`,+ await flash(request, success("Updated kanban"))+ );+}++export default function EditKanbanRoute() {+ const { kanban } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ const initialValues = {+ id: kanban?.id ?? undefined,+ itemId: kanban?.itemId ?? "",+ quantity: kanban?.quantity ?? 1,+ replenishmentSystem: kanban?.replenishmentSystem ?? "Buy",+ locationId: kanban?.locationId ?? "",+ };++ return (+ <KanbanForm+ key={initialValues.id}+ initialValues={initialValues}+ locationId={initialValues.locationId}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsxnew file mode 100644index 0000000000..f6f17bbdcc--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsx@@ -0,0 +1,75 @@+import { error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import { ConfirmDelete } from "~/components/Modals";+import { deleteKanban, getKanban } from "~/modules/inventory";+import { getParams, path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "inventory",+ });+ const { id } = params;+ if (!id) throw notFound("id not found");++ const kanban = await getKanban(client, id);+ if (kanban.error) {+ throw redirect(+ path.to.kanbans,+ await flash(request, error(kanban.error, "Failed to get kanban"))+ );+ }++ return json({ kanban: kanban.data });+}++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "inventory",+ });++ const { id } = params;+ if (!id) {+ throw redirect(+ path.to.kanbans,+ await flash(request, error(params, "Failed to get a kanban id"))+ );+ }++ const { error: deleteKanbanError } = await deleteKanban(client, id);+ if (deleteKanbanError) {+ throw redirect(+ path.to.kanbans,+ await flash(request, error(deleteKanbanError, "Failed to delete kanban"))+ );+ }++ throw redirect(+ `${path.to.kanbans}?${getParams(request)}`,+ await flash(request, success("Successfully deleted kanban"))+ );+}++export default function DeleteKanbanRoute() {+ const { id } = useParams();+ if (!id) throw notFound("id not found");++ const { kanban } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ if (!id) return null;++ const onCancel = () => navigate(path.to.kanbans);++ return (+ <ConfirmDelete+ action={path.to.deleteKanban(id)}+ name={`Kanban for ${kanban.item?.name || kanban.itemId}`}+ text={`Are you sure you want to delete this kanban card? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.new.tsxnew file mode 100644index 0000000000..b718dc5d4a--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx@@ -0,0 +1,78 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { useNavigate, useSearchParams } from "@remix-run/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import { useUser } from "~/hooks";+import { KanbanForm, kanbanValidator, upsertKanban } from "~/modules/inventory";+import { getParams, path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ create: "inventory",+ });++ return null;+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "inventory",+ });++ const formData = await request.formData();+ const modal = formData.get("type") === "modal";++ const validation = await validator(kanbanValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const createKanban = await upsertKanban(client, {+ ...data,+ companyId,+ createdBy: userId,+ });+ if (createKanban.error) {+ return json(+ {},+ await flash(request, error(createKanban.error, "Failed to insert kanban"))+ );+ }++ return modal+ ? json(createKanban, { status: 201 })+ : redirect(+ `${path.to.kanbans}?${getParams(request)}`,+ await flash(request, success("Kanban created"))+ );+}++export default function NewKanbanRoute() {+ const navigate = useNavigate();+ const [searchParams] = useSearchParams();+ const { defaults } = useUser();+ const locationId =+ (searchParams.get("location") || defaults.locationId) ?? "";++ const initialValues = {+ itemId: "",+ quantity: 1,+ replenishmentSystem: "Buy" as const,+ locationId,+ };++ return (+ <KanbanForm+ initialValues={initialValues}+ locationId={locationId}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.tsxnew file mode 100644index 0000000000..bbbc95b424--- /dev/null+++ b/apps/erp/app/routes/x+/inventory+/kanbans.tsx@@ -0,0 +1,97 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { VStack } from "@carbon/react";+import { Outlet, useLoaderData } from "@remix-run/react";+import type { LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import { getKanbans } from "~/modules/inventory";+import KanbansTable from "~/modules/inventory/ui/Kanbans/KanbansTable";+import { getLocationsList } from "~/modules/resources";+import { getUserDefaults } from "~/modules/users/users.server";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: "Kanbans",+ to: path.to.kanbans,+ module: "inventory",+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ view: "inventory",+ bypassRls: true,+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");++ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ let locationId = searchParams.get("location");++ if (!locationId) {+ const userDefaults = await getUserDefaults(client, userId, companyId);+ if (userDefaults.error) {+ throw redirect(+ path.to.kanbans,+ await flash(+ request,+ error(userDefaults.error, "Failed to load default location")+ )+ );+ }++ locationId = userDefaults.data?.locationId ?? null;+ }++ if (!locationId) {+ const locations = await getLocationsList(client, companyId);+ if (locations.error || !locations.data?.length) {+ throw redirect(+ path.to.kanbans,+ await flash(+ request,+ error(locations.error, "Failed to load any locations")+ )+ );+ }+ locationId = locations.data?.[0].id as string;+ }++ const kanbans = await getKanbans(client, locationId, companyId, {+ search,+ limit,+ offset,+ sorts,+ filters,+ });++ if (kanbans.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(request, error(kanbans.error, "Failed to fetch kanbans"))+ );+ }++ return json({+ count: kanbans.count ?? 0,+ kanbans: kanbans.data ?? [],+ locationId,+ });+}++export default function KanbansRoute() {+ const { count, kanbans, locationId } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <KanbansTable data={kanbans} count={count} locationId={locationId} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 37d55e1e87..3983848f0d 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -545,6 +545,8 @@ export const path = {generatePath(`${x}/quality/required-actions/delete/${id}`),deleteIssueType: (id: string) =>generatePath(`${x}/quality/issue-types/delete/${id}`),+ deleteKanban: (id: string) =>+ generatePath(`${x}/inventory/kanbans/delete/${id}`),deleteNoQuoteReason: (id: string) =>generatePath(`${x}/sales/no-quote-reasons/delete/${id}`),deleteCustomerPortal: (id: string) =>@@ -661,7 +663,6 @@ export const path = {externalQuote: (id: string) => generatePath(`/share/quote/${id}`),feedback: `${x}/feedback`,fiscalYears: `${x}/accounting/years`,-gauge: (id: string) => generatePath(`${x}/quality/gauges/${id}`),gauges: `${x}/quality/gauges`,gaugeCalibrationRecord: (id: string) =>@@ -707,9 +708,6 @@ export const path = {investigationType: (id: string) =>generatePath(`${x}/quality/investigation-types/${id}`),investigationTypes: `${x}/quality/investigation-types`,- requiredAction: (id: string) =>- generatePath(`${x}/quality/required-actions/${id}`),- requiredActions: `${x}/quality/required-actions`,issueType: (id: string) => generatePath(`${x}/quality/issue-types/${id}`),issueTypes: `${x}/quality/issue-types`,items: `${x}/items`,@@ -756,6 +754,9 @@ export const path = {jobRecalculate: (id: string) => generatePath(`${x}/job/${id}/recalculate`),jobRelease: (id: string) => generatePath(`${x}/job/${id}/release`),jobStatus: (id: string) => generatePath(`${x}/job/${id}/status`),+ kanban: (id: string) => generatePath(`${x}/inventory/kanbans/${id}`),+ kanbans: `${x}/inventory/kanbans`,+labelsSettings: `${x}/settings/labels`,location: (id: string) => generatePath(`${x}/resources/locations/${id}`),locations: `${x}/resources/locations`,@@ -868,6 +869,7 @@ export const path = {newJobOperationAttribute: `${x}/job/methods/operation/attribute/new`,newJobOperationParameter: `${x}/job/methods/operation/parameter/new`,newJobOperationTool: `${x}/job/methods/operation/tool/new`,+ newKanban: `${x}/inventory/kanbans/new`,newLocation: `${x}/resources/locations/new`,newMakeMethodVersion: `${x}/items/methods/version/new`,newMaterial: `${x}/material/new`,@@ -1142,6 +1144,9 @@ export const path = {receiptPost: (id: string) => generatePath(`${x}/receipt/${id}/post`),receiptRoot: `${x}/receipt`,refreshSession: "/refresh-session",+ requiredAction: (id: string) =>+ generatePath(`${x}/quality/required-actions/${id}`),+ requiredActions: `${x}/quality/required-actions`,resendInvite: `${x}/users/resend-invite`,resources: `${x}/resources`,revision: (id: string) => generatePath(`${x}/items/revisions/${id}`),diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 5bfa1085d5..9e724b3019 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -54714,6 +54714,186 @@ export default {tags: ["integration"],},},+ "/kanban": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.kanban.id",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.itemId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.replenishmentSystem",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.quantity",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.locationId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.updatedBy",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/kanban",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["kanban"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.kanban",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["kanban"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.kanban.id",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.itemId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.replenishmentSystem",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.quantity",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.locationId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.updatedBy",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["kanban"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.kanban.id",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.itemId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.replenishmentSystem",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.quantity",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.locationId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.kanban.updatedBy",+ },+ {+ $ref: "#/parameters/body.kanban",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["kanban"],+ },+ },"/salesOrderTransaction": {get: {parameters: [@@ -85686,6 +85866,76 @@ export default {},type: "object",},+ kanban: {+ required: [+ "id",+ "itemId",+ "replenishmentSystem",+ "quantity",+ "locationId",+ "companyId",+ "createdAt",+ "createdBy",+ ],+ properties: {+ id: {+ default: "public.id('kb'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ itemId: {+ description:+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",+ format: "text",+ type: "string",+ },+ replenishmentSystem: {+ default: "Buy",+ enum: ["Buy", "Make", "Buy and Make"],+ format: 'public."itemReplenishmentSystem"',+ type: "string",+ },+ quantity: {+ format: "integer",+ type: "integer",+ },+ locationId: {+ description:+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",+ format: "text",+ type: "string",+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string",+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ },+ type: "object",+ },salesOrderTransaction: {required: ["id", "salesOrderId", "type", "userId", "createdAt"],properties: {@@ -114695,6 +114945,75 @@ export default {in: "query",type: "string",},+ "body.kanban": {+ name: "kanban",+ description: "kanban",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/kanban",+ },+ },+ "rowFilter.kanban.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.replenishmentSystem": {+ name: "replenishmentSystem",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.quantity": {+ name: "quantity",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.locationId": {+ name: "locationId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.kanban.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string",+ },"body.salesOrderTransaction": {name: "salesOrderTransaction",description: "salesOrderTransaction",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 018499e4d8..9845ce172c 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -11627,6 +11627,186 @@ export type Database = {},]}+ kanban: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ itemId: string+ locationId: string+ quantity: number+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ itemId: string+ locationId: string+ quantity: number+ replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ itemId?: string+ locationId?: string+ quantity?: number+ replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }lessonCompletion: {Row: {courseId: string@@ -39133,6 +39313,167 @@ export type Database = {},]}+ kanbans: {+ Row: {+ companyId: string | null+ createdAt: string | null+ createdBy: string | null+ id: string | null+ itemId: string | null+ locationId: string | null+ locationName: string | null+ name: string | null+ quantity: number | null+ readableIdWithRevision: string | null+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Relationships: [+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }materialDimensions: {Row: {companyId: string | null@@ -41479,14 +41820,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -43914,14 +44255,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"]@@ -44457,14 +44798,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 018499e4d8..9845ce172c 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -11627,6 +11627,186 @@ export type Database = {},]}+ kanban: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ itemId: string+ locationId: string+ quantity: number+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ itemId: string+ locationId: string+ quantity: number+ replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ itemId?: string+ locationId?: string+ quantity?: number+ replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }lessonCompletion: {Row: {courseId: string@@ -39133,6 +39313,167 @@ export type Database = {},]}+ kanbans: {+ Row: {+ companyId: string | null+ createdAt: string | null+ createdBy: string | null+ id: string | null+ itemId: string | null+ locationId: string | null+ locationName: string | null+ name: string | null+ quantity: number | null+ readableIdWithRevision: string | null+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Relationships: [+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "kanban_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }materialDimensions: {Row: {companyId: string | null@@ -41479,14 +41820,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -43914,14 +44255,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"]@@ -44457,14 +44798,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/migrations/20250909012102_kanban.sql b/packages/database/supabase/migrations/20250909012102_kanban.sqlnew file mode 100644index 0000000000..c361f83f4d--- /dev/null+++ b/packages/database/supabase/migrations/20250909012102_kanban.sql@@ -0,0 +1,76 @@+CREATE TABLE "kanban" (+ "id" TEXT NOT NULL DEFAULT id('kb'),+ "itemId" TEXT NOT NULL,+ "replenishmentSystem" "itemReplenishmentSystem" NOT NULL DEFAULT 'Buy',+ "quantity" INTEGER NOT NULL,+ "locationId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "kanban_pkey" PRIMARY KEY ("id", "companyId"),+ 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_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+);++CREATE INDEX "kanban_itemId_idx" ON "kanban" ("itemId");+CREATE INDEX "kanban_locationId_idx" ON "kanban" ("companyId", "locationId");+CREATE INDEX "kanban_companyId_idx" ON "kanban" ("companyId");++ALTER TABLE "kanban" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."kanban"+FOR SELECT USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_role()+ )::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."kanban"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('inventory_create')+ )::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."kanban"+FOR UPDATE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('inventory_update')+ )::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."kanban"+FOR DELETE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('inventory_delete')+ )::text[]+ )+);++DROP VIEW IF EXISTS "kanbans";+CREATE VIEW "kanbans" WITH(SECURITY_INVOKER=true) AS+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";\ No newline at end of file