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.

refactor: sales order lines

Brad Barbin838154930034
diff --git a/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx
index 4b3f6ada31..f205fb4ac1 100644
--- a/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx
@@ -86,8 +86,6 @@ const EditableSalesOrderLineNumber =
description: item.data?.name ?? "",
unitPrice: itemUnitSalePrice?.unitSalePrice ?? 0,
unitOfMeasureCode: part.data?.unitOfMeasureCode ?? "EA",
-
- conversionFactor: itemReplenishment?.conversionFactor ?? 1,
shelfId: inventory.data?.defaultShelfId ?? null,
});
@@ -101,8 +99,6 @@ const EditableSalesOrderLineNumber =
description: item.data?.name ?? "",
unitPrice: itemUnitSalePrice?.unitSalePrice ?? 0,
unitOfMeasureCode: part.data?.unitOfMeasureCode ?? "EA",
-
- conversionFactor: itemReplenishment?.conversionFactor ?? 1,
shelfId: inventory.data?.defaultShelfId ?? null,
updatedBy: userId,
})
diff --git a/apps/carbon/app/modules/parts/parts.service.ts b/apps/carbon/app/modules/parts/parts.service.ts
index 1e874127b7..d603e6fd49 100644
--- a/apps/carbon/app/modules/parts/parts.service.ts
+++ b/apps/carbon/app/modules/parts/parts.service.ts
@@ -184,8 +184,8 @@ export async function getPartsList(
replenishmentSystem: ItemReplenishmentSystem | null
) {
let query = client
- .from("part")
- .select("id, name")
+ .from("item")
+ .select("id, name, readableId")
.eq("companyId", companyId)
.eq("blocked", false)
.eq("active", true);
diff --git a/apps/carbon/app/modules/purchasing/purchasing.models.ts b/apps/carbon/app/modules/purchasing/purchasing.models.ts
index 6ec08f735c..d71d2367ff 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.models.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.models.ts
@@ -124,7 +124,7 @@ export const purchaseOrderLineValidator = z
: true,
{
message: "Part is required",
- path: ["partId"], // path of error
+ path: ["itemId"], // path of error
}
)
.refine(
diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx b/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx
index cf88c69e28..01d183f5b1 100644
--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx
@@ -168,9 +168,9 @@ const RequestForQuotesTable = memo(
},
},
{
- id: "partIds",
- header: "Parts",
- cell: ({ row }) => row.original.partIds?.length ?? 0,
+ id: "itemIds",
+ header: "Items",
+ cell: ({ row }) => row.original.itemIds?.length ?? 0,
meta: {
filter: {
type: "static",
@@ -235,7 +235,7 @@ const RequestForQuotesTable = memo(
createdBy: false,
updatedAt: false,
updatedBy: false,
- partIds: false,
+ itemIds: false,
supplierIds: false,
};
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index 1bcdd51ceb..528826e11b 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -86,7 +86,7 @@ export const quotationValidator = z.object({
export const quotationAssemblyValidator = z.object({
id: zfd.text(z.string().optional()),
parentAssemblyId: zfd.text(z.string().optional()),
- partId: z.string().min(1, { message: "Part is required" }),
+ itemId: z.string().min(1, { message: "Part is required" }),
description: z.string().min(1, { message: "Description is required" }),
unitOfMeasureCode: zfd.text(z.string().optional()),
quantityPerParent: zfd.numeric(
@@ -96,7 +96,7 @@ export const quotationAssemblyValidator = z.object({
export const quotationMaterialValidator = z.object({
id: zfd.text(z.string().optional()),
- partId: z.string().min(1, { message: "Part is required" }),
+ itemId: z.string().min(1, { message: "Part is required" }),
quantity: zfd.numeric(
z.number().min(0.00001, { message: "Quantity is required" })
),
@@ -135,7 +135,7 @@ export const quotationPricingValidator = z.object({
export const quotationLineValidator = z.object({
id: zfd.text(z.string().optional()),
quoteId: z.string(),
- partId: z.string().min(1, { message: "Part is required" }),
+ itemId: z.string().min(1, { message: "Part is required" }),
status: z.enum(quoteLineStatusType, {
errorMap: () => ({ message: "Status is required" }),
}),
@@ -161,7 +161,16 @@ export const quotationReleaseValidator = z
}
);
-export const salesOrderLineType = ["Part", "Service", "Comment"] as const;
+export const salesOrderLineType = [
+ "Part",
+ "Service",
+ "Material",
+ "Tool",
+ "Fixture",
+ "Hardware",
+ "Consumable",
+ "Comment",
+] as const;
export const salesOrderStatusType = [
"Draft",
@@ -237,7 +246,8 @@ export const salesOrderLineValidator = z
message: "Type is required",
}),
}),
- partId: zfd.text(z.string().optional()),
+ itemId: zfd.text(z.string().optional()),
+ itemReadableId: zfd.text(z.string().optional()),
serviceId: zfd.text(z.string().optional()),
accountNumber: zfd.text(z.string().optional()),
assetId: zfd.text(z.string().optional()),
@@ -249,9 +259,9 @@ export const salesOrderLineValidator = z
locationId: zfd.text(z.string().optional()),
shelfId: zfd.text(z.string().optional()),
})
- .refine((data) => (data.salesOrderLineType === "Part" ? data.partId : true), {
+ .refine((data) => (data.salesOrderLineType === "Part" ? data.itemId : true), {
message: "Part is required",
- path: ["partId"], // path of error
+ path: ["itemId"], // path of error
})
.refine(
(data) => (data.salesOrderLineType === "Comment" ? data.description : true),
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 88668ebe1a..897cdb707a 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -646,16 +646,16 @@ export async function insertQuoteLinePrice(
let unitCost = 0;
if (quoteLine.data?.replenishmentSystem === "Buy") {
- const partId = quoteLine.data?.partId;
- const [partCost] = await Promise.all([
- client.from("partCost").select("unitCost").eq("partId", partId).single(),
+ const itemId = quoteLine.data?.itemId;
+ const [itemCost] = await Promise.all([
+ client.from("itemCost").select("unitCost").eq("itemId", itemId).single(),
]);
- if (partCost.error) {
- return partCost;
+ if (itemCost.error) {
+ return itemCost;
}
- unitCost = partCost.data?.unitCost;
+ unitCost = itemCost.data?.unitCost;
}
const totalCost = unitCost * (quoteLinePrice.quantity ?? 0);
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationAssemblyForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationAssemblyForm.tsx
index 9723339a3a..0763958cdb 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationAssemblyForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationAssemblyForm.tsx
@@ -59,29 +59,35 @@ const QuotationAssemblyForm = ({
const isEditing = initialValues.id !== undefined;
const [partData, setPartData] = useState<{
- partId: string;
+ itemId: string;
description: string;
uom: string;
}>({
- partId: initialValues.partId ?? "",
+ itemId: initialValues.itemId ?? "",
description: initialValues.description ?? "",
uom: initialValues.unitOfMeasureCode ?? "",
});
- const onPartChange = async (partId: string) => {
+ const onPartChange = async (itemId: string) => {
if (!supabase || !company.id) return;
- const [part] = await Promise.all([
+ const [item, part] = await Promise.all([
+ supabase
+ .from("item")
+ .select("name")
+ .eq("id", itemId)
+ .eq("companyId", company.id)
+ .single(),
supabase
.from("part")
- .select("name, replenishmentSystem, unitOfMeasureCode")
- .eq("id", partId)
+ .select("replenishmentSystem, unitOfMeasureCode")
+ .eq("id", itemId)
.eq("companyId", company.id)
.single(),
]);
setPartData({
- partId,
- description: part.data?.name ?? "",
+ itemId,
+ description: item.data?.name ?? "",
uom: part.data?.unitOfMeasureCode ?? "",
});
};
@@ -109,7 +115,7 @@ const QuotationAssemblyForm = ({
<CardTitle>{isEditing ? "Assembly" : "New Assembly"}</CardTitle>
<CardDescription>
{isEditing
- ? partData?.partId
+ ? partData?.itemId
: "A quote assembly is a collection of operations, materials, and subassemblies that are used to build a product."}
</CardDescription>
</CardHeader>
@@ -151,7 +157,7 @@ const QuotationAssemblyForm = ({
<VStack>
<div className="grid w-full gap-x-8 gap-y-2 grid-cols-1 lg:grid-cols-3">
<Part
- name="partId"
+ name="itemId"
label="Manufactured Part"
partReplenishmentSystem="Make"
onChange={(value) => {
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx
index d328749d9e..b1c72f6077 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx
@@ -28,7 +28,7 @@ import {
Hidden,
Input,
InputControlled,
- Part,
+ Item,
Select,
SelectControlled,
Submit,
@@ -69,31 +69,32 @@ const QuotationLineForm = ({ initialValues }: QuotationLineFormProps) => {
: !permissions.can("create", "sales");
const [partData, setPartData] = useState<{
- partId: string;
+ itemId: string;
description: string;
replenishmentSystem: string;
uom: string;
}>({
- partId: initialValues.partId ?? "",
+ itemId: initialValues.itemId ?? "",
description: initialValues.description ?? "",
replenishmentSystem: initialValues.replenishmentSystem ?? "",
uom: initialValues.unitOfMeasureCode ?? "",
});
- const onPartChange = async (partId: string) => {
+ const onPartChange = async (itemId: string) => {
if (!supabase || !company.id) return;
- const [part] = await Promise.all([
+ const [item, part] = await Promise.all([
+ supabase.from("item").select("name").eq("id", itemId).single(),
supabase
.from("part")
- .select("name, replenishmentSystem, unitOfMeasureCode")
- .eq("id", partId)
+ .select("replenishmentSystem, unitOfMeasureCode")
+ .eq("itemId", itemId)
.eq("companyId", company.id)
.single(),
]);
setPartData({
- partId,
- description: part.data?.name ?? "",
+ itemId,
+ description: item.data?.name ?? "",
replenishmentSystem:
part.data?.replenishmentSystem === "Buy and Make"
? ""
@@ -159,8 +160,9 @@ const QuotationLineForm = ({ initialValues }: QuotationLineFormProps) => {
<Hidden name="unitOfMeasureCode" value={partData?.uom} />
<VStack>
<div className="grid w-full gap-x-8 gap-y-2 grid-cols-1 lg:grid-cols-3">
- <Part
- name="partId"
+ <Item
+ name="itemId"
+ type="Part"
label="Part"
onChange={(value) => {
onPartChange(value?.value as string);
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialForm.tsx
index b39f06e9d7..63627c3088 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialForm.tsx
@@ -52,12 +52,12 @@ const QuotationMaterialForm = ({
const isEditable = ["Draft"].includes(routeData?.quotation?.status ?? "");
const [partData, setPartData] = useState<{
- partId: string;
+ itemId: string;
description: string;
unitCost: number;
uom: string;
}>({
- partId: initialValues.partId ?? "",
+ itemId: initialValues.itemId ?? "",
description: initialValues.description ?? "",
unitCost: initialValues.unitCost ?? 0,
uom: initialValues.unitOfMeasureCode ?? "",
@@ -72,26 +72,32 @@ const QuotationMaterialForm = ({
const onClose = () => navigate(-1);
- const onPartChange = async (partId: string) => {
+ const onPartChange = async (itemId: string) => {
if (!supabase || !company.id) return;
- const [part, cost] = await Promise.all([
+ const [item, part, cost] = await Promise.all([
+ supabase
+ .from("item")
+ .select("name")
+ .eq("id", itemId)
+ .eq("companyId", company.id)
+ .single(),
supabase
.from("part")
- .select("name, unitOfMeasureCode")
- .eq("id", partId)
+ .select("unitOfMeasureCode")
+ .eq("id", itemId)
.eq("companyId", company.id)
.single(),
supabase
- .from("partCost")
+ .from("itemCost")
.select("unitCost")
- .eq("partId", partId)
+ .eq("itemId", itemId)
.eq("companyId", company.id)
.single(),
]);
setPartData({
- partId,
- description: part.data?.name ?? "",
+ itemId,
+ description: item.data?.name ?? "",
unitCost: cost.data?.unitCost ?? 0,
uom: part.data?.unitOfMeasureCode ?? "EA",
});
@@ -129,7 +135,7 @@ const QuotationMaterialForm = ({
<VStack spacing={4}>
<Part
- name="partId"
+ name="itemId"
label="Part"
partReplenishmentSystem="Buy"
onChange={(value) => {
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialLines.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialLines.tsx
index ae405479f0..a17803bffa 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialLines.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationMaterialLines.tsx
@@ -19,6 +19,7 @@ import {
type Quotation,
type QuotationMaterial,
} from "~/modules/sales";
+import { useItems } from "~/stores";
import { path } from "~/utils/path";
type QuotationMaterialLinesProps = {
@@ -69,12 +70,16 @@ const QuotationMaterialLines = ({
currency: "USD",
});
+ const [items] = useItems();
+
const columns = useMemo<ColumnDef<QuotationMaterial>[]>(() => {
return [
{
- accessorKey: "partId",
+ accessorKey: "itemId",
header: "Part",
- cell: (item) => item.getValue(),
+ cell: ({ row }) =>
+ items.find((item) => item.id === row.original.itemId)?.readableId ??
+ null,
},
{
accessorKey: "description",
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index ad343901ff..5317a6e2a7 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -18,12 +18,10 @@ import {
ComboboxControlled,
CustomFormFields,
Hidden,
- InputControlled,
+ Item,
Number,
NumberControlled,
- Part,
Select,
- Service,
Submit,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
@@ -64,14 +62,16 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
const [type, setType] = useState(initialValues.salesOrderLineType);
const [locationId, setLocationId] = useState(defaults.locationId ?? "");
- const [partData, setPartData] = useState<{
- partId: string;
+ const [itemData, setItemData] = useState<{
+ itemId: string;
+ itemReadableId?: string;
description: string;
unitPrice: number;
uom: string;
shelfId: string;
}>({
- partId: initialValues.partId ?? "",
+ itemId: initialValues.itemId ?? "",
+ itemReadableId: initialValues.itemReadableId ?? "",
description: initialValues.description ?? "",
unitPrice: initialValues.unitPrice ?? 0,
uom: initialValues.unitOfMeasureCode ?? "",
@@ -111,9 +111,11 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
const onClose = () => navigate(-1);
const onTypeChange = (type: SalesOrderLineType) => {
+ // @ts-ignore
setType(type);
- setPartData({
- partId: "",
+ setItemData({
+ itemId: "",
+ itemReadableId: "",
description: "",
unitPrice: 0,
uom: "EA",
@@ -121,73 +123,63 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
});
};
- const onPartChange = async (partId: string) => {
+ const onChange = async (itemId: string) => {
+ if (!itemId) return;
if (!supabase || !company.id) return;
- const [part, shelf, price] = await Promise.all([
+ const [item, part, shelf, price] = await Promise.all([
supabase
- .from("part")
- .select("name, unitOfMeasureCode")
- .eq("id", partId)
+ .from("item")
+ .select("name, readableId")
+ .eq("id", itemId)
.eq("companyId", company.id)
.single(),
supabase
- .from("partInventory")
+ .from("part")
+ .select("unitOfMeasureCode")
+ .eq("itemId", itemId)
+ .eq("companyId", company.id)
+ .maybeSingle(),
+ supabase
+ .from("itemInventory")
.select("defaultShelfId")
- .eq("partId", partId)
+ .eq("itemId", itemId)
.eq("companyId", company.id)
.eq("locationId", locationId)
.maybeSingle(),
supabase
- .from("partUnitSalePrice")
+ .from("itemUnitSalePrice")
.select("unitSalePrice")
- .eq("partId", partId)
+ .eq("itemId", itemId)
.eq("companyId", company.id)
- .single(),
+ .maybeSingle(),
]);
- setPartData({
- partId,
- description: part.data?.name ?? "",
+ setItemData({
+ itemId,
+ itemReadableId: item.data?.readableId,
+ description: item.data?.name ?? "",
unitPrice: price.data?.unitSalePrice ?? 0,
uom: part.data?.unitOfMeasureCode ?? "EA",
shelfId: shelf.data?.defaultShelfId ?? "",
});
};
- const onServiceChange = async (serviceId: string) => {
- if (!supabase) return;
- const service = await supabase
- .from("service")
- .select("name")
- .eq("id", serviceId)
- .eq("companyId", company.id)
- .single();
-
- setPartData({
- partId: "",
- description: service.data?.name ?? "",
- unitPrice: 0,
- uom: "EA",
- shelfId: "",
- });
- };
-
const onLocationChange = async (newLocation: { value: string } | null) => {
if (!supabase) throw new Error("supabase is not defined");
if (typeof newLocation?.value !== "string")
throw new Error("locationId is not a string");
setLocationId(newLocation.value);
- if (!partData.partId) return;
+ if (!itemData.itemId) return;
const shelf = await supabase
- .from("partInventory")
+ .from("itemInventory")
.select("defaultShelfId")
- .eq("partId", partData.partId)
+ .eq("itemId", itemData.itemId)
.eq("companyId", company.id)
.eq("locationId", newLocation.value)
.maybeSingle();
- setPartData((d) => ({
+ setItemData((d) => ({
...d,
shelfId: shelf?.data?.defaultShelfId ?? "",
}));
@@ -220,7 +212,8 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
<DrawerBody>
<Hidden name="id" />
<Hidden name="salesOrderId" />
-
+ <Hidden name="itemReadableId" value={itemData?.itemReadableId} />
+ <Hidden name="description" value={itemData?.description} />
<VStack spacing={4}>
<Select
name="salesOrderLineType"
@@ -230,35 +223,27 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
onTypeChange(value?.value as SalesOrderLineType);
}}
/>
- {type === "Part" && (
- <Part
- name="partId"
- label="Part"
- partReplenishmentSystem="Buy and Make"
- onChange={(value) => {
- onPartChange(value?.value as string);
- }}
- />
- )}
- {type === "Service" && (
- <Service
- name="serviceId"
- label="Service"
- serviceType="External"
+ {[
+ "Part",
+ "Material",
+ "Service",
+ "Hardware",
+ "Tool",
+ "Fixture",
+ "Consumable",
+ ].includes(type) && (
+ <Item
+ name="itemId"
+ label={type}
+ // @ts-ignore
+ type={type}
onChange={(value) => {
- onServiceChange(value?.value as string);
+ onChange(value?.value as string);
}}
/>
)}
- <InputControlled
- name="description"
- label="Description"
- value={partData.description}
- onChange={(newValue) =>
- setPartData((d) => ({ ...d, description: newValue }))
- }
- />
+
{type !== "Comment" && (
<>
<Number name="saleQuantity" label="Quantity" />
@@ -268,9 +253,9 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
<NumberControlled
name="unitPrice"
label="Unit Price"
- value={partData.unitPrice}
+ value={itemData.unitPrice}
onChange={(value) =>
- setPartData((d) => ({
+ setItemData((d) => ({
...d,
unitPrice: value,
}))
@@ -290,10 +275,10 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
name="shelfId"
label="Shelf"
options={shelfOptions}
- value={partData.shelfId}
+ value={itemData.shelfId}
onChange={(newValue) => {
if (newValue) {
- setPartData((d) => ({
+ setItemData((d) => ({
...d,
shelfId: newValue?.value as string,
}));
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx
index 6b0d2609a8..02ad6e9fb6 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx
@@ -112,7 +112,7 @@ const SalesOrderLines = () => {
case "Comment":
return null;
default:
- return <span>{row.original.itemId}</span>;
+ return <span>{row.original.itemReadableId}</span>;
}
},
},
diff --git a/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx b/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx
index 5c35378760..3d4de3013b 100644
--- a/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx
+++ b/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx
@@ -102,7 +102,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
{
event: "*",
schema: "public",
- table: "part",
+ table: "item",
},
(payload) => {
if ("companyId" in payload.new && payload.new.companyId !== companyId)
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 6ca0ebe8dd..324330a246 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -23063,8 +23063,6 @@ export type Database = {
requestForQuoteStatus: "Draft" | "Sent" | "Expired" | "Closed"
salesOrderLineType:
| "Comment"
- | "G/L Account"
- | "Fixed Asset"
| "Part"
| "Material"
| "Tool"
@@ -23072,6 +23070,7 @@ export type Database = {
| "Service"
| "Consumable"
| "Fixture"
+ | "Fixed Asset"
salesOrderStatus:
| "Draft"
| "Needs Approval"
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 6ca0ebe8dd..324330a246 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -23063,8 +23063,6 @@ export type Database = {
requestForQuoteStatus: "Draft" | "Sent" | "Expired" | "Closed"
salesOrderLineType:
| "Comment"
- | "G/L Account"
- | "Fixed Asset"
| "Part"
| "Material"
| "Tool"
@@ -23072,6 +23070,7 @@ export type Database = {
| "Service"
| "Consumable"
| "Fixture"
+ | "Fixed Asset"
salesOrderStatus:
| "Draft"
| "Needs Approval"
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index 87959e0489..70e0af687b 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -31,9 +31,9 @@ serve(async (req: Request) => {
if (purchaseInvoiceLines.error)
throw new Error("Failed to fetch receipt lines");
- const partIds = purchaseInvoiceLines.data
- .filter((line) => Boolean(line.partId))
- .map((line) => line.partId);
+ const itemIds = purchaseInvoiceLines.data
+ .filter((line) => Boolean(line.itemId))
+ .map((line) => line.itemId);
const dateOneYearAgo = format(
new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
@@ -42,26 +42,27 @@ serve(async (req: Request) => {
const companyId = purchaseInvoice.data.companyId;
- const [costLedgers, partSuppliers] = await Promise.all([
+ const [costLedgers, itemSuppliers] = await Promise.all([
client
.from("costLedger")
.select("*")
- .in("partId", partIds)
+ .in("itemId", itemIds)
.eq("companyId", companyId)
.gte("postingDate", dateOneYearAgo),
client
- .from("partSupplier")
+ .from("itemSupplier")
.select("*")
+
.eq("supplierId", purchaseInvoice.data?.supplierId ?? "")
- .in("partId", partIds)
+ .in("itemId", itemIds)
.eq("companyId", companyId),
]);
- const partCostUpdates: Database["public"]["Tables"]["partCost"]["Update"][] =
+ const itemCostUpdates: Database["public"]["Tables"]["itemCost"]["Update"][] =
[];
- const partSupplierInserts: Database["public"]["Tables"]["partSupplier"]["Insert"][] =
+ const itemSupplierInserts: Database["public"]["Tables"]["itemSupplier"]["Insert"][] =
[];
- const partSupplierUpdates: Database["public"]["Tables"]["partSupplier"]["Update"][] =
+ const itemSupplierUpdates: Database["public"]["Tables"]["itemSupplier"]["Update"][] =
[];
const historicalPartCosts: Record<
@@ -70,46 +71,46 @@ serve(async (req: Request) => {
> = {};
costLedgers.data?.forEach((ledger) => {
- if (ledger.partId) {
- if (!historicalPartCosts[ledger.partId]) {
- historicalPartCosts[ledger.partId] = {
+ if (ledger.itemId) {
+ if (!historicalPartCosts[ledger.itemId]) {
+ historicalPartCosts[ledger.itemId] = {
quantity: 0,
cost: 0,
};
}
- historicalPartCosts[ledger.partId].quantity += ledger.quantity;
- historicalPartCosts[ledger.partId].cost += ledger.cost;
+ historicalPartCosts[ledger.itemId].quantity += ledger.quantity;
+ historicalPartCosts[ledger.itemId].cost += ledger.cost;
}
});
purchaseInvoiceLines.data.forEach((line) => {
- if (line.partId && historicalPartCosts[line.partId]) {
- partCostUpdates.push({
- partId: line.partId,
+ if (line.itemId && historicalPartCosts[line.itemId]) {
+ itemCostUpdates.push({
+ itemId: line.itemId,
unitCost:
- historicalPartCosts[line.partId].cost /
- historicalPartCosts[line.partId].quantity,
+ historicalPartCosts[line.itemId].cost /
+ historicalPartCosts[line.itemId].quantity,
updatedBy: "system",
});
- const partSupplier = partSuppliers.data?.find(
- (partSupplier) =>
- partSupplier.partId === line.partId &&
- partSupplier.supplierId === purchaseInvoice.data?.supplierId
+ const itemSupplier = itemSuppliers.data?.find(
+ (itemSupplier) =>
+ itemSupplier.itemId === line.itemId &&
+ itemSupplier.supplierId === purchaseInvoice.data?.supplierId
);
- if (partSupplier && partSupplier.id) {
- partSupplierUpdates.push({
- id: partSupplier.id,
+ if (itemSupplier && itemSupplier.id) {
+ itemSupplierUpdates.push({
+ id: itemSupplier.id,
unitPrice: line.unitPrice,
conversionFactor: line.conversionFactor ?? 1,
supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
updatedBy: "system",
});
} else {
- partSupplierInserts.push({
- partId: line.partId,
+ itemSupplierInserts.push({
+ itemId: line.itemId,
supplierId: purchaseInvoice.data?.supplierId!,
unitPrice: line.unitPrice,
conversionFactor: line.conversionFactor ?? 1,
@@ -122,30 +123,30 @@ serve(async (req: Request) => {
});
await db.transaction().execute(async (trx) => {
- if (partCostUpdates.length > 0) {
- for await (const partCostUpdate of partCostUpdates) {
+ if (itemCostUpdates.length > 0) {
+ for await (const itemCostUpdate of itemCostUpdates) {
await trx
- .updateTable("partCost")
- .set(partCostUpdate)
- .where("partId", "=", partCostUpdate.partId!)
+ .updateTable("itemCost")
+ .set(itemCostUpdate)
+ .where("itemId", "=", itemCostUpdate.itemId!)
.where("companyId", "=", companyId)
.execute();
}
}
- if (partSupplierInserts.length > 0) {
+ if (itemSupplierInserts.length > 0) {
await trx
- .insertInto("partSupplier")
- .values(partSupplierInserts)
+ .insertInto("itemSupplier")
+ .values(itemSupplierInserts)
.execute();
}
- if (partSupplierUpdates.length > 0) {
- for await (const partSupplierUpdate of partSupplierUpdates) {
+ if (itemSupplierUpdates.length > 0) {
+ for await (const itemSupplierUpdate of itemSupplierUpdates) {
await trx
- .updateTable("partSupplier")
- .set(partSupplierUpdate)
- .where("id", "=", partSupplierUpdate.id!)
+ .updateTable("itemSupplier")
+ .set(itemSupplierUpdate)
+ .where("id", "=", itemSupplierUpdate.id!)
.execute();
}
}
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index b87c0605eb..52f6ed2524 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -84,6 +84,8 @@ CREATE TABLE "item" (
CONSTRAINT "item_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
+ALTER publication supabase_realtime ADD TABLE "item";
+
CREATE INDEX "item_companyId_idx" ON "item" ("companyId");
CREATE INDEX "item_name_companyId_idx" ON "item" ("name", "companyId");
CREATE INDEX "item_type_companyId_idx" ON "item" ("type", "companyId");
diff --git a/packages/database/supabase/migrations/20240412224648_sales-orders.sql b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
index bd2853438a..166b51ea1b 100644
--- a/packages/database/supabase/migrations/20240412224648_sales-orders.sql
+++ b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
@@ -54,15 +54,14 @@ CREATE INDEX "salesOrder_companyId_idx" ON "salesOrder" ("companyId");
CREATE TYPE "salesOrderLineType" AS ENUM (
'Comment',
- 'G/L Account',
- 'Fixed Asset',
'Part',
'Material',
'Tool',
'Hardware',
'Service',
'Consumable',
- 'Fixture'
+ 'Fixture',
+ 'Fixed Asset'
);
CREATE TABLE "salesOrderStatusHistory" (