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.

Inventory (#46)

Brad Barbinc6bdb436fc25
diff --git a/apps/carbon/app/components/Activity.tsx b/apps/carbon/app/components/Activity.tsx
new file mode 100644
index 0000000000..284fe336fd
--- /dev/null
+++ b/apps/carbon/app/components/Activity.tsx
@@ -0,0 +1,49 @@
+import { formatTimeAgo } from "@carbon/utils";
+import { usePeople } from "~/stores";
+import Avatar from "./Avatar";
+
+type ActivityProps = {
+ employeeId: string;
+ activityMessage: string;
+ activityTime: string;
+ activityIcon?: React.ReactNode;
+};
+
+const Activity = ({
+ employeeId,
+ activityMessage,
+ activityTime,
+ activityIcon,
+}: ActivityProps) => {
+ const [people] = usePeople();
+ if (!employeeId) return null;
+
+ const person = people.find((p) => p.id === employeeId);
+
+ return (
+ <li className="relative pl-14 pb-10 flex-grow w-full">
+ <div className="absolute left-0 top-0 flex items-center justify-center w-10 h-10">
+ <Avatar
+ path={person?.avatarUrl ?? undefined}
+ name={person?.name ?? ""}
+ />
+ </div>
+ <div className="flex items-center space-x-4">
+ <div className="flex-grow">
+ <p>
+ <span className="font-semibold mr-2">
+ {person?.name ?? "Deactivated user"}
+ </span>
+ <span className="text-gray-400">{activityMessage}</span>
+ </p>
+ <div className="text-sm text-gray-400 mt-1">
+ {formatTimeAgo(activityTime)}
+ </div>
+ </div>
+ <div className="flex-shrink-0">{activityIcon}</div>
+ </div>
+ </li>
+ );
+};
+
+export default Activity;
diff --git a/apps/carbon/app/components/EmployeeAvatar.tsx b/apps/carbon/app/components/EmployeeAvatar.tsx
index 39c711976c..086eaeb19d 100644
--- a/apps/carbon/app/components/EmployeeAvatar.tsx
+++ b/apps/carbon/app/components/EmployeeAvatar.tsx
@@ -6,11 +6,13 @@ import Avatar from "./Avatar";
type EmployeeAvatarProps = AvatarProps & {
employeeId: string | null;
className?: string;
+ withName: boolean;
};
const EmployeeAvatar = ({
employeeId,
size,
+ withName = true,
className,
...props
}: EmployeeAvatarProps) => {
@@ -23,7 +25,9 @@ const EmployeeAvatar = ({
return (
<HStack>
<Avatar size={"xs"} {...props} />
- <span className="text-muted-foreground">Deactivated user</span>
+ {withName && (
+ <span className="text-muted-foreground">Deactivated user</span>
+ )}
</HStack>
);
}
@@ -39,7 +43,7 @@ const EmployeeAvatar = ({
path={person.avatarUrl ?? undefined}
name={person?.name ?? ""}
/>
- <span className={className}>{person.name}</span>
+ {withName && <span className={className}>{person.name}</span>}
</HStack>
);
};
diff --git a/apps/carbon/app/components/Form/Shelf.tsx b/apps/carbon/app/components/Form/Shelf.tsx
new file mode 100644
index 0000000000..1bae96c223
--- /dev/null
+++ b/apps/carbon/app/components/Form/Shelf.tsx
@@ -0,0 +1,80 @@
+import type { ComboboxProps } from "@carbon/form";
+import { CreatableCombobox } from "@carbon/form";
+import { useDisclosure } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import type { getShelvesList } from "~/modules/inventory";
+
+import { ShelfForm } from "~/modules/inventory";
+import type { ListItem } from "~/types";
+import { path } from "~/utils/path";
+
+type ShelfSelectProps = Omit<ComboboxProps, "options" | "onChange"> & {
+ locationId?: string;
+ onChange?: (shelf: ListItem | null) => void;
+};
+
+const Shelf = (props: ShelfSelectProps) => {
+ const shelvesFetcher =
+ useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();
+
+ const newShelfModal = useDisclosure();
+ const [created, setCreated] = useState<string>("");
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (props?.locationId) {
+ shelvesFetcher.load(path.to.api.shelves(props.locationId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [props.locationId]);
+
+ const options = useMemo(
+ () =>
+ shelvesFetcher.data?.data?.map((c) => ({
+ value: c.id,
+ label: c.name,
+ })) ?? [],
+
+ [shelvesFetcher.data]
+ );
+
+ const onChange = (newValue: { label: string; value: string } | null) => {
+ const shelf =
+ shelvesFetcher.data?.data?.find(
+ (shelf) => shelf.id === newValue?.value
+ ) ?? null;
+
+ props.onChange?.(shelf as ListItem | null);
+ };
+
+ return (
+ <>
+ <CreatableCombobox
+ ref={triggerRef}
+ options={options}
+ {...props}
+ label={props?.label ?? "Shelf"}
+ onChange={onChange}
+ onCreateOption={(option) => {
+ newShelfModal.onOpen();
+ setCreated(option);
+ }}
+ />
+ {newShelfModal.isOpen && (
+ <ShelfForm
+ locationId={props.locationId!}
+ type="modal"
+ onClose={() => {
+ setCreated("");
+ newShelfModal.onClose();
+ triggerRef.current?.click();
+ }}
+ initialValues={{ name: created, locationId: props?.locationId ?? "" }}
+ />
+ )}
+ </>
+ );
+};
+
+export default Shelf;
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index 8c320205d1..bc5301a077 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -53,6 +53,7 @@ import RichText from "./RichText";
import Sequence from "./Sequence";
import SequenceOrCustomId from "./SequenceOrCustomId";
import Service from "./Service";
+import Shelf from "./Shelf";
import Shift from "./Shift";
import ShippingMethod from "./ShippingMethod";
import StandardFactor from "./StandardFactor";
@@ -120,6 +121,7 @@ export {
Sequence,
SequenceOrCustomId,
Service,
+ Shelf,
Shift,
ShippingMethod,
StandardFactor,
diff --git a/apps/carbon/app/components/Icons.tsx b/apps/carbon/app/components/Icons.tsx
index 1671948e92..8ba2f2e797 100644
--- a/apps/carbon/app/components/Icons.tsx
+++ b/apps/carbon/app/components/Icons.tsx
@@ -3,17 +3,17 @@ import { AiOutlinePartition } from "react-icons/ai";
import { FaCodePullRequest } from "react-icons/fa6";
import { HiSquares2X2 } from "react-icons/hi2";
import {
+ LuAtom,
LuExternalLink,
LuGrip,
LuHammer,
LuHardHat,
+ LuHeadphones,
+ LuPizza,
LuShoppingCart,
LuTimer,
} from "react-icons/lu";
-import { CiFries } from "react-icons/ci";
-import { GiIBeam } from "react-icons/gi";
-import { RiCustomerServiceLine } from "react-icons/ri";
import { RxCodesandboxLogo } from "react-icons/rx";
import { TbTargetArrow, TbTargetOff } from "react-icons/tb";
@@ -52,15 +52,15 @@ export const MethodItemTypeIcon = ({
case "Part":
return <AiOutlinePartition className={className} />;
case "Material":
- return <GiIBeam className={className} />;
+ return <LuAtom className={className} />;
case "Tool":
return <LuHammer className={className} />;
case "Fixture":
return <LuGrip className={className} />;
case "Consumable":
- return <CiFries className={className} />;
+ return <LuPizza className={className} />;
case "Service":
- return <RiCustomerServiceLine className={className} />;
+ return <LuHeadphones className={className} />;
}
return <HiSquares2X2 className={cn("text-muted-foreground", className)} />;
diff --git a/apps/carbon/app/components/InfiniteScroll.tsx b/apps/carbon/app/components/InfiniteScroll.tsx
new file mode 100644
index 0000000000..312bd4c0f4
--- /dev/null
+++ b/apps/carbon/app/components/InfiniteScroll.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import { Skeleton } from "@carbon/react";
+import { useEffect } from "react";
+import { useInView } from "react-intersection-observer";
+
+interface InfiniteScrollProps<T extends { id: string }> {
+ component: React.FC<{ item: T }>;
+ items: T[];
+ loadMore: () => Promise<void>;
+ hasMore: boolean;
+}
+
+export function LoadingSkeleton({
+ ref,
+}: {
+ ref?: React.RefObject<HTMLDivElement>;
+}) {
+ return (
+ <>
+ <div ref={ref} className="flex items-center space-x-4 p-4">
+ <Skeleton className="h-8 w-8 rounded-full" />
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-[250px]" />
+ <Skeleton className="h-4 w-[200px]" />
+ </div>
+ </div>
+ <div className="flex items-center space-x-4 p-4">
+ <Skeleton className="h-8 w-8 rounded-full" />
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-[250px]" />
+ <Skeleton className="h-4 w-[200px]" />
+ </div>
+ </div>
+ <div className="flex items-center space-x-4 p-4">
+ <Skeleton className="h-8 w-8 rounded-full" />
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-[250px]" />
+ <Skeleton className="h-4 w-[200px]" />
+ </div>
+ </div>
+ </>
+ );
+}
+
+export default function InfiniteScroll<T extends { id: string }>({
+ component: Component,
+ items,
+ loadMore,
+ hasMore,
+}: InfiniteScrollProps<T>) {
+ const { ref, inView } = useInView({
+ threshold: 0,
+ });
+
+ useEffect(() => {
+ if (inView) {
+ loadMore();
+ }
+ }, [inView, loadMore]);
+
+ return (
+ <div className="w-full">
+ <ul className="relative h-full overflow-y-auto ">
+ {items.map((item) => (
+ <Component key={item.id} item={item} />
+ ))}
+ <div ref={ref}>{hasMore && <LoadingSkeleton />}</div>
+ </ul>
+ </div>
+ );
+}
diff --git a/apps/carbon/app/components/Layout/Navigation/DetailsTopbar.tsx b/apps/carbon/app/components/Layout/Navigation/DetailsTopbar.tsx
index 9f4f61221d..ea33d5c967 100644
--- a/apps/carbon/app/components/Layout/Navigation/DetailsTopbar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/DetailsTopbar.tsx
@@ -10,7 +10,7 @@ import {
import { prettifyKeyboardShortcut } from "@carbon/utils";
import { Link, useNavigate } from "@remix-run/react";
import type { IconType } from "react-icons";
-import { useOptimisticLocation } from "~/hooks";
+import { useOptimisticLocation, useUrlParams } from "~/hooks";
type DetailTopbarProps = {
links: {
@@ -20,16 +20,23 @@ type DetailTopbarProps = {
count?: number;
shortcut?: string;
}[];
+ preserveParams?: boolean;
};
-const DetailTopbar = ({ links }: DetailTopbarProps) => {
+const DetailTopbar = ({ links, preserveParams = false }: DetailTopbarProps) => {
const navigate = useNavigate();
const location = useOptimisticLocation();
+ const [params] = useUrlParams();
useKeyboardShortcuts(
links.reduce<Record<string, () => void>>((acc, link) => {
if (link.shortcut) {
- acc[link.shortcut] = () => navigate(link.to);
+ acc[link.shortcut] = () => {
+ const url = preserveParams
+ ? `${link.to}?${params.toString()}`
+ : link.to;
+ navigate(url);
+ };
}
return acc;
}, {})
@@ -39,12 +46,15 @@ const DetailTopbar = ({ links }: DetailTopbarProps) => {
<div className="inline-flex h-8 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground">
{links.map((route) => {
const isActive = location.pathname.includes(route.to);
+ const linkTo = preserveParams
+ ? `${route.to}?${params.toString()}`
+ : route.to;
return (
<Tooltip key={route.name}>
<TooltipTrigger className="w-full">
<Link
- to={route.to}
+ to={linkTo}
prefetch="intent"
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-xs font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
diff --git a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index d61008eecf..eb51e4ee83 100644
--- a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -23,7 +23,7 @@ const GroupedContentSidebar = ({
spacing={1}
className="border-b border-border p-2"
>
- <h4 className="text-xs text-muted-foreground font-mono pl-4 py-1 uppercase">
+ <h4 className="text-xs text-muted-foreground font-mono pl-2 py-1 uppercase">
{group.name}
</h4>
{group.routes.map((route) => {
diff --git a/apps/carbon/app/components/Layout/Navigation/useModules.tsx b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
index 4bde1981c3..a46a494b37 100644
--- a/apps/carbon/app/components/Layout/Navigation/useModules.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
@@ -1,4 +1,5 @@
import {
+ LuBox,
LuComponent,
LuCreditCard,
LuCrown,
@@ -24,25 +25,13 @@ export function useModules() {
to: path.to.parts,
icon: LuComponent,
},
- // {
- // permission: "jobs",
- // name: "Jobs",
- // to: path.to.jobs,
- // icon: LuCalendarClock,
- // },
- // {
- // permission: "inventory",
- // name: "Inventory",
- // to: path.to.receipts,
- // icon: LuBox,
- // },
- // {
- // permission: "timecards",
- // name: "Timecards",
- // to: path.to.timecards,
- // icon: AiOutlineFieldTime,
- // },
+ {
+ permission: "inventory",
+ name: "Inventory",
+ to: path.to.inventory,
+ icon: LuBox,
+ },
{
permission: "production",
name: "Production",
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index c2704051eb..7fda6218c6 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -679,12 +679,12 @@ const Table = <T extends object>({
<span className="pl-2">
{sorted ? (
sorted === -1 ? (
- <LuArrowUp
+ <LuArrowDown
aria-label="sorted descending"
className="text-primary"
/>
) : (
- <LuArrowDown
+ <LuArrowUp
aria-label="sorted ascending"
className="text-primary"
/>
diff --git a/apps/carbon/app/modules/accounting/accounting.models.ts b/apps/carbon/app/modules/accounting/accounting.models.ts
index f1a337db48..a2d8235533 100644
--- a/apps/carbon/app/modules/accounting/accounting.models.ts
+++ b/apps/carbon/app/modules/accounting/accounting.models.ts
@@ -1,6 +1,10 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
import { months } from "~/modules/shared";
+import {
+ itemLedgerDocumentTypes,
+ itemLedgerTypes,
+} from "../inventory/inventory.models";
export const accountTypes = [
"Posting",
@@ -33,38 +37,6 @@ export const journalLineDocumentType = [
"Return Order",
] as const;
-const itemLedgerTypes = [
- "Purchase",
- "Sale",
- "Positive Adjmt.",
- "Negative Adjmt.",
- "Transfer",
- "Consumption",
- "Output",
- "Assembly Consumption",
- "Assembly Output",
-] as const;
-
-const itemLedgerDocumentTypes = [
- "Sales Shipment",
- "Sales Invoice",
- "Sales Return Receipt",
- "Sales Credit Memo",
- "Purchase Receipt",
- "Purchase Invoice",
- "Purchase Return Shipment",
- "Purchase Credit Memo",
- "Transfer Shipment",
- "Transfer Receipt",
- "Service Shipment",
- "Service Invoice",
- "Service Credit Memo",
- "Posted Assembly",
- "Inventory Receipt",
- "Inventory Shipment",
- "Direct Transfer",
-] as const;
-
export const incomeBalanceTypes = [
"Balance Sheet",
"Income Statement",
@@ -337,18 +309,6 @@ export const defaultIncomeAcountValidator = z.object({
}),
});
-export const itemLedgerValidator = z.object({
- postingDate: zfd.text(z.string().optional()),
- entryType: z.enum(itemLedgerTypes),
- documentType: z.union([z.enum(itemLedgerDocumentTypes), z.undefined()]),
- documentId: z.string().optional(),
- itemId: z.string().min(1, { message: "Item is required" }),
- itemReadableId: z.string().optional(),
- locationId: z.string().optional(),
- shelfId: z.string().optional(),
- quantity: z.number(),
-});
-
export const paymentTermsCalculationMethod = [
"Net",
"End of Month",
diff --git a/apps/carbon/app/modules/accounting/accounting.service.ts b/apps/carbon/app/modules/accounting/accounting.service.ts
index 68b4307fba..d8a15d8745 100644
--- a/apps/carbon/app/modules/accounting/accounting.service.ts
+++ b/apps/carbon/app/modules/accounting/accounting.service.ts
@@ -13,7 +13,6 @@ import type {
defaultBalanceSheetAccountValidator,
defaultIncomeAcountValidator,
fiscalYearSettingsValidator,
- itemLedgerValidator,
paymentTermValidator,
} from "./accounting.models";
import type { Account, Transaction } from "./types";
@@ -643,24 +642,6 @@ export async function getSalesPostingGroups(
return query;
}
-export async function insertPartEntries(
- client: SupabaseClient<Database>,
- itemEntries: (z.infer<typeof itemLedgerValidator> & {
- companyId: string;
- })[]
-) {
- return client.from("itemLedger").insert(itemEntries);
-}
-
-export async function insertItemLedger(
- client: SupabaseClient<Database>,
- itemEntry: z.infer<typeof itemLedgerValidator> & {
- companyId: string;
- }
-) {
- return client.from("itemLedger").insert([itemEntry]);
-}
-
export async function updateDefaultBalanceSheetAccounts(
client: SupabaseClient<Database>,
defaultAccounts: z.infer<typeof defaultBalanceSheetAccountValidator> & {
diff --git a/apps/carbon/app/modules/inventory/inventory.models.ts b/apps/carbon/app/modules/inventory/inventory.models.ts
index 617bdd8570..bb9c6a3d1f 100644
--- a/apps/carbon/app/modules/inventory/inventory.models.ts
+++ b/apps/carbon/app/modules/inventory/inventory.models.ts
@@ -1,6 +1,67 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
+export const itemTypes = [
+ "Part",
+ "Material",
+ "Tool",
+ "Fixture",
+ "Consumable",
+ "Service",
+] as const;
+
+export const itemLedgerTypes = [
+ "Purchase",
+ "Sale",
+ "Positive Adjmt.",
+ "Negative Adjmt.",
+ "Transfer",
+ "Consumption",
+ "Output",
+ "Assembly Consumption",
+ "Assembly Output",
+] as const;
+
+export const itemLedgerDocumentTypes = [
+ "Sales Shipment",
+ "Sales Invoice",
+ "Sales Return Receipt",
+ "Sales Credit Memo",
+ "Purchase Receipt",
+ "Purchase Invoice",
+ "Purchase Return Shipment",
+ "Purchase Credit Memo",
+ "Transfer Shipment",
+ "Transfer Receipt",
+ "Service Shipment",
+ "Service Invoice",
+ "Service Credit Memo",
+ "Posted Assembly",
+ "Inventory Receipt",
+ "Inventory Shipment",
+ "Direct Transfer",
+] as const;
+
+export const inventoryAdjustmentValidator = z.object({
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ locationId: z.string().min(20, { message: "Location is required" }),
+ shelfId: zfd.text(z.string().optional()),
+ adjustmentType: z.enum([...itemLedgerTypes, "Set Quantity"]),
+ quantity: zfd.numeric(z.number()),
+});
+
+export const itemLedgerValidator = z.object({
+ postingDate: zfd.text(z.string().optional()),
+ entryType: z.enum(itemLedgerTypes),
+ documentType: z.union([z.enum(itemLedgerDocumentTypes), z.undefined()]),
+ documentId: z.string().optional(),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ itemReadableId: z.string().optional(),
+ locationId: z.string().optional(),
+ shelfId: z.string().optional(),
+ quantity: z.number(),
+});
+
export const receiptSourceDocumentType = [
// "Sales Order",
// "Sales Invoice",
@@ -29,6 +90,12 @@ export const receiptValidator = z.object({
supplierId: zfd.text(z.string().optional()),
});
+export const shelfValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ locationId: z.string().min(1, { message: "Location ID is required" }),
+});
+
export const shippingCarrierType = [
"UPS",
"FedEx",
diff --git a/apps/carbon/app/modules/inventory/inventory.service.ts b/apps/carbon/app/modules/inventory/inventory.service.ts
index 8597d76cae..1edd2740a4 100644
--- a/apps/carbon/app/modules/inventory/inventory.service.ts
+++ b/apps/carbon/app/modules/inventory/inventory.service.ts
@@ -1,15 +1,112 @@
import type { Database, Json } from "@carbon/database";
import { getLocalTimeZone, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { nanoid } from "nanoid";
import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
+ inventoryAdjustmentValidator,
receiptValidator,
+ shelfValidator,
shippingMethodValidator,
} from "./inventory.models";
+export async function insertManualInventoryAdjustment(
+ client: SupabaseClient<Database>,
+ inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ const { adjustmentType, ...rest } = inventoryAdjustment;
+ const data = {
+ ...rest,
+ entryType:
+ adjustmentType === "Set Quantity" ? "Positive Adjmt." : adjustmentType, // This will be overwritten below
+ };
+
+ // Look up the current quantity for this itemId, locationId, and shelfId
+ const query = client
+ .from("itemInventory")
+ .select("quantityOnHand")
+ .eq("itemId", data.itemId)
+ .eq("locationId", data.locationId);
+
+ if (data.shelfId) {
+ query.eq("shelfId", data.shelfId);
+ }
+
+ const { data: currentQuantity, error: quantityError } =
+ await query.maybeSingle();
+ const currentQuantityOnHand = currentQuantity?.quantityOnHand ?? 0;
+
+ if (quantityError) {
+ return { error: "Failed to fetch current quantity" };
+ }
+
+ if (adjustmentType === "Set Quantity" && currentQuantity) {
+ const quantityDifference = data.quantity - currentQuantityOnHand;
+ if (quantityDifference > 0) {
+ data.entryType = "Positive Adjmt.";
+ data.quantity = quantityDifference;
+ } else if (quantityDifference < 0) {
+ data.entryType = "Negative Adjmt.";
+ data.quantity = Math.abs(quantityDifference);
+ } else {
+ // No change in quantity, we can return early
+ return { data: null };
+ }
+ }
+
+ // Check if it's a negative adjustment and if the quantity is sufficient
+ if (data.entryType === "Negative Adjmt.") {
+ if (data.quantity > currentQuantityOnHand) {
+ return {
+ error: "Insufficient quantity for negative adjustment",
+ };
+ }
+ }
+
+ return client.from("itemLedger").insert([data]).select("*").single();
+}
+
+export async function getItemLedger(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string,
+ locationId: string,
+ sortDescending: boolean = false,
+ page: number = 1
+) {
+ const pageSize = 20;
+ const offset = (page - 1) * pageSize;
+
+ let query = client
+ .from("itemLedger")
+ .select("*, shelf(name)", { count: "exact" })
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .eq("locationId", locationId)
+ .order("createdAt", { ascending: !sortDescending })
+ .range(offset, offset + pageSize - 1);
+
+ const { data, error, count } = await query;
+
+ if (error) {
+ return { error };
+ }
+
+ return {
+ data,
+ count,
+ page,
+ pageSize,
+ hasMore: count !== null && offset + pageSize < count,
+ };
+}
+
export async function deleteReceipt(
client: SupabaseClient<Database>,
receiptId: string
@@ -27,6 +124,26 @@ export async function deleteShippingMethod(
.eq("id", shippingMethodId);
}
+export async function getInventoryItems(
+ client: SupabaseClient<Database>,
+ locationId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client.rpc("get_item_quantities", { location_id: locationId });
+
+ if (args?.search) {
+ query = query.or(
+ `name.ilike.%${args.search}%,readableId.ilike.%${args.search}%`
+ );
+ }
+
+ query = setGenericQueryFilters(query, args);
+
+ return query;
+}
+
export async function getReceipts(
client: SupabaseClient<Database>,
companyId: string,
@@ -68,6 +185,32 @@ export async function getReceiptLines(
return client.from("receiptLine").select("*").eq("receiptId", receiptId);
}
+export async function getShelvesList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("shelf")
+ .select("id, name")
+ .eq("active", true)
+ .eq("companyId", companyId)
+ .order("name");
+}
+
+export async function getShelvesListForLocation(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ locationId: string
+) {
+ return client
+ .from("shelf")
+ .select("id, name")
+ .eq("active", true)
+ .eq("companyId", companyId)
+ .eq("locationId", locationId)
+ .order("name");
+}
+
export async function getShippingMethod(
client: SupabaseClient<Database>,
shippingMethodId: string
@@ -160,6 +303,41 @@ export async function upsertReceipt(
.single();
}
+export async function upsertShelf(
+ client: SupabaseClient<Database>,
+ shelf:
+ | (Omit<z.infer<typeof shelfValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof shelfValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in shelf) {
+ return client
+ .from("shelf")
+ .insert({
+ ...shelf,
+ id: nanoid(),
+ })
+ .select("id")
+ .single();
+ }
+ return client
+ .from("shelf")
+ .update({
+ ...sanitize(shelf),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", shelf.id)
+ .select("id")
+ .single();
+}
+
export async function upsertShippingMethod(
client: SupabaseClient<Database>,
shippingMethod:
diff --git a/apps/carbon/app/modules/inventory/types.ts b/apps/carbon/app/modules/inventory/types.ts
index 820b045474..b9c5cd9204 100644
--- a/apps/carbon/app/modules/inventory/types.ts
+++ b/apps/carbon/app/modules/inventory/types.ts
@@ -1,10 +1,20 @@
import type { Database } from "@carbon/database";
import type {
+ getInventoryItems,
+ getItemLedger,
getReceiptLines,
getReceipts,
getShippingMethods,
} from "./inventory.service";
+export type InventoryItem = NonNullable<
+ Awaited<ReturnType<typeof getInventoryItems>>["data"]
+>[number];
+
+export type ItemLedger = NonNullable<
+ Awaited<ReturnType<typeof getItemLedger>>["data"]
+>[number];
+
export type Receipt = NonNullable<
Awaited<ReturnType<typeof getReceipts>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
new file mode 100644
index 0000000000..8b42f81c41
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
@@ -0,0 +1,46 @@
+import { LuMinusCircle, LuPlusCircle } from "react-icons/lu";
+import Activity from "~/components/Activity";
+import type { ItemLedger } from "../../types";
+
+const getActivityText = (ledgerRecord: ItemLedger) => {
+ switch (ledgerRecord.entryType) {
+ case "Positive Adjmt.":
+ return `made a positive adjustment of ${ledgerRecord.quantity}${
+ ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf?.name}` : ""
+ }`;
+ case "Negative Adjmt.":
+ return `made a negative adjustment of ${ledgerRecord.quantity}${
+ ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""
+ }`;
+ default:
+ return "";
+ }
+};
+
+const getActivityIcon = (ledgerRecord: ItemLedger) => {
+ switch (ledgerRecord.entryType) {
+ case "Positive Adjmt.":
+ return <LuPlusCircle className="text-blue-500 w-5 h-5" />;
+ case "Negative Adjmt.":
+ return <LuMinusCircle className="text-red-500 w-5 h-5" />;
+ default:
+ return "";
+ }
+};
+
+type InventoryActivityProps = {
+ item: ItemLedger;
+};
+
+const InventoryActivity = ({ item }: InventoryActivityProps) => {
+ return (
+ <Activity
+ employeeId={item.createdBy}
+ activityMessage={getActivityText(item)}
+ activityTime={item.createdAt}
+ activityIcon={getActivityIcon(item)}
+ />
+ );
+};
+
+export default InventoryActivity;
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/InventoryDetails.tsx b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryDetails.tsx
new file mode 100644
index 0000000000..155754b095
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryDetails.tsx
@@ -0,0 +1,101 @@
+import {
+ Card,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ VStack,
+} from "@carbon/react";
+import { useLocale } from "@react-aria/i18n";
+import type { z } from "zod";
+import type {
+ ItemQuantities,
+ ItemShelfQuantities,
+ pickMethodValidator,
+ UnitOfMeasureListItem,
+} from "~/modules/items";
+import type { ListItem } from "~/types";
+import InventoryShelves from "./InventoryShelves";
+
+type InventoryDetailsProps = {
+ itemShelfQuantities: ItemShelfQuantities[];
+ itemUnitOfMeasureCode: string;
+ locations: ListItem[];
+ pickMethod: z.infer<typeof pickMethodValidator>;
+ quantities: ItemQuantities | null;
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+};
+
+const InventoryDetails = ({
+ itemShelfQuantities,
+ itemUnitOfMeasureCode,
+ locations,
+ pickMethod,
+ quantities,
+ shelves,
+ unitOfMeasures,
+}: InventoryDetailsProps) => {
+ const { locale } = useLocale();
+ const formatter = Intl.NumberFormat(locale, {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 2,
+ useGrouping: true,
+ });
+
+ return (
+ <VStack>
+ <div className="w-full grid gap-2 grid-cols-1 md:grid-cols-2 lg:grid-cols-2">
+ <Card>
+ <CardHeader className="pb-8">
+ <CardDescription>
+ <VStack>Quantity on Hand</VStack>
+ </CardDescription>
+ <CardTitle className="text-4xl">
+ {`${formatter.format(quantities?.quantityOnHand ?? 0)}`}
+ </CardTitle>
+ </CardHeader>
+ </Card>
+ <Card>
+ <CardHeader className="pb-8">
+ <CardDescription>
+ <VStack>Quantity on Purchase Order</VStack>
+ </CardDescription>
+ <CardTitle className="text-4xl">
+ {`${formatter.format(quantities?.quantityOnPurchaseOrder ?? 0)}`}
+ </CardTitle>
+ </CardHeader>
+ </Card>
+ <Card>
+ <CardHeader className="pb-8">
+ <CardDescription>
+ <VStack>Quantity on Sales Order</VStack>
+ </CardDescription>
+ <CardTitle className="text-4xl">
+ {`${formatter.format(quantities?.quantityOnSalesOrder ?? 0)}`}
+ </CardTitle>
+ </CardHeader>
+ </Card>
+ <Card>
+ <CardHeader className="pb-8">
+ <CardDescription>
+ <VStack>Quantity on Production Order</VStack>
+ </CardDescription>
+ <CardTitle className="text-4xl">
+ {`${formatter.format(quantities?.quantityOnProdOrder ?? 0)}`}
+ </CardTitle>
+ </CardHeader>
+ </Card>
+ </div>
+ <InventoryShelves
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={itemUnitOfMeasureCode}
+ locations={locations}
+ pickMethod={pickMethod}
+ shelves={shelves}
+ unitOfMeasures={unitOfMeasures}
+ />
+ </VStack>
+ );
+};
+
+export default InventoryDetails;
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/InventoryItemHeader.tsx b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryItemHeader.tsx
new file mode 100644
index 0000000000..edb0a81b19
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryItemHeader.tsx
@@ -0,0 +1,43 @@
+import { Button, VStack } from "@carbon/react";
+
+import { useNavigate, useParams } from "@remix-run/react";
+import { LuX } from "react-icons/lu";
+import { DetailsTopbar } from "~/components/Layout";
+import { useUrlParams } from "~/hooks";
+import { path } from "~/utils/path";
+import { useInventoryNavigation } from "./useInventoryNavigation";
+
+type InventoryItemHeaderProps = {
+ itemReadableId: string;
+};
+
+const InventoryItemHeader = ({ itemReadableId }: InventoryItemHeaderProps) => {
+ const links = useInventoryNavigation();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
+ const [params] = useUrlParams();
+
+ const navigate = useNavigate();
+
+ return (
+ <div>
+ <VStack className="w-full">
+ <div className="flex justify-between items-center border-b border-border p-2 bg-card w-full">
+ <Button
+ isIcon
+ variant="ghost"
+ onClick={() =>
+ navigate(`${path.to.inventory}?${params.toString()}`)
+ }
+ >
+ <LuX className="w-4 h-4" />
+ </Button>
+ <span className="font-semibold text-center">{itemReadableId}</span>
+ <DetailsTopbar links={links} preserveParams />
+ </div>
+ </VStack>
+ </div>
+ );
+};
+
+export default InventoryItemHeader;
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/InventoryShelves.tsx b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
new file mode 100644
index 0000000000..5235551f3a
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
@@ -0,0 +1,189 @@
+import { Hidden, Submit, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+ useDisclosure,
+ VStack,
+} from "@carbon/react";
+import { Outlet } from "@remix-run/react";
+import { useMemo } from "react";
+import type { z } from "zod";
+import { Enumerable } from "~/components/Enumerable";
+import { Input, Location, Number, Select, Shelf } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import type {
+ ItemShelfQuantities,
+ pickMethodValidator,
+ UnitOfMeasureListItem,
+} from "~/modules/items";
+import type { ListItem } from "~/types";
+import { path } from "~/utils/path";
+import { inventoryAdjustmentValidator } from "../../inventory.models";
+
+type InventoryShelvesProps = {
+ pickMethod: z.infer<typeof pickMethodValidator>;
+ itemShelfQuantities: ItemShelfQuantities[];
+ itemUnitOfMeasureCode: string;
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+};
+
+const InventoryShelves = ({
+ itemShelfQuantities,
+ itemUnitOfMeasureCode,
+ locations,
+ pickMethod,
+ shelves,
+ unitOfMeasures,
+}: InventoryShelvesProps) => {
+ const permissions = usePermissions();
+ const adjustmentModal = useDisclosure();
+
+ const itemUnitOfMeasure = useMemo(
+ () => unitOfMeasures.find((unit) => unit.code === itemUnitOfMeasureCode),
+ [itemUnitOfMeasureCode, unitOfMeasures]
+ );
+
+ return (
+ <>
+ <Card className="w-full">
+ <HStack className="w-full justify-between">
+ <CardHeader>
+ <CardTitle>Shelves</CardTitle>
+ </CardHeader>
+ <CardAction>
+ <Button onClick={adjustmentModal.onOpen}>Update Inventory</Button>
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <Table className="table-fixed">
+ <Thead>
+ <Tr>
+ <Th>Location</Th>
+ <Th>Shelf</Th>
+ <Th>QoH</Th>
+ <Th>UoM</Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {itemShelfQuantities.map((item, index) => (
+ <Tr key={index}>
+ <Td>
+ <Enumerable
+ value={
+ locations.find((loc) => loc.id === item.locationId)
+ ?.name ?? null
+ }
+ />
+ </Td>
+ <Td>
+ {shelves.find((s) => s.id === item.shelfId)?.name ||
+ item.shelfId}
+ </Td>
+ <Td>{item.quantityOnHand}</Td>
+ <Td>
+ {unitOfMeasures.find(
+ (uom) => uom.code === itemUnitOfMeasureCode
+ )?.name || itemUnitOfMeasureCode}
+ </Td>
+ </Tr>
+ ))}
+ </Tbody>
+ </Table>
+ </CardContent>
+ </Card>
+ {adjustmentModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ adjustmentModal.onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ validator={inventoryAdjustmentValidator}
+ action={path.to.inventoryItemAdjustment(pickMethod.itemId)}
+ defaultValues={{
+ itemId: pickMethod.itemId,
+ locationId: pickMethod.locationId,
+ shelfId: pickMethod.defaultShelfId,
+ adjustmentType: "Set Quantity",
+ }}
+ onSubmit={adjustmentModal.onClose}
+ >
+ <ModalHeader>
+ <ModalTitle>Inventory Adjustment</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="itemId" />
+
+ <VStack spacing={2}>
+ <Location name="locationId" label="Location" isReadOnly />
+ <Shelf
+ name="shelfId"
+ locationId={pickMethod.locationId}
+ label="Shelf"
+ />
+ <Select
+ name="adjustmentType"
+ label="Adjustment Type"
+ options={[
+ { label: "Set Quantity", value: "Set Quantity" },
+ {
+ label: "Positive Adjustment",
+ value: "Positive Adjmt.",
+ },
+ {
+ label: "Negative Adjustment",
+ value: "Negative Adjmt.",
+ },
+ ]}
+ />
+ <Number name="quantity" label="Quantity" minValue={0} />
+ <Input
+ name="unitOfMeasure"
+ label="Unit of Measure"
+ value={itemUnitOfMeasure?.name ?? ""}
+ isReadOnly
+ />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button onClick={adjustmentModal.onClose} variant="secondary">
+ Cancel
+ </Button>
+ <Submit isDisabled={!permissions.can("update", "inventory")}>
+ Save
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+ <Outlet />
+ </>
+ );
+};
+
+export default InventoryShelves;
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryTable.tsx
new file mode 100644
index 0000000000..187391c8a3
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -0,0 +1,233 @@
+import { Combobox, HStack, Heading, VStack } from "@carbon/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import {
+ Hyperlink,
+ ItemThumbnail,
+ MethodItemTypeIcon,
+ New,
+ Table,
+} from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useFilters } from "~/components/Table/components/Filter/useFilters";
+import { useUrlParams } from "~/hooks";
+import type { UnitOfMeasureListItem } from "~/modules/items";
+import type { ListItem } from "~/types";
+import { path } from "~/utils/path";
+import { itemTypes } from "../../inventory.models";
+import type { InventoryItem } from "../../types";
+
+type InventoryTableProps = {
+ data: InventoryItem[];
+ count: number;
+ locationId: string;
+ locations: ListItem[];
+ forms: ListItem[];
+ substances: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+};
+
+const InventoryTable = memo(
+ ({
+ data,
+ count,
+ locationId,
+ locations,
+ unitOfMeasures,
+ forms,
+ substances,
+ }: InventoryTableProps) => {
+ const { hasFilters } = useFilters();
+ const [params] = useUrlParams();
+
+ const locationOptions = locations.map((location) => ({
+ label: location.name,
+ value: location.id,
+ }));
+
+ const columns = useMemo<ColumnDef<InventoryItem>[]>(() => {
+ return [
+ {
+ accessorKey: "readableId",
+ header: "Item ID",
+ cell: ({ row }) => (
+ <HStack className="py-1">
+ <ItemThumbnail thumbnailPath={row.original.thumbnailPath} />
+ <Hyperlink
+ to={`${path.to.inventoryItem(row.original.itemId!)}/?${params}`}
+ className="max-w-[260px] truncate"
+ >
+ <>{row.original.readableId}</>
+ </Hyperlink>
+ </HStack>
+ ),
+ },
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: ({ row }) =>
+ row.original.type && (
+ <HStack>
+ <MethodItemTypeIcon type={row.original.type} />
+ <span>{row.original.type}</span>
+ </HStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: itemTypes.map((type) => ({
+ label: (
+ <HStack spacing={2}>
+ <MethodItemTypeIcon type={type} />
+ <span>{type}</span>
+ </HStack>
+ ),
+ value: type,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => row.original.name,
+ },
+ {
+ accessorKey: "locationName",
+ header: "Location",
+ cell: ({ row }) => <Enumerable value={row.original.locationName} />,
+ },
+ {
+ accessorKey: "unitOfMeasureCode",
+ header: "Unit of Measure",
+ cell: ({ row }) => {
+ const unitOfMeasure = unitOfMeasures.find(
+ (uom) => uom.code === row.original.unitOfMeasureCode
+ );
+ return unitOfMeasure
+ ? unitOfMeasure.name
+ : row.original.unitOfMeasureCode;
+ },
+ },
+ {
+ accessorKey: "materialFormId",
+ header: "Form",
+ cell: ({ row }) => {
+ const form = forms.find(
+ (f) => f.id === row.original.materialFormId
+ );
+ return <Enumerable value={form?.name ?? null} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: forms.map((form) => ({
+ label: <Enumerable value={form.name} />,
+ value: form.id,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "materialSubstanceId",
+ header: "Substance",
+ cell: ({ row }) => {
+ const substance = substances.find(
+ (s) => s.id === row.original.materialSubstanceId
+ );
+ return <Enumerable value={substance?.name ?? null} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: substances.map((substance) => ({
+ label: <Enumerable value={substance.name ?? null} />,
+ value: substance.id,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "quantityOnHand",
+ header: "On Hand",
+ cell: ({ row }) => row.original.quantityOnHand,
+ },
+
+ {
+ accessorKey: "quantityOnPurchaseOrder",
+ header: "On Purchase Order",
+ cell: ({ row }) => row.original.quantityOnPurchaseOrder,
+ },
+ {
+ accessorKey: "quantityOnProdOrder",
+ header: "On Prod Order",
+ cell: ({ row }) => row.original.quantityOnProdOrder,
+ },
+ {
+ accessorKey: "quantityOnSalesOrder",
+ header: "On Sales Order",
+ cell: ({ row }) => row.original.quantityOnSalesOrder,
+ },
+ ];
+ }, [forms, params, substances, unitOfMeasures]);
+
+ const actions = useMemo(() => {
+ return [];
+ }, []);
+
+ const defaultColumnVisibility = {
+ readableId: true,
+ type: true,
+ name: true,
+ description: true,
+ };
+
+ return (
+ <>
+ {count === 0 && !hasFilters ? (
+ <HStack className="w-full h-screen flex items-start justify-center">
+ <VStack className="border rounded-md shadow-md w-96 mt-20">
+ <div className="w-full flex flex-col gap-4 items-center justify-center py-8 bg-gradient-to-bl from-card to-background rounded-lg text-center group ring-4 ring-transparent hover:ring-white/10">
+ <Heading size="h2">No Items Yet</Heading>
+ <p className="text-muted-foreground text-base font-light">
+ Start by creating your first part
+ </p>
+ <New label="Part" to={path.to.newPart} />
+ </div>
+ </VStack>
+ </HStack>
+ ) : (
+ <>
+ <Table<InventoryItem>
+ actions={actions}
+ count={count}
+ columns={columns}
+ data={data}
+ defaultColumnVisibility={defaultColumnVisibility}
+ primaryAction={
+ <Combobox
+ size="sm"
+ value={locationId}
+ options={locationOptions}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ className="w-64"
+ />
+ }
+ />
+ </>
+ )}
+ </>
+ );
+ }
+);
+
+InventoryTable.displayName = "InventoryTable";
+
+export default InventoryTable;
+
+function getLocationPath(locationId: string) {
+ return `${path.to.inventory}?location=${locationId}`;
+}
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/index.ts b/apps/carbon/app/modules/inventory/ui/Inventory/index.ts
new file mode 100644
index 0000000000..9a7ae07ca0
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/index.ts
@@ -0,0 +1,4 @@
+import InventoryActivity from "./InventoryActivity";
+import InventoryDetails from "./InventoryDetails";
+
+export { InventoryActivity, InventoryDetails };
diff --git a/apps/carbon/app/modules/inventory/ui/Inventory/useInventoryNavigation.tsx b/apps/carbon/app/modules/inventory/ui/Inventory/useInventoryNavigation.tsx
new file mode 100644
index 0000000000..8524d22481
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Inventory/useInventoryNavigation.tsx
@@ -0,0 +1,28 @@
+import { useParams } from "@remix-run/react";
+
+import { LuFileBarChart, LuFileText } from "react-icons/lu";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+
+export function useInventoryNavigation() {
+ usePermissions();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
+
+ return [
+ {
+ name: "Details",
+ to: path.to.inventoryItem(itemId),
+ role: ["employee"],
+ icon: LuFileText,
+ shortcut: "Command+Shift+d",
+ },
+ {
+ name: "Activity",
+ to: path.to.inventoryItemActivity(itemId),
+ role: ["employee"],
+ icon: LuFileBarChart,
+ shortcut: "Command+Shift+a",
+ },
+ ];
+}
diff --git a/apps/carbon/app/modules/inventory/ui/Shelves/ShelfForm.tsx b/apps/carbon/app/modules/inventory/ui/Shelves/ShelfForm.tsx
new file mode 100644
index 0000000000..df7b113325
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Shelves/ShelfForm.tsx
@@ -0,0 +1,98 @@
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack,
+} from "@carbon/react";
+
+import { ValidatedForm } from "@carbon/form";
+import { useFetcher } from "@remix-run/react";
+import type { z } from "zod";
+import { Hidden, Input, Location, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { shelfValidator } from "~/modules/inventory";
+import { path } from "~/utils/path";
+
+type ShelfFormProps = {
+ locationId: string;
+ initialValues: z.infer<typeof shelfValidator>;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: () => void;
+};
+
+const ShelfForm = ({
+ locationId,
+ initialValues,
+ open = true,
+ type = "drawer",
+ onClose,
+}: ShelfFormProps) => {
+ const fetcher = useFetcher<{}>();
+
+ const permissions = usePermissions();
+ const isEditing = !!initialValues?.id;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "sales")
+ : !permissions.can("create", "sales");
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={shelfValidator}
+ method="post"
+ action={
+ isEditing ? path.to.shelf(initialValues.id!) : path.to.newShelf
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ onSubmit={() => {
+ if (type === "modal") {
+ onClose?.();
+ }
+ }}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Shelf
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <Location name="locationId" label="Location" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default ShelfForm;
diff --git a/apps/carbon/app/modules/inventory/ui/Shelves/index.ts b/apps/carbon/app/modules/inventory/ui/Shelves/index.ts
new file mode 100644
index 0000000000..a538fd0250
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Shelves/index.ts
@@ -0,0 +1,3 @@
+import ShelfForm from "./ShelfForm";
+
+export { ShelfForm };
diff --git a/apps/carbon/app/modules/inventory/ui/index.ts b/apps/carbon/app/modules/inventory/ui/index.ts
index 78c1a96b85..df10a78433 100644
--- a/apps/carbon/app/modules/inventory/ui/index.ts
+++ b/apps/carbon/app/modules/inventory/ui/index.ts
@@ -1,5 +1,6 @@
import useInventorySubmodules from "./useInventorySubmodules";
-
+export * from "./Inventory";
export * from "./Receipts";
+export * from "./Shelves";
export * from "./ShippingMethods";
export { useInventorySubmodules };
diff --git a/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx
index c1b91093dd..9f2ac40f1f 100644
--- a/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -7,25 +7,30 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [
name: "Manage",
routes: [
{
- name: "Receipts",
- to: path.to.receipts,
+ name: "Inventory",
+ to: path.to.inventory,
+ role: "employee",
},
// {
+ // name: "Receipts",
+ // to: path.to.receipts,
+ // },
+ // {
// name: "Shipments",
// to: path.to.shipments,
// },
],
},
- {
- name: "Configure",
- routes: [
- {
- name: "Shipping Methods",
- to: path.to.shippingMethods,
- role: "employee",
- },
- ],
- },
+ // {
+ // name: "Configure",
+ // routes: [
+ // {
+ // name: "Shipping Methods",
+ // to: path.to.shippingMethods,
+ // role: "employee",
+ // },
+ // ],
+ // },
];
export default function useAccountingSubmodules() {
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
index a336e9a3ec..d576a982c9 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
@@ -14,8 +14,8 @@ import {
} from "@carbon/react";
import { ValidatedForm } from "@carbon/form";
-import { useFetcher, useNavigate, useParams } from "@remix-run/react";
-import { useEffect, useMemo, useState } from "react";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useState } from "react";
import type { z } from "zod";
import {
Account,
@@ -26,6 +26,7 @@ import {
Item,
NumberControlled,
Select,
+ Shelf,
Submit,
UnitOfMeasure,
} from "~/components/Form";
@@ -39,7 +40,6 @@ import {
purchaseInvoiceLineType,
purchaseInvoiceLineValidator,
} from "~/modules/invoicing";
-import type { getShelvesList } from "~/modules/items";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
@@ -99,24 +99,6 @@ const PurchaseInvoiceLineForm = ({
minimumOrderQuantity: undefined,
});
- const shelfFetcher = useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();
-
- useEffect(() => {
- if (locationId) {
- shelfFetcher.load(path.to.api.shelves(locationId));
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [locationId]);
-
- const shelfOptions = useMemo(
- () =>
- shelfFetcher.data?.data?.map((shelf) => ({
- label: shelf.id,
- value: shelf.id,
- })) ?? [],
- [shelfFetcher.data]
- );
-
const isEditing = initialValues.id !== undefined;
const isDisabled = !isEditable
? true
@@ -429,16 +411,16 @@ const PurchaseInvoiceLineForm = ({
"Consumable",
"Fixed Asset",
].includes(type) && (
- <ComboboxControlled
+ <Shelf
name="shelfId"
label="Shelf"
- options={shelfOptions}
- value={itemData.shelfId ?? ""}
+ locationId={locationId}
+ value={itemData.shelfId ?? undefined}
onChange={(newValue) => {
if (newValue) {
setItemData((d) => ({
...d,
- shelfId: newValue.value,
+ shelfId: newValue?.id,
}));
}
}}
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 2d4f74b6ad..cd77052a7b 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -397,12 +397,23 @@ export async function getItemQuantities(
locationId: string
) {
return client
- .from("itemQuantities")
+ .rpc("get_item_quantities", { location_id: locationId })
+ .eq("itemId", itemId)
+ .maybeSingle();
+}
+
+export async function getItemShelfQuantities(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string,
+ locationId: string
+) {
+ return client
+ .from("itemInventory")
.select("*")
.eq("itemId", itemId)
.eq("companyId", companyId)
- .eq("locationId", locationId)
- .maybeSingle();
+ .eq("locationId", locationId);
}
export async function getItemUnitSalePrice(
@@ -861,18 +872,6 @@ export async function getServicesList(
return query;
}
-export async function getShelvesList(
- client: SupabaseClient<Database>,
- locationId: string
-) {
- return client
- .from("shelf")
- .select("id")
- .eq("active", true)
- .eq("locationId", locationId)
- .order("id");
-}
-
export async function getTool(
client: SupabaseClient<Database>,
itemId: string,
@@ -999,41 +998,6 @@ export async function getModelUploadByUrn(
.single();
}
-export async function insertShelf(
- client: SupabaseClient<Database>,
- shelfId: string,
- locationId: string,
- userId: string,
- companyId: string
-) {
- const shelfLookup = await client
- .from("shelf")
- .select("id")
- .eq("id", shelfId)
- .eq("locationId", locationId)
- .maybeSingle();
- if (shelfLookup.error) return shelfLookup;
-
- // the shelf is inactive, so we can just reactivate it
- if (shelfLookup.data) {
- return client.from("shelf").update({ active: true }).eq("id", shelfId);
- }
-
- // otherwise we'll create a new shelf
- return client
- .from("shelf")
- .insert([
- {
- id: shelfId,
- companyId,
- locationId,
- createdBy: userId,
- },
- ])
- .select("id")
- .single();
-}
-
export async function updateItemCost(
client: SupabaseClient<Database>,
itemId: string,
diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.ts
index af9644fa1f..9c0b161779 100644
--- a/apps/carbon/app/modules/items/types.ts
+++ b/apps/carbon/app/modules/items/types.ts
@@ -9,6 +9,7 @@ import type {
getItemPostingGroups,
getItemPostingGroupsList,
getItemQuantities,
+ getItemShelfQuantities,
getMakeMethod,
getMaterialForms,
getMaterialSubstances,
@@ -71,6 +72,10 @@ export type ItemQuantities = NonNullable<
Awaited<ReturnType<typeof getItemQuantities>>["data"]
>;
+export type ItemShelfQuantities = NonNullable<
+ Awaited<ReturnType<typeof getItemShelfQuantities>>["data"]
+>[number];
+
export type ItemReorderingPolicy =
Database["public"]["Enums"]["itemReorderingPolicy"];
diff --git a/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx b/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx
index fe6e445d84..4a40b2b057 100644
--- a/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx
@@ -167,11 +167,7 @@ const ConsumableProperties = () => {
<MethodBadge
key={method.locationId}
type="Pick"
- text={
- method.defaultShelfId ??
- locations.find((l) => l.id === method.locationId)?.name ??
- ""
- }
+ text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
to={path.to.partInventoryLocation(itemId, method.locationId)}
/>
))}
diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixtureHeader.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixtureHeader.tsx
index 40a391de97..57e2174f86 100644
--- a/apps/carbon/app/modules/items/ui/Fixtures/FixtureHeader.tsx
+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixtureHeader.tsx
@@ -18,7 +18,7 @@ const FixtureHeader = () => {
);
return (
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
<VStack spacing={0} className="flex-grow">
<HStack>
<Link to={path.to.fixtureDetails(itemId)}>
diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx
index 2f8a8e4c63..68c4a04893 100644
--- a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx
@@ -193,11 +193,7 @@ const FixtureProperties = () => {
<MethodBadge
key={method.locationId}
type="Pick"
- text={
- method.defaultShelfId ??
- locations.find((l) => l.id === method.locationId)?.name ??
- ""
- }
+ text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
to={path.to.fixtureInventoryLocation(itemId, method.locationId)}
/>
))}
diff --git a/apps/carbon/app/modules/items/ui/Item/PickMethodForm.tsx b/apps/carbon/app/modules/items/ui/Item/PickMethodForm.tsx
index 123cb0de7f..8fe40f4879 100644
--- a/apps/carbon/app/modules/items/ui/Item/PickMethodForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/PickMethodForm.tsx
@@ -9,43 +9,37 @@ import {
Combobox,
HStack,
} from "@carbon/react";
-import { useRevalidator } from "@remix-run/react";
import type { z } from "zod";
import {
CreatableCombobox,
CustomFormFields,
Hidden,
- Number,
Submit,
} from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
-import type { ItemQuantities } from "~/modules/items";
+import { usePermissions } from "~/hooks";
import { pickMethodValidator } from "~/modules/items";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
type PickMethodFormProps = {
initialValues: z.infer<typeof pickMethodValidator>;
- quantities: ItemQuantities;
locations: ListItem[];
- shelves: string[];
+ shelves: ListItem[];
type: "Part" | "Material" | "Tool" | "Fixture" | "Consumable";
};
const PickMethodForm = ({
initialValues,
locations,
- quantities,
shelves,
type,
}: PickMethodFormProps) => {
const permissions = usePermissions();
- const { supabase } = useSupabase();
- const user = useUser();
- const revalidator = useRevalidator();
- const shelfOptions = shelves.map((shelf) => ({ value: shelf, label: shelf }));
+ const shelfOptions = shelves.map((shelf) => ({
+ value: shelf.id,
+ label: shelf.name,
+ }));
const locationOptions = locations.map((location) => ({
label: location.name,
value: location.id,
@@ -56,7 +50,7 @@ const PickMethodForm = ({
<ValidatedForm
method="post"
validator={pickMethodValidator}
- defaultValues={{ ...quantities, ...initialValues }}
+ defaultValues={initialValues}
>
<HStack className="w-full justify-between items-start">
<CardHeader>
@@ -88,42 +82,9 @@ const PickMethodForm = ({
name="defaultShelfId"
label="Default Shelf"
options={shelfOptions}
- onCreateOption={async (option) => {
- const response = await supabase?.from("shelf").insert({
- id: option,
- companyId: user.company.id,
- locationId: initialValues.locationId,
- createdBy: user.id,
- });
- if (response && response.error === null)
- revalidator.revalidate();
- }}
className="w-full"
/>
- <Number name="quantityOnHand" label="Quantity On Hand" isReadOnly />
-
- <Number
- name="quantityAvailable"
- label="Quantity Available"
- isReadOnly
- />
- <Number
- name="quantityOnPurchaseOrder"
- label="Quantity On Purchase Order"
- isReadOnly
- />
-
- <Number
- name="quantityOnProdOrder"
- label="Quantity On Prod Order"
- isReadOnly
- />
- <Number
- name="quantityOnSalesOrder"
- label="Quantity On Sales Order"
- isReadOnly
- />
<CustomFormFields table="partInventory" />
</div>
</CardContent>
diff --git a/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx
index e3184fc39e..d1f92486dc 100644
--- a/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx
@@ -177,11 +177,7 @@ const MaterialProperties = () => {
<MethodBadge
key={method.locationId}
type="Pick"
- text={
- method.defaultShelfId ??
- locations.find((l) => l.id === method.locationId)?.name ??
- ""
- }
+ text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
to={path.to.partInventoryLocation(itemId, method.locationId)}
/>
))}
diff --git a/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx
index 5d35f46463..e3a230b67a 100644
--- a/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx
+++ b/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx
@@ -1,6 +1,7 @@
import {
Badge,
Checkbox,
+ HStack,
MenuIcon,
MenuItem,
useDisclosure,
@@ -51,9 +52,11 @@ const MaterialsTable = memo(({ data, count }: MaterialsTableProps) => {
accessorKey: "id",
header: "Material ID",
cell: ({ row }) => (
- <Hyperlink to={path.to.materialDetails(row.original.itemId!)}>
- {row.original.id}
- </Hyperlink>
+ <HStack className="py-1">
+ <Hyperlink to={path.to.materialDetails(row.original.itemId!)}>
+ {row.original.id}
+ </Hyperlink>
+ </HStack>
),
},
{
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartHeader.tsx b/apps/carbon/app/modules/items/ui/Parts/PartHeader.tsx
index ba5211843c..0c3d8fe79a 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartHeader.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartHeader.tsx
@@ -18,7 +18,7 @@ const PartHeader = () => {
);
return (
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
<VStack spacing={0} className="flex-grow">
<HStack>
<Link to={path.to.partDetails(itemId)}>
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx
index 4890ac459d..f705c73c7a 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx
@@ -189,11 +189,7 @@ const PartProperties = () => {
<MethodBadge
key={method.locationId}
type="Pick"
- text={
- method.defaultShelfId ??
- locations.find((l) => l.id === method.locationId)?.name ??
- ""
- }
+ text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
to={path.to.partInventoryLocation(itemId, method.locationId)}
/>
))}
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx b/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx
index c62af1324b..9c59e050fc 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx
@@ -1,6 +1,7 @@
import {
Badge,
Checkbox,
+ HStack,
MenuIcon,
MenuItem,
useDisclosure,
@@ -13,6 +14,7 @@ import { LuPencil, LuTrash } from "react-icons/lu";
import {
EmployeeAvatar,
Hyperlink,
+ ItemThumbnail,
MethodIcon,
New,
Table,
@@ -51,9 +53,12 @@ const PartsTable = memo(({ data, count }: PartsTableProps) => {
accessorKey: "id",
header: "Part ID",
cell: ({ row }) => (
- <Hyperlink to={path.to.partDetails(row.original.itemId!)}>
- {row.original.id}
- </Hyperlink>
+ <HStack className="py-1">
+ <ItemThumbnail thumbnailPath={row.original.thumbnailPath} />
+ <Hyperlink to={path.to.partDetails(row.original.itemId!)}>
+ {row.original.id}
+ </Hyperlink>
+ </HStack>
),
},
{
diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolHeader.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolHeader.tsx
index 724212f371..5f43ac5d24 100644
--- a/apps/carbon/app/modules/items/ui/Tools/ToolHeader.tsx
+++ b/apps/carbon/app/modules/items/ui/Tools/ToolHeader.tsx
@@ -16,7 +16,7 @@ const ToolHeader = () => {
const routeData = useRouteData<{ toolSummary: Tool }>(path.to.tool(itemId));
return (
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
<VStack spacing={0} className="flex-grow">
<HStack>
<Link to={path.to.toolDetails(itemId)}>
diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx
index d51a74ba06..a258b369f4 100644
--- a/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx
@@ -165,11 +165,7 @@ const ToolProperties = () => {
<MethodBadge
key={method.locationId}
type="Pick"
- text={
- method.defaultShelfId ??
- locations.find((l) => l.id === method.locationId)?.name ??
- ""
- }
+ text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
to={path.to.partInventoryLocation(itemId, method.locationId)}
/>
))}
diff --git a/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx b/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
index ef91dea8d8..d314f0e8a5 100644
--- a/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
+++ b/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
@@ -1,9 +1,15 @@
import { AiOutlinePartition } from "react-icons/ai";
-import { CiFries } from "react-icons/ci";
-import { GiIBeam, GiWoodBeam } from "react-icons/gi";
-import { LuGrip, LuHammer, LuRuler, LuShapes } from "react-icons/lu";
+import { GiWoodBeam } from "react-icons/gi";
+import {
+ LuAtom,
+ LuGrip,
+ LuHammer,
+ LuHeadphones,
+ LuPizza,
+ LuRuler,
+ LuShapes,
+} from "react-icons/lu";
import { PiPiggyBank } from "react-icons/pi";
-import { RiCustomerServiceLine } from "react-icons/ri";
import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -20,7 +26,7 @@ const itemsRoutes: AuthenticatedRouteGroup[] = [
{
name: "Materials",
to: path.to.materials,
- icon: <GiIBeam />,
+ icon: <LuAtom />,
},
{
name: "Tools",
@@ -35,12 +41,12 @@ const itemsRoutes: AuthenticatedRouteGroup[] = [
{
name: "Consumables",
to: path.to.consumables,
- icon: <CiFries />,
+ icon: <LuPizza />,
},
{
name: "Services",
to: path.to.services,
- icon: <RiCustomerServiceLine />,
+ icon: <LuHeadphones />,
},
// {
// name: "Routing",
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
index 95517b95d4..e7230d6eac 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -71,6 +71,7 @@ const JobHeader = () => {
const currentValue = getOptionFromPath();
return (
+
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
<HStack>
<Link to={path.to.jobDetails(jobId)}>
@@ -82,7 +83,6 @@ const JobHeader = () => {
<Copy text={routeData?.job?.jobId ?? ""} />
<JobStatus status={routeData?.job?.status} />
</HStack>
-
<HStack>
<Assignee
id={jobId}
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index 46f0ac6814..fdbd8894b9 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -14,8 +14,8 @@ import {
} from "@carbon/react";
import { ValidatedForm } from "@carbon/form";
-import { useFetcher, useNavigate, useParams } from "@remix-run/react";
-import { useEffect, useMemo, useState } from "react";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useState } from "react";
import type { z } from "zod";
import {
Account,
@@ -26,12 +26,12 @@ import {
Item,
NumberControlled,
Select,
+ Shelf,
Submit,
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
-import type { getShelvesList } from "~/modules/items";
import type {
PurchaseOrder,
PurchaseOrderLineType,
@@ -98,24 +98,6 @@ const PurchaseOrderLineForm = ({
minimumOrderQuantity: undefined,
});
- const shelfFetcher = useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();
-
- useEffect(() => {
- if (locationId) {
- shelfFetcher.load(path.to.api.shelves(locationId));
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [locationId]);
-
- const shelfOptions = useMemo(
- () =>
- shelfFetcher.data?.data?.map((shelf) => ({
- label: shelf.id,
- value: shelf.id,
- })) ?? [],
- [shelfFetcher.data]
- );
-
const isEditing = initialValues.id !== undefined;
const isDisabled = !isEditable
? true
@@ -420,16 +402,16 @@ const PurchaseOrderLineForm = ({
"Consumable",
"Fixed Asset",
].includes(type) && (
- <ComboboxControlled
+ <Shelf
name="shelfId"
label="Shelf"
- options={shelfOptions}
- value={itemData.shelfId ?? ""}
+ locationId={locationId}
+ value={itemData.shelfId ?? undefined}
onChange={(newValue) => {
if (newValue) {
setItemData((d) => ({
...d,
- shelfId: newValue.value,
+ shelfId: newValue?.id,
}));
}
}}
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm.tsx
index dd3a5d5ad6..7f61a113ce 100644
--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm.tsx
@@ -1,12 +1,13 @@
import {
Button,
- Drawer,
- DrawerBody,
- DrawerContent,
- DrawerFooter,
- DrawerHeader,
- DrawerTitle,
HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
VStack,
toast,
} from "@carbon/react";
@@ -58,54 +59,58 @@ const SupplierLocationForm = ({
: !permissions.can("create", "purchasing");
return (
- <Drawer
- open={open}
- onOpenChange={(open) => {
- if (!open) onClose?.();
- }}
- >
- <DrawerContent>
- <ValidatedForm
- validator={supplierLocationValidator}
- method="post"
- action={
- isEditing
- ? path.to.supplierLocation(supplierId, initialValues.id!)
- : path.to.newSupplierLocation(supplierId)
- }
- defaultValues={initialValues}
- fetcher={fetcher}
- className="flex flex-col h-full"
- >
- <DrawerHeader>
- <DrawerTitle>{isEditing ? "Edit" : "New"} Location</DrawerTitle>
- </DrawerHeader>
- <DrawerBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
- <Hidden name="addressId" />
- <VStack spacing={4}>
- <Input name="name" label="Name" />
- <Input name="addressLine1" label="Address Line 1" />
- <Input name="addressLine2" label="Address Line 2" />
- <Input name="city" label="City" />
- <Input name="state" label="State" />
- <Input name="postalCode" label="Zip Code" />
- {/* Country dropdown */}
- <CustomFormFields table="supplierLocation" />
- </VStack>
- </DrawerBody>
- <DrawerFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- <Button size="md" variant="solid" onClick={onClose}>
- Cancel
- </Button>
- </HStack>
- </DrawerFooter>
- </ValidatedForm>
- </DrawerContent>
- </Drawer>
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={supplierLocationValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.supplierLocation(supplierId, initialValues.id!)
+ : path.to.newSupplierLocation(supplierId)
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Location
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <Hidden name="addressId" />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ {/* Country dropdown */}
+ <CustomFormFields table="supplierLocation" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
);
};
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index e964fdc52e..49a4400092 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -486,6 +486,7 @@ export const salesOrderStatusType = [
"Completed",
"Invoiced",
"Cancelled",
+ "Closed",
] as const;
export const salesOrderValidator = z.object({
@@ -499,6 +500,7 @@ export const salesOrderValidator = z.object({
customerContactId: zfd.text(z.string().optional()),
customerReference: zfd.text(z.string().optional()),
quoteId: zfd.text(z.string().optional()),
+ locationId: zfd.text(z.string().optional()),
});
export const salesOrderShipmentValidator = z
@@ -546,7 +548,7 @@ export const salesOrderLineValidator = z
description: zfd.text(z.string().optional()),
itemId: zfd.text(z.string().optional()),
itemReadableId: zfd.text(z.string().optional()),
- locationId: zfd.text(z.string().optional()),
+ locationId: z.string().min(0, { message: "Location is required" }),
methodType: z
.enum(methodType, {
errorMap: () => ({ message: "Method is required" }),
@@ -627,6 +629,7 @@ export const salesOrderReleaseValidator = z
export const salesRfqValidator = z.object({
id: zfd.text(z.string().optional()),
rfqId: zfd.text(z.string().optional()),
+ customerLocationId: zfd.text(z.string().optional()),
customerContactId: zfd.text(z.string().optional()),
customerId: z.string().min(36, { message: "Customer is required" }),
customerReference: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 57c85b6baf..05dee449f0 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -26,6 +26,7 @@ import type {
salesOrderLineValidator,
salesOrderPaymentValidator,
salesOrderShipmentValidator,
+ salesOrderStatusType,
salesOrderValidator,
salesRfqLineValidator,
salesRFQStatusType,
@@ -1849,6 +1850,18 @@ export async function updateSalesOrderFavorite(
}
}
+export async function updateSalesOrderStatus(
+ client: SupabaseClient<Database>,
+ update: {
+ id: string;
+ status: (typeof salesOrderStatusType)[number];
+ assignee: null | undefined;
+ updatedBy: string;
+ }
+) {
+ return client.from("salesOrder").update(update).eq("id", update.id);
+}
+
export async function upsertSalesOrder(
client: SupabaseClient<Database>,
salesOrder:
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm.tsx
index d3040c8358..e166cdb1fe 100644
--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm.tsx
@@ -1,12 +1,13 @@
import {
Button,
- Drawer,
- DrawerBody,
- DrawerContent,
- DrawerFooter,
- DrawerHeader,
- DrawerTitle,
HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
VStack,
} from "@carbon/react";
@@ -42,59 +43,63 @@ const CustomerLocationForm = ({
: !permissions.can("create", "sales");
return (
- <Drawer
- open={open}
- onOpenChange={(open) => {
- if (!open) onClose?.();
- }}
- >
- <DrawerContent>
- <ValidatedForm
- validator={customerLocationValidator}
- method="post"
- action={
- isEditing
- ? path.to.customerLocation(customerId, initialValues.id!)
- : path.to.newCustomerLocation(customerId)
- }
- defaultValues={initialValues}
- fetcher={fetcher}
- onSubmit={() => {
- if (type === "modal") {
- onClose?.();
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={customerLocationValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.customerLocation(customerId, initialValues.id!)
+ : path.to.newCustomerLocation(customerId)
}
- }}
- className="flex flex-col h-full"
- >
- <DrawerHeader>
- <DrawerTitle>{isEditing ? "Edit" : "New"} Location</DrawerTitle>
- </DrawerHeader>
- <DrawerBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
- <Hidden name="addressId" />
- <VStack spacing={4}>
- <Input name="name" label="Name" />
- <Input name="addressLine1" label="Address Line 1" />
- <Input name="addressLine2" label="Address Line 2" />
- <Input name="city" label="City" />
- <Input name="state" label="State" />
- <Input name="postalCode" label="Zip Code" />
- {/* Country dropdown */}
- <CustomFormFields table="customerLocation" />
- </VStack>
- </DrawerBody>
- <DrawerFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- <Button size="md" variant="solid" onClick={onClose}>
- Cancel
- </Button>
- </HStack>
- </DrawerFooter>
- </ValidatedForm>
- </DrawerContent>
- </Drawer>
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ onSubmit={() => {
+ if (type === "modal") {
+ onClose?.();
+ }
+ }}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Location
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <Hidden name="addressId" />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ {/* Country dropdown */}
+ <CustomFormFields table="customerLocation" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
);
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index 3bf434ea84..9773f0a894 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -43,6 +43,7 @@ type QuoteExplorerProps = {
};
export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
+ const { defaults } = useUser();
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
const quoteData = useRouteData<{ quote: Quotation; lines: QuotationLine[] }>(
@@ -57,6 +58,7 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
estimatorId: userId,
itemId: "",
itemReadableId: "",
+ locationId: quoteData?.quote?.locationId ?? defaults.locationId ?? "",
methodType: "Make" as const,
status: "Draft" as const,
quantity: [1],
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 87742f662c..e59c92ee67 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -88,7 +88,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
/>
<Employee name="salesPersonId" label="Sales Person" />
<Employee name="estimatorId" label="Estimator" />
- <Location name="locationId" label="Location" />
+ <Location name="locationId" label="Quote Location" />
<DatePicker
name="dueDate"
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index e91732774e..ecaa53495c 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -46,7 +46,7 @@ const QuoteHeader = () => {
return (
<>
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
<HStack className="w-full justify-between">
<HStack>
<Link to={path.to.quoteDetails(quoteId)}>
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index 5cc0eb6571..02795952bb 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -28,6 +28,7 @@ import {
usePermissions,
useRealtime,
useRouteData,
+ useUser,
} from "~/hooks";
import { path } from "~/utils/path";
import type { SalesOrder, SalesOrderLine } from "../../types";
@@ -35,6 +36,7 @@ import DeleteSalesOrderLine from "./DeleteSalesOrderLine";
import SalesOrderLineForm from "./SalesOrderLineForm";
export default function SalesOrderExplorer() {
+ const { defaults } = useUser();
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
const salesOrderData = useRouteData<{
@@ -49,6 +51,8 @@ export default function SalesOrderExplorer() {
saleQuantity: 1,
unitPrice: 0,
addOnCost: 0,
+ locationId:
+ salesOrderData?.salesOrder?.locationId ?? defaults.locationId ?? "",
};
const newSalesOrderLineDisclosure = useDisclosure();
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx
index 9e2b00e515..36d7b1c847 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx
@@ -19,6 +19,7 @@ import {
DatePicker,
Hidden,
Input,
+ Location,
Select,
Submit,
} from "~/components/Form";
@@ -107,7 +108,7 @@ const SalesOrderForm = ({ initialValues }: SalesOrderFormProps) => {
isReadOnly={isCustomer}
/>
)}
-
+ <Location name="locationId" label="Sales Location" />
<CustomFormFields table="salesOrder" />
</div>
</VStack>
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index 86fb780312..687490d67e 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -1,7 +1,13 @@
import { Button, HStack, Heading } from "@carbon/react";
-import { Link, useParams } from "@remix-run/react";
-import { LuEye, LuFile, LuTruck, LuXCircle } from "react-icons/lu";
+import { Form, Link, useParams } from "@remix-run/react";
+import {
+ LuCheckCheck,
+ LuEye,
+ LuFile,
+ LuTruck,
+ LuXCircle,
+} from "react-icons/lu";
import { RiProgress8Line } from "react-icons/ri";
import { Assignee, Copy, useOptimisticAssignment } from "~/components";
@@ -32,7 +38,7 @@ const SalesOrderHeader = () => {
return (
<>
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
<HStack className="w-full justify-between">
<HStack>
<Link to={path.to.salesOrderDetails(orderId)}>
@@ -61,13 +67,33 @@ const SalesOrderHeader = () => {
Preview
</a>
</Button>
- <Button variant="secondary" isDisabled leftIcon={<LuTruck />}>
- Ship
- </Button>
+ {routeData?.salesOrder?.status === "Draft" && (
+ <>
+ <Form method="post" action={path.to.salesOrderStatus(orderId)}>
+ <input type="hidden" name="status" value="Confirmed" />
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuCheckCheck />}
+ type="submit"
+ variant="secondary"
+ >
+ Confirm
+ </Button>
+ </Form>
+ </>
+ )}
+ {routeData?.salesOrder?.status !== "Draft" && (
+ <>
+ <Button variant="secondary" isDisabled leftIcon={<LuTruck />}>
+ Ship
+ </Button>
+
+ <Button variant="secondary" isDisabled leftIcon={<LuFile />}>
+ Invoice
+ </Button>
+ </>
+ )}
- <Button variant="secondary" isDisabled leftIcon={<LuFile />}>
- Invoice
- </Button>
<Button variant="secondary" isDisabled leftIcon={<LuXCircle />}>
Cancel
</Button>
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index 28c852c66f..b1f007cb37 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -21,13 +21,12 @@ import {
} from "@carbon/react";
import { ValidatedForm } from "@carbon/form";
-import { useFetcher, useParams } from "@remix-run/react";
-import { useEffect, useMemo, useState } from "react";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
import { BsThreeDotsVertical } from "react-icons/bs";
import { LuTrash } from "react-icons/lu";
import type { z } from "zod";
import {
- ComboboxControlled,
CustomFormFields,
DatePicker,
Hidden,
@@ -37,12 +36,13 @@ import {
Number,
NumberControlled,
SelectControlled,
+ Shelf,
Submit,
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
-import type { getShelvesList } from "~/modules/items";
+
import type {
SalesOrder,
SalesOrderLine,
@@ -66,7 +66,7 @@ const SalesOrderLineForm = ({
}: SalesOrderLineFormProps) => {
const permissions = usePermissions();
const { supabase } = useSupabase();
- const { company, defaults } = useUser();
+ const { company } = useUser();
const { orderId } = useParams();
if (!orderId) throw new Error("orderId not found");
@@ -80,7 +80,7 @@ const SalesOrderLineForm = ({
);
const [lineType, setLineType] = useState(initialValues.salesOrderLineType);
- const [locationId, setLocationId] = useState(defaults.locationId ?? "");
+ const [locationId, setLocationId] = useState(initialValues.locationId ?? "");
const [itemData, setItemData] = useState<{
itemId: string;
itemReadableId?: string;
@@ -101,24 +101,6 @@ const SalesOrderLineForm = ({
modelUploadId: initialValues.modelUploadId ?? null,
});
- const shelfFetcher = useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();
-
- useEffect(() => {
- if (locationId) {
- shelfFetcher.load(path.to.api.shelves(locationId));
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [locationId]);
-
- const shelfOptions = useMemo(
- () =>
- shelfFetcher.data?.data?.map((shelf) => ({
- label: shelf.id,
- value: shelf.id,
- })) ?? [],
- [shelfFetcher.data]
- );
-
const isEditing = initialValues.id !== undefined;
const onTypeChange = (t: SalesOrderLineType) => {
@@ -363,16 +345,16 @@ const SalesOrderLineForm = ({
"Fixture",
"Consumable",
].includes(lineType) && (
- <ComboboxControlled
+ <Shelf
name="shelfId"
label="Shelf"
- options={shelfOptions}
- value={itemData.shelfId}
+ locationId={locationId}
+ value={itemData.shelfId ?? undefined}
onChange={(newValue) => {
if (newValue) {
setItemData((d) => ({
...d,
- shelfId: newValue?.value as string,
+ shelfId: newValue?.id,
}));
}
}}
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
index 10c5e20c37..0755c010fb 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
@@ -54,7 +54,7 @@ const SalesRFQHeader = () => {
const status = routeData?.rfqSummary?.status ?? "Draft";
return (
- <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border shadow-md">
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
<HStack className="w-full justify-between">
<HStack>
<Link to={path.to.salesRfqDetails(rfqId)}>
diff --git a/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal.tsx b/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
index 92c856f3b3..145afcf8ff 100644
--- a/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
+++ b/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
@@ -22,9 +22,11 @@ import {
Hidden,
Input,
InputControlled,
+ Location,
Select,
Submit,
} from "~/components/Form";
+import { useUser } from "~/hooks";
import type { getEmployeeTypes, getInvitable } from "~/modules/users";
import { createEmployeeValidator } from "~/modules/users";
import type { Result } from "~/types";
@@ -35,6 +37,7 @@ type CreateEmployeeModalProps = {
};
const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
+ const { defaults } = useUser();
const navigate = useNavigate();
const formFetcher = useFetcher<Result>();
const employeeTypeFetcher =
@@ -72,7 +75,9 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
method="post"
action={path.to.newEmployee}
validator={createEmployeeValidator}
- // @ts-ignore
+ defaultValues={{
+ locationId: defaults?.locationId ?? undefined,
+ }}
fetcher={formFetcher}
className="flex flex-col h-full"
>
@@ -94,6 +99,7 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
options={employeeTypeOptions}
placeholder="Select Employee Type"
/>
+ <Location name="locationId" label="Location" />
</VStack>
<ModalFooter>
<HStack>
diff --git a/apps/carbon/app/modules/users/users.models.ts b/apps/carbon/app/modules/users/users.models.ts
index 67d8a04d7f..e5cd690d30 100644
--- a/apps/carbon/app/modules/users/users.models.ts
+++ b/apps/carbon/app/modules/users/users.models.ts
@@ -25,6 +25,7 @@ export const createEmployeeValidator = z.object({
firstName: z.string().min(1, { message: "First name is required" }),
lastName: z.string().min(1, { message: "Last name is required" }),
employeeType: z.string().min(20, { message: "Employee type is required" }),
+ locationId: z.string().min(0, { message: "Location is required" }),
});
export const createSupplierAccountValidator = z.object({
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 18df5c7c08..1fc1817a86 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -146,12 +146,14 @@ export async function createEmployeeAccount(
firstName,
lastName,
employeeType,
+ locationId,
companyId,
}: {
email: string;
firstName: string;
lastName: string;
employeeType: string;
+ locationId: string;
companyId: string;
}
): Promise<Result> {
@@ -208,6 +210,7 @@ export async function createEmployeeAccount(
insertEmployeeJob(client, {
id: userId,
companyId,
+ locationId,
}),
addUserToCompany(client, { userId, companyId, role: "employee" }),
setUserPermissions(supabaseAdmin, userId, permissions),
diff --git a/apps/carbon/app/routes/api+/items.shelf.ts b/apps/carbon/app/routes/api+/inventory.shelves.ts
similarity index 67%
rename from apps/carbon/app/routes/api+/items.shelf.ts
rename to apps/carbon/app/routes/api+/inventory.shelves.ts
index 5d05ed2799..156ac8a9a8 100644
--- a/apps/carbon/app/routes/api+/items.shelf.ts
+++ b/apps/carbon/app/routes/api+/inventory.shelves.ts
@@ -1,10 +1,10 @@
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { getShelvesList } from "~/modules/items";
+import { getShelvesListForLocation } from "~/modules/inventory";
import { requirePermissions } from "~/services/auth/auth.server";
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "parts",
});
@@ -17,5 +17,5 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
}
- return json(await getShelvesList(client, locationId));
+ return json(await getShelvesListForLocation(client, companyId, locationId));
}
diff --git a/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx b/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
index f779dc9ca3..ab6961a10a 100644
--- a/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
@@ -36,23 +36,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
]);
if (company.error) {
- console.log(company.error);
+ console.error(company.error);
}
if (purchaseOrder.error) {
- console.log(purchaseOrder.error);
+ console.error(purchaseOrder.error);
}
if (purchaseOrderLines.error) {
- console.log(purchaseOrderLines.error);
+ console.error(purchaseOrderLines.error);
}
if (purchaseOrderLocations.error) {
- console.log(purchaseOrderLocations.error);
+ console.error(purchaseOrderLocations.error);
}
if (terms.error) {
- console.log(terms.error);
+ console.error(terms.error);
}
if (
diff --git a/apps/carbon/app/routes/x+/account+/_layout.tsx b/apps/carbon/app/routes/x+/account+/_layout.tsx
index 0be7b2a3b5..b859664414 100644
--- a/apps/carbon/app/routes/x+/account+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/account+/_layout.tsx
@@ -22,7 +22,7 @@ export default function AccountRoute() {
return (
<div className="grid w-full h-full grid-cols-[auto_1fr]">
<ContentSidebar links={links} />
- <VStack spacing={0} className="h-full p-4">
+ <VStack spacing={0} className="h-full p-2">
<Outlet />
</VStack>
</div>
diff --git a/apps/carbon/app/routes/x+/account+/profile.tsx b/apps/carbon/app/routes/x+/account+/profile.tsx
index a8a4903932..404d032295 100644
--- a/apps/carbon/app/routes/x+/account+/profile.tsx
+++ b/apps/carbon/app/routes/x+/account+/profile.tsx
@@ -115,7 +115,7 @@ export default function AccountProfile() {
const { user } = useLoaderData<typeof loader>();
return (
- <VStack spacing={4}>
+ <VStack spacing={2}>
<Card>
<CardHeader>
<CardTitle>Profile</CardTitle>
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx
index a52d8737ee..882f80a8c5 100644
--- a/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx
@@ -1,13 +1,16 @@
import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
import { useLoaderData } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
+import { InventoryDetails } from "~/modules/inventory";
+import type { Consumable, UnitOfMeasureListItem } from "~/modules/items";
import {
PickMethodForm,
getItemQuantities,
+ getItemShelfQuantities,
getPickMethod,
- getShelvesList,
pickMethodValidator,
upsertPickMethod,
} from "~/modules/items";
@@ -62,9 +65,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- let [consumableInventory, shelves] = await Promise.all([
+ let [consumableInventory] = await Promise.all([
getPickMethod(client, itemId, companyId, locationId),
- getShelvesList(client, locationId),
]);
if (consumableInventory.error || !consumableInventory.data) {
@@ -106,33 +108,43 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
}
- if (shelves.error) {
+ const quantities = await getItemQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (quantities.error) {
throw redirect(
path.to.items,
- await flash(request, error(shelves.error, "Failed to load shelves"))
+ await flash(
+ request,
+ error(quantities, "Failed to load consumable quantities")
+ )
);
}
- const quantities = await getItemQuantities(
+ const itemShelfQuantities = await getItemShelfQuantities(
client,
itemId,
companyId,
locationId
);
- if (quantities.error || !quantities.data) {
+ if (itemShelfQuantities.error || !itemShelfQuantities.data) {
throw redirect(
path.to.items,
await flash(
request,
- error(quantities, "Failed to load consumable quantities")
+ error(itemShelfQuantities, "Failed to load consumable quantities")
)
);
}
return json({
consumableInventory: consumableInventory.data,
+ itemShelfQuantities: itemShelfQuantities.data,
quantities: quantities.data,
- shelves: shelves.data.map((s) => s.id),
+ itemId,
});
}
@@ -178,25 +190,45 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function ConsumableInventoryRoute() {
- const sharedConsumablesData = useRouteData<{ locations: ListItem[] }>(
- path.to.consumableRoot
- );
- const { consumableInventory, quantities, shelves } =
+ const sharedConsumablesData = useRouteData<{
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.consumableRoot);
+
+ const { consumableInventory, itemShelfQuantities, quantities, itemId } =
useLoaderData<typeof loader>();
+ const consumableData = useRouteData<{
+ consumableSummary: Consumable;
+ }>(path.to.consumable(itemId));
+ if (!consumableData) throw new Error("Could not find consumable data");
+ const itemUnitOfMeasureCode =
+ consumableData?.consumableSummary?.unitOfMeasureCode;
+
const initialValues = {
...consumableInventory,
defaultShelfId: consumableInventory.defaultShelfId ?? undefined,
...getCustomFields(consumableInventory.customFields ?? {}),
};
return (
- <PickMethodForm
- key={initialValues.itemId}
- initialValues={initialValues}
- quantities={quantities}
- locations={sharedConsumablesData?.locations ?? []}
- shelves={shelves}
- type="Consumable"
- />
+ <VStack spacing={2}>
+ <PickMethodForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ locations={sharedConsumablesData?.locations ?? []}
+ shelves={sharedConsumablesData?.shelves ?? []}
+ type="Part"
+ />
+ <InventoryDetails
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={itemUnitOfMeasureCode ?? "EA"}
+ locations={sharedConsumablesData?.locations ?? []}
+ pickMethod={initialValues}
+ quantities={quantities}
+ shelves={sharedConsumablesData?.shelves ?? []}
+ unitOfMeasures={sharedConsumablesData?.unitOfMeasures ?? []}
+ />
+ </VStack>
);
}
diff --git a/apps/carbon/app/routes/x+/consumable+/_layout.tsx b/apps/carbon/app/routes/x+/consumable+/_layout.tsx
index 211ac37a5c..ee22333392 100644
--- a/apps/carbon/app/routes/x+/consumable+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/consumable+/_layout.tsx
@@ -1,5 +1,6 @@
import { Outlet } from "@remix-run/react";
import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { getShelvesList } from "~/modules/inventory";
import { getUnitOfMeasuresList } from "~/modules/items";
import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -21,14 +22,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "parts",
});
- const [unitOfMeasures, locations] = await Promise.all([
+ const [unitOfMeasures, locations, shelves] = await Promise.all([
getUnitOfMeasuresList(client, companyId),
getLocationsList(client, companyId),
+ getShelvesList(client, companyId),
]);
return {
locations: locations?.data ?? [],
unitOfMeasures: unitOfMeasures?.data ?? [],
+ shelves: shelves?.data ?? [],
};
}
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.inventory.tsx
index 703513d0e4..66d0ed6ebb 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.inventory.tsx
@@ -4,11 +4,13 @@ import { useLoaderData } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
+import { InventoryDetails } from "~/modules/inventory";
+import type { Fixture, UnitOfMeasureListItem } from "~/modules/items";
import {
PickMethodForm,
getItemQuantities,
+ getItemShelfQuantities,
getPickMethod,
- getShelvesList,
pickMethodValidator,
upsertPickMethod,
} from "~/modules/items";
@@ -63,9 +65,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- let [fixtureInventory, shelves] = await Promise.all([
+ let [fixtureInventory] = await Promise.all([
getPickMethod(client, itemId, companyId, locationId),
- getShelvesList(client, locationId),
]);
if (fixtureInventory.error || !fixtureInventory.data) {
@@ -104,20 +105,29 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
}
- if (shelves.error) {
+ const quantities = await getItemQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (quantities.error) {
throw redirect(
path.to.items,
- await flash(request, error(shelves.error, "Failed to load shelves"))
+ await flash(
+ request,
+ error(quantities, "Failed to load fixture quantities")
+ )
);
}
- const quantities = await getItemQuantities(
+ const itemShelfQuantities = await getItemShelfQuantities(
client,
itemId,
companyId,
locationId
);
- if (quantities.error || !quantities.data) {
+ if (itemShelfQuantities.error || !itemShelfQuantities.data) {
throw redirect(
path.to.items,
await flash(
@@ -129,8 +139,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return json({
fixtureInventory: fixtureInventory.data,
+ itemShelfQuantities: itemShelfQuantities.data,
quantities: quantities.data,
- shelves: shelves.data.map((s) => s.id),
+ itemId,
});
}
@@ -176,12 +187,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function FixtureInventoryRoute() {
- const sharedFixturesData = useRouteData<{ locations: ListItem[] }>(
- path.to.fixtureRoot
- );
- const { fixtureInventory, quantities, shelves } =
+ const sharedFixturesData = useRouteData<{
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.fixtureRoot);
+
+ const { fixtureInventory, itemShelfQuantities, quantities, itemId } =
useLoaderData<typeof loader>();
+ const fixtureData = useRouteData<{
+ fixtureSummary: Fixture;
+ }>(path.to.fixture(itemId));
+ if (!fixtureData) throw new Error("Could not find fixture data");
+ const itemUnitOfMeasureCode = fixtureData?.fixtureSummary?.unitOfMeasureCode;
+
const initialValues = {
...fixtureInventory,
defaultShelfId: fixtureInventory.defaultShelfId ?? undefined,
@@ -192,11 +212,19 @@ export default function FixtureInventoryRoute() {
<PickMethodForm
key={initialValues.itemId}
initialValues={initialValues}
- quantities={quantities}
locations={sharedFixturesData?.locations ?? []}
- shelves={shelves}
+ shelves={sharedFixturesData?.shelves ?? []}
type="Fixture"
/>
+ <InventoryDetails
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={itemUnitOfMeasureCode ?? "EA"}
+ locations={sharedFixturesData?.locations ?? []}
+ pickMethod={initialValues}
+ quantities={quantities}
+ shelves={sharedFixturesData?.shelves ?? []}
+ unitOfMeasures={sharedFixturesData?.unitOfMeasures ?? []}
+ />
</VStack>
);
}
diff --git a/apps/carbon/app/routes/x+/fixture+/_layout.tsx b/apps/carbon/app/routes/x+/fixture+/_layout.tsx
index 34e41ce310..a326481377 100644
--- a/apps/carbon/app/routes/x+/fixture+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/_layout.tsx
@@ -1,5 +1,6 @@
import { Outlet } from "@remix-run/react";
import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { getShelvesList } from "~/modules/inventory";
import { getUnitOfMeasuresList } from "~/modules/items";
import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -21,14 +22,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "parts",
});
- const [unitOfMeasures, locations] = await Promise.all([
+ const [unitOfMeasures, locations, shelves] = await Promise.all([
getUnitOfMeasuresList(client, companyId),
getLocationsList(client, companyId),
+ getShelvesList(client, companyId),
]);
return {
locations: locations?.data ?? [],
unitOfMeasures: unitOfMeasures?.data ?? [],
+ shelves: shelves?.data ?? [],
};
}
diff --git a/apps/carbon/app/routes/x+/inventory+/_index.tsx b/apps/carbon/app/routes/x+/inventory+/_index.tsx
index 178f86df8d..57e94a30cb 100644
--- a/apps/carbon/app/routes/x+/inventory+/_index.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/_index.tsx
@@ -2,5 +2,5 @@ import { redirect } from "@vercel/remix";
import { path } from "~/utils/path";
export async function loader() {
- throw redirect(path.to.receipts);
+ throw redirect(path.to.inventory);
}
diff --git a/apps/carbon/app/routes/x+/inventory+/_layout.tsx b/apps/carbon/app/routes/x+/inventory+/_layout.tsx
index 908dea4360..67139d70bc 100644
--- a/apps/carbon/app/routes/x+/inventory+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/_layout.tsx
@@ -1,8 +1,11 @@
import { VStack } from "@carbon/react";
import { Outlet } from "@remix-run/react";
-import type { MetaFunction } from "@vercel/remix";
+import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
import { GroupedContentSidebar } from "~/components/Layout";
-import { useInventorySubmodules } from "~/modules/inventory";
+import { getShelvesList, useInventorySubmodules } from "~/modules/inventory";
+import { getUnitOfMeasuresList } from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { requirePermissions } from "~/services/auth/auth.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -12,11 +15,29 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Inventory",
- to: path.to.receipts,
+ to: path.to.inventory,
module: "inventory",
};
-export default function UsersRoute() {
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const [unitOfMeasures, locations, shelves] = await Promise.all([
+ getUnitOfMeasuresList(client, companyId),
+ getLocationsList(client, companyId),
+ getShelvesList(client, companyId),
+ ]);
+
+ return {
+ locations: locations?.data ?? [],
+ shelves: shelves?.data ?? [],
+ unitOfMeasures: unitOfMeasures?.data ?? [],
+ };
+}
+
+export default function InventoryRoute() {
const { groups } = useInventorySubmodules();
return (
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
new file mode 100644
index 0000000000..2125bb0ae9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
@@ -0,0 +1,134 @@
+import { useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { useCallback, useState } from "react";
+import InfiniteScroll from "~/components/InfiniteScroll";
+import { useSupabase } from "~/lib/supabase";
+import { getItemLedger, InventoryActivity } from "~/modules/inventory";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { notFound } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "inventory",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw notFound("itemId not found");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ const itemLedgerRecords = await getItemLedger(
+ client,
+ itemId,
+ companyId,
+ locationId,
+ true
+ );
+ if (itemLedgerRecords.error || !itemLedgerRecords.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(itemLedgerRecords, "Failed to load item inventory activity")
+ )
+ );
+ }
+
+ return json({
+ initialItemLedgers: itemLedgerRecords.data,
+ itemId,
+ companyId,
+ locationId,
+ });
+}
+
+export default function ItemInventoryActivityRoute() {
+ const { initialItemLedgers, itemId, companyId, locationId } =
+ useLoaderData<typeof loader>();
+
+ const { supabase } = useSupabase();
+
+ const [itemLedgers, setItemLedgers] = useState<any[]>(initialItemLedgers);
+ const [page, setPage] = useState(1);
+ const [isLoading, setIsLoading] = useState(false);
+ const [hasMore, setHasMore] = useState(true);
+
+ const loadMoreItemLedgers = useCallback(async () => {
+ if (isLoading || !hasMore) return;
+
+ setIsLoading(true);
+
+ const newItemLedgers = await getItemLedger(
+ supabase!,
+ itemId,
+ companyId,
+ locationId,
+ true,
+ page + 1
+ );
+
+ if (newItemLedgers.data && newItemLedgers.data.length > 0) {
+ setItemLedgers((prevItemLedgers) => [
+ ...prevItemLedgers,
+ ...newItemLedgers.data,
+ ]);
+ setPage((prevPage) => prevPage + 1);
+ } else {
+ setHasMore(false);
+ }
+
+ setIsLoading(false);
+ }, [page, supabase, companyId, locationId, itemId, isLoading, hasMore]);
+
+ return (
+ <>
+ <div className="w-full space-y-4 pt-6 px-4">
+ <h2 className="text-2xl font-semibold mb-4">Activity</h2>
+
+ <InfiniteScroll
+ component={InventoryActivity}
+ items={itemLedgers}
+ loadMore={loadMoreItemLedgers}
+ hasMore={hasMore}
+ />
+ </div>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx
new file mode 100644
index 0000000000..f778ad04a6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx
@@ -0,0 +1,52 @@
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import {
+ insertManualInventoryAdjustment,
+ inventoryAdjustmentValidator,
+} from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path, requestReferrer } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(inventoryAdjustmentValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+ const { ...data } = validation.data;
+
+ const itemLedger = await insertManualInventoryAdjustment(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (itemLedger.error) {
+ const flashMessage =
+ itemLedger.error === "Insufficient quantity for negative adjustment"
+ ? "Insufficient quantity for negative adjustment"
+ : "Failed to create manual inventory adjustment";
+
+ throw redirect(
+ path.to.inventoryItem(itemId),
+ await flash(request, error(itemLedger.error, flashMessage))
+ );
+ }
+
+ throw redirect(requestReferrer(request) ?? path.to.inventoryItem(itemId));
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.details.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.details.tsx
new file mode 100644
index 0000000000..8e439c0545
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.details.tsx
@@ -0,0 +1,165 @@
+import { useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { useRouteData } from "~/hooks";
+import { InventoryDetails } from "~/modules/inventory";
+import type { UnitOfMeasureListItem } from "~/modules/items";
+import {
+ getItem,
+ getItemQuantities,
+ getItemShelfQuantities,
+ getPickMethod,
+ upsertPickMethod,
+} from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { ListItem } from "~/types";
+import { notFound } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "inventory",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw notFound("itemId not found");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let [pickMethod] = await Promise.all([
+ getPickMethod(client, itemId, companyId, locationId),
+ ]);
+
+ if (pickMethod.error || !pickMethod.data) {
+ const insertPickMethod = await upsertPickMethod(client, {
+ itemId,
+ companyId,
+ locationId,
+ customFields: {},
+ createdBy: userId,
+ });
+
+ if (insertPickMethod.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(insertPickMethod.error, "Failed to insert part inventory")
+ )
+ );
+ }
+
+ pickMethod = await getPickMethod(client, itemId, companyId, locationId);
+ if (pickMethod.error || !pickMethod.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(pickMethod.error, "Failed to load part inventory")
+ )
+ );
+ }
+ }
+
+ const [quantities, item] = await Promise.all([
+ getItemQuantities(client, itemId, companyId, locationId),
+ getItem(client, itemId),
+ ]);
+ if (quantities.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(request, error(quantities, "Failed to load part quantities"))
+ );
+ }
+
+ if (item.error || !item.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(request, error(item.error, "Failed to load item"))
+ );
+ }
+
+ const itemShelfQuantities = await getItemShelfQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (itemShelfQuantities.error || !itemShelfQuantities.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(itemShelfQuantities.error, "Failed to load item shelf quantities")
+ )
+ );
+ }
+
+ return json({
+ pickMethod: pickMethod.data,
+ quantities: quantities.data,
+ itemShelfQuantities: itemShelfQuantities.data,
+ item: item.data,
+ });
+}
+
+export default function ItemInventoryRoute() {
+ const { pickMethod, quantities, itemShelfQuantities, item } =
+ useLoaderData<typeof loader>();
+
+ const routeData = useRouteData<{
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.inventoryRoot);
+
+ return (
+ <InventoryDetails
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={item.unitOfMeasureCode ?? "EA"}
+ locations={routeData?.locations ?? []}
+ pickMethod={{
+ ...pickMethod,
+ defaultShelfId: pickMethod.defaultShelfId ?? undefined,
+ }}
+ quantities={quantities}
+ shelves={routeData?.shelves ?? []}
+ unitOfMeasures={routeData?.unitOfMeasures ?? []}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx
new file mode 100644
index 0000000000..659cfca398
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.tsx
@@ -0,0 +1,131 @@
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ScrollArea,
+ VStack,
+} from "@carbon/react";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import InventoryItemHeader from "~/modules/inventory/ui/Inventory/InventoryItemHeader";
+import { getItem, getPickMethod, upsertPickMethod } from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { notFound } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "inventory",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw notFound("itemId not found");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let [pickMethod] = await Promise.all([
+ getPickMethod(client, itemId, companyId, locationId),
+ ]);
+
+ if (pickMethod.error || !pickMethod.data) {
+ const insertPickMethod = await upsertPickMethod(client, {
+ itemId,
+ companyId,
+ locationId,
+ customFields: {},
+ createdBy: userId,
+ });
+
+ if (insertPickMethod.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(insertPickMethod.error, "Failed to insert part inventory")
+ )
+ );
+ }
+
+ pickMethod = await getPickMethod(client, itemId, companyId, locationId);
+ if (pickMethod.error || !pickMethod.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(pickMethod.error, "Failed to load part inventory")
+ )
+ );
+ }
+ }
+
+ const item = await getItem(client, itemId);
+ if (item.error || !item.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(request, error(item.error, "Failed to load item"))
+ );
+ }
+
+ return json({
+ pickMethod: pickMethod.data,
+ item: item.data,
+ });
+}
+
+export default function ItemInventoryRoute() {
+ const { item } = useLoaderData<typeof loader>();
+
+ return (
+ <>
+ <ResizableHandle withHandle />
+ <ResizablePanel
+ defaultSize={50}
+ maxSize={70}
+ minSize={25}
+ className="bg-background"
+ >
+ <ScrollArea className="h-[calc(100vh-49px)]">
+ <InventoryItemHeader itemReadableId={item.readableId} />
+ <VStack className="p-2">
+ <Outlet />
+ </VStack>
+ </ScrollArea>
+ </ResizablePanel>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities.tsx b/apps/carbon/app/routes/x+/inventory+/quantities.tsx
new file mode 100644
index 0000000000..9ae7bb524e
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/quantities.tsx
@@ -0,0 +1,148 @@
+import {
+ ClientOnly,
+ ResizablePanel,
+ ResizablePanelGroup,
+ VStack,
+} from "@carbon/react";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { useRouteData } from "~/hooks";
+import type { InventoryItem } from "~/modules/inventory";
+import { getInventoryItems } from "~/modules/inventory";
+import InventoryTable from "~/modules/inventory/ui/Inventory/InventoryTable";
+import {
+ getMaterialFormsList,
+ getMaterialSubstancesList,
+ type UnitOfMeasureListItem,
+} from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { ListItem } from "~/types";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "inventory",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ const [inventoryItems, items, forms, substances] = await Promise.all([
+ getInventoryItems(client, locationId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ client
+ .from("item")
+ .select("id", { count: "exact" })
+ .eq("itemTrackingType", "Inventory"),
+ getMaterialFormsList(client, companyId),
+ getMaterialSubstancesList(client, companyId),
+ ]);
+
+ if (inventoryItems.error) {
+ redirect(
+ path.to.authenticatedRoot,
+ await flash(
+ request,
+ error(inventoryItems.error, "Failed to fetch inventory items")
+ )
+ );
+ }
+
+ if (items.error) {
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(items.error, "Failed to fetch item count"))
+ );
+ }
+
+ return json({
+ count: items.count ?? 0,
+ inventoryItems: (inventoryItems.data ?? []) as InventoryItem[],
+ locationId,
+ forms: forms.data ?? [],
+ substances: substances.data ?? [],
+ });
+}
+
+export default function QuantitiesRoute() {
+ const sharedData = useRouteData<{
+ locations: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.inventoryRoot);
+ const { count, inventoryItems, locationId, forms, substances } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full ">
+ <ClientOnly>
+ {() => (
+ <ResizablePanelGroup direction="horizontal">
+ <ResizablePanel
+ defaultSize={50}
+ maxSize={70}
+ minSize={25}
+ className="bg-background"
+ >
+ <InventoryTable
+ data={inventoryItems}
+ count={count}
+ locationId={locationId}
+ locations={sharedData?.locations ?? []}
+ unitOfMeasures={sharedData?.unitOfMeasures ?? []}
+ forms={forms}
+ substances={substances}
+ />
+ </ResizablePanel>
+ <Outlet />
+ </ResizablePanelGroup>
+ )}
+ </ClientOnly>
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shelves.$id.tsx b/apps/carbon/app/routes/x+/inventory+/shelves.$id.tsx
new file mode 100644
index 0000000000..3c0d39586a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/shelves.$id.tsx
@@ -0,0 +1,48 @@
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { shelfValidator, upsertShelf } from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(shelfValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ if (!id) {
+ throw redirect(
+ path.to.inventory,
+ await flash(request, error(null, "Failed to update shelf"))
+ );
+ }
+
+ const update = await upsertShelf(client, {
+ id,
+ ...data,
+ customFields: setCustomFields(formData),
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(request, error(update.error, "Failed to update shelf"))
+ );
+ }
+
+ return json(null, await flash(request, success("Updated shelf")));
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shelves.new.tsx b/apps/carbon/app/routes/x+/inventory+/shelves.new.tsx
new file mode 100644
index 0000000000..a1930adfdf
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/shelves.new.tsx
@@ -0,0 +1,62 @@
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { shelfValidator, upsertShelf } from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+// export const handle: Handle = {
+// breadcrumb: "Shelves",
+// to: path.to.shelves,
+// module: "inventory",
+// };
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") === "modal";
+
+ const validation = await validator(shelfValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createShelf = await upsertShelf(client, {
+ ...data,
+ companyId,
+ customFields: setCustomFields(formData),
+ createdBy: userId,
+ });
+ if (createShelf.error) {
+ return modal
+ ? json(
+ createShelf,
+ await flash(
+ request,
+ error(createShelf.error, "Failed to insert shelf")
+ )
+ )
+ : redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(createShelf.error, "Failed to insert shelf")
+ )
+ );
+ }
+
+ // const shelfId = createShelf.data?.id;
+
+ return modal ? json(createShelf) : redirect(path.to.inventory);
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.details.tsx b/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
index 0c8a4b566d..a7c3997419 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
@@ -1,8 +1,15 @@
import { validationError, validator } from "@carbon/form";
-import { VStack } from "@carbon/react";
-import { useParams } from "@remix-run/react";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ VStack,
+} from "@carbon/react";
+import { Await, useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
+import { Suspense } from "react";
import { CadModel, Documents } from "~/components";
import { usePermissions, useRealtime, useRouteData } from "~/hooks";
import { getSupabaseServiceRole } from "~/lib/supabase";
@@ -83,7 +90,7 @@ export default function JobDetailsRoute() {
const jobData = useRouteData<{
job: Job;
- files: StorageItem[];
+ files: Promise<StorageItem[]> | StorageItem[];
}>(path.to.job(jobId));
if (!jobData) throw new Error("Could not find job data");
@@ -122,14 +129,30 @@ export default function JobDetailsRoute() {
uploadClassName="min-h-[360px]"
viewerClassName="min-h-[360px]"
/>
- <Documents
- files={jobData.files}
- modelUpload={{ ...jobData.job }}
- sourceDocument="Job"
- sourceDocumentId={jobData.job.id ?? ""}
- writeBucket="job"
- writeBucketPermission="production"
- />
+
+ <Suspense
+ fallback={
+ <Card className="flex-grow">
+ <CardHeader>
+ <CardTitle>Files</CardTitle>
+ </CardHeader>
+ <CardContent className=""></CardContent>
+ </Card>
+ }
+ >
+ <Await resolve={jobData.files}>
+ {(files) => (
+ <Documents
+ files={files}
+ modelUpload={{ ...jobData.job }}
+ sourceDocument="Job"
+ sourceDocumentId={jobData.job.id ?? ""}
+ writeBucket="job"
+ writeBucketPermission="production"
+ />
+ )}
+ </Await>
+ </Suspense>
</div>
)}
</VStack>
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.tsx
index 05e1ac2bcc..dabf49429b 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.tsx
@@ -54,11 +54,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const files = await getJobDocuments(client, companyId, job.data);
-
return defer({
job: job.data,
- files,
+ files: getJobDocuments(client, companyId, job.data),
method: getJobMethodTree(client, jobId), // returns a promise
});
}
diff --git a/apps/carbon/app/routes/x+/material+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/material+/$itemId.inventory.tsx
index a436d610d8..b5a5b5d12a 100644
--- a/apps/carbon/app/routes/x+/material+/$itemId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/material+/$itemId.inventory.tsx
@@ -1,13 +1,16 @@
import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
import { useLoaderData } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
+import { InventoryDetails } from "~/modules/inventory";
+import type { Material, UnitOfMeasureListItem } from "~/modules/items";
import {
PickMethodForm,
getItemQuantities,
+ getItemShelfQuantities,
getPickMethod,
- getShelvesList,
pickMethodValidator,
upsertPickMethod,
} from "~/modules/items";
@@ -62,9 +65,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- let [materialInventory, shelves] = await Promise.all([
+ let [materialInventory] = await Promise.all([
getPickMethod(client, itemId, companyId, locationId),
- getShelvesList(client, locationId),
]);
if (materialInventory.error || !materialInventory.data) {
@@ -103,33 +105,43 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
}
- if (shelves.error) {
+ const quantities = await getItemQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (quantities.error) {
throw redirect(
path.to.items,
- await flash(request, error(shelves.error, "Failed to load shelves"))
+ await flash(
+ request,
+ error(quantities, "Failed to load material quantities")
+ )
);
}
- const quantities = await getItemQuantities(
+ const itemShelfQuantities = await getItemShelfQuantities(
client,
itemId,
companyId,
locationId
);
- if (quantities.error || !quantities.data) {
+ if (itemShelfQuantities.error || !itemShelfQuantities.data) {
throw redirect(
path.to.items,
await flash(
request,
- error(quantities, "Failed to load material quantities")
+ error(itemShelfQuantities, "Failed to load material quantities")
)
);
}
return json({
materialInventory: materialInventory.data,
+ itemShelfQuantities: itemShelfQuantities.data,
quantities: quantities.data,
- shelves: shelves.data.map((s) => s.id),
+ itemId,
});
}
@@ -175,25 +187,45 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function MaterialInventoryRoute() {
- const sharedMaterialsData = useRouteData<{ locations: ListItem[] }>(
- path.to.materialRoot
- );
- const { materialInventory, quantities, shelves } =
+ const sharedMaterialsData = useRouteData<{
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.materialRoot);
+
+ const { materialInventory, itemShelfQuantities, quantities, itemId } =
useLoaderData<typeof loader>();
+ const materialData = useRouteData<{
+ materialSummary: Material;
+ }>(path.to.material(itemId));
+ if (!materialData) throw new Error("Could not find material data");
+ const itemUnitOfMeasureCode =
+ materialData?.materialSummary?.unitOfMeasureCode;
+
const initialValues = {
...materialInventory,
defaultShelfId: materialInventory.defaultShelfId ?? undefined,
...getCustomFields(materialInventory.customFields ?? {}),
};
return (
- <PickMethodForm
- key={initialValues.itemId}
- initialValues={initialValues}
- quantities={quantities}
- locations={sharedMaterialsData?.locations ?? []}
- shelves={shelves}
- type="Material"
- />
+ <VStack spacing={2}>
+ <PickMethodForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ locations={sharedMaterialsData?.locations ?? []}
+ shelves={sharedMaterialsData?.shelves ?? []}
+ type="Part"
+ />
+ <InventoryDetails
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={itemUnitOfMeasureCode ?? "EA"}
+ locations={sharedMaterialsData?.locations ?? []}
+ pickMethod={initialValues}
+ quantities={quantities}
+ shelves={sharedMaterialsData?.shelves ?? []}
+ unitOfMeasures={sharedMaterialsData?.unitOfMeasures ?? []}
+ />
+ </VStack>
);
}
diff --git a/apps/carbon/app/routes/x+/material+/_layout.tsx b/apps/carbon/app/routes/x+/material+/_layout.tsx
index 7b9eb53637..93ea0c9d7b 100644
--- a/apps/carbon/app/routes/x+/material+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/material+/_layout.tsx
@@ -1,5 +1,6 @@
import { Outlet } from "@remix-run/react";
import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { getShelvesList } from "~/modules/inventory";
import {
getMaterialFormsList,
getMaterialSubstancesList,
@@ -25,18 +26,21 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "parts",
});
- const [unitOfMeasures, locations, forms, substances] = await Promise.all([
- getUnitOfMeasuresList(client, companyId),
- getLocationsList(client, companyId),
- getMaterialFormsList(client, companyId),
- getMaterialSubstancesList(client, companyId),
- ]);
+ const [unitOfMeasures, locations, forms, substances, shelves] =
+ await Promise.all([
+ getUnitOfMeasuresList(client, companyId),
+ getLocationsList(client, companyId),
+ getMaterialFormsList(client, companyId),
+ getMaterialSubstancesList(client, companyId),
+ getShelvesList(client, companyId),
+ ]);
return {
locations: locations?.data ?? [],
unitOfMeasures: unitOfMeasures?.data ?? [],
forms: forms?.data ?? [],
substances: substances?.data ?? [],
+ shelves: shelves?.data ?? [],
};
}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx
index 5166f579a0..2efc8f3d04 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx
@@ -4,11 +4,13 @@ import { useLoaderData } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
+import { InventoryDetails } from "~/modules/inventory";
+import type { PartSummary, UnitOfMeasureListItem } from "~/modules/items";
import {
PickMethodForm,
getItemQuantities,
+ getItemShelfQuantities,
getPickMethod,
- getShelvesList,
pickMethodValidator,
upsertPickMethod,
} from "~/modules/items";
@@ -63,9 +65,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- let [partInventory, shelves] = await Promise.all([
+ let [partInventory] = await Promise.all([
getPickMethod(client, itemId, companyId, locationId),
- getShelvesList(client, locationId),
]);
if (partInventory.error || !partInventory.data) {
@@ -99,30 +100,40 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
}
- if (shelves.error) {
+ const quantities = await getItemQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (quantities.error) {
throw redirect(
path.to.items,
- await flash(request, error(shelves.error, "Failed to load shelves"))
+ await flash(request, error(quantities, "Failed to load part quantities"))
);
}
- const quantities = await getItemQuantities(
+ const itemShelfQuantities = await getItemShelfQuantities(
client,
itemId,
companyId,
locationId
);
- if (quantities.error || !quantities.data) {
+ if (itemShelfQuantities.error || !itemShelfQuantities.data) {
throw redirect(
path.to.items,
- await flash(request, error(quantities, "Failed to load part quantities"))
+ await flash(
+ request,
+ error(itemShelfQuantities, "Failed to load part quantities")
+ )
);
}
return json({
partInventory: partInventory.data,
+ itemShelfQuantities: itemShelfQuantities.data,
quantities: quantities.data,
- shelves: shelves.data.map((s) => s.id),
+ itemId,
});
}
@@ -168,10 +179,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function PartInventoryRoute() {
- const sharedPartsData = useRouteData<{ locations: ListItem[] }>(
- path.to.partRoot
- );
- const { partInventory, quantities, shelves } = useLoaderData<typeof loader>();
+ const sharedPartsData = useRouteData<{
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.partRoot);
+
+ const { partInventory, itemShelfQuantities, quantities, itemId } =
+ useLoaderData<typeof loader>();
+
+ const partData = useRouteData<{
+ partSummary: PartSummary;
+ }>(path.to.part(itemId));
+ if (!partData) throw new Error("Could not find part data");
+ const itemUnitOfMeasureCode = partData?.partSummary?.unitOfMeasureCode;
const initialValues = {
...partInventory,
@@ -183,11 +204,19 @@ export default function PartInventoryRoute() {
<PickMethodForm
key={initialValues.itemId}
initialValues={initialValues}
- quantities={quantities}
locations={sharedPartsData?.locations ?? []}
- shelves={shelves}
+ shelves={sharedPartsData?.shelves ?? []}
type="Part"
/>
+ <InventoryDetails
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={itemUnitOfMeasureCode ?? "EA"}
+ locations={sharedPartsData?.locations ?? []}
+ pickMethod={initialValues}
+ quantities={quantities}
+ shelves={sharedPartsData?.shelves ?? []}
+ unitOfMeasures={sharedPartsData?.unitOfMeasures ?? []}
+ />
</VStack>
);
}
diff --git a/apps/carbon/app/routes/x+/part+/_layout.tsx b/apps/carbon/app/routes/x+/part+/_layout.tsx
index f4eb73af74..9ddfadb934 100644
--- a/apps/carbon/app/routes/x+/part+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/part+/_layout.tsx
@@ -1,5 +1,6 @@
import { Outlet } from "@remix-run/react";
import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { getShelvesList } from "~/modules/inventory";
import { getUnitOfMeasuresList } from "~/modules/items";
import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -21,13 +22,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "parts",
});
- const [unitOfMeasures, locations] = await Promise.all([
+ const [unitOfMeasures, locations, shelves] = await Promise.all([
getUnitOfMeasuresList(client, companyId),
getLocationsList(client, companyId),
+ getShelvesList(client, companyId),
]);
return {
locations: locations?.data ?? [],
+ shelves: shelves?.data ?? [],
unitOfMeasures: unitOfMeasures?.data ?? [],
};
}
diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
index d40e3569ac..aff5b73a69 100644
--- a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
+++ b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
@@ -10,7 +10,7 @@ import { error } from "~/utils/result";
export const config = { runtime: "nodejs" };
export async function action({ request, params }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, userId } = await requirePermissions(request, {
update: "invoicing",
});
@@ -37,6 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await tasks.trigger<typeof postTransactionTask>("post-transactions", {
type: "purchase-invoice",
documentId: invoiceId,
+ userId,
});
throw redirect(path.to.purchaseInvoices);
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
index 14d157ccf2..5fd86dfa68 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
@@ -29,7 +29,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const update = await updateQuoteStatus(client, {
id,
status,
- assignee: ["Draft", "Sent"].includes(status) ? null : undefined,
+ assignee: ["Closed"].includes(status) ? null : undefined,
updatedBy: userId,
});
if (update.error) {
diff --git a/apps/carbon/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/carbon/app/routes/x+/receipt+/$receiptId.post.tsx
index 64ba0debf3..46e79c4ffd 100644
--- a/apps/carbon/app/routes/x+/receipt+/$receiptId.post.tsx
+++ b/apps/carbon/app/routes/x+/receipt+/$receiptId.post.tsx
@@ -10,7 +10,7 @@ import { error } from "~/utils/result";
export const config = { runtime: "nodejs" };
export async function action({ request, params }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, userId } = await requirePermissions(request, {
update: "inventory",
});
@@ -37,6 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await tasks.trigger<typeof postTransactionTask>("post-transactions", {
type: "receipt",
documentId: receiptId,
+ userId,
});
throw redirect(path.to.receipts);
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
index f775c8918d..59e9dd3592 100644
--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
@@ -111,7 +111,7 @@ export default function EditSalesOrderLineRoute() {
assetId: line?.assetId ?? "",
description: line?.description ?? "",
itemReadableId: line?.itemReadableId ?? "",
- locationId: line?.locationId ?? undefined,
+ locationId: line?.locationId ?? "",
methodType: line?.methodType ?? "Make",
promisedDate: line?.promisedDate ?? undefined,
saleQuantity: line?.saleQuantity ?? 1,
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.new.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.new.tsx
index 7f47f092c6..37203f8172 100644
--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.new.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.new.tsx
@@ -2,7 +2,8 @@ import { validationError, validator } from "@carbon/form";
import { useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import type { SalesOrderLineType } from "~/modules/sales";
+import { useRouteData, useUser } from "~/hooks";
+import type { SalesOrder, SalesOrderLineType } from "~/modules/sales";
import {
SalesOrderLineForm,
salesOrderLineValidator,
@@ -58,9 +59,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function NewSalesOrderLineRoute() {
+ const { defaults } = useUser();
const { orderId } = useParams();
-
- if (!orderId) throw new Error("Could not find sales order id");
+ if (!orderId) throw new Error("Could not find orderId");
+ const salesOrderData = useRouteData<{
+ salesOrder: SalesOrder;
+ }>(path.to.salesOrder(orderId));
const initialValues = {
salesOrderId: orderId,
@@ -71,6 +75,8 @@ export default function NewSalesOrderLineRoute() {
shelfId: "",
unitOfMeasureCode: "",
unitPrice: 0,
+ locationId:
+ salesOrderData?.salesOrder?.locationId ?? defaults.locationId ?? "",
};
return <SalesOrderLineForm initialValues={initialValues} />;
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.status.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.status.tsx
new file mode 100644
index 0000000000..c8f6b7a6a2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.status.tsx
@@ -0,0 +1,51 @@
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { salesOrderStatusType, updateSalesOrderStatus } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path, requestReferrer } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { orderId: id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const status = formData.get(
+ "status"
+ ) as (typeof salesOrderStatusType)[number];
+
+ if (!status || !salesOrderStatusType.includes(status)) {
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const update = await updateSalesOrderStatus(client, {
+ id,
+ status,
+ assignee: ["Closed"].includes(status) ? null : undefined,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.quote(id),
+ await flash(
+ request,
+ error(update.error, "Failed to update sales order status")
+ )
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.quote(id),
+ await flash(request, success("Updated sales order status"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
index aa8a1b6026..f4ae03da96 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -93,6 +93,7 @@ export default function SalesRFQDetailsRoute() {
const initialValues = {
customerContactId: rfqData?.rfqSummary?.customerContactId ?? "",
+ customerLocationId: rfqData?.rfqSummary?.customerLocationId ?? "",
customerId: rfqData?.rfqSummary?.customerId ?? "",
customerReference: rfqData?.rfqSummary?.customerReference ?? "",
expirationDate: rfqData?.rfqSummary?.expirationDate
diff --git a/apps/carbon/app/routes/x+/settings+/company.tsx b/apps/carbon/app/routes/x+/settings+/company.tsx
index a6cd03a8d9..0a05633dea 100644
--- a/apps/carbon/app/routes/x+/settings+/company.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.tsx
@@ -114,7 +114,7 @@ export default function Company() {
};
return (
- <VStack spacing={0} className="p-4 h-full">
+ <VStack spacing={0} className="p-2 h-full">
<Card>
<CardHeader>
<CardTitle>Company</CardTitle>
diff --git a/apps/carbon/app/routes/x+/settings+/terms.tsx b/apps/carbon/app/routes/x+/settings+/terms.tsx
index 9057c9cf8b..f2518ff761 100644
--- a/apps/carbon/app/routes/x+/settings+/terms.tsx
+++ b/apps/carbon/app/routes/x+/settings+/terms.tsx
@@ -109,7 +109,7 @@ export default function Terms() {
};
return (
- <VStack spacing={4} className="p-4 h-full">
+ <VStack spacing={2} className="p-2 h-full">
<Card>
<HStack className="justify-between items-start">
<CardHeader>
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx
index 5e796f2b2b..e93e83c47e 100644
--- a/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx
@@ -1,13 +1,16 @@
import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
import { useLoaderData } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
+import { InventoryDetails } from "~/modules/inventory";
+import type { ToolSummary, UnitOfMeasureListItem } from "~/modules/items";
import {
PickMethodForm,
getItemQuantities,
+ getItemShelfQuantities,
getPickMethod,
- getShelvesList,
pickMethodValidator,
upsertPickMethod,
} from "~/modules/items";
@@ -62,9 +65,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- let [toolInventory, shelves] = await Promise.all([
+ let [toolInventory] = await Promise.all([
getPickMethod(client, itemId, companyId, locationId),
- getShelvesList(client, locationId),
]);
if (toolInventory.error || !toolInventory.data) {
@@ -98,30 +100,40 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
}
- if (shelves.error) {
+ const quantities = await getItemQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (quantities.error) {
throw redirect(
path.to.items,
- await flash(request, error(shelves.error, "Failed to load shelves"))
+ await flash(request, error(quantities, "Failed to load tool quantities"))
);
}
- const quantities = await getItemQuantities(
+ const itemShelfQuantities = await getItemShelfQuantities(
client,
itemId,
companyId,
locationId
);
- if (quantities.error || !quantities.data) {
+ if (itemShelfQuantities.error || !itemShelfQuantities.data) {
throw redirect(
path.to.items,
- await flash(request, error(quantities, "Failed to load tool quantities"))
+ await flash(
+ request,
+ error(itemShelfQuantities, "Failed to load tool quantities")
+ )
);
}
return json({
toolInventory: toolInventory.data,
+ itemShelfQuantities: itemShelfQuantities.data,
quantities: quantities.data,
- shelves: shelves.data.map((s) => s.id),
+ itemId,
});
}
@@ -167,10 +179,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function ToolInventoryRoute() {
- const sharedToolsData = useRouteData<{ locations: ListItem[] }>(
- path.to.toolRoot
- );
- const { toolInventory, quantities, shelves } = useLoaderData<typeof loader>();
+ const sharedToolsData = useRouteData<{
+ locations: ListItem[];
+ shelves: ListItem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>(path.to.toolRoot);
+
+ const { toolInventory, itemShelfQuantities, quantities, itemId } =
+ useLoaderData<typeof loader>();
+
+ const toolData = useRouteData<{
+ toolSummary: ToolSummary;
+ }>(path.to.tool(itemId));
+ if (!toolData) throw new Error("Could not find tool data");
+ const itemUnitOfMeasureCode = toolData?.toolSummary?.unitOfMeasureCode;
const initialValues = {
...toolInventory,
@@ -178,13 +200,23 @@ export default function ToolInventoryRoute() {
...getCustomFields(toolInventory.customFields ?? {}),
};
return (
- <PickMethodForm
- key={initialValues.itemId}
- initialValues={initialValues}
- quantities={quantities}
- locations={sharedToolsData?.locations ?? []}
- shelves={shelves}
- type="Tool"
- />
+ <VStack spacing={2}>
+ <PickMethodForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ locations={sharedToolsData?.locations ?? []}
+ shelves={sharedToolsData?.shelves ?? []}
+ type="Part"
+ />
+ <InventoryDetails
+ itemShelfQuantities={itemShelfQuantities}
+ itemUnitOfMeasureCode={itemUnitOfMeasureCode ?? "EA"}
+ locations={sharedToolsData?.locations ?? []}
+ pickMethod={initialValues}
+ quantities={quantities}
+ shelves={sharedToolsData?.shelves ?? []}
+ unitOfMeasures={sharedToolsData?.unitOfMeasures ?? []}
+ />
+ </VStack>
);
}
diff --git a/apps/carbon/app/routes/x+/tool+/_layout.tsx b/apps/carbon/app/routes/x+/tool+/_layout.tsx
index 88d558884b..c3ff2ea367 100644
--- a/apps/carbon/app/routes/x+/tool+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/tool+/_layout.tsx
@@ -1,5 +1,6 @@
import { Outlet } from "@remix-run/react";
import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { getShelvesList } from "~/modules/inventory";
import { getUnitOfMeasuresList } from "~/modules/items";
import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -21,13 +22,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "parts",
});
- const [unitOfMeasures, locations] = await Promise.all([
+ const [unitOfMeasures, locations, shelves] = await Promise.all([
getUnitOfMeasuresList(client, companyId),
getLocationsList(client, companyId),
+ getShelvesList(client, companyId),
]);
return {
locations: locations?.data ?? [],
+ shelves: shelves?.data ?? [],
unitOfMeasures: unitOfMeasures?.data ?? [],
};
}
diff --git a/apps/carbon/app/routes/x+/users+/employees.new.tsx b/apps/carbon/app/routes/x+/users+/employees.new.tsx
index b762f67c19..0cde5646dc 100644
--- a/apps/carbon/app/routes/x+/users+/employees.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/employees.new.tsx
@@ -49,12 +49,14 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { email, firstName, lastName, employeeType } = validation.data;
+ const { email, firstName, lastName, locationId, employeeType } =
+ validation.data;
const result = await createEmployeeAccount(client, {
email,
firstName,
lastName,
employeeType,
+ locationId,
companyId,
});
diff --git a/apps/carbon/app/styles/background.css b/apps/carbon/app/styles/background.css
index 0d626c7625..8bcd13aac2 100644
--- a/apps/carbon/app/styles/background.css
+++ b/apps/carbon/app/styles/background.css
@@ -21,7 +21,11 @@
}
.dark .background:before {
- background: radial-gradient(circle, rgba(2, 0, 36, 0) 0, #161616 100%);
+ background: radial-gradient(
+ circle,
+ hsl(var(--muted)) 0,
+ hsl(var(--background)) 100%
+ );
}
.background:after {
diff --git a/apps/carbon/app/trigger/post-transaction.ts b/apps/carbon/app/trigger/post-transaction.ts
index c89d24fb92..664cfe27d7 100644
--- a/apps/carbon/app/trigger/post-transaction.ts
+++ b/apps/carbon/app/trigger/post-transaction.ts
@@ -9,6 +9,7 @@ const supabaseClient = getSupabaseServiceRole();
const postTransactionSchema = z.object({
documentId: z.string(),
type: z.enum(["receipt", "purchase-invoice"]),
+ userId: z.string(),
});
export const postTransactionTask = task({
@@ -28,6 +29,7 @@ export const postTransactionTask = task({
{
body: {
receiptId: payload.documentId,
+ userId: payload.userId,
},
}
);
@@ -45,6 +47,7 @@ export const postTransactionTask = task({
{
body: {
invoiceId: payload.documentId,
+ userId: payload.userId,
},
}
);
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index ec7780d6e0..6d6549b0ff 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -44,10 +44,11 @@ export const path = {
),
sequences: (table: string) => `${api}/settings/sequences?table=${table}`,
services: `${api}/items/services`,
+
shifts: (id: string) =>
generatePath(`${api}/people/shifts?location=${id}`),
shelves: (id: string) =>
- generatePath(`${api}/items/shelf?locationId=${id}`),
+ generatePath(`${api}/inventory/shelves?locationId=${id}`),
supplierContacts: (id: string) =>
generatePath(`${api}/purchasing/supplier-contacts?supplierId=${id}`),
supplierLocations: (id: string) =>
@@ -351,7 +352,14 @@ export const path = {
integration: (name: string) =>
generatePath(`${x}/settings/integrations/${name}`),
integrations: `${x}/settings/integrations`,
- inventory: `${x}/inventory`,
+ inventory: `${x}/inventory/quantities`,
+ inventoryItem: (id: string) =>
+ generatePath(`${x}/inventory/quantities/${id}/details`),
+ inventoryItemActivity: (id: string) =>
+ generatePath(`${x}/inventory/quantities/${id}/activity`),
+ inventoryItemAdjustment: (id: string) =>
+ generatePath(`${x}/inventory/quantities/${id}/adjustment`),
+ inventoryRoot: `${x}/inventory`,
invoicing: `${x}/invoicing`,
items: `${x}/items`,
itemCostUpdate: (id: string) => generatePath(`${x}/items/cost/${id}`),
@@ -504,6 +512,7 @@ export const path = {
generatePath(`${x}/sales-order/${id}/new`),
newSalesRFQ: `${x}/sales-rfq/new`,
newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),
+ newShelf: `${x}/inventory/shelves/new`,
newShift: `${x}/people/shifts/new`,
newShippingMethod: `${x}/inventory/shipping-methods/new`,
newService: `${x}/service/new`,
@@ -681,6 +690,8 @@ export const path = {
generatePath(`${x}/sales-order/${id}/payment`),
salesOrderRelease: (id: string) =>
generatePath(`${x}/sales-order/${id}/release`),
+ salesOrderStatus: (id: string) =>
+ generatePath(`${x}/sales-order/${id}/status`),
salesOrders: `${x}/sales/orders`,
salesRfq: (id: string) => generatePath(`${x}/sales-rfq/${id}`),
salesRfqConvert: (id: string) =>
@@ -709,6 +720,7 @@ export const path = {
generatePath(`${x}/service/${id}/suppliers`),
settings: `${x}/settings`,
sequences: `${x}/settings/sequences`,
+ shelf: (id: string) => generatePath(`${x}/inventory/shelves/${id}`),
shift: (id: string) => generatePath(`${x}/people/shifts/${id}`),
shifts: `${x}/people/shifts`,
shipments: `${x}/inventory/shipments`,
diff --git a/apps/developers/app/components/Navigation/PrimaryNavigation.tsx b/apps/developers/app/components/Navigation/PrimaryNavigation.tsx
index 49e3ad6b61..46ed6efba1 100644
--- a/apps/developers/app/components/Navigation/PrimaryNavigation.tsx
+++ b/apps/developers/app/components/Navigation/PrimaryNavigation.tsx
@@ -108,11 +108,12 @@ const NavigationIconLink = forwardRef<
ref
) => {
const iconClasses = [
- "absolute left-3 top-3 flex rounded-md items-center items-center justify-center", // Layout
+ "absolute left-3 top-3 flex rounded-md items-center justify-center",
+ // Layout and sizing
];
const classes = [
- "relative",
+ "group relative",
"h-10 w-10 group-data-[state=expanded]:w-full",
"transition-all duration-200",
"flex items-center rounded-md",
diff --git a/package-lock.json b/package-lock.json
index 77a8cd5e34..89722c27bb 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,7 +10,8 @@
"packages/*"
],
"dependencies": {
- "@xyflow/react": "^12.2.0"
+ "@xyflow/react": "^12.2.0",
+ "react-intersection-observer": "^9.13.1"
},
"devDependencies": {
"eslint": "^8.23.1",
@@ -27923,6 +27924,20 @@
"react": "*"
}
},
+ "node_modules/react-intersection-observer": {
+ "version": "9.13.1",
+ "resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.13.1.tgz",
+ "integrity": "sha512-tSzDaTy0qwNPLJHg8XZhlyHTgGW6drFKTtvjdL+p6um12rcnp8Z5XstE+QNBJ7c64n5o0Lj4ilUleA41bmDoMw==",
+ "peerDependencies": {
+ "react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
diff --git a/package.json b/package.json
index 2be0097978..90685b0760 100755
--- a/package.json
+++ b/package.json
@@ -68,7 +68,8 @@
"packages/*"
],
"dependencies": {
- "@xyflow/react": "^12.2.0"
+ "@xyflow/react": "^12.2.0",
+ "react-intersection-observer": "^9.13.1"
},
"packageManager": "[email protected]"
}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 9c5493e80d..bb154703fd 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -159,6 +159,177 @@ export default {
tags: ["purchaseInvoiceStatusHistory"],
},
},
+ "/itemInventory": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.shelfId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnHand",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnPurchase",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnSalesOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnProductionOrder",
+ },
+ {
+ $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/itemInventory",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["itemInventory"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.itemInventory",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["itemInventory"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.shelfId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnHand",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnPurchase",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnSalesOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnProductionOrder",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["itemInventory"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.shelfId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnHand",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnPurchase",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnSalesOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInventory.quantityOnProductionOrder",
+ },
+ {
+ $ref: "#/parameters/body.itemInventory",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["itemInventory"],
+ },
+ },
"/userPermission": {
get: {
parameters: [
@@ -8364,6 +8535,9 @@ export default {
{
$ref: "#/parameters/rowFilter.fixtures.itemTrackingType",
},
+ {
+ $ref: "#/parameters/rowFilter.fixtures.unitOfMeasureCode",
+ },
{
$ref: "#/parameters/rowFilter.fixtures.active",
},
@@ -11319,6 +11493,9 @@ export default {
{
$ref: "#/parameters/rowFilter.shelf.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.shelf.name",
+ },
{
$ref: "#/parameters/select",
},
@@ -11408,6 +11585,9 @@ export default {
{
$ref: "#/parameters/rowFilter.shelf.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.shelf.name",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -11451,6 +11631,9 @@ export default {
{
$ref: "#/parameters/rowFilter.shelf.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.shelf.name",
+ },
{
$ref: "#/parameters/body.shelf",
},
@@ -21033,6 +21216,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemLedger.createdAt",
},
+ {
+ $ref: "#/parameters/rowFilter.itemLedger.createdBy",
+ },
{
$ref: "#/parameters/select",
},
@@ -21134,6 +21320,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemLedger.createdAt",
},
+ {
+ $ref: "#/parameters/rowFilter.itemLedger.createdBy",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -21189,6 +21378,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemLedger.createdAt",
},
+ {
+ $ref: "#/parameters/rowFilter.itemLedger.createdBy",
+ },
{
$ref: "#/parameters/body.itemLedger",
},
@@ -23709,72 +23901,6 @@ export default {
tags: ["workCenterProcess"],
},
},
- "/itemQuantities": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.itemQuantities.itemId",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.companyId",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.locationId",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.quantityOnHand",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.quantityOnPurchaseOrder",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.quantityOnSalesOrder",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.quantityOnProdOrder",
- },
- {
- $ref: "#/parameters/rowFilter.itemQuantities.quantityAvailable",
- },
- {
- $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/itemQuantities",
- },
- type: "array",
- },
- },
- "206": {
- description: "Partial Content",
- },
- },
- tags: ["itemQuantities"],
- },
- },
"/partners": {
get: {
parameters: [
@@ -34733,6 +34859,63 @@ export default {
tags: ["(rpc) get_my_claim"],
},
},
+ "/rpc/get_item_quantities": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "location_id",
+ required: true,
+ 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_quantities"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ location_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["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_quantities"],
+ },
+ },
"/rpc/get_method_tree": {
get: {
parameters: [
@@ -34890,6 +35073,70 @@ export default {
},
type: "object",
},
+ itemInventory: {
+ required: [
+ "id",
+ "itemId",
+ "companyId",
+ "quantityOnHand",
+ "quantityOnPurchase",
+ "quantityOnSalesOrder",
+ "quantityOnProductionOrder",
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ locationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ quantityOnHand: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ quantityOnPurchase: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ quantityOnSalesOrder: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ quantityOnProductionOrder: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ },
+ type: "object",
+ },
userPermission: {
required: ["id"],
properties: {
@@ -36599,6 +36846,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -37112,6 +37361,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -38669,6 +38920,10 @@ export default {
format: 'public."itemTrackingType"',
type: "string",
},
+ unitOfMeasureCode: {
+ format: "text",
+ type: "string",
+ },
active: {
format: "boolean",
type: "boolean",
@@ -39012,6 +39267,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -39784,6 +40041,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -39993,6 +40252,7 @@ export default {
"companyId",
"createdBy",
"createdAt",
+ "name",
],
properties: {
id: {
@@ -40002,7 +40262,7 @@ export default {
},
locationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
format: "text",
type: "string",
},
@@ -40047,6 +40307,10 @@ export default {
customFields: {
format: "jsonb",
},
+ name: {
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -41365,6 +41629,7 @@ export default {
"Completed",
"Invoiced",
"Cancelled",
+ "Closed",
],
format: 'public."salesOrderStatus"',
type: "string",
@@ -43320,6 +43585,7 @@ export default {
"Completed",
"Invoiced",
"Cancelled",
+ "Closed",
],
format: 'public."salesOrderStatus"',
type: "string",
@@ -43693,6 +43959,8 @@ export default {
type: "string",
},
defaultShelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -43998,6 +44266,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -44489,6 +44759,7 @@ export default {
"quantity",
"companyId",
"createdAt",
+ "createdBy",
],
properties: {
id: {
@@ -44569,6 +44840,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -44587,6 +44860,13 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ createdBy: {
+ default: "system",
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -45635,52 +45915,11 @@ export default {
},
type: "object",
},
- itemQuantities: {
- properties: {
- itemId: {
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string",
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string",
- },
- locationId: {
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string",
- },
- quantityOnHand: {
- format: "numeric",
- type: "number",
- },
- quantityOnPurchaseOrder: {
- format: "numeric",
- type: "number",
- },
- quantityOnSalesOrder: {
- format: "integer",
- type: "integer",
- },
- quantityOnProdOrder: {
- format: "integer",
- type: "integer",
- },
- quantityAvailable: {
- format: "integer",
- type: "integer",
- },
- },
- type: "object",
- },
partners: {
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",
},
@@ -45729,7 +45968,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",
},
@@ -46593,6 +46832,7 @@ export default {
"Completed",
"Invoiced",
"Cancelled",
+ "Closed",
],
format: 'public."salesOrderStatus"',
type: "string",
@@ -49775,6 +50015,8 @@ export default {
type: "string",
},
shelfId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shelf.id`.<fk table='shelf' column='id'/>",
format: "text",
type: "string",
},
@@ -50112,6 +50354,78 @@ export default {
in: "query",
type: "string",
},
+ "body.itemInventory": {
+ name: "itemInventory",
+ description: "itemInventory",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/itemInventory",
+ },
+ },
+ "rowFilter.itemInventory.id": {
+ name: "id",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.itemId": {
+ name: "itemId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.locationId": {
+ name: "locationId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.shelfId": {
+ name: "shelfId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.companyId": {
+ name: "companyId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.quantityOnHand": {
+ name: "quantityOnHand",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.quantityOnPurchase": {
+ name: "quantityOnPurchase",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.quantityOnSalesOrder": {
+ name: "quantityOnSalesOrder",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.itemInventory.quantityOnProductionOrder": {
+ name: "quantityOnProductionOrder",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
"body.userPermission": {
name: "userPermission",
description: "userPermission",
@@ -54921,6 +55235,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.fixtures.unitOfMeasureCode": {
+ name: "unitOfMeasureCode",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"rowFilter.fixtures.active": {
name: "active",
required: false,
@@ -56738,6 +57059,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.shelf.name": {
+ name: "name",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"body.supplierLedger": {
name: "supplierLedger",
description: "supplierLedger",
@@ -62711,6 +63039,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.itemLedger.createdBy": {
+ name: "createdBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"body.salesRfqFavorite": {
name: "salesRfqFavorite",
description: "salesRfqFavorite",
@@ -64117,71 +64452,6 @@ export default {
in: "query",
type: "string",
},
- "body.itemQuantities": {
- name: "itemQuantities",
- description: "itemQuantities",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/itemQuantities",
- },
- },
- "rowFilter.itemQuantities.itemId": {
- name: "itemId",
- required: false,
- format: "text",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.companyId": {
- name: "companyId",
- required: false,
- format: "text",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.locationId": {
- name: "locationId",
- required: false,
- format: "text",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.quantityOnHand": {
- name: "quantityOnHand",
- required: false,
- format: "numeric",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.quantityOnPurchaseOrder": {
- name: "quantityOnPurchaseOrder",
- required: false,
- format: "numeric",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.quantityOnSalesOrder": {
- name: "quantityOnSalesOrder",
- required: false,
- format: "integer",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.quantityOnProdOrder": {
- name: "quantityOnProdOrder",
- required: false,
- format: "integer",
- in: "query",
- type: "string",
- },
- "rowFilter.itemQuantities.quantityAvailable": {
- name: "quantityAvailable",
- required: false,
- format: "integer",
- in: "query",
- type: "string",
- },
"body.partners": {
name: "partners",
description: "partners",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 1270b64af2..11056a461d 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1836,13 +1836,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "buyMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "buyMethod_supplierId_fkey"
columns: ["supplierId"]
@@ -2218,13 +2211,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "consumable_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "consumable_updatedBy_fkey"
columns: ["updatedBy"]
@@ -3351,13 +3337,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "customerPartToItem_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
]
}
customerPayment: {
@@ -4804,13 +4783,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "employeeJob_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "employeeJob_locationId_fkey"
columns: ["locationId"]
@@ -5335,13 +5307,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "fixture_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "fixture_updatedBy_fkey"
columns: ["updatedBy"]
@@ -5895,13 +5860,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemCost_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "itemCost_itemPostingGroupId_fkey"
columns: ["itemPostingGroupId"]
@@ -5981,10 +5939,111 @@ export type Database = {
},
]
}
+ itemInventory: {
+ Row: {
+ companyId: string
+ id: string
+ itemId: string
+ locationId: string | null
+ quantityOnHand: number
+ quantityOnProductionOrder: number
+ quantityOnPurchase: number
+ quantityOnSalesOrder: number
+ shelfId: string | null
+ }
+ Insert: {
+ companyId: string
+ id?: string
+ itemId: string
+ locationId?: string | null
+ quantityOnHand?: number
+ quantityOnProductionOrder?: number
+ quantityOnPurchase?: number
+ quantityOnSalesOrder?: number
+ shelfId?: string | null
+ }
+ Update: {
+ companyId?: string
+ id?: string
+ itemId?: string
+ locationId?: string | null
+ quantityOnHand?: number
+ quantityOnProductionOrder?: number
+ quantityOnPurchase?: number
+ quantityOnSalesOrder?: number
+ shelfId?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInventory_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrders"
+ referencedColumns: ["locationId"]
+ },
+ {
+ foreignKeyName: "itemInventory_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["locationId"]
+ },
+ {
+ foreignKeyName: "itemInventory_shelfId_fkey"
+ columns: ["shelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
itemLedger: {
Row: {
companyId: string
createdAt: string
+ createdBy: string
documentId: string | null
documentType:
| Database["public"]["Enums"]["itemLedgerDocumentType"]
@@ -6003,6 +6062,7 @@ export type Database = {
Insert: {
companyId: string
createdAt?: string
+ createdBy?: string
documentId?: string | null
documentType?:
| Database["public"]["Enums"]["itemLedgerDocumentType"]
@@ -6021,6 +6081,7 @@ export type Database = {
Update: {
companyId?: string
createdAt?: string
+ createdBy?: string
documentId?: string | null
documentType?:
| Database["public"]["Enums"]["itemLedgerDocumentType"]
@@ -6038,25 +6099,46 @@ export type Database = {
}
Relationships: [
{
- foreignKeyName: "itemLedger_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
isOneToOne: false
- referencedRelation: "item"
+ referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "itemLedger_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "itemLedger_locationId_fkey"
- columns: ["locationId"]
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
},
{
foreignKeyName: "itemLedger_locationId_fkey"
@@ -6081,10 +6163,10 @@ export type Database = {
},
{
foreignKeyName: "itemLedger_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "partLeger_companyId_fkey"
@@ -6257,20 +6339,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemPlanning_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "itemPlanning_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "itemPlanning_locationId_fkey"
columns: ["locationId"]
@@ -6593,13 +6661,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemReplenishment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "itemReplenishment_preferredSupplierId_fkey"
columns: ["preferredSupplierId"]
@@ -6803,13 +6864,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemUnitSalePrice_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "itemUnitSalePrice_salesUnitOfMeasureId_fkey"
columns: ["salesUnitOfMeasureCode", "companyId"]
@@ -7072,20 +7126,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "job_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "job_locationId_fkey"
columns: ["locationId"]
@@ -7397,13 +7437,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobMakeMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "jobMakeMethod_jobId_fkey"
columns: ["jobId"]
@@ -7610,13 +7643,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "jobMaterial_jobId_fkey"
columns: ["jobId"]
@@ -8323,13 +8349,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "method_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
]
}
material: {
@@ -8490,13 +8509,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "material_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "material_materialFormId_fkey"
columns: ["materialFormId"]
@@ -9018,13 +9030,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "methodMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "methodMaterial_materialMakeMethodId_fkey"
columns: ["materialMakeMethodId"]
@@ -10101,13 +10106,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_id_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -10549,20 +10547,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "pickMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "pickMethod_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "pickMethod_locationId_fkey"
columns: ["locationId"]
@@ -10586,10 +10570,10 @@ export type Database = {
},
{
foreignKeyName: "pickMethod_shelfId_fkey"
- columns: ["defaultShelfId", "locationId"]
+ columns: ["defaultShelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "pickMethod_updatedBy_fkey"
@@ -10826,13 +10810,6 @@ export type Database = {
referencedRelation: "itemPostingGroup"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "postingGroupInventory_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "postingGroupInventory_locationId_fkey"
columns: ["locationId"]
@@ -12030,20 +12007,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "purchaseInvoiceLines_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "purchaseInvoiceLines_locationId_fkey"
columns: ["locationId"]
@@ -12109,10 +12072,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseInvoiceLines_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "purchaseInvoiceLines_updatedBy_fkey"
@@ -12709,13 +12672,6 @@ export type Database = {
referencedRelation: "purchaseOrders"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseOrderDelivery_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "purchaseOrderDelivery_locationId_fkey"
columns: ["locationId"]
@@ -13018,13 +12974,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "purchaseOrderLine_purchaseOrderId_fkey"
columns: ["purchaseOrderId"]
@@ -13055,10 +13004,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "purchaseOrderLine_updatedBy_fkey"
@@ -13817,13 +13766,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "quote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
@@ -14168,13 +14110,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -14499,13 +14434,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteMakeMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteMakeMethod_parentMaterialId_fkey"
columns: ["parentMaterialId"]
@@ -14736,13 +14664,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteMaterial_quoteId_fkey"
columns: ["quoteId"]
@@ -15358,13 +15279,6 @@ export type Database = {
referencedRelation: "quotes"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteShipment_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "quoteShipment_locationId_fkey"
columns: ["locationId"]
@@ -15603,13 +15517,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "receipt_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "receipt_locationId_fkey"
columns: ["locationId"]
@@ -15807,20 +15714,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "receiptLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "receiptLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "receiptLine_locationId_fkey"
columns: ["locationId"]
@@ -15858,10 +15751,10 @@ export type Database = {
},
{
foreignKeyName: "receiptLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "receiptLine_updatedBy_fkey"
@@ -16146,13 +16039,6 @@ export type Database = {
referencedRelation: "customerLocation"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrder_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesOrder_locationId_fkey"
columns: ["locationId"]
@@ -16443,13 +16329,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesOrderLine_salesOrderId_fkey"
columns: ["salesOrderId"]
@@ -16473,10 +16352,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey"
@@ -16840,13 +16719,6 @@ export type Database = {
referencedRelation: "salesOrders"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrderShipment_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesOrderShipment_locationId_fkey"
columns: ["locationId"]
@@ -17320,13 +17192,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "salesRfq_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesRfq_locationId_fkey"
columns: ["locationId"]
@@ -17582,13 +17447,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesRfqLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesRfqLine_salesRfqId_fkey"
columns: ["salesRfqId"]
@@ -17967,13 +17825,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "service_updatedBy_fkey"
columns: ["updatedBy"]
@@ -18020,6 +17871,7 @@ export type Database = {
customFields: Json | null
id: string
locationId: string
+ name: string
updatedAt: string | null
updatedBy: string | null
warehouseId: string | null
@@ -18032,6 +17884,7 @@ export type Database = {
customFields?: Json | null
id: string
locationId: string
+ name: string
updatedAt?: string | null
updatedBy?: string | null
warehouseId?: string | null
@@ -18044,6 +17897,7 @@ export type Database = {
customFields?: Json | null
id?: string
locationId?: string
+ name?: string
updatedAt?: string | null
updatedBy?: string | null
warehouseId?: string | null
@@ -18112,13 +17966,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "shelf_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "shelf_locationId_fkey"
columns: ["locationId"]
@@ -18312,13 +18159,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "shifts_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "shifts_locationId_fkey"
columns: ["locationId"]
@@ -20399,13 +20239,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "tool_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
@@ -21333,13 +21166,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "warehouse_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "warehouse_locationId_fkey"
columns: ["locationId"]
@@ -21517,13 +21343,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "workCenter_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "workCenter_locationId_fkey"
columns: ["locationId"]
@@ -22330,13 +22149,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "consumable_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "consumable_updatedBy_fkey"
columns: ["updatedBy"]
@@ -22959,6 +22771,7 @@ export type Database = {
| null
supplierIds: string[] | null
thumbnailPath: string | null
+ unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -23089,13 +22902,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "fixture_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "fixture_updatedBy_fkey"
columns: ["updatedBy"]
@@ -23345,48 +23151,6 @@ export type Database = {
}
Relationships: []
}
- itemQuantities: {
- Row: {
- companyId: string | null
- itemId: string | null
- locationId: string | null
- quantityAvailable: number | null
- quantityOnHand: number | null
- quantityOnProdOrder: number | null
- quantityOnPurchaseOrder: number | null
- quantityOnSalesOrder: number | null
- }
- Relationships: [
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- ]
- }
jobMaterialWithMakeMethodId: {
Row: {
companyId: string | null
@@ -23483,13 +23247,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "jobMaterial_jobId_fkey"
columns: ["jobId"]
@@ -23945,13 +23702,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "job_locationId_fkey"
columns: ["locationId"]
@@ -23959,13 +23709,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "job_locationId_fkey"
columns: ["locationId"]
@@ -24269,13 +24012,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "material_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "material_materialFormId_fkey"
columns: ["materialFormId"]
@@ -24650,13 +24386,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_id_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -25196,13 +24925,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "purchaseOrderLine_purchaseOrderId_fkey"
columns: ["purchaseOrderId"]
@@ -25233,10 +24955,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "purchaseOrderLine_updatedBy_fkey"
@@ -25766,13 +25488,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -25933,13 +25648,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteMaterial_quoteId_fkey"
columns: ["quoteId"]
@@ -26517,13 +26225,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
@@ -26740,13 +26441,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "receipt_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "receipt_locationId_fkey"
columns: ["locationId"]
@@ -26973,13 +26667,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesOrderLine_salesOrderId_fkey"
columns: ["salesOrderId"]
@@ -27003,10 +26690,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey"
@@ -27441,13 +27128,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesRfqLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesRfqLine_salesRfqId_fkey"
columns: ["salesRfqId"]
@@ -27752,13 +27432,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesRfq_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesRfq_locationId_fkey"
columns: ["locationId"]
@@ -27976,13 +27649,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "service_updatedBy_fkey"
columns: ["updatedBy"]
@@ -28114,13 +27780,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "shifts_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "shifts_locationId_fkey"
columns: ["locationId"]
@@ -28712,13 +28371,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "tool_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
@@ -28770,13 +28422,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "employeeJob_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "employeeJob_locationId_fkey"
columns: ["locationId"]
@@ -28913,13 +28558,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "workCenter_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "workCenter_locationId_fkey"
columns: ["locationId"]
@@ -29002,6 +28640,34 @@ export type Database = {
}
Returns: string
}
+ get_item_quantities: {
+ Args: {
+ location_id: string
+ }
+ Returns: {
+ itemId: string
+ companyId: string
+ locationId: string
+ quantityOnHand: number
+ quantityOnPurchaseOrder: number
+ quantityOnSalesOrder: number
+ quantityOnProdOrder: number
+ quantityAvailable: number
+ materialSubstanceId: string
+ materialFormId: string
+ grade: string
+ dimensions: string
+ finish: string
+ readableId: string
+ type: string
+ name: string
+ active: boolean
+ itemTrackingType: string
+ thumbnailPath: string
+ locationName: string
+ unitOfMeasureCode: string
+ }[]
+ }
get_job_method: {
Args: {
jid: string
@@ -29507,6 +29173,7 @@ export type Database = {
| "Completed"
| "Invoiced"
| "Cancelled"
+ | "Closed"
salesOrderTransactionType:
| "Edit"
| "Favorite"
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 9a090de28f..fa9f864a73 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -371,6 +371,7 @@ serve(async (req: Request) => {
customerPartRevision: line.customerPartRevision,
description: line.description ?? line.itemName ?? "",
itemType: line.itemType!,
+ locationId: salesRfq.data?.locationId,
methodType: line.methodType!,
modelUploadId: line.modelUploadId,
notes: line.internalNotes,
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 096fd38d4b..831f6fc09a 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -1348,14 +1348,11 @@ serve(async (req: Request) => {
quoteMethodTree,
(node: QuoteMethodTreeItem) => {
if (node.data.itemId && node.data.methodType === "Make") {
- console.log(`Adding item ID: ${node.data.itemId}`);
madeItemIds.push(node.data.itemId);
}
}
);
- console.log({ madeItemIds });
-
const makeMethods = await client
.from("makeMethod")
.select("*")
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 1270b64af2..11056a461d 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1836,13 +1836,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "buyMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "buyMethod_supplierId_fkey"
columns: ["supplierId"]
@@ -2218,13 +2211,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "consumable_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "consumable_updatedBy_fkey"
columns: ["updatedBy"]
@@ -3351,13 +3337,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "customerPartToItem_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
]
}
customerPayment: {
@@ -4804,13 +4783,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "employeeJob_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "employeeJob_locationId_fkey"
columns: ["locationId"]
@@ -5335,13 +5307,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "fixture_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "fixture_updatedBy_fkey"
columns: ["updatedBy"]
@@ -5895,13 +5860,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemCost_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "itemCost_itemPostingGroupId_fkey"
columns: ["itemPostingGroupId"]
@@ -5981,10 +5939,111 @@ export type Database = {
},
]
}
+ itemInventory: {
+ Row: {
+ companyId: string
+ id: string
+ itemId: string
+ locationId: string | null
+ quantityOnHand: number
+ quantityOnProductionOrder: number
+ quantityOnPurchase: number
+ quantityOnSalesOrder: number
+ shelfId: string | null
+ }
+ Insert: {
+ companyId: string
+ id?: string
+ itemId: string
+ locationId?: string | null
+ quantityOnHand?: number
+ quantityOnProductionOrder?: number
+ quantityOnPurchase?: number
+ quantityOnSalesOrder?: number
+ shelfId?: string | null
+ }
+ Update: {
+ companyId?: string
+ id?: string
+ itemId?: string
+ locationId?: string | null
+ quantityOnHand?: number
+ quantityOnProductionOrder?: number
+ quantityOnPurchase?: number
+ quantityOnSalesOrder?: number
+ shelfId?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInventory_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInventory_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInventory_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrders"
+ referencedColumns: ["locationId"]
+ },
+ {
+ foreignKeyName: "itemInventory_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "salesOrders"
+ referencedColumns: ["locationId"]
+ },
+ {
+ foreignKeyName: "itemInventory_shelfId_fkey"
+ columns: ["shelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
itemLedger: {
Row: {
companyId: string
createdAt: string
+ createdBy: string
documentId: string | null
documentType:
| Database["public"]["Enums"]["itemLedgerDocumentType"]
@@ -6003,6 +6062,7 @@ export type Database = {
Insert: {
companyId: string
createdAt?: string
+ createdBy?: string
documentId?: string | null
documentType?:
| Database["public"]["Enums"]["itemLedgerDocumentType"]
@@ -6021,6 +6081,7 @@ export type Database = {
Update: {
companyId?: string
createdAt?: string
+ createdBy?: string
documentId?: string | null
documentType?:
| Database["public"]["Enums"]["itemLedgerDocumentType"]
@@ -6038,25 +6099,46 @@ export type Database = {
}
Relationships: [
{
- foreignKeyName: "itemLedger_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
isOneToOne: false
- referencedRelation: "item"
+ referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "itemLedger_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "itemLedger_locationId_fkey"
- columns: ["locationId"]
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
},
{
foreignKeyName: "itemLedger_locationId_fkey"
@@ -6081,10 +6163,10 @@ export type Database = {
},
{
foreignKeyName: "itemLedger_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "partLeger_companyId_fkey"
@@ -6257,20 +6339,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemPlanning_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "itemPlanning_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "itemPlanning_locationId_fkey"
columns: ["locationId"]
@@ -6593,13 +6661,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemReplenishment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "itemReplenishment_preferredSupplierId_fkey"
columns: ["preferredSupplierId"]
@@ -6803,13 +6864,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "itemUnitSalePrice_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "itemUnitSalePrice_salesUnitOfMeasureId_fkey"
columns: ["salesUnitOfMeasureCode", "companyId"]
@@ -7072,20 +7126,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "job_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "job_locationId_fkey"
columns: ["locationId"]
@@ -7397,13 +7437,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobMakeMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "jobMakeMethod_jobId_fkey"
columns: ["jobId"]
@@ -7610,13 +7643,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "jobMaterial_jobId_fkey"
columns: ["jobId"]
@@ -8323,13 +8349,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "method_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
]
}
material: {
@@ -8490,13 +8509,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "material_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "material_materialFormId_fkey"
columns: ["materialFormId"]
@@ -9018,13 +9030,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "methodMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "methodMaterial_materialMakeMethodId_fkey"
columns: ["materialMakeMethodId"]
@@ -10101,13 +10106,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_id_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -10549,20 +10547,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "pickMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "pickMethod_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "pickMethod_locationId_fkey"
columns: ["locationId"]
@@ -10586,10 +10570,10 @@ export type Database = {
},
{
foreignKeyName: "pickMethod_shelfId_fkey"
- columns: ["defaultShelfId", "locationId"]
+ columns: ["defaultShelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "pickMethod_updatedBy_fkey"
@@ -10826,13 +10810,6 @@ export type Database = {
referencedRelation: "itemPostingGroup"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "postingGroupInventory_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "postingGroupInventory_locationId_fkey"
columns: ["locationId"]
@@ -12030,20 +12007,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "purchaseInvoiceLines_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "purchaseInvoiceLines_locationId_fkey"
columns: ["locationId"]
@@ -12109,10 +12072,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseInvoiceLines_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "purchaseInvoiceLines_updatedBy_fkey"
@@ -12709,13 +12672,6 @@ export type Database = {
referencedRelation: "purchaseOrders"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseOrderDelivery_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "purchaseOrderDelivery_locationId_fkey"
columns: ["locationId"]
@@ -13018,13 +12974,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "purchaseOrderLine_purchaseOrderId_fkey"
columns: ["purchaseOrderId"]
@@ -13055,10 +13004,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "purchaseOrderLine_updatedBy_fkey"
@@ -13817,13 +13766,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "quote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
@@ -14168,13 +14110,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -14499,13 +14434,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteMakeMethod_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteMakeMethod_parentMaterialId_fkey"
columns: ["parentMaterialId"]
@@ -14736,13 +14664,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteMaterial_quoteId_fkey"
columns: ["quoteId"]
@@ -15358,13 +15279,6 @@ export type Database = {
referencedRelation: "quotes"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteShipment_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "quoteShipment_locationId_fkey"
columns: ["locationId"]
@@ -15603,13 +15517,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "receipt_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "receipt_locationId_fkey"
columns: ["locationId"]
@@ -15807,20 +15714,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "receiptLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "receiptLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "receiptLine_locationId_fkey"
columns: ["locationId"]
@@ -15858,10 +15751,10 @@ export type Database = {
},
{
foreignKeyName: "receiptLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "receiptLine_updatedBy_fkey"
@@ -16146,13 +16039,6 @@ export type Database = {
referencedRelation: "customerLocation"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrder_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesOrder_locationId_fkey"
columns: ["locationId"]
@@ -16443,13 +16329,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesOrderLine_salesOrderId_fkey"
columns: ["salesOrderId"]
@@ -16473,10 +16352,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey"
@@ -16840,13 +16719,6 @@ export type Database = {
referencedRelation: "salesOrders"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrderShipment_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesOrderShipment_locationId_fkey"
columns: ["locationId"]
@@ -17320,13 +17192,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "salesRfq_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesRfq_locationId_fkey"
columns: ["locationId"]
@@ -17582,13 +17447,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesRfqLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesRfqLine_salesRfqId_fkey"
columns: ["salesRfqId"]
@@ -17967,13 +17825,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "service_updatedBy_fkey"
columns: ["updatedBy"]
@@ -18020,6 +17871,7 @@ export type Database = {
customFields: Json | null
id: string
locationId: string
+ name: string
updatedAt: string | null
updatedBy: string | null
warehouseId: string | null
@@ -18032,6 +17884,7 @@ export type Database = {
customFields?: Json | null
id: string
locationId: string
+ name: string
updatedAt?: string | null
updatedBy?: string | null
warehouseId?: string | null
@@ -18044,6 +17897,7 @@ export type Database = {
customFields?: Json | null
id?: string
locationId?: string
+ name?: string
updatedAt?: string | null
updatedBy?: string | null
warehouseId?: string | null
@@ -18112,13 +17966,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "shelf_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "shelf_locationId_fkey"
columns: ["locationId"]
@@ -18312,13 +18159,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "shifts_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "shifts_locationId_fkey"
columns: ["locationId"]
@@ -20399,13 +20239,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "tool_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
@@ -21333,13 +21166,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "warehouse_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "warehouse_locationId_fkey"
columns: ["locationId"]
@@ -21517,13 +21343,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "workCenter_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "workCenter_locationId_fkey"
columns: ["locationId"]
@@ -22330,13 +22149,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "consumable_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "consumable_updatedBy_fkey"
columns: ["updatedBy"]
@@ -22959,6 +22771,7 @@ export type Database = {
| null
supplierIds: string[] | null
thumbnailPath: string | null
+ unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -23089,13 +22902,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "fixture_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "fixture_updatedBy_fkey"
columns: ["updatedBy"]
@@ -23345,48 +23151,6 @@ export type Database = {
}
Relationships: []
}
- itemQuantities: {
- Row: {
- companyId: string | null
- itemId: string | null
- locationId: string | null
- quantityAvailable: number | null
- quantityOnHand: number | null
- quantityOnProdOrder: number | null
- quantityOnPurchaseOrder: number | null
- quantityOnSalesOrder: number | null
- }
- Relationships: [
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "item_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- ]
- }
jobMaterialWithMakeMethodId: {
Row: {
companyId: string | null
@@ -23483,13 +23247,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "jobMaterial_jobId_fkey"
columns: ["jobId"]
@@ -23945,13 +23702,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "job_locationId_fkey"
columns: ["locationId"]
@@ -23959,13 +23709,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "job_locationId_fkey"
columns: ["locationId"]
@@ -24269,13 +24012,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "material_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "material_materialFormId_fkey"
columns: ["materialFormId"]
@@ -24650,13 +24386,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_id_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -25196,13 +24925,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "purchaseOrderLine_purchaseOrderId_fkey"
columns: ["purchaseOrderId"]
@@ -25233,10 +24955,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "purchaseOrderLine_updatedBy_fkey"
@@ -25766,13 +25488,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -25933,13 +25648,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quoteMaterial_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "quoteMaterial_quoteId_fkey"
columns: ["quoteId"]
@@ -26517,13 +26225,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
@@ -26740,13 +26441,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "receipt_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "receipt_locationId_fkey"
columns: ["locationId"]
@@ -26973,13 +26667,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesOrderLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesOrderLine_salesOrderId_fkey"
columns: ["salesOrderId"]
@@ -27003,10 +26690,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
+ columns: ["shelfId"]
isOneToOne: false
referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
+ referencedColumns: ["id"]
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey"
@@ -27441,13 +27128,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesRfqLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "salesRfqLine_salesRfqId_fkey"
columns: ["salesRfqId"]
@@ -27752,13 +27432,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "salesRfq_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "salesRfq_locationId_fkey"
columns: ["locationId"]
@@ -27976,13 +27649,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "service_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "service_updatedBy_fkey"
columns: ["updatedBy"]
@@ -28114,13 +27780,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "shifts_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "shifts_locationId_fkey"
columns: ["locationId"]
@@ -28712,13 +28371,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "tool_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
@@ -28770,13 +28422,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "employeeJob_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "employeeJob_locationId_fkey"
columns: ["locationId"]
@@ -28913,13 +28558,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "workCenter_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
{
foreignKeyName: "workCenter_locationId_fkey"
columns: ["locationId"]
@@ -29002,6 +28640,34 @@ export type Database = {
}
Returns: string
}
+ get_item_quantities: {
+ Args: {
+ location_id: string
+ }
+ Returns: {
+ itemId: string
+ companyId: string
+ locationId: string
+ quantityOnHand: number
+ quantityOnPurchaseOrder: number
+ quantityOnSalesOrder: number
+ quantityOnProdOrder: number
+ quantityAvailable: number
+ materialSubstanceId: string
+ materialFormId: string
+ grade: string
+ dimensions: string
+ finish: string
+ readableId: string
+ type: string
+ name: string
+ active: boolean
+ itemTrackingType: string
+ thumbnailPath: string
+ locationName: string
+ unitOfMeasureCode: string
+ }[]
+ }
get_job_method: {
Args: {
jid: string
@@ -29507,6 +29173,7 @@ export type Database = {
| "Completed"
| "Invoiced"
| "Cancelled"
+ | "Closed"
salesOrderTransactionType:
| "Edit"
| "Favorite"
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index b1f574321c..fc89e64b97 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -2,6 +2,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import z from "https://deno.land/x/[email protected]/index.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
@@ -17,22 +18,27 @@ import {
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
+const payloadValidator = z.object({
+ invoiceId: z.string(),
+ userId: z.string(),
+});
+
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
- const { invoiceId } = await req.json();
+ const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
- console.log({
- function: "post-purchase-invoice",
- invoiceId,
- });
-
try {
- if (!invoiceId) throw new Error("Payload is missing invoiceId");
+ const { invoiceId, userId } = payloadValidator.parse(payload);
+ console.log({
+ function: "post-purchase-invoice",
+ invoiceId,
+ userId,
+ });
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
const [purchaseInvoice, purchaseInvoiceLines] = await Promise.all([
@@ -356,6 +362,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id ?? undefined,
externalDocumentId:
purchaseInvoice.data?.supplierReference ?? undefined,
+ createdBy: userId,
companyId,
});
}
@@ -1138,12 +1145,12 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- if (invoiceId) {
+ if ("invoiceId" in payload) {
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
- client
+ await client
.from("purchaseInvoice")
.update({ status: "Draft" })
- .eq("id", invoiceId);
+ .eq("id", payload.invoiceId);
}
return new Response(JSON.stringify(err), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 8c169510c4..ed6d3ffcf7 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -1,6 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
@@ -15,21 +16,27 @@ import {
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
+const payloadValidator = z.object({
+ receiptId: z.string(),
+ userId: z.string(),
+});
+
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
- const { receiptId } = await req.json();
+ const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
- console.log({
- function: "post-receipt",
- receiptId,
- });
-
try {
- if (!receiptId) throw new Error("Payload is missing receiptId");
+ const { receiptId, userId } = payloadValidator.parse(payload);
+
+ console.log({
+ function: "post-receipt",
+ receiptId,
+ userId,
+ });
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
@@ -612,6 +619,7 @@ serve(async (req: Request) => {
documentType: "Purchase Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId: receipt.data?.externalDocumentId ?? undefined,
+ createdBy: userId,
companyId,
});
}
@@ -749,9 +757,12 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- if (receiptId) {
+ if ("receiptId" in payload) {
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
- client.from("receipt").update({ status: "Draft" }).eq("id", receiptId);
+ await client
+ .from("receipt")
+ .update({ status: "Draft" })
+ .eq("id", payload.receiptId);
}
return new Response(JSON.stringify(err), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
diff --git a/packages/database/supabase/migrations/20240905235530_update-itemQuantities-view.sql b/packages/database/supabase/migrations/20240905235530_update-itemQuantities-view.sql
new file mode 100644
index 0000000000..046e424e0f
--- /dev/null
+++ b/packages/database/supabase/migrations/20240905235530_update-itemQuantities-view.sql
@@ -0,0 +1,52 @@
+CREATE OR REPLACE VIEW "itemQuantities" AS
+ SELECT
+ i."id" AS "itemId",
+ i."companyId",
+ loc."id" AS "locationId",
+ COALESCE(SUM(
+ CASE
+ WHEN il."entryType" = 'Positive Adjmt.' THEN il."quantity"
+ WHEN il."entryType" = 'Negative Adjmt.' THEN -il."quantity"
+ ELSE il."quantity"
+ END
+ ), 0) AS "quantityOnHand",
+ COALESCE(pol."quantityToReceive", 0) AS "quantityOnPurchaseOrder",
+ 0 AS "quantityOnSalesOrder",
+ 0 AS "quantityOnProdOrder",
+ 0 AS "quantityAvailable",
+ i."readableId",
+ i."type",
+ i."name",
+ i."active",
+ i."itemTrackingType",
+ m."thumbnailPath",
+ loc."name" AS "locationName"
+ FROM "item" i
+ CROSS JOIN "location" loc
+ LEFT JOIN "modelUpload" m ON m."id" = i."modelUploadId"
+ LEFT JOIN "itemLedger" il
+ ON il."itemId" = i."id" AND il."locationId" = loc."id"
+ LEFT JOIN (
+ -- TODO: multiply by conversion factor
+ SELECT
+ pol."itemId",
+ pol."locationId",
+ COALESCE(SUM(GREATEST(pol."quantityToReceive", 0)), 0) AS "quantityToReceive"
+ FROM "purchaseOrderLine" pol
+ INNER JOIN "purchaseOrder" po
+ ON pol."purchaseOrderId" = po."id"
+ WHERE po."status" != 'Draft'
+ AND po."status" != 'Rejected'
+ AND po."status" != 'Closed'
+ GROUP BY
+ pol."itemId",
+ pol."locationId"
+ ) pol ON pol."itemId" = i."id" AND pol."locationId" = loc."id"
+ GROUP BY
+ i."id",
+ i."companyId",
+ i."type",
+ i."name",
+ loc."id",
+ pol."quantityToReceive",
+ m."thumbnailPath"
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240912181702_item-ledger-rls-update.sql b/packages/database/supabase/migrations/20240912181702_item-ledger-rls-update.sql
new file mode 100644
index 0000000000..8d4c9262ef
--- /dev/null
+++ b/packages/database/supabase/migrations/20240912181702_item-ledger-rls-update.sql
@@ -0,0 +1,31 @@
+DROP POLICY IF EXISTS "Certain employees can view the parts ledger" ON public."itemLedger";
+CREATE POLICY "Certain employees can view the parts ledger" ON "itemLedger"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId") AND
+ (
+ has_company_permission('inventory_view', "companyId") OR
+ has_company_permission('accounting_view', "companyId")
+ )
+ );
+
+ CREATE POLICY "Certain employees can insert into the parts ledger" ON "itemLedger"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ (
+ has_company_permission('inventory_create', "companyId") OR
+ has_company_permission('accounting_create', "companyId")
+ )
+ );
+
+DROP POLICY IF EXISTS "Requests with an API key can access item ledger" ON "itemLedger";
+CREATE POLICY "Requests with an API key can view item ledger" ON "itemLedger"
+FOR SELECT USING (
+ has_valid_api_key_for_company("companyId")
+);
+
+CREATE POLICY "Requests with an API key can insert into item ledger" ON "itemLedger"
+FOR INSERT WITH CHECK (
+ has_valid_api_key_for_company("companyId")
+);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240913162203_item-inventory.sql b/packages/database/supabase/migrations/20240913162203_item-inventory.sql
new file mode 100644
index 0000000000..e4e4bdb276
--- /dev/null
+++ b/packages/database/supabase/migrations/20240913162203_item-inventory.sql
@@ -0,0 +1,412 @@
+
+
+-- Create itemInventory table
+CREATE TABLE "itemInventory" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "itemId" TEXT NOT NULL,
+ "locationId" TEXT,
+ "shelfId" TEXT,
+ "companyId" TEXT NOT NULL,
+ "quantityOnHand" NUMERIC(12, 4) NOT NULL DEFAULT 0,
+ "quantityOnPurchase" NUMERIC(12, 4) NOT NULL DEFAULT 0,
+ "quantityOnSalesOrder" NUMERIC(12, 4) NOT NULL DEFAULT 0,
+ "quantityOnProductionOrder" NUMERIC(12, 4) NOT NULL DEFAULT 0,
+ CONSTRAINT "itemInventory_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "itemInventory_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "itemInventory_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "itemInventory_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf"("id", "locationId") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "itemInventory_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE
+);
+
+-- Create index on companyId
+CREATE INDEX "itemInventory_companyId_idx" ON "itemInventory" ("companyId");
+
+-- Create composite index on companyId and locationId
+CREATE INDEX "itemInventory_companyId_locationId_idx" ON "itemInventory" ("companyId", "locationId");
+
+
+ALTER TABLE "itemInventory" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with parts_view or inventory_view inventory_view can view item inventory" ON "itemInventory"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId") AND (
+ has_company_permission('parts_view', "companyId") OR
+ has_company_permission('inventory_view', "companyId")
+ )
+ );
+
+-- Create function to update itemInventory
+CREATE OR REPLACE FUNCTION update_item_inventory_from_item_ledger()
+RETURNS TRIGGER AS $$
+BEGIN
+ -- Check if a row exists, handling NULL shelfId and locationId
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = NEW."itemId"
+ AND "companyId" = NEW."companyId"
+ AND (("locationId" = NEW."locationId") OR (NEW."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = NEW."shelfId") OR (NEW."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ -- Update existing row
+ UPDATE "itemInventory"
+ SET "quantityOnHand" = "quantityOnHand" +
+ CASE
+ WHEN NEW."entryType" IN ('Positive Adjmt.', 'Purchase', 'Output', 'Assembly Output') THEN NEW."quantity"
+ WHEN NEW."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption') THEN -NEW."quantity"
+ WHEN NEW."entryType" = 'Transfer' THEN
+ CASE
+ WHEN NEW."locationId" = OLD."locationId" THEN -NEW."quantity"
+ ELSE NEW."quantity"
+ END
+ ELSE 0
+ END
+ WHERE "itemId" = NEW."itemId"
+ AND "companyId" = NEW."companyId"
+ AND (("locationId" = NEW."locationId") OR (NEW."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = NEW."shelfId") OR (NEW."shelfId" IS NULL AND "shelfId" IS NULL));
+ ELSE
+ -- Insert new row
+ INSERT INTO "itemInventory" ("itemId", "locationId", "shelfId", "companyId", "quantityOnHand")
+ VALUES (NEW."itemId", NEW."locationId", NEW."shelfId", NEW."companyId",
+ CASE
+ WHEN NEW."entryType" IN ('Positive Adjmt.', 'Purchase', 'Output', 'Assembly Output') THEN NEW."quantity"
+ WHEN NEW."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption') THEN -NEW."quantity"
+ WHEN NEW."entryType" = 'Transfer' THEN
+ CASE
+ WHEN NEW."locationId" = OLD."locationId" THEN -NEW."quantity"
+ ELSE NEW."quantity"
+ END
+ ELSE 0
+ END);
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+
+-- Create trigger on itemLedger
+CREATE TRIGGER update_item_inventory_from_item_ledger_trigger
+AFTER INSERT OR UPDATE ON "itemLedger"
+FOR EACH ROW
+EXECUTE FUNCTION update_item_inventory_from_item_ledger();
+
+-- Function to update inventory quantity on purchase order based on purchase order status changes
+CREATE OR REPLACE FUNCTION update_inventory_quantity_on_purchase_order()
+RETURNS TRIGGER AS $$
+DECLARE
+ line RECORD;
+BEGIN
+ -- When status changes to 'To Receive and Invoice'
+ IF (OLD.status = 'Draft' OR OLD.status = 'To Review') AND NEW.status = 'To Receive and Invoice' THEN
+ FOR line IN (SELECT * FROM "purchaseOrderLine" WHERE "purchaseOrderId" = NEW.id)
+ LOOP
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ -- Update existing row
+ UPDATE "itemInventory"
+ SET "quantityOnPurchase" = "quantityOnPurchase" + (line."quantityToReceive" - COALESCE(line."quantityReceived", 0))
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL));
+ ELSE
+ -- Insert new row
+ INSERT INTO "itemInventory" ("itemId", "locationId", "shelfId", "companyId", "quantityOnPurchase")
+ VALUES (line."itemId", line."locationId", line."shelfId", line."companyId", line."quantityToReceive" - COALESCE(line."quantityReceived", 0));
+ END IF;
+ END LOOP;
+
+ -- When status changes back to 'Draft' or to 'Closed'
+ ELSIF (NEW.status = 'Draft' AND OLD.status != 'Draft') OR (NEW.status = 'Closed' AND OLD.status != 'Closed') THEN
+ FOR line IN (SELECT * FROM "purchaseOrderLine" WHERE "purchaseOrderId" = NEW.id)
+ LOOP
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ UPDATE "itemInventory"
+ SET "quantityOnPurchase" = "quantityOnPurchase" - (line."quantityToReceive" - COALESCE(line."quantityReceived", 0))
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL));
+ END IF;
+ END LOOP;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Create trigger on purchaseOrder
+CREATE TRIGGER update_inventory_quantity_on_purchase_order_trigger
+AFTER UPDATE OF status ON "purchaseOrder"
+FOR EACH ROW
+WHEN (OLD.status IS DISTINCT FROM NEW.status)
+EXECUTE FUNCTION update_inventory_quantity_on_purchase_order();
+
+-- Function to update inventory quantity when purchaseOrderLine is updated
+CREATE OR REPLACE FUNCTION update_inventory_quantity_on_purchase_order_line()
+RETURNS TRIGGER AS $$
+BEGIN
+ -- Only proceed if quantityReceived has changed and is not 0
+ IF NEW."quantityReceived" != OLD."quantityReceived" AND NEW."quantityReceived" != 0 THEN
+ -- Check if an entry exists in itemInventory
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = NEW."itemId"
+ AND "companyId" = NEW."companyId"
+ AND (("locationId" = NEW."locationId") OR (NEW."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = NEW."shelfId") OR (NEW."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ -- Update existing row
+ UPDATE "itemInventory"
+ SET "quantityOnPurchase" = "quantityOnPurchase" - (NEW."quantityReceived" - OLD."quantityReceived")
+ WHERE "itemId" = NEW."itemId"
+ AND "companyId" = NEW."companyId"
+ AND (("locationId" = NEW."locationId") OR (NEW."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = NEW."shelfId") OR (NEW."shelfId" IS NULL AND "shelfId" IS NULL));
+ ELSE
+ -- Insert new row
+ INSERT INTO "itemInventory" ("itemId", "locationId", "shelfId", "companyId", "quantityOnPurchase")
+ VALUES (NEW."itemId", NEW."locationId", NEW."shelfId", NEW."companyId", NEW."quantityToReceive");
+ END IF;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Create trigger on purchaseOrderLine
+CREATE TRIGGER update_inventory_quantity_on_purchase_order_line_trigger
+AFTER UPDATE OF "quantityReceived" ON "purchaseOrderLine"
+FOR EACH ROW
+WHEN (OLD."quantityReceived" IS DISTINCT FROM NEW."quantityReceived")
+EXECUTE FUNCTION update_inventory_quantity_on_purchase_order_line();
+
+-- Function to update inventory quantity on sales order based on sales order status changes
+CREATE OR REPLACE FUNCTION update_inventory_quantity_on_sales_order()
+RETURNS TRIGGER AS $$
+DECLARE
+ line RECORD;
+BEGIN
+ -- When status changes to 'To Ship and Invoice'
+ IF (OLD.status = 'Draft' OR OLD.status = 'Needs Approval') AND NEW.status = 'Confirmed' THEN
+ FOR line IN (SELECT * FROM "salesOrderLine" WHERE "salesOrderId" = NEW.id)
+ LOOP
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ -- Update existing row
+ UPDATE "itemInventory"
+ SET "quantityOnSalesOrder" = "quantityOnSalesOrder" + line."quantityToSend"
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL));
+ ELSE
+ -- Insert new row
+ INSERT INTO "itemInventory" ("itemId", "locationId", "shelfId", "companyId", "quantityOnSalesOrder")
+ VALUES (line."itemId", line."locationId", line."shelfId", line."companyId", line."quantityToSend");
+ END IF;
+ END LOOP;
+
+ -- When status changes back to 'Draft' or to 'Closed'
+ ELSIF (NEW.status = 'Draft' AND OLD.status != 'Draft') OR (NEW.status = 'Closed' AND OLD.status != 'Closed') OR (NEW.status = 'Cancelled' AND OLD.status != 'Cancelled') THEN
+ FOR line IN (SELECT * FROM "salesOrderLine" WHERE "salesOrderId" = NEW.id)
+ LOOP
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ UPDATE "itemInventory"
+ SET "quantityOnSalesOrder" = "quantityOnSalesOrder" - line."quantityToSend"
+ WHERE "itemId" = line."itemId"
+ AND "companyId" = line."companyId"
+ AND (("locationId" = line."locationId") OR (line."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = line."shelfId") OR (line."shelfId" IS NULL AND "shelfId" IS NULL));
+ END IF;
+ END LOOP;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+ALTER TYPE "salesOrderStatus" ADD VALUE 'Closed';
+
+-- Create trigger on salesOrder
+CREATE TRIGGER update_inventory_quantity_on_sales_order_trigger
+AFTER UPDATE OF status ON "salesOrder"
+FOR EACH ROW
+WHEN (OLD.status IS DISTINCT FROM NEW.status)
+EXECUTE FUNCTION update_inventory_quantity_on_sales_order();
+
+-- Function to update inventory quantity when salesOrderLine is updated
+CREATE OR REPLACE FUNCTION update_inventory_quantity_on_sales_order_line()
+RETURNS TRIGGER AS $$
+BEGIN
+ -- Only proceed if quantitySent has changed and is not 0
+ IF NEW."quantitySent" != OLD."quantitySent" AND NEW."quantitySent" != 0 THEN
+ -- Check if an entry exists in itemInventory
+ IF EXISTS (
+ SELECT 1 FROM "itemInventory"
+ WHERE "itemId" = NEW."itemId"
+ AND "companyId" = NEW."companyId"
+ AND (("locationId" = NEW."locationId") OR (NEW."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = NEW."shelfId") OR (NEW."shelfId" IS NULL AND "shelfId" IS NULL))
+ ) THEN
+ -- Update existing row
+ UPDATE "itemInventory"
+
+ SET "quantityOnSalesOrder" = "quantityOnSalesOrder" - (NEW."quantitySent" - OLD."quantitySent")
+ WHERE "itemId" = NEW."itemId"
+ AND "companyId" = NEW."companyId"
+ AND (("locationId" = NEW."locationId") OR (NEW."locationId" IS NULL AND "locationId" IS NULL))
+ AND (("shelfId" = NEW."shelfId") OR (NEW."shelfId" IS NULL AND "shelfId" IS NULL));
+ ELSE
+ -- Insert new row
+ INSERT INTO "itemInventory" ("itemId", "locationId", "shelfId", "companyId", "quantityOnSalesOrder")
+ VALUES (
+ NEW."itemId",
+ NEW."locationId",
+ NEW."shelfId",
+ NEW."companyId",
+ NEW."quantitySent"
+ );
+ END IF;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Create trigger on salesOrderLine
+CREATE TRIGGER update_inventory_quantity_on_sales_order_line_trigger
+AFTER UPDATE OF "quantitySent" ON "salesOrderLine"
+FOR EACH ROW
+EXECUTE FUNCTION update_inventory_quantity_on_sales_order_line();
+
+
+
+ALTER TABLE "pickMethod" DROP CONSTRAINT IF EXISTS "pickMethod_shelfId_fkey";
+ALTER TABLE "purchaseOrderLine" DROP CONSTRAINT IF EXISTS "purchaseOrderLine_shelfId_fkey";
+ALTER TABLE "itemLedger" DROP CONSTRAINT IF EXISTS "itemLedger_shelfId_fkey";
+ALTER TABLE "receiptLine" DROP CONSTRAINT IF EXISTS "receiptLine_shelfId_fkey";
+ALTER TABLE "purchaseInvoiceLine" DROP CONSTRAINT IF EXISTS "purchaseInvoiceLines_shelfId_fkey";
+ALTER TABLE "salesOrderLine" DROP CONSTRAINT IF EXISTS "salesOrderLine_shelfId_fkey";
+ALTER TABLE "itemInventory" DROP CONSTRAINT IF EXISTS "itemInventory_shelfId_fkey";
+
+-- Drop the existing primary key constraint
+ALTER TABLE "shelf" DROP CONSTRAINT IF EXISTS "shelf_pkey";
+
+-- Add the 'id' column as the new primary key
+ALTER TABLE "shelf" ADD COLUMN IF NOT EXISTS "id" TEXT NOT NULL DEFAULT xid();
+ALTER TABLE "shelf" ADD PRIMARY KEY ("id");
+
+-- Add the 'name' column
+ALTER TABLE "shelf" ADD COLUMN IF NOT EXISTS "name" TEXT NOT NULL;
+
+-- Add a unique constraint for name and locationId
+ALTER TABLE "shelf" ADD CONSTRAINT "shelf_name_locationId_key" UNIQUE ("name", "locationId");
+
+-- Add back the foreign key constraints
+ALTER TABLE "pickMethod" ADD CONSTRAINT "pickMethod_shelfId_fkey" FOREIGN KEY ("defaultShelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "purchaseOrderLine" ADD CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "itemLedger" ADD CONSTRAINT "itemLedger_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "receiptLine" ADD CONSTRAINT "receiptLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "purchaseInvoiceLine" ADD CONSTRAINT "purchaseInvoiceLines_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "salesOrderLine" ADD CONSTRAINT "salesOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "itemInventory" ADD CONSTRAINT "itemInventory_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+
+
+DROP VIEW IF EXISTS "itemQuantities";
+
+CREATE INDEX IF NOT EXISTS "item_itemTrackingType_idx" ON "item" ("itemTrackingType");
+
+CREATE OR REPLACE FUNCTION get_item_quantities(location_id TEXT)
+RETURNS TABLE (
+ "itemId" TEXT,
+ "companyId" TEXT,
+ "locationId" TEXT,
+ "quantityOnHand" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnProdOrder" NUMERIC,
+ "quantityAvailable" NUMERIC,
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "grade" TEXT,
+ "dimensions" TEXT,
+ "finish" TEXT,
+ "readableId" TEXT,
+ "type" "itemType",
+ "name" TEXT,
+ "active" BOOLEAN,
+ "itemTrackingType" "itemTrackingType",
+ "thumbnailPath" TEXT,
+ "locationName" TEXT,
+ "unitOfMeasureCode" TEXT
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ i."id" AS "itemId",
+ i."companyId",
+ loc."id" AS "locationId",
+ COALESCE(inv."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(inv."quantityOnPurchase", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(inv."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(inv."quantityOnProductionOrder", 0) AS "quantityOnProdOrder",
+ COALESCE(inv."quantityOnHand", 0) -
+ COALESCE(inv."quantityOnSalesOrder", 0) -
+ COALESCE(inv."quantityOnProductionOrder", 0) AS "quantityAvailable",
+ mat."materialSubstanceId",
+ mat."materialFormId",
+ mat."grade",
+ mat."dimensions",
+ mat."finish",
+ i."readableId",
+ i."type",
+ i."name",
+ i."active",
+ i."itemTrackingType",
+ m."thumbnailPath",
+ loc."name" AS "locationName",
+ i."unitOfMeasureCode"
+ FROM "item" i
+ CROSS JOIN (SELECT * FROM "location" WHERE "id" = location_id) loc
+ LEFT JOIN "itemInventory" inv ON i."id" = inv."itemId" AND loc."id" = inv."locationId"
+ LEFT JOIN "material" mat ON i."id" = mat."itemId"
+ LEFT JOIN "modelUpload" m ON m."id" = i."modelUploadId"
+ WHERE i."itemTrackingType" = 'Inventory';
+END;
+$$ LANGUAGE plpgsql SECURITY INVOKER;
+
+
+ALTER TABLE "itemLedger" ADD COLUMN "createdBy" TEXT REFERENCES "user"("id");
+-- Set default value for createdBy column to 'system' for existing rows
+UPDATE "itemLedger" SET "createdBy" = 'system' WHERE "createdBy" IS NULL;
+
+-- Make createdBy column NOT NULL
+ALTER TABLE "itemLedger" ALTER COLUMN "createdBy" SET NOT NULL;
+
+-- Set default value for createdBy column to 'system' for new rows
+ALTER TABLE "itemLedger" ALTER COLUMN "createdBy" SET DEFAULT 'system';
diff --git a/packages/database/supabase/migrations/20240922010232_add-uom-to-fixtures-view.sql b/packages/database/supabase/migrations/20240922010232_add-uom-to-fixtures-view.sql
new file mode 100644
index 0000000000..e1f4232176
--- /dev/null
+++ b/packages/database/supabase/migrations/20240922010232_add-uom-to-fixtures-view.sql
@@ -0,0 +1,31 @@
+DROP VIEW "fixtures";
+CREATE OR REPLACE VIEW "fixtures" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ i.name,
+ i.description,
+ i."itemTrackingType",
+ i."unitOfMeasureCode",
+ i.active,
+ i."replenishmentSystem",
+ i."defaultMethodType",
+ i.assignee,
+ f.*,
+ mu.id as "modelId",
+ mu."autodeskUrn",
+ mu."modelPath",
+ mu."thumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ s."supplierIds",
+ c.name as "customer"
+ FROM "fixture" f
+ INNER JOIN "item" i ON i.id = f."itemId"
+ LEFT JOIN (
+ SELECT
+ "itemId",
+ array_agg(s."supplierId") AS "supplierIds"
+ FROM "buyMethod" s
+ GROUP BY "itemId"
+ ) s ON s."itemId" = f."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "customer" c ON c.id = f."customerId";
\ No newline at end of file
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index d878df0b43..8e724425ba 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -13,14 +13,14 @@ export const buttonVariants = cva(
variants: {
variant: {
primary:
- "bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm shadow-[inset_0_2px_4px_0_theme(colors.white/15%)]",
+ "bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm shadow-[inset_0_2px_3px_0_theme(colors.white/15%)]",
active:
"bg-active text-active-foreground hover:bg-active/90 hover:text-active-foreground",
secondary:
"border border-input bg-card hover:bg-accent hover:text-accent-foreground",
solid: "bg-accent text-accent-foreground hover:bg-accent/90",
destructive:
- "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm shadow-[inset_0_2px_4px_0_theme(colors.white/15%)]",
+ "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm shadow-[inset_0_2px_3px_0_theme(colors.white/15%)]",
ghost:
"bg-transparent hover:bg-primary/10 text-accent-foreground hover:text-accent-foreground/90",
link: "text-foreground hover:text-foreground underline-offset-4 hover:underline",
diff --git a/packages/react/src/Table.tsx b/packages/react/src/Table.tsx
index 06df1a935d..a950f74809 100644
--- a/packages/react/src/Table.tsx
+++ b/packages/react/src/Table.tsx
@@ -72,7 +72,7 @@ const Th = forwardRef<
<th
ref={ref}
className={cn(
- "group-hover:bg-muted/30 h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-muted-foreground [&:has([role=checkbox])]:pr-0",
+ "group-hover:bg-primary/5 h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
@@ -87,7 +87,7 @@ const Td = forwardRef<
<td
ref={ref}
className={cn(
- "group-hover:bg-muted/30 text-muted-foreground px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",
+ "group-hover:bg-primary/5 text-muted-foreground px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",
className
)}
{...props}
diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.ts
index 2354bc41af..b07d6b6faf 100644
--- a/packages/utils/src/themes.ts
+++ b/packages/utils/src/themes.ts
@@ -16,8 +16,8 @@ export const themes = [
"card-foreground": "220 10% 3.9%",
popover: "0 0% 100%",
"popover-foreground": "220 10% 3.9%",
- active: "220 5.9% 10%",
- "active-foreground": "0 0% 98%",
+ active: "220 5.9% 83%",
+ "active-foreground": "220 10% 3.9%",
primary: "220 5.9% 10%",
"primary-foreground": "0 0% 98%",
secondary: "220 4.8% 95.9%",
@@ -97,8 +97,8 @@ export const themes = [
"popover-foreground": "0 0% 98%",
primary: "30 24% 81%",
"primary-foreground": "0 0% 9%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "0 0% 14.9%",
"secondary-foreground": "0 0% 98%",
muted: "0 0% 14.9%",
@@ -130,8 +130,8 @@ export const themes = [
"popover-foreground": "0 0% 3.9%",
primary: "0 72.2% 50.6%",
"primary-foreground": "0 85.7% 97.3%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "0 0% 96.1%",
"secondary-foreground": "0 0% 9%",
muted: "0 0% 96.1%",
@@ -153,8 +153,8 @@ export const themes = [
"popover-foreground": "0 0% 98%",
primary: "0 72.2% 50.6%",
"primary-foreground": "0 85.7% 97.3%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "0 0% 14.9%",
"secondary-foreground": "0 0% 98%",
muted: "0 0% 14.9%",
@@ -186,8 +186,8 @@ export const themes = [
"popover-foreground": "240 10% 3.9%",
primary: "346.8 77.2% 49.8%",
"primary-foreground": "355.7 100% 97.3%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "240 4.8% 95.9%",
"secondary-foreground": "240 5.9% 10%",
muted: "240 4.8% 95.9%",
@@ -209,8 +209,8 @@ export const themes = [
"card-foreground": "0 0% 95%",
primary: "346.8 77.2% 49.8%",
"primary-foreground": "355.7 100% 97.3%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "240 3.7% 15.9%",
"secondary-foreground": "0 0% 98%",
muted: "0 0% 15%",
@@ -298,8 +298,8 @@ export const themes = [
"popover-foreground": "240 10% 3.9%",
primary: "151 47% 40%",
"primary-foreground": "355.7 100% 97.3%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "240 4.8% 95.9%",
"secondary-foreground": "240 5.9% 10%",
muted: "240 4.8% 95.9%",
@@ -354,13 +354,13 @@ export const themes = [
"popover-foreground": "216 98% 4.9%",
primary: "216 98% 52%",
"primary-foreground": "210 40% 98%",
- active: "216 98% 92%",
- "active-foreground": "216 98% 2.9%",
+ active: "222 40% 20%",
+ "active-foreground": "222 41 98%",
secondary: "210 40% 96.1%",
"secondary-foreground": "222.2 47.4% 11.2%",
- muted: "210 40% 96.1%",
+ muted: "222 40% 96.1%",
"muted-foreground": "215.4 16.3% 46.9%",
- accent: "210 40% 96.1%",
+ accent: "222 40% 96.1%",
"accent-foreground": "222.2 47.4% 11.2%",
destructive: "0 84.2% 60.2%",
"destructive-foreground": "210 40% 98%",
@@ -410,8 +410,8 @@ export const themes = [
"popover-foreground": "20 14.3% 4.1%",
primary: "47.9 95.8% 53.1%",
"primary-foreground": "26 83.3% 14.1%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "60 4.8% 95.9%",
"secondary-foreground": "24 9.8% 10%",
muted: "60 4.8% 95.9%",
@@ -466,8 +466,8 @@ export const themes = [
"popover-foreground": "224 71.4% 4.1%",
primary: "252.1 83.3% 47.8%",
"primary-foreground": "210 20% 98%",
- active: "0 0% 90%",
- "active-foreground": "0 0% 3.9%",
+ active: "0 0% 86%",
+ "active-foreground": "0 0% 4.1%",
secondary: "220 14.3% 95.9%",
"secondary-foreground": "220.9 39.3% 11%",
muted: "220 14.3% 95.9%",
@@ -481,26 +481,26 @@ export const themes = [
ring: "262.1 83.3% 57.8%",
},
dark: {
- background: "244 41.4 6.1%",
- foreground: "240 20% 98%",
- card: "244 41.4 8.9%",
+ background: "263 41.4 6.1%",
+ foreground: "263 20% 98%",
+ card: "263 41.4 8.9%",
"card-foreground": "210 20% 98%",
- popover: "244 41.4 8.9%",
+ popover: "263 41.4 8.9%",
"popover-foreground": "210 20% 98%",
- primary: "253.4 70% 40.4%",
+ primary: "263 70% 40.4%",
"primary-foreground": "210 20% 98%",
- active: "253.4 70% 81.4%",
- "active-foreground": "253.4 70% 30.4%",
+ active: "263 40% 20%",
+ "active-foreground": "263 41 98%",
secondary: "215 27.9% 16.9%",
"secondary-foreground": "210 20% 98%",
- muted: "215 27.9% 16.9%",
+ muted: "263 27.9% 16.9%",
"muted-foreground": "217.9 10.6% 64.9%",
- accent: "215 27.9% 16.9%",
+ accent: "263 27.9% 16.9%",
"accent-foreground": "210 20% 98%",
destructive: "0 62.8% 30.6%",
"destructive-foreground": "210 20% 98%",
- border: "215 27.9% 16.9%",
- input: "215 27.9% 16.9%",
+ border: "263 27.9% 16.9%",
+ input: "263 27.9% 16.9%",
ring: "263.4 70% 50.4%",
},
},