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 item ledger transactions for transfers
Brad Barbin4f245ebd6ce5
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 5537a5467a..bd1fe046cc 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -224,6 +224,14 @@ function GenericNotification({{...props}/>);+ case NotificationEvent.StockTransferAssignment:+ return (+ <Notification+ icon={<LuListChecks />}+ to={path.to.salesOrderDetails(id)}+ {...props}+ />+ );case NotificationEvent.SupplierQuoteAssignment:return (<Notificationdiff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 9638c9d8ac..6c6843e637 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -283,7 +283,9 @@ export async function getStockTransferLines(return client.from("stockTransferLines").select("*")- .eq("stockTransferId", stockTransferId);+ .eq("stockTransferId", stockTransferId)+ .order("itemReadableId", { ascending: true })+ .order("createdAt", { ascending: true });}export async function getStockTransferTracking(diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsxindex d4afa4d38d..c19dc0691f 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx@@ -1,4 +1,4 @@-import { LuCircleMinus, LuCirclePlus } from "react-icons/lu";+import { LuArrowRightLeft, LuCircleMinus, LuCirclePlus } from "react-icons/lu";import { Hyperlink } from "~/components";import Activity from "~/components/Activity";import { path } from "~/utils/path";@@ -43,8 +43,12 @@ const getActivityText = (ledgerRecord: ItemLedger) => {ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""} from transfer`;case "Direct Transfer":- return `directly transferred ${ledgerRecord.quantity} units${- ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""+ return `transferred ${Math.abs(ledgerRecord.quantity)} units${+ ledgerRecord.shelf?.name+ ? ` ${ledgerRecord.quantity > 0 ? "to" : "from"} ${+ ledgerRecord.shelf.name+ }`+ : ""}`;case "Inventory Receipt":return `received ${ledgerRecord.quantity} units into inventory${@@ -127,7 +131,9 @@ const getActivityText = (ledgerRecord: ItemLedger) => {<><span>received {ledgerRecord.quantity} units- {ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""}{" "}+ {ledgerRecord.shelf?.name+ ? ` to ${ledgerRecord.shelf.name}`+ : ""}{" "}from a</span>{" "}<Hyperlink@@ -170,6 +176,8 @@ const getActivityText = (ledgerRecord: ItemLedger) => {const getActivityIcon = (ledgerRecord: ItemLedger) => {switch (ledgerRecord.entryType) {+ case "Transfer":+ return <LuArrowRightLeft className="text-blue-500 w-5 h-5" />;case "Positive Adjmt.":return <LuCirclePlus className="text-emerald-500 w-5 h-5" />;case "Negative Adjmt.":diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsxindex 171c47c852..3569ec9bb1 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx@@ -57,7 +57,8 @@ const StockTransferHeader = () => {routeData.stockTransferLines.length > 0 &&routeData.stockTransferLines.some((line) => (line.pickedQuantity ?? 0) !== 0- );+ ) &&+ ["Released", "In Progress"].includes(status);const isCompleted = status === "Completed";diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsxindex a6818a86e6..ae2446ece8 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx@@ -17,15 +17,15 @@ import {cn,useDisclosure,} from "@carbon/react";-import { getItemReadableId } from "@carbon/utils";-import { Link, useParams } from "@remix-run/react";-import { useMemo, useState } from "react";+import { Link, useFetchers, useParams, useSubmit } from "@remix-run/react";+import { useState } from "react";import {LuCircleCheck,LuCirclePlus,LuEllipsisVertical,LuPencilLine,LuTrash,+ LuUndo2,} from "react-icons/lu";import { Empty, ItemThumbnail } from "~/components";import { Enumerable } from "~/components/Enumerable";@@ -65,15 +65,67 @@ export default function StockTransferLines() {);const deleteDisclosure = useDisclosure();- const lines = useMemo(() => {- const list = routeData?.stockTransferLines ?? [];- return list- .map((line) => ({- ...line,- itemReadableId: getItemReadableId(items, line.itemId) ?? "",- }))- .sort((a, b) => a.itemReadableId.localeCompare(b.itemReadableId));- }, [routeData?.stockTransferLines, items]);+ const lines = (routeData?.stockTransferLines ?? []).sort((a, b) => {+ // First sort by itemReadableId+ const itemComparison = (a.itemReadableId ?? "").localeCompare(+ b.itemReadableId ?? ""+ );+ if (itemComparison !== 0) return itemComparison;++ // Then sort by toShelfName+ const toShelfComparison = (a.toShelfName ?? "").localeCompare(+ b.toShelfName ?? ""+ );+ if (toShelfComparison !== 0) return toShelfComparison;++ // Finally sort by fromShelfName+ return (a.fromShelfName ?? "").localeCompare(b.fromShelfName ?? "");+ });++ const pickedQuantitiesById = new Map<string, number>();++ lines.forEach((line) => {+ if (!line.id) return;+ pickedQuantitiesById.set(line.id, line.pickedQuantity ?? 0);+ });++ const pendingQuantities = usePendingItems({ id });++ pendingQuantities.forEach((pendingQuantity) => {+ if (pendingQuantity.id) {+ pickedQuantitiesById.set(pendingQuantity.id, pendingQuantity.quantity);+ }+ });++ const submit = useSubmit();++ const onPick = (line: StockTransferLine) => {+ const formData = new FormData();+ formData.append("id", line.id!);+ formData.append("quantity", line.quantity!.toString());+ formData.append("locationId", routeData?.stockTransfer?.locationId ?? "");++ submit(formData, {+ method: "post",+ action: path.to.stockTransferLineQuantity(id),+ navigate: false,+ fetcherKey: `stockTransferLine:${line.id}`,+ });+ };++ const onUnpick = (line: StockTransferLine) => {+ const formData = new FormData();+ formData.append("id", line.id!);+ formData.append("quantity", "0");+ formData.append("locationId", routeData?.stockTransfer?.locationId ?? "");++ submit(formData, {+ method: "post",+ action: path.to.stockTransferLineQuantity(id),+ navigate: false,+ fetcherKey: `stockTransferLine:${line.id}`,+ });+ };return (<>@@ -156,6 +208,7 @@ export default function StockTransferLines() {Quantity</label><span className="text-sm py-1.5">+ {pickedQuantitiesById.get(line.id ?? "") ?? 0}/{line.quantity ?? 0}</span></VStack>@@ -193,12 +246,41 @@ export default function StockTransferLines() {)}</HStack><HStack spacing={1}>- <Button- isDisabled={!isPickable}- leftIcon={<LuCircleCheck />}- >- Pick- </Button>+ {pickedQuantitiesById.get(line.id ?? "") ===+ line.quantity ? (+ <Button+ variant="secondary"+ isDisabled={+ !isPickable ||+ pendingQuantities?.some((q) => q.id === line.id)+ }+ isLoading={pendingQuantities?.some(+ (q) => q.id === line.id+ )}+ leftIcon={<LuUndo2 />}+ onClick={() => {+ onUnpick(line);+ }}+ >+ Unpick+ </Button>+ ) : (+ <Button+ isDisabled={+ !isPickable ||+ pendingQuantities?.some((q) => q.id === line.id)+ }+ isLoading={pendingQuantities?.some(+ (q) => q.id === line.id+ )}+ leftIcon={<LuCircleCheck />}+ onClick={() => {+ onPick(line);+ }}+ >+ Pick+ </Button>+ )}<DropdownMenu><DropdownMenuTrigger asChild><IconButton@@ -261,3 +343,24 @@ export default function StockTransferLines() {</>);}++const usePendingItems = ({ id }: { id: string }) => {+ type PendingItem = ReturnType<typeof useFetchers>[number] & {+ formData: FormData;+ };++ return useFetchers()+ .filter((fetcher): fetcher is PendingItem => {+ return fetcher.formAction === path.to.stockTransferLineQuantity(id);+ })+ .reduce<{ id: string; quantity: number }[]>((acc, fetcher) => {+ const formData = fetcher.formData;+ const quantity = parseInt(formData.get("quantity") as string, 10);+ const lineId = fetcher.formData.get("id") as string;++ if (lineId && Number.isFinite(quantity)) {+ return [...acc, { id: lineId, quantity }];+ }+ return acc;+ }, []);+};diff --git a/apps/erp/app/novu/workflows.ts b/apps/erp/app/novu/workflows.tsindex f15307da0a..f1f4d750ec 100644--- a/apps/erp/app/novu/workflows.ts+++ b/apps/erp/app/novu/workflows.ts@@ -24,6 +24,7 @@ const payloadSchema = z.object({NotificationEvent.SalesOrderAssignment,NotificationEvent.SalesRfqAssignment,NotificationEvent.SalesRfqReady,+ NotificationEvent.StockTransferAssignment,NotificationEvent.SupplierQuoteAssignment,]),from: z.string().optional(),diff --git a/apps/erp/app/routes/api+/assign.ts b/apps/erp/app/routes/api+/assign.tsindex 415e9a4e73..b06934043d 100644--- a/apps/erp/app/routes/api+/assign.ts+++ b/apps/erp/app/routes/api+/assign.ts@@ -115,6 +115,8 @@ function getNotificationEvent(table: string): NotificationEvent | null {return NotificationEvent.PurchaseInvoiceAssignment;case "supplierQuote":return NotificationEvent.SupplierQuoteAssignment;+ case "stockTransfer":+ return NotificationEvent.StockTransferAssignment;default:return null;}diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsxnew file mode 100644index 0000000000..525dad643f--- /dev/null+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx@@ -0,0 +1,147 @@+import {+ assertIsPost,+ error,+ getCarbonServiceRole,+ notFound,+ success,+} from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { Database } from "@carbon/database";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "inventory",+ });++ const { id } = params;+ if (!id) throw notFound("id not found");++ const formData = await request.formData();++ const lineId = formData.get("id") as string;+ const pickedQuantity = parseInt(formData.get("quantity") as string, 10);+ const locationId = formData.get("locationId") as string;++ if (!lineId || !Number.isFinite(pickedQuantity)) {+ return json(+ {+ success: false,+ },+ await flash(request, error("Invalid form data", "Invalid form data"))+ );+ }++ const stockTransferLine = await client+ .from("stockTransferLine")+ .select("*")+ .eq("id", lineId)+ .single();++ if (!stockTransferLine.data) {+ return json(+ {+ success: false,+ },+ await flash(+ request,+ error("Stock transfer line not found", "Stock transfer line not found")+ )+ );+ }++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ const today = new Date().toISOString().split("T")[0];+ const transactionQuantity =+ pickedQuantity === 0+ ? -stockTransferLine.data.pickedQuantity+ : pickedQuantity;++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.data.itemId,+ quantity: transactionQuantity,+ locationId: locationId,+ shelfId: stockTransferLine.data.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferLine.data.stockTransferId ?? undefined,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.data.itemId,+ quantity: -transactionQuantity,+ locationId: locationId,+ shelfId: stockTransferLine.data.fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferLine.data.stockTransferId ?? undefined,+ createdBy: userId,+ companyId,+ });++ const serviceRole = getCarbonServiceRole();++ const insertItemTransactions = await serviceRole+ .from("itemLedger")+ .insert(itemLedgerInserts)+ .select("id");++ if (insertItemTransactions.error) {+ return json(+ {+ success: false,+ },+ await flash(+ request,+ error(insertItemTransactions.error, "Failed to insert item ledger")+ )+ );+ }++ const quantityUpdate = await client+ .from("stockTransferLine")+ .update({+ pickedQuantity,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", lineId)+ .eq("companyId", companyId);++ if (quantityUpdate.error) {+ await serviceRole+ .from("itemLedger")+ .delete()+ .in("id", insertItemTransactions.data?.map((item) => item.id) ?? []);++ return json(+ {+ success: false,+ },+ await flash(request, error(quantityUpdate.error, "Failed to update line"))+ );+ }++ return json(+ {+ success: true,+ },+ await flash(+ request,+ success(+ `${pickedQuantity} ${+ pickedQuantity === 1 ? "item" : "items"+ } marked as picked`+ )+ )+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex fed340ebfa..f54cc493e5 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1074,6 +1074,8 @@ export const path = {generatePath(`${x}/stock-transfer/${id}/complete`),stockTransferLine: (id: string, lineId: string) =>generatePath(`${x}/stock-transfer/${id}/line/${lineId}`),+ stockTransferLineQuantity: (id: string) =>+ generatePath(`${x}/stock-transfer/${id}/line/quantity`),stockTransferStatus: (id: string) =>generatePath(`${x}/stock-transfer/${id}/status`),stockTransfers: `${x}/inventory/stock-transfers`,diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 90b46f56bf..313b32a183 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -23334,6 +23334,114 @@ export default {tags: ["purchaseOrderLine"],},},+ "/stockTransferLines": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.id",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.stockTransferId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.jobId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.jobMaterialId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.itemId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.fromShelfId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.toShelfId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.quantity",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.pickedQuantity",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.outstandingQuantity",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.requiresBatchTracking",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.requiresSerialTracking",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.thumbnailPath",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.itemReadableId",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.unitOfMeasure",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.fromShelfName",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.toShelfName",+ },+ {+ $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/stockTransferLines",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["stockTransferLines"],+ },+ },"/accountDefault": {get: {parameters: [@@ -50187,6 +50295,9 @@ export default {{$ref: "#/parameters/rowFilter.stockTransfer.updatedBy",},+ {+ $ref: "#/parameters/rowFilter.stockTransfer.notes",+ },{$ref: "#/parameters/rowFilter.stockTransfer.assignee",},@@ -50285,6 +50396,9 @@ export default {{$ref: "#/parameters/rowFilter.stockTransfer.updatedBy",},+ {+ $ref: "#/parameters/rowFilter.stockTransfer.notes",+ },{$ref: "#/parameters/rowFilter.stockTransfer.assignee",},@@ -50337,6 +50451,9 @@ export default {{$ref: "#/parameters/rowFilter.stockTransfer.updatedBy",},+ {+ $ref: "#/parameters/rowFilter.stockTransfer.notes",+ },{$ref: "#/parameters/rowFilter.stockTransfer.assignee",},@@ -52167,6 +52284,15 @@ export default {{$ref: "#/parameters/rowFilter.stockTransferLine.pickedQuantity",},+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.outstandingQuantity",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.requiresBatchTracking",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.requiresSerialTracking",+ },{$ref: "#/parameters/rowFilter.stockTransferLine.companyId",},@@ -52268,6 +52394,15 @@ export default {{$ref: "#/parameters/rowFilter.stockTransferLine.pickedQuantity",},+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.outstandingQuantity",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.requiresBatchTracking",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.requiresSerialTracking",+ },{$ref: "#/parameters/rowFilter.stockTransferLine.companyId",},@@ -52323,6 +52458,15 @@ export default {{$ref: "#/parameters/rowFilter.stockTransferLine.pickedQuantity",},+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.outstandingQuantity",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.requiresBatchTracking",+ },+ {+ $ref: "#/parameters/rowFilter.stockTransferLine.requiresSerialTracking",+ },{$ref: "#/parameters/rowFilter.stockTransferLine.companyId",},@@ -56271,6 +56415,85 @@ export default {tags: ["salesOrderTransaction"],},},+ "/rpc/get_item_shelf_requirements_by_location_and_item": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "company_id",+ required: true,+ type: "string",+ },+ {+ format: "text",+ in: "query",+ name: "location_id",+ required: true,+ type: "string",+ },+ {+ format: "text",+ in: "query",+ name: "item_id",+ required: false,+ type: "string",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) get_item_shelf_requirements_by_location_and_item"],+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ company_id: {+ format: "text",+ type: "string",+ },+ item_id: {+ format: "text",+ type: "string",+ },+ location_id: {+ format: "text",+ type: "string",+ },+ },+ required: ["company_id", "location_id"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) get_item_shelf_requirements_by_location_and_item"],+ },+ },"/rpc/has_company_permission": {get: {parameters: [@@ -65098,7 +65321,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string",},@@ -65147,7 +65370,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string",},@@ -72333,6 +72556,116 @@ export default {},type: "object",},+ stockTransferLines: {+ properties: {+ id: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ stockTransferId: {+ format: "text",+ type: "string",+ },+ jobId: {+ description:+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",+ format: "text",+ type: "string",+ },+ jobMaterialId: {+ description:+ "Note:\nThis is a Foreign Key to `jobMaterial.id`.<fk table='jobMaterial' column='id'/>",+ format: "text",+ type: "string",+ },+ itemId: {+ description:+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",+ format: "text",+ type: "string",+ },+ fromShelfId: {+ description:+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",+ format: "text",+ type: "string",+ },+ toShelfId: {+ description:+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",+ format: "text",+ type: "string",+ },+ quantity: {+ format: "numeric",+ type: "number",+ },+ pickedQuantity: {+ format: "numeric",+ type: "number",+ },+ outstandingQuantity: {+ format: "numeric",+ type: "number",+ },+ requiresBatchTracking: {+ format: "boolean",+ type: "boolean",+ },+ requiresSerialTracking: {+ format: "boolean",+ type: "boolean",+ },+ 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: {+ 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",+ },+ thumbnailPath: {+ format: "text",+ type: "string",+ },+ itemReadableId: {+ format: "text",+ type: "string",+ },+ unitOfMeasure: {+ format: "text",+ type: "string",+ },+ fromShelfName: {+ format: "text",+ type: "string",+ },+ toShelfName: {+ format: "text",+ type: "string",+ },+ },+ type: "object",+ },accountDefault: {required: ["companyId",@@ -85186,6 +85519,9 @@ export default {format: "text",type: "string",},+ notes: {+ format: "json",+ },assignee: {description:"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",@@ -86293,6 +86629,8 @@ export default {"itemId","quantity","pickedQuantity",+ "requiresBatchTracking",+ "requiresSerialTracking","companyId","createdAt","createdBy",@@ -86348,6 +86686,20 @@ export default {format: "numeric",type: "number",},+ outstandingQuantity: {+ format: "numeric",+ type: "number",+ },+ requiresBatchTracking: {+ default: false,+ format: "boolean",+ type: "boolean",+ },+ requiresSerialTracking: {+ default: false,+ format: "boolean",+ type: "boolean",+ },companyId: {description:"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",@@ -100242,6 +100594,147 @@ export default {in: "query",type: "string",},+ "body.stockTransferLines": {+ name: "stockTransferLines",+ description: "stockTransferLines",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/stockTransferLines",+ },+ },+ "rowFilter.stockTransferLines.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.stockTransferId": {+ name: "stockTransferId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.jobId": {+ name: "jobId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.jobMaterialId": {+ name: "jobMaterialId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.fromShelfId": {+ name: "fromShelfId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.toShelfId": {+ name: "toShelfId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.quantity": {+ name: "quantity",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.pickedQuantity": {+ name: "pickedQuantity",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.outstandingQuantity": {+ name: "outstandingQuantity",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.requiresBatchTracking": {+ name: "requiresBatchTracking",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.requiresSerialTracking": {+ name: "requiresSerialTracking",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.thumbnailPath": {+ name: "thumbnailPath",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.itemReadableId": {+ name: "itemReadableId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.unitOfMeasure": {+ name: "unitOfMeasure",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.fromShelfName": {+ name: "fromShelfName",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLines.toShelfName": {+ name: "toShelfName",+ required: false,+ in: "query",+ type: "string",+ },"body.accountDefault": {name: "accountDefault",description: "accountDefault",@@ -114786,6 +115279,12 @@ export default {in: "query",type: "string",},+ "rowFilter.stockTransfer.notes": {+ name: "notes",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.stockTransfer.assignee": {name: "assignee",required: false,@@ -116097,6 +116596,24 @@ export default {in: "query",type: "string",},+ "rowFilter.stockTransferLine.outstandingQuantity": {+ name: "outstandingQuantity",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLine.requiresBatchTracking": {+ name: "requiresBatchTracking",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.stockTransferLine.requiresSerialTracking": {+ name: "requiresSerialTracking",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.stockTransferLine.companyId": {name: "companyId",required: false,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 54992b609b..013604b756 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -42906,14 +42906,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"]@@ -45425,14 +45425,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"]@@ -45968,14 +45968,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"]@@ -47051,6 +47051,7 @@ export type Database = {fromShelfName: string | nullid: string | nullitemId: string | null+ itemReadableId: string | nulljobId: string | nulljobMaterialId: string | nulloutstandingQuantity: number | nulldiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 54992b609b..013604b756 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -42906,14 +42906,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"]@@ -45425,14 +45425,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"]@@ -45968,14 +45968,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"]@@ -47051,6 +47051,7 @@ export type Database = {fromShelfName: string | nullid: string | nullitemId: string | null+ itemReadableId: string | nulljobId: string | nulljobMaterialId: string | nulloutstandingQuantity: number | nulldiff --git a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql b/packages/database/supabase/migrations/20251007014240_stock-transfers.sqlindex 0a3626a3c8..6380afb1e5 100644--- a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql+++ b/packages/database/supabase/migrations/20251007014240_stock-transfers.sql@@ -83,6 +83,7 @@ CREATE TABLE "stockTransfer" ("createdBy" TEXT NOT NULL,"updatedAt" TIMESTAMP WITH TIME ZONE,"updatedBy" TEXT,+ "notes" JSON DEFAULT '{}'::json,"assignee" TEXT,"customFields" JSONB,"tags" TEXT[],@@ -140,8 +141,6 @@ FOR DELETE USING ());--CREATE TABLE "stockTransferLine" ("id" TEXT NOT NULL DEFAULT xid(),"stockTransferId" TEXT NOT NULL,@@ -155,7 +154,6 @@ CREATE TABLE "stockTransferLine" ("outstandingQuantity" NUMERIC GENERATED ALWAYS AS (CASE WHEN "quantity" >= "pickedQuantity" THEN "quantity" - "pickedQuantity" ELSE 0 END) STORED,"requiresBatchTracking" BOOLEAN NOT NULL DEFAULT false,"requiresSerialTracking" BOOLEAN NOT NULL DEFAULT false,- "notes" JSON DEFAULT '{}'::json,"companyId" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),"createdBy" TEXT NOT NULL,@@ -233,6 +231,7 @@ SELECT"id"FROM "company";+DROP VIEW IF EXISTS "stockTransferLines";CREATE VIEW "stockTransferLines" ASSELECTstl.*,@@ -240,6 +239,7 @@ SELECTWHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"ELSE i."thumbnailPath"END AS "thumbnailPath",+ i."readableIdWithRevision" as "itemReadableId",uom."name" AS "unitOfMeasure",sf."name" AS "fromShelfName",st."name" AS "toShelfName"@@ -248,5 +248,40 @@ LEFT JOIN "item" i ON i."id" = stl."itemId"LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"LEFT JOIN "unitOfMeasure" uom ON uom."code" = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"LEFT JOIN "shelf" sf ON sf."id" = stl."fromShelfId"-LEFT JOIN "shelf" st ON st."id" = stl."toShelfId";+LEFT JOIN "shelf" st ON st."id" = stl."toShelfId"+ORDER BY "itemReadableId" ASC, "toShelfName" ASC;++-- Trigger function to update stock transfer status based on picked quantities+CREATE OR REPLACE FUNCTION update_stock_transfer_status()+RETURNS TRIGGER AS $$+BEGIN+ -- Only proceed if pickedQuantity has changed and is not 0+ IF OLD."pickedQuantity" IS DISTINCT FROM NEW."pickedQuantity" AND NEW."pickedQuantity" != 0 THEN+ -- Check if all lines for this stock transfer have pickedQuantity = quantity+ IF EXISTS (+ SELECT 1+ FROM "stockTransferLine"+ WHERE "stockTransferId" = NEW."stockTransferId"+ AND ("pickedQuantity" IS NULL OR "pickedQuantity" != "quantity")+ ) THEN+ -- Not all lines are fully picked, set status to In Progress+ UPDATE "stockTransfer"+ SET "status" = 'In Progress'+ WHERE "id" = NEW."stockTransferId";+ ELSE+ -- All lines are fully picked, set status to Completed+ UPDATE "stockTransfer"+ SET "status" = 'Completed'+ WHERE "id" = NEW."stockTransferId";+ END IF;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;+-- Create trigger on stockTransferLine UPDATE+CREATE TRIGGER update_stock_transfer_status_trigger+ AFTER UPDATE ON "stockTransferLine"+ FOR EACH ROW+ EXECUTE FUNCTION update_stock_transfer_status();diff --git a/packages/jobs/trigger/notify.ts b/packages/jobs/trigger/notify.tsindex 8e503cbc25..1926cd4b33 100644--- a/packages/jobs/trigger/notify.ts+++ b/packages/jobs/trigger/notify.ts@@ -67,6 +67,7 @@ export const notifyTask = task({case NotificationEvent.SalesOrderAssignment:case NotificationEvent.SalesRfqAssignment:case NotificationEvent.SalesRfqReady:+ case NotificationEvent.StockTransferAssignment:case NotificationEvent.SupplierQuoteAssignment:return NotificationWorkflow.Assignment;case NotificationEvent.JobCompleted:@@ -221,6 +222,21 @@ export const notifyTask = task({}return `Digital Quote ${digitalQuote?.data?.quoteId} was accepted`;++ case NotificationEvent.StockTransferAssignment:+ const stockTransfer = await client+ .from("stockTransfer")+ .select("*")+ .eq("id", documentId)+ .single();++ if (stockTransfer.error) {+ console.error("Failed to get stockTransfer", stockTransfer.error);+ throw stockTransfer.error;+ }++ return `Stock Transfer ${stockTransfer?.data?.stockTransferId} assigned to you`;+default:return null;}diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 9c7ede9cb0..5426e8c856 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -25,6 +25,7 @@ export enum NotificationEvent {SalesOrderAssignment = "sales-order-assignment",SalesRfqAssignment = "sales-rfq-assignment",SalesRfqReady = "sales-rfq-ready",+ StockTransferAssignment = "stock-transfer-assignment",SupplierQuoteAssignment = "supplier-quote-assignment",}