Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add ability to receive negative quantity

Brad Barbinefdd453f4978
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 4346d097ad..47dcf3299b 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -185,7 +185,7 @@ export async function getReceiptLines(
client: SupabaseClient<Database>,
receiptId: string
) {
- return client.from("receiptLine").select("*").eq("receiptId", receiptId);
+ return client.from("receiptLines").select("*").eq("receiptId", receiptId);
}
export async function getReceiptTracking(
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
index e3e0c965eb..0dbe445ad9 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
@@ -36,7 +36,7 @@ const ReceiptHeader = () => {
const canPost =
routeData.receiptLines.length > 0 &&
- routeData.receiptLines.some((line) => line.receivedQuantity > 0);
+ routeData.receiptLines.some((line) => (line.receivedQuantity ?? 0) !== 0);
const isPosted = routeData.receipt.status === "Posted";
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index a39827b240..9d88640798 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -42,13 +42,12 @@ import {
import type { PostgrestResponse } from "@supabase/supabase-js";
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
import { LuCircleAlert, LuGroup, LuQrCode, LuSplit, LuX } from "react-icons/lu";
-import { DocumentPreview, Empty } from "~/components";
+import { DocumentPreview, Empty, ItemThumbnail } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { Enumerable } from "~/components/Enumerable";
import FileDropzone from "~/components/FileDropzone";
import { useShelves } from "~/components/Form/Shelf";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
-import { TrackingTypeIcon } from "~/components/Icons";
import { useRouteData, useUser } from "~/hooks";
import {
ShelfForm,
@@ -72,6 +71,8 @@ const ReceiptLines = () => {
const { receiptId } = useParams();
if (!receiptId) throw new Error("receiptId not found");
+
+
const fetcher = useFetcher<typeof receiptLinesUpdateAction>();
const { upload, deleteFile, getPath } = useReceiptFiles(receiptId);
const routeData = useRouteData<{
@@ -83,6 +84,7 @@ const ReceiptLines = () => {
}>(path.to.receipt(receiptId));
const receiptsById = new Map<string, ReceiptLine>(
+ // @ts-ignore
routeData?.receiptLines.map((line) => [line.id, line])
);
const pendingReceiptLines = usePendingReceiptLines();
@@ -111,7 +113,7 @@ const ReceiptLines = () => {
if (!trackedEntitiesForLine) return acc;
return {
...acc,
- [line.id]: Array.from({ length: line.receivedQuantity }, (_, index) => {
+ [line.id!]: Array.from({ length: line.receivedQuantity ?? 0 }, (_, index) => {
const serialNumberEntity = trackedEntitiesForLine.find((t) => {
const attributes = t.attributes as TrackedEntityAttributes;
return attributes["Receipt Line Index"] === index;
@@ -146,8 +148,8 @@ const ReceiptLines = () => {
if (!trackedEntitiesForLine) return acc;
return {
...acc,
- [line.id]: Array.from(
- { length: line.receivedQuantity },
+ [line.id!]: Array.from(
+ { length: line.receivedQuantity ?? 0 },
(_, index) => {
const serialNumberEntity = trackedEntitiesForLine.find((t) => {
const attributes = t.attributes as TrackedEntityAttributes;
@@ -233,18 +235,18 @@ const ReceiptLines = () => {
className={
index === receiptLines.length - 1 ? "border-none" : ""
}
- serialNumbers={serialNumbersByLineId[line.id] || []}
- getPath={(file) => getPath(file, line.id)}
+ serialNumbers={serialNumbersByLineId[line.id!] || []}
+ getPath={(file) => getPath(file, line.id!)}
onSerialNumbersChange={(newSerialNumbers) => {
setSerialNumbersByLineId((prev) => ({
...prev,
- [line.id]: newSerialNumbers,
+ [line.id!]: newSerialNumbers,
}));
}}
batchProperties={routeData?.batchProperties}
tracking={tracking}
- upload={(files) => upload(files, line.id)}
- deleteFile={(file) => deleteFile(file, line.id)}
+ upload={(files) => upload(files, line.id!)}
+ deleteFile={(file) => deleteFile(file, line.id!)}
/>
);
})
@@ -326,9 +328,7 @@ function ReceiptLineItem({
<div className="flex flex-1 justify-between items-center w-full">
<HStack spacing={4} className="w-1/2">
<HStack spacing={4} className="flex-1">
- <div className="bg-muted border rounded-full flex items-center justify-center p-2">
- <TrackingTypeIcon type={item?.itemTrackingType ?? "Inventory"} />
- </div>
+ <ItemThumbnail size="md" thumbnailPath={line.thumbnailPath} type={item?.type as "Part" ?? "Part"} />
<VStack spacing={0}>
<span className="text-sm font-medium">{item?.name}</span>
<span className="text-xs text-muted-foreground line-clamp-2">
@@ -347,10 +347,10 @@ function ReceiptLineItem({
<label className="text-xs text-muted-foreground">Received</label>
<NumberField
- value={line.receivedQuantity}
+ value={line.receivedQuantity ?? 0}
onChange={(value) => {
onUpdate({
- lineId: line.id,
+ lineId: line.id!,
field: "receivedQuantity",
value,
});
@@ -385,7 +385,7 @@ function ReceiptLineItem({
<HStack spacing={4}>
<VStack spacing={1} className="text-center items-center">
<label className="text-xs text-muted-foreground">Ordered</label>
- <span className="text-sm py-1.5">{line.orderQuantity}</span>
+ <span className="text-sm py-1.5">{line.orderQuantity ?? 0}</span>
</VStack>
<VStack spacing={1} className="text-center items-center">
@@ -394,10 +394,10 @@ function ReceiptLineItem({
</label>
<HStack className="justify-center">
<span className="text-sm py-1.5">
- {line.outstandingQuantity}
+ {line.outstandingQuantity ?? 0}
</span>
- {line.receivedQuantity > line.outstandingQuantity && (
+ {(line.receivedQuantity ?? 0) > (line.outstandingQuantity ?? 0) && (
<Tooltip>
<TooltipTrigger>
<LuCircleAlert className="text-red-500" />
@@ -416,7 +416,7 @@ function ReceiptLineItem({
isReadOnly={isReadOnly}
onChange={(shelf) => {
onUpdate({
- lineId: line.id,
+ lineId: line.id!,
field: "shelfId",
value: shelf,
});
@@ -572,13 +572,13 @@ function BatchForm({
}
const formData = new FormData();
- formData.append("itemId", line.itemId);
+ formData.append("itemId", line.itemId!);
formData.append("receiptId", receipt.id);
- formData.append("receiptLineId", line.id);
+ formData.append("receiptLineId", line.id!);
formData.append("trackingType", "batch");
formData.append("batchNumber", valuesToSubmit.number.trim());
formData.append("properties", JSON.stringify(valuesToSubmit.properties));
- formData.append("quantity", line.receivedQuantity.toString());
+ formData.append("quantity", (line.receivedQuantity ?? 0).toString());
submit(formData, {
method: "post",
@@ -602,7 +602,7 @@ function BatchForm({
window.open(
window.location.origin +
path.to.file.receiptLabelsZpl(receipt?.id ?? "", {
- lineId: line.id,
+ lineId: line.id!,
labelSize,
}),
"_blank"
@@ -611,7 +611,7 @@ function BatchForm({
window.open(
window.location.origin +
path.to.file.receiptLabelsPdf(receipt?.id ?? "", {
- lineId: line.id,
+ lineId: line.id!,
labelSize,
}),
"_blank"
@@ -674,7 +674,7 @@ function BatchForm({
{(resolvedBatchProperties) => {
return (
<BatchPropertiesFields
- itemId={line.itemId}
+ itemId={line.itemId!}
properties={
resolvedBatchProperties?.data?.filter(
(p) => p.itemId === line.itemId
@@ -697,7 +697,7 @@ function BatchForm({
{(resolvedBatchProperties) => {
return (
<BatchPropertiesConfig
- itemId={line.itemId}
+ itemId={line.itemId!}
properties={resolvedBatchProperties?.data ?? []}
type="modal"
onClose={propertiesDisclosure.onClose}
@@ -759,9 +759,9 @@ function SerialForm({
}
const formData = new FormData();
- formData.append("itemId", line.itemId);
+ formData.append("itemId", line.itemId!);
formData.append("receiptId", receipt.id);
- formData.append("receiptLineId", line.id);
+ formData.append("receiptLineId", line.id!);
formData.append("trackingType", "serial");
formData.append("index", serialNumber.index.toString());
formData.append("serialNumber", serialNumber.number.trim());
@@ -803,7 +803,7 @@ function SerialForm({
window.open(
window.location.origin +
path.to.file.receiptLabelsZpl(receipt?.id ?? "", {
- lineId: line.id,
+ lineId: line.id!,
labelSize,
}),
"_blank"
@@ -812,7 +812,7 @@ function SerialForm({
window.open(
window.location.origin +
path.to.file.receiptLabelsPdf(receipt?.id ?? "", {
- lineId: line.id,
+ lineId: line.id!,
labelSize,
}),
"_blank"
@@ -903,7 +903,7 @@ function SerialForm({
{(resolvedBatchProperties) => {
return (
<BatchPropertiesConfig
- itemId={line.itemId}
+ itemId={line.itemId!}
properties={resolvedBatchProperties?.data ?? []}
type="modal"
onClose={propertiesDisclosure.onClose}
@@ -949,8 +949,8 @@ function SplitReceiptLineModal({
</ModalHeader>
<ModalBody>
- <input type="hidden" name="documentId" value={line.receiptId} />
- <input type="hidden" name="documentLineId" value={line.id} />
+ <input type="hidden" name="documentId" value={line.receiptId ?? ""} />
+ <input type="hidden" name="documentLineId" value={line.id!} />
<input
type="hidden"
name="locationId"
@@ -959,7 +959,7 @@ function SplitReceiptLineModal({
<Number
name="quantity"
label="Quantity"
- maxValue={line.orderQuantity - 0.0001}
+ maxValue={line.orderQuantity ?? 0 - 0.0001}
minValue={0.0001}
/>
</ModalBody>
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
index 28c0ad0bb8..b21ea16539 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
@@ -34,7 +34,8 @@ const ShipmentHeader = () => {
const canPost =
routeData.shipmentLines.length > 0 &&
- routeData.shipmentLines.some((line) => line.shippedQuantity > 0);
+ routeData.shipmentLines.some((line) => (line.shippedQuantity ?? 0) !== 0);
+
const isPosted = routeData.shipment.status === "Posted";
const hasTrackingLabels = routeData.shipmentLineTracking.some(
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index c21a21a94c..f0ed12ce7c 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -252,7 +252,7 @@ function LineItems({
(j) => (j as unknown as SalesOrderJob).salesOrderLineId === line.id
) ?? []) as SalesOrderJob[];
- console.log({ jobs });
+
const isMade = line.methodType === "Make";
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
index 9e3cb397c2..a0d4ec887d 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
@@ -150,7 +150,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
methodType: "Buy" | "Make" | "Pick";
}[]) ?? [];
- console.log({ jobs, lines });
+
if (
lines.length === 0 ||
lines.every((line) => line.methodType !== "Make")
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
index 3d7725303b..bf3d15efb7 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
@@ -54,10 +54,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
let itemsWithBatchProperties: string[] = [];
if (receiptLines.data) {
- receiptLineIds = receiptLines.data.map((line) => line.id);
+ receiptLineIds = receiptLines.data.map((line) => line.id!).filter(Boolean);
itemsWithBatchProperties = receiptLines.data
- .filter((line) => line.itemId && line.requiresBatchTracking)
- .map((line) => line.itemId);
+ .filter((line) => line && line.itemId && line.requiresBatchTracking)
+ .map((line) => line.itemId)
+ .filter((itemId) => itemId !== null);
}
return defer({
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a720bedb0e..d0924dfef4 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -15589,6 +15589,7 @@ export type Database = {
internalNotes: Json | null
orderDate: string | null
purchaseOrderId: string
+ purchaseOrderType: Database["public"]["Enums"]["purchaseOrderType"]
revisionId: number
status: Database["public"]["Enums"]["purchaseOrderStatus"]
supplierContactId: string | null
@@ -15616,6 +15617,7 @@ export type Database = {
internalNotes?: Json | null
orderDate?: string | null
purchaseOrderId: string
+ purchaseOrderType?: Database["public"]["Enums"]["purchaseOrderType"]
revisionId?: number
status?: Database["public"]["Enums"]["purchaseOrderStatus"]
supplierContactId?: string | null
@@ -15643,6 +15645,7 @@ export type Database = {
internalNotes?: Json | null
orderDate?: string | null
purchaseOrderId?: string
+ purchaseOrderType?: Database["public"]["Enums"]["purchaseOrderType"]
revisionId?: number
status?: Database["public"]["Enums"]["purchaseOrderStatus"]
supplierContactId?: string | null
@@ -16148,6 +16151,8 @@ export type Database = {
invoicedComplete: boolean
itemId: string | null
itemReadableId: string | null
+ jobId: string | null
+ jobOperationId: string | null
locationId: string | null
modelUploadId: string | null
purchaseOrderId: string
@@ -16192,6 +16197,8 @@ export type Database = {
invoicedComplete?: boolean
itemId?: string | null
itemReadableId?: string | null
+ jobId?: string | null
+ jobOperationId?: string | null
locationId?: string | null
modelUploadId?: string | null
purchaseOrderId: string
@@ -16236,6 +16243,8 @@ export type Database = {
invoicedComplete?: boolean
itemId?: string | null
itemReadableId?: string | null
+ jobId?: string | null
+ jobOperationId?: string | null
locationId?: string | null
modelUploadId?: string | null
purchaseOrderId?: string
@@ -16326,6 +16335,34 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_modelUploadId_fkey"
columns: ["modelUploadId"]
@@ -30505,14 +30542,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -31809,14 +31846,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -31846,6 +31883,9 @@ export type Database = {
orderTotal: number | null
paymentTermId: string | null
purchaseOrderId: string | null
+ purchaseOrderType:
+ | Database["public"]["Enums"]["purchaseOrderType"]
+ | null
receiptPromisedDate: string | null
receiptRequestedDate: string | null
revisionId: number | null
@@ -33490,6 +33530,132 @@ export type Database = {
},
]
}
+ receiptLines: {
+ Row: {
+ companyId: string | null
+ conversionFactor: number | null
+ createdAt: string | null
+ createdBy: string | null
+ description: string | null
+ id: string | null
+ itemId: string | null
+ itemReadableId: string | null
+ lineId: string | null
+ locationId: string | null
+ orderQuantity: number | null
+ outstandingQuantity: number | null
+ receiptId: string | null
+ receivedQuantity: number | null
+ requiresBatchTracking: boolean | null
+ requiresSerialTracking: boolean | null
+ shelfId: string | null
+ thumbnailPath: string | null
+ unitOfMeasure: string | null
+ unitPrice: number | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "receiptLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_receiptId_fkey"
+ columns: ["receiptId"]
+ isOneToOne: false
+ referencedRelation: "receipt"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_shelfId_fkey"
+ columns: ["shelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
salesOrderCustomers: {
Row: {
companyId: string | null
@@ -33758,14 +33924,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -37035,7 +37201,7 @@ export type Database = {
| "Approved"
| "Reject"
| "Request Approval"
- purchaseOrderType: "Purchase" | "Return"
+ purchaseOrderType: "Purchase" | "Return" | "Outside Processing"
quoteLineStatus: "Not Started" | "In Progress" | "Complete" | "No Quote"
quoteStatus:
| "Draft"
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a720bedb0e..d0924dfef4 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -15589,6 +15589,7 @@ export type Database = {
internalNotes: Json | null
orderDate: string | null
purchaseOrderId: string
+ purchaseOrderType: Database["public"]["Enums"]["purchaseOrderType"]
revisionId: number
status: Database["public"]["Enums"]["purchaseOrderStatus"]
supplierContactId: string | null
@@ -15616,6 +15617,7 @@ export type Database = {
internalNotes?: Json | null
orderDate?: string | null
purchaseOrderId: string
+ purchaseOrderType?: Database["public"]["Enums"]["purchaseOrderType"]
revisionId?: number
status?: Database["public"]["Enums"]["purchaseOrderStatus"]
supplierContactId?: string | null
@@ -15643,6 +15645,7 @@ export type Database = {
internalNotes?: Json | null
orderDate?: string | null
purchaseOrderId?: string
+ purchaseOrderType?: Database["public"]["Enums"]["purchaseOrderType"]
revisionId?: number
status?: Database["public"]["Enums"]["purchaseOrderStatus"]
supplierContactId?: string | null
@@ -16148,6 +16151,8 @@ export type Database = {
invoicedComplete: boolean
itemId: string | null
itemReadableId: string | null
+ jobId: string | null
+ jobOperationId: string | null
locationId: string | null
modelUploadId: string | null
purchaseOrderId: string
@@ -16192,6 +16197,8 @@ export type Database = {
invoicedComplete?: boolean
itemId?: string | null
itemReadableId?: string | null
+ jobId?: string | null
+ jobOperationId?: string | null
locationId?: string | null
modelUploadId?: string | null
purchaseOrderId: string
@@ -16236,6 +16243,8 @@ export type Database = {
invoicedComplete?: boolean
itemId?: string | null
itemReadableId?: string | null
+ jobId?: string | null
+ jobOperationId?: string | null
locationId?: string | null
modelUploadId?: string | null
purchaseOrderId?: string
@@ -16326,6 +16335,34 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_modelUploadId_fkey"
columns: ["modelUploadId"]
@@ -30505,14 +30542,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -31809,14 +31846,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -31846,6 +31883,9 @@ export type Database = {
orderTotal: number | null
paymentTermId: string | null
purchaseOrderId: string | null
+ purchaseOrderType:
+ | Database["public"]["Enums"]["purchaseOrderType"]
+ | null
receiptPromisedDate: string | null
receiptRequestedDate: string | null
revisionId: number | null
@@ -33490,6 +33530,132 @@ export type Database = {
},
]
}
+ receiptLines: {
+ Row: {
+ companyId: string | null
+ conversionFactor: number | null
+ createdAt: string | null
+ createdBy: string | null
+ description: string | null
+ id: string | null
+ itemId: string | null
+ itemReadableId: string | null
+ lineId: string | null
+ locationId: string | null
+ orderQuantity: number | null
+ outstandingQuantity: number | null
+ receiptId: string | null
+ receivedQuantity: number | null
+ requiresBatchTracking: boolean | null
+ requiresSerialTracking: boolean | null
+ shelfId: string | null
+ thumbnailPath: string | null
+ unitOfMeasure: string | null
+ unitPrice: number | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "receiptLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_receiptId_fkey"
+ columns: ["receiptId"]
+ isOneToOne: false
+ referencedRelation: "receipt"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_shelfId_fkey"
+ columns: ["shelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
salesOrderCustomers: {
Row: {
companyId: string | null
@@ -33758,14 +33924,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -37035,7 +37201,7 @@ export type Database = {
| "Approved"
| "Reject"
| "Request Approval"
- purchaseOrderType: "Purchase" | "Return"
+ purchaseOrderType: "Purchase" | "Return" | "Outside Processing"
quoteLineStatus: "Not Started" | "In Progress" | "Complete" | "No Quote"
quoteStatus:
| "Draft"
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 2286e4aaa4..5376f199a2 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -125,7 +125,7 @@ serve(async (req: Request) => {
const totalLinesCost = receiptLines.data.reduce((acc, receiptLine) => {
const lineCost =
- (receiptLine.receivedQuantity ?? 0) * (receiptLine.unitPrice ?? 0);
+ Math.abs(receiptLine.receivedQuantity ?? 0) * (receiptLine.unitPrice ?? 0);
return acc + lineCost;
}, 0);
@@ -401,7 +401,7 @@ serve(async (req: Request) => {
const quantityToReverse = Math.max(
0,
Math.min(
- receiptLine.receivedQuantity ?? 0,
+ Math.abs(receiptLine.receivedQuantity ?? 0),
quantityInvoiced - quantityReceived
)
);
@@ -613,13 +613,16 @@ serve(async (req: Request) => {
});
}
- if (receiptLine.receivedQuantity > quantityToReverse) {
+ const receivedQuantity = receiptLine.receivedQuantity ?? 0;
+ const isNegativeReceipt = receivedQuantity < 0;
+ const absReceivedQuantity = Math.abs(receivedQuantity);
+
+ if (absReceivedQuantity > quantityToReverse) {
// create the accrual entries for received not invoiced
- const quantityToAccrue =
- receiptLine.receivedQuantity - quantityToReverse;
+ const quantityToAccrue = absReceivedQuantity - quantityToReverse;
const expectedValue =
- (receiptLine.receivedQuantity - quantityToReverse) *
+ (absReceivedQuantity - quantityToReverse) *
receiptLine.unitPrice;
// Add proportional shipping cost to the expected value based on line value percentage
@@ -631,48 +634,86 @@ serve(async (req: Request) => {
const journalLineReference = nanoid();
- journalLineInserts.push({
- accountNumber:
- postingGroupInventory.inventoryInterimAccrualAccount,
- description: "Interim Inventory Accrual",
- accrual: true,
- amount: debit("asset", expectedValueWithShipping),
- quantity: quantityToAccrue,
- documentType: "Receipt",
- documentId: receipt.data?.id ?? undefined,
- externalDocumentId:
- purchaseOrder.data?.supplierReference ?? undefined,
- documentLineReference: `receipt:${receiptLine.lineId}`,
- journalLineReference,
- companyId,
- });
+ // For negative receipts, we need to reverse the debit/credit entries
+ if (isNegativeReceipt) {
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryInterimAccrualAccount,
+ description: "Interim Inventory Accrual",
+ accrual: true,
+ amount: credit("asset", expectedValueWithShipping),
+ quantity: quantityToAccrue,
+ documentType: "Receipt",
+ documentId: receipt.data?.id ?? undefined,
+ externalDocumentId:
+ purchaseOrder.data?.supplierReference ?? undefined,
+ documentLineReference: `receipt:${receiptLine.lineId}`,
+ journalLineReference,
+ companyId,
+ });
- journalLineInserts.push({
- accountNumber:
- postingGroupInventory.inventoryReceivedNotInvoicedAccount,
- description: "Inventory Received Not Invoiced",
- accrual: true,
- amount: credit("liability", expectedValueWithShipping),
- quantity: quantityToAccrue,
- documentType: "Receipt",
- documentId: receipt.data?.id ?? undefined,
- externalDocumentId:
- purchaseOrder.data?.supplierReference ?? undefined,
- documentLineReference: `receipt:${receiptLine.lineId}`,
- journalLineReference,
- companyId,
- });
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryReceivedNotInvoicedAccount,
+ description: "Inventory Received Not Invoiced",
+ accrual: true,
+ amount: debit("liability", expectedValueWithShipping),
+ quantity: quantityToAccrue,
+ documentType: "Receipt",
+ documentId: receipt.data?.id ?? undefined,
+ externalDocumentId:
+ purchaseOrder.data?.supplierReference ?? undefined,
+ documentLineReference: `receipt:${receiptLine.lineId}`,
+ journalLineReference,
+ companyId,
+ });
+ } else {
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryInterimAccrualAccount,
+ description: "Interim Inventory Accrual",
+ accrual: true,
+ amount: debit("asset", expectedValueWithShipping),
+ quantity: quantityToAccrue,
+ documentType: "Receipt",
+ documentId: receipt.data?.id ?? undefined,
+ externalDocumentId:
+ purchaseOrder.data?.supplierReference ?? undefined,
+ documentLineReference: `receipt:${receiptLine.lineId}`,
+ journalLineReference,
+ companyId,
+ });
+
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryReceivedNotInvoicedAccount,
+ description: "Inventory Received Not Invoiced",
+ accrual: true,
+ amount: credit("liability", expectedValueWithShipping),
+ quantity: quantityToAccrue,
+ documentType: "Receipt",
+ documentId: receipt.data?.id ?? undefined,
+ externalDocumentId:
+ purchaseOrder.data?.supplierReference ?? undefined,
+ documentLineReference: `receipt:${receiptLine.lineId}`,
+ journalLineReference,
+ companyId,
+ });
+ }
}
if (itemTrackingType === "Inventory") {
+ // For inventory entries, use the appropriate entry type based on quantity sign
+ const entryType = receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";
+
itemLedgerInserts.push({
postingDate: today,
itemId: receiptLine.itemId,
itemReadableId: receiptLine.itemReadableId ?? "",
- quantity: receiptLine.receivedQuantity,
+ quantity: receivedQuantity,
locationId: receiptLine.locationId,
shelfId: receiptLine.shelfId,
- entryType: "Positive Adjmt.",
+ entryType,
documentType: "Purchase Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId: receipt.data?.externalDocumentId ?? undefined,
@@ -682,14 +723,16 @@ serve(async (req: Request) => {
}
if (receiptLine.requiresBatchTracking) {
+ const entryType = receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";
+
itemLedgerInserts.push({
postingDate: today,
itemId: receiptLine.itemId,
itemReadableId: receiptLine.itemReadableId ?? "",
- quantity: receiptLine.receivedQuantity,
+ quantity: receivedQuantity,
locationId: receiptLine.locationId,
shelfId: receiptLine.shelfId,
- entryType: "Positive Adjmt.",
+ entryType,
documentType: "Purchase Receipt",
documentId: receipt.data?.id ?? undefined,
trackedEntityId: receiptLineTracking.data?.find(
@@ -712,9 +755,11 @@ serve(async (req: Request) => {
] === receiptLine.id
);
- const receivedQuantity = receiptLine.receivedQuantity || 0;
+ const absReceivedQuantity = Math.abs(receiptLine.receivedQuantity || 0);
+ const entryType = receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";
+ const quantityPerEntry = receivedQuantity < 0 ? -1 : 1;
- for (let i = 0; i < receivedQuantity; i++) {
+ for (let i = 0; i < absReceivedQuantity; i++) {
const trackingWithIndex = lineTracking?.find(
(tracking) =>
(
@@ -726,10 +771,10 @@ serve(async (req: Request) => {
postingDate: today,
itemId: receiptLine.itemId,
itemReadableId: receiptLine.itemReadableId ?? "",
- quantity: 1,
+ quantity: quantityPerEntry,
locationId: receiptLine.locationId,
shelfId: receiptLine.shelfId,
- entryType: "Positive Adjmt.",
+ entryType,
documentType: "Purchase Receipt",
documentId: receipt.data?.id ?? undefined,
trackedEntityId: trackingWithIndex?.id,
diff --git a/packages/database/supabase/migrations/20250331171424_receipt-lines-thumbnail.sql b/packages/database/supabase/migrations/20250331171424_receipt-lines-thumbnail.sql
new file mode 100644
index 0000000000..1244195b28
--- /dev/null
+++ b/packages/database/supabase/migrations/20250331171424_receipt-lines-thumbnail.sql
@@ -0,0 +1,12 @@
+DROP VIEW IF EXISTS "receiptLines";
+CREATE OR REPLACE VIEW "receiptLines" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ rl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."name" as "description"
+ FROM "receiptLine" rl
+ INNER JOIN "item" i ON i."id" = rl."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId";
\ No newline at end of file