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.

Purchase Orders (#31)

Brad Barbin362e5fd095b9
diff --git a/SCHEMA.md b/SCHEMA.md
index 9c7fdb4cc7..039b5dd157 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -3957,13 +3957,13 @@ CREATE TABLE "documentTransaction" (
"userId" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- CONSTRAINT "documentActivity_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "documentActivity_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
- CONSTRAINT "documentActivity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+ CONSTRAINT "documentTransaction_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "documentTransaction_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
+ CONSTRAINT "documentTransaction_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
);
-CREATE INDEX "documentActivity_documentId_idx" ON "documentTransaction" ("documentId");
-CREATE INDEX "documentActivity_userId_idx" ON "documentTransaction" ("userId");
+CREATE INDEX "documentTransaction_documentId_idx" ON "documentTransaction" ("documentId");
+CREATE INDEX "documentTransaction_userId_idx" ON "documentTransaction" ("userId");
CREATE TABLE "documentFavorite" (
"documentId" TEXT NOT NULL,
@@ -3979,17 +3979,17 @@ CREATE INDEX "documentFavorites_documentId_idx" ON "documentFavorite" ("document
ALTER TABLE "documentFavorite" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Users can view their own favorites" ON "documentFavorite"
+CREATE POLICY "Users can view their own document favorites" ON "documentFavorite"
FOR SELECT USING (
auth.uid()::text = "userId"
);
-CREATE POLICY "Users can create their own favorites" ON "documentFavorite"
+CREATE POLICY "Users can create their own document favorites" ON "documentFavorite"
FOR INSERT WITH CHECK (
auth.uid()::text = "userId"
);
-CREATE POLICY "Users can delete their own favorites" ON "documentFavorite"
+CREATE POLICY "Users can delete their own document favorites" ON "documentFavorite"
FOR DELETE USING (
auth.uid()::text = "userId"
);
@@ -4087,3 +4087,262 @@ CREATE VIEW "documents_view" AS
```
+
+
+## `purchasing`
+
+```sql
+CREATE TYPE "paymentTermCalculationMethod" AS ENUM (
+ 'Net',
+ 'End of Month',
+ 'Day of Month'
+);
+
+CREATE TABLE "paymentTerm" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "daysDue" INTEGER NOT NULL DEFAULT 0,
+ "daysDiscount" INTEGER NOT NULL DEFAULT 0,
+ "discountPercentage" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "calculationMethod" "paymentTermCalculationMethod" NOT NULL DEFAULT 'Net',
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "paymentTerm_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "paymentTerm_name_key" UNIQUE ("name", "active"),
+ CONSTRAINT "paymentTerm_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "paymentTerm_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+INSERT INTO "paymentTerm" ("name", "daysDue", "calculationMethod", "daysDiscount", "discountPercentage", "createdBy")
+VALUES
+ ('Net 15', 15, 'Net', 0, 0, 'system'),
+ ('Net 30', 30, 'Net', 0, 0, 'system'),
+ ('Net 50', 50, 'Net', 0, 0, 'system'),
+ ('Net 60', 60, 'Net', 0, 0, 'system'),
+ ('Net 90', 90, 'Net', 0, 0, 'system'),
+ ('1% 10 Net 30', 30, 'Net', 10, 1, 'system'),
+ ('2% 10 Net 30', 30, 'Net', 10, 2, 'system'),
+ ('Due on Receipt', 0, 'Net', 0, 0, 'system'),
+ ('Net EOM 10', 10, 'End of Month', 0, 0, 'system');
+
+
+CREATE TYPE "shippingCarrier" AS ENUM (
+ 'UPS',
+ 'FedEx',
+ 'USPS',
+ 'DHL',
+ 'Other'
+);
+
+CREATE TABLE "shippingMethod" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "carrier" "shippingCarrier" NOT NULL DEFAULT 'Other',
+ "carrierAccountId" TEXT,
+ "trackingUrl" TEXT,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "shippingMethod_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "shippingMethod_name_key" UNIQUE ("name"),
+ CONSTRAINT "shippingMethod_carrierAccountId_fkey" FOREIGN KEY ("carrierAccountId") REFERENCES "account" ("number") ON DELETE CASCADE,
+ CONSTRAINT "shippingMethod_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "shippingMethod_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "shippingMethod_name_idx" ON "shippingMethod" ("name");
+
+CREATE TYPE "purchaseOrderType" AS ENUM (
+ 'Draft',
+ 'Purchase',
+ 'Return'
+);
+
+CREATE TYPE "purchaseOrderApprovalStatus" AS ENUM (
+ 'Draft',
+ 'In Review',
+ 'In External Review',
+ 'Approved',
+ 'Rejected',
+ 'Confirmed'
+);
+
+CREATE TABLE "purchaseOrder" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT NOT NULL,
+ "type" "purchaseOrderType" NOT NULL,
+ "status" "purchaseOrderApprovalStatus" NOT NULL,
+ "orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
+ "orderDueDate" DATE,
+ "receivedDate" DATE,
+ "orderSubTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderTax" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderDiscount" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderShipping" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "notes" TEXT,
+ "supplierId" TEXT NOT NULL,
+ "supplierContactId" TEXT,
+ "supplierReference" TEXT,
+ "invoiceSupplierId" TEXT,
+ "invoiceSupplierLocationId" TEXT,
+ "invoiceSupplierContactId" TEXT,
+ "paymentTermId" TEXT,
+ "shippingMethodId" TEXT,
+ "currencyCode" TEXT NOT NULL,
+ -- "approvalRequestDate" DATE,
+ -- "approvalDecisionDate" DATE,
+ -- "approvalDecisionUserId" TEXT,
+ -- "approvalDecisionNotes" TEXT,
+ "closed" BOOLEAN NOT NULL DEFAULT FALSE,
+ "closedAt" DATE,
+ "closedBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "purchaseOrder_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrder_purchaseOrderId_key" UNIQUE ("purchaseOrderId"),
+ CONSTRAINT "purchaseOrder_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_supplierContactId_fkey" FOREIGN KEY ("supplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_invoiceSupplierLocationId_fkey" FOREIGN KEY ("invoiceSupplierLocationId") REFERENCES "supplierLocation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_invoiceSupplierContactId_fkey" FOREIGN KEY ("invoiceSupplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE,
+ -- CONSTRAINT "purchaseOrder_approvalDecisionUserId_fkey" FOREIGN KEY ("approvalDecisionUserId") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_closedBy_fkey" FOREIGN KEY ("closedBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrder_purchaseOrderId_idx" ON "purchaseOrder" ("purchaseOrderId");
+CREATE INDEX "purchaseOrder_supplierId_idx" ON "purchaseOrder" ("supplierId");
+CREATE INDEX "purchaseOrder_supplierContactId_idx" ON "purchaseOrder" ("supplierContactId");
+CREATE INDEX "purchaseOrder_invoiceSupplierId_idx" ON "purchaseOrder" ("invoiceSupplierId");
+CREATE INDEX "purchaseOrder_invoiceSupplierLocationId_idx" ON "purchaseOrder" ("invoiceSupplierLocationId");
+CREATE INDEX "purchaseOrder_invoiceSupplierContactId_idx" ON "purchaseOrder" ("invoiceSupplierContactId");
+-- CREATE INDEX "purchaseOrder_approvalDecisionUserId_idx" ON "purchaseOrder" ("approvalDecisionUserId");
+
+CREATE TYPE "purchaseOrderTransactionType" AS ENUM (
+ 'Edit',
+ 'Favorite',
+ 'Unfavorite',
+ 'Approved',
+ 'Reject',
+ 'Request Approval'
+);
+
+CREATE TABLE "purchaseOrderTransaction" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT NOT NULL,
+ "type" "purchaseOrderTransactionType" NOT NULL,
+ "userId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "purchaseOrderTransaction_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderTransaction_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder"("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderTransaction_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrderTransaction_purchaseOrderId_idx" ON "purchaseOrderTransaction" ("purchaseOrderId");
+CREATE INDEX "purchaseOrderTransaction_userId_idx" ON "purchaseOrderTransaction" ("userId");
+
+CREATE TABLE "purchaseOrderFavorite" (
+ "purchaseOrderId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+
+ CONSTRAINT "purchaseOrderFavorites_pkey" PRIMARY KEY ("purchaseOrderId", "userId"),
+ CONSTRAINT "purchaseOrderFavorites_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder"("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrderFavorites_userId_idx" ON "purchaseOrderFavorite" ("userId");
+CREATE INDEX "purchaseOrderFavorites_purchaseOrderId_idx" ON "purchaseOrderFavorite" ("purchaseOrderId");
+
+ALTER TABLE "purchaseOrderFavorite" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Users can view their own purchase order favorites" ON "purchaseOrderFavorite"
+ FOR SELECT USING (
+ auth.uid()::text = "userId"
+ );
+
+CREATE POLICY "Users can create their own purchase order favorites" ON "purchaseOrderFavorite"
+ FOR INSERT WITH CHECK (
+ auth.uid()::text = "userId"
+ );
+
+CREATE POLICY "Users can delete their own purchase order favorites" ON "purchaseOrderFavorite"
+ FOR DELETE USING (
+ auth.uid()::text = "userId"
+ );
+
+CREATE VIEW "purchase_order_view" AS
+ SELECT
+ p."id",
+ p."purchaseOrderId",
+ p."status",
+ p."type",
+ p."orderDate",
+ p."orderDueDate",
+ p."createdBy",
+ s."name" AS "supplierName",
+ u."avatarUrl" AS "createdByAvatar",
+ u."fullName" AS "createdByFullName",
+ p."createdAt",
+ p."updatedBy",
+ u2."avatarUrl" AS "updatedByAvatar",
+ u2."fullName" AS "updatedByFullName",
+ p."updatedAt",
+ p."closed",
+ p."closedAt",
+ u3."avatarUrl" AS "closedByAvatar",
+ u3."fullName" AS "closedByFullName",
+ EXISTS(SELECT 1 FROM "purchaseOrderFavorite" pf WHERE pf."purchaseOrderId" = p.id AND pf."userId" = auth.uid()::text) AS favorite
+ FROM "purchaseOrder" p
+ LEFT JOIN "supplier" s ON s."id" = p."supplierId"
+ LEFT JOIN "user" u ON u."id" = p."createdBy"
+ LEFT JOIN "user" u2 ON u2."id" = p."updatedBy"
+ LEFT JOIN "user" u3 ON u3."id" = p."closedBy";
+
+
+```
+
+
+
+## `sequences`
+
+```sql
+CREATE TABLE "sequence" (
+ "table" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "prefix" TEXT,
+ "suffix" TEXT,
+ "next" BIGINT NOT NULL DEFAULT 1,
+ "size" INTEGER NOT NULL DEFAULT 5,
+ "step" INTEGER NOT NULL DEFAULT 1,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "sequence_pkey" PRIMARY KEY ("table"),
+ CONSTRAINT "sequence_next_check" CHECK ("next" >= 1),
+ CONSTRAINT "sequence_size_check" CHECK ("size" >= 1),
+ CONSTRAINT "sequence_step_check" CHECK ("step" >= 1),
+ CONSTRAINT "sequence_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
+VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 1, 5, 1);
+
+
+```
+
diff --git a/apps/carbon/app/components/Form/Input.tsx b/apps/carbon/app/components/Form/Input.tsx
index a891832e8a..7db4d53a86 100644
--- a/apps/carbon/app/components/Form/Input.tsx
+++ b/apps/carbon/app/components/Form/Input.tsx
@@ -1,4 +1,5 @@
import type { InputProps } from "@chakra-ui/react";
+import { InputLeftAddon } from "@chakra-ui/react";
import {
FormControl,
FormErrorMessage,
@@ -16,17 +17,19 @@ type FormInputProps = InputProps & {
label?: string;
isRequired?: boolean;
helperText?: string;
+ prefix?: string;
suffix?: string;
};
const Input = forwardRef<HTMLInputElement, FormInputProps>(
- ({ name, label, isRequired, helperText, suffix, ...rest }, ref) => {
+ ({ name, label, isRequired, helperText, prefix, suffix, ...rest }, ref) => {
const { getInputProps, error } = useField(name);
return (
<FormControl isInvalid={!!error} isRequired={isRequired}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<InputGroup>
+ {prefix && <InputLeftAddon children={prefix} />}
<ChakraInput
ref={ref}
{...getInputProps({
diff --git a/apps/carbon/app/components/Form/Select.tsx b/apps/carbon/app/components/Form/Select.tsx
index 2b3859be86..a689f153bd 100644
--- a/apps/carbon/app/components/Form/Select.tsx
+++ b/apps/carbon/app/components/Form/Select.tsx
@@ -64,10 +64,9 @@ const Select = ({
)}
</FormControl>
) : (
- <Box>
+ <Box w="full">
{label && <FormLabel>{label}</FormLabel>}
<CarbonSelect
- isDisabled
isLoading={isLoading}
options={[]}
// @ts-ignore
diff --git a/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx
index 820d137132..938587f49a 100644
--- a/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx
@@ -24,6 +24,8 @@ const IconSidebar = () => {
variant="ghost"
size="lg"
icon={<BsFillHexagonFill />}
+ position="sticky"
+ top={0}
mb={4}
/>
diff --git a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx
index 26f90ecb13..6311e4ff52 100644
--- a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx
@@ -9,7 +9,7 @@ import {
BsShieldLock,
} from "react-icons/bs";
import { CgProfile } from "react-icons/cg";
-// import { GoSettings } from "react-icons/go";
+import { GoSettings } from "react-icons/go";
import { HiOutlineCube, HiOutlineDocumentDuplicate } from "react-icons/hi";
import { TbPigMoney } from "react-icons/tb";
import { usePermissions } from "~/hooks";
@@ -90,12 +90,12 @@ export function useSidebar() {
to: "/x/users",
icon: <BsShieldLock />,
},
- // {
- // permission: "settings",
- // name: "Settings",
- // to: "/x/settings",
- // icon: <GoSettings />,
- // },
+ {
+ permission: "settings",
+ name: "Settings",
+ to: "/x/settings",
+ icon: <GoSettings />,
+ },
{
name: "My Account",
to: "/x/account",
diff --git a/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
new file mode 100644
index 0000000000..c016e409a2
--- /dev/null
+++ b/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
@@ -0,0 +1,36 @@
+import {
+ IconButton,
+ Menu,
+ MenuButton,
+ MenuItem,
+ MenuList,
+} from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { BiPlus } from "react-icons/bi";
+import useNewMenu from "./useNewMenu";
+
+const NewMenu = () => {
+ const newMenuLinks = useNewMenu();
+
+ return (
+ <Menu>
+ <MenuButton
+ arial-label="User Menu"
+ as={IconButton}
+ icon={<BiPlus />}
+ variant="ghost"
+ size="sm"
+ cursor="pointer"
+ />
+ <MenuList fontSize="sm" boxShadow="xl" minW={48}>
+ {newMenuLinks.map((link) => (
+ <MenuItem key={link.to} as={Link} to={link.to} icon={link.icon}>
+ {link.name}
+ </MenuItem>
+ ))}
+ </MenuList>
+ </Menu>
+ );
+};
+
+export default NewMenu;
diff --git a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
index 7dfa624ede..d1167cffd8 100644
--- a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
@@ -5,10 +5,12 @@ import { BsChatSquare } from "react-icons/bs";
import { Search } from "~/components/Search";
import AvatarMenu from "./AvatarMenu";
import Breadcrumbs from "./Breadcrumbs";
+import NewMenu from "./NewMenu";
import useBreadcrumbs from "./useBreadcrumbs";
const Topbar = () => {
const breadcrumbLinks = useBreadcrumbs();
+
const borderColor = useColor("gray.200");
return (
@@ -27,7 +29,7 @@ const Topbar = () => {
>
<Breadcrumbs links={breadcrumbLinks} />
<Search />
- <HStack py={2} justifyContent="end">
+ <HStack py={2} justifyContent="end" spacing={1}>
<a
target="_blank"
href="https://github.com/barbinbrad/carbon/issues/new/choose"
@@ -36,7 +38,7 @@ const Topbar = () => {
<Button
colorScheme="gray"
leftIcon={<BiHelpCircle />}
- variant="solid"
+ variant="ghost"
>
Help
</Button>
@@ -49,11 +51,12 @@ const Topbar = () => {
<Button
colorScheme="gray"
leftIcon={<BsChatSquare />}
- variant="solid"
+ variant="ghost"
>
Feedback
</Button>
</a>
+ <NewMenu />
<AvatarMenu />
</HStack>
</GridItem>
diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
index 27bad80ab5..03548ba7b9 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -57,11 +57,7 @@ export default function useBreadcrumbs(): Route[] {
name: "Parts",
to: match.pathname,
});
- case "routes/x+/resources+/_layout":
- return acc.concat({
- name: "Resources",
- to: match.pathname,
- });
+
case "routes/x+/part+/_layout":
case "routes/x+/parts+/_layout":
return acc.concat({
@@ -88,6 +84,32 @@ export default function useBreadcrumbs(): Route[] {
name: "Groups",
to: match.pathname,
});
+ case "routes/x+/purchase-order+/_layout":
+ case "routes/x+/purchasing+/_layout":
+ return acc.concat({
+ name: "Purchasing",
+ to: match.pathname,
+ });
+ case "routes/x+/purchasing+/orders":
+ return acc.concat({
+ name: "Orders",
+ to: match.pathname,
+ });
+ case "routes/x+/purchasing+/suppliers":
+ return acc.concat({
+ name: "Suppliers",
+ to: match.pathname,
+ });
+ case "routes/x+/purchasing+/supplier-types":
+ return acc.concat({
+ name: "Supplier Types",
+ to: match.pathname,
+ });
+ case "routes/x+/resources+/_layout":
+ return acc.concat({
+ name: "Resources",
+ to: match.pathname,
+ });
case "routes/x+/resources+/abilities":
return acc.concat({
name: "Abilities",
@@ -154,21 +176,6 @@ export default function useBreadcrumbs(): Route[] {
name: "Work Cells",
to: match.pathname,
});
- case "routes/x+/purchasing+/_layout":
- return acc.concat({
- name: "Purchasing",
- to: match.pathname,
- });
- case "routes/x+/purchasing+/suppliers":
- return acc.concat({
- name: "Suppliers",
- to: match.pathname,
- });
- case "routes/x+/purchasing+/supplier-types":
- return acc.concat({
- name: "Supplier Types",
- to: match.pathname,
- });
case "routes/x+/sales+/_layout":
return acc.concat({
name: "Sales",
@@ -184,6 +191,16 @@ export default function useBreadcrumbs(): Route[] {
name: "Customer Types",
to: match.pathname,
});
+ case "routes/x+/settings+/_layout":
+ return acc.concat({
+ name: "Settings",
+ to: match.pathname,
+ });
+ case "routes/x+/settings+/sequences":
+ return acc.concat({
+ name: "Sequences",
+ to: match.pathname,
+ });
case "routes/x+/users+/_layout":
return acc.concat({
name: "Users",
diff --git a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
new file mode 100644
index 0000000000..df1ecea3cb
--- /dev/null
+++ b/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
@@ -0,0 +1,43 @@
+import { useMemo } from "react";
+import { usePermissions } from "~/hooks";
+
+import type { Route } from "~/types";
+
+export default function useNewMenu(): Route[] {
+ const permissions = usePermissions();
+
+ const result = useMemo(() => {
+ let links: Route[] = [];
+ if (permissions.can("create", "parts")) {
+ links.push({
+ name: "New Part",
+ to: "/x/part/new",
+ });
+ }
+
+ if (permissions.can("create", "purchasing")) {
+ links.push({
+ name: "New Purchase Order",
+ to: "/x/purchase-order/new",
+ });
+ }
+
+ if (permissions.can("create", "users")) {
+ links.push({
+ name: "New Employee",
+ to: "/x/users/employees/new",
+ });
+ }
+
+ // if (permissions.can("create", "sales")) {
+ // links.push({
+ // name: "New Customer",
+ // to: "/x/sales/customers/new",
+ // });
+ // }
+
+ return links;
+ }, [permissions]);
+
+ return result;
+}
diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsx
index 15465b63a3..6e116edec4 100644
--- a/apps/carbon/app/components/Search/Search/Search.tsx
+++ b/apps/carbon/app/components/Search/Search/Search.tsx
@@ -63,9 +63,10 @@ const SearchModal = ({
const [query, setQuery] = useState("");
const [debouncedQuery] = useDebounce(query, 500);
+ const defaultResults = useSidebar();
+ const [moduleResults, setModuleResults] = useState<NavItem[]>(defaultResults);
const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
const [selectedIndex, setSelectedIndex] = useState<number>(0);
- const defaultResults = useSidebar();
const listboxRef = useRef<HTMLUListElement>(null);
@@ -85,23 +86,30 @@ const SearchModal = ({
const result = await supabase
?.from("search")
.select()
- .textSearch("fts", search)
+ .textSearch("fts", `${search}:*`)
.limit(20);
+
if (result?.data) {
setSearchResults(result.data);
- return result.data;
} else {
setSearchResults([]);
- return [];
}
},
[supabase]
);
+ const getModuleResults = useCallback((q: string) => {
+ setModuleResults(
+ defaultResults.filter((item) => {
+ return item.name.toLowerCase().includes(q.toLowerCase());
+ })
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
const onKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
- const results =
- debouncedQuery.length === 0 ? defaultResults : searchResults;
+ const results = [...moduleResults, ...searchResults];
const scrollToListItem = (index: number) => {
const listbox = listboxRef.current;
@@ -138,7 +146,7 @@ const SearchModal = ({
} else {
navigate(selectedResult.to);
}
- onClose();
+ onResultClick();
}
break;
default:
@@ -152,11 +160,15 @@ const SearchModal = ({
useEffect(() => {
setSelectedIndex(0);
if (debouncedQuery) {
- getSearchResults(debouncedQuery);
+ getSearchResults(debouncedQuery).then(() => {
+ getModuleResults(debouncedQuery);
+ });
} else {
setSearchResults([]);
+ setModuleResults(defaultResults);
}
- }, [debouncedQuery, getSearchResults]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [debouncedQuery, getModuleResults, getSearchResults]);
return (
<Modal
@@ -187,40 +199,39 @@ const SearchModal = ({
}}
/>
</InputGroup>
- {(searchResults.length > 0 || debouncedQuery.length === 0) && (
- <Box
- bg="white"
- borderBottomRadius="lg"
- boxShadow="lg"
- maxH="66vh"
- overflowY="scroll"
- px={4}
- pt={0}
- pb={4}
- >
- <List role="listbox" ref={listboxRef}>
- {searchResults.length > 0
- ? searchResults.map((result, resultIndex) => (
- <Result
- key={result.uuid}
- result={result}
- selected={selectedIndex === resultIndex}
- onClick={onResultClick}
- onHover={() => setSelectedIndex(resultIndex)}
- />
- ))
- : defaultResults.map((item, itemIndex) => (
- <Module
- key={item.to}
- item={item}
- selected={selectedIndex === itemIndex}
- onClick={onResultClick}
- onHover={() => setSelectedIndex(itemIndex)}
- />
- ))}
- </List>
- </Box>
- )}
+
+ <Box
+ bg="white"
+ borderBottomRadius="lg"
+ boxShadow="lg"
+ maxH="66vh"
+ overflowY="scroll"
+ px={4}
+ pt={0}
+ pb={4}
+ >
+ <List role="listbox" ref={listboxRef}>
+ {moduleResults.map((item, itemIndex) => (
+ <Module
+ key={item.to}
+ item={item}
+ selected={selectedIndex === itemIndex}
+ onClick={onResultClick}
+ onHover={() => setSelectedIndex(itemIndex)}
+ />
+ ))}
+
+ {searchResults.map((result, resultIndex) => (
+ <Result
+ key={result.uuid}
+ result={result}
+ selected={selectedIndex === resultIndex}
+ onClick={onResultClick}
+ onHover={() => setSelectedIndex(resultIndex)}
+ />
+ ))}
+ </List>
+ </Box>
</ModalBody>
</ModalContent>
</Modal>
@@ -234,7 +245,7 @@ const resultIconProps = {
color: "gray.500",
};
-function ResultIcon({ entity }: { entity: SearchResult["entity"] }) {
+function ResultIcon({ entity }: { entity: SearchResult["entity"] | "Module" }) {
switch (entity) {
case "Customer":
return <Icon as={SiHandshake} {...resultIconProps} />;
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index bb82e902a5..5fdf436fcf 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -427,8 +427,7 @@ const Table = <T extends object>({
{(withColumnOrdering ||
withFilters ||
withSelectableRows ||
- withInlineEditing ||
- withSimpleSorting) && (
+ withInlineEditing) && (
<TableHeader
actions={actions}
columnAccessors={columnAccessors}
diff --git a/apps/carbon/app/modules/accounting/index.ts b/apps/carbon/app/modules/accounting/index.ts
index b2221a94a8..490fd762ea 100644
--- a/apps/carbon/app/modules/accounting/index.ts
+++ b/apps/carbon/app/modules/accounting/index.ts
@@ -1 +1,3 @@
+export * from "./interfaces";
export * from "./services";
+export * from "./types";
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermForm/PaymentTermForm.tsx b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermForm/PaymentTermForm.tsx
new file mode 100644
index 0000000000..a9dab5fcf2
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermForm/PaymentTermForm.tsx
@@ -0,0 +1,117 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import { Hidden, Input, Number, Select, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import type { PaymentTermCalculationMethod } from "~/modules/accounting";
+import { paymentTermValidator } from "~/modules/accounting";
+import type { TypeOfValidator } from "~/types/validators";
+
+type PaymentTermFormProps = {
+ initialValues: TypeOfValidator<typeof paymentTermValidator>;
+};
+
+const PaymentTermForm = ({ initialValues }: PaymentTermFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "accounting")
+ : !permissions.can("create", "accounting");
+
+ const [selectedCalculationMethod, setSelectedCalculationMethod] = useState(
+ initialValues.calculationMethod
+ );
+
+ const calculationMethodOptions = ["Net", "End of Month", "Day of Month"].map(
+ (v) => ({
+ label: v,
+ value: v,
+ })
+ );
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={paymentTermValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/accounting/payment-terms/${initialValues.id}`
+ : "/x/accounting/payment-terms/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Payment Term</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="name" label="Name" />
+ <Select
+ name="calculationMethod"
+ label="After"
+ options={calculationMethodOptions}
+ onChange={({ value }) => {
+ setSelectedCalculationMethod(
+ value as PaymentTermCalculationMethod
+ );
+ }}
+ />
+ <Number
+ name="daysDue"
+ label={`Due Days after ${selectedCalculationMethod}`}
+ min={0}
+ helperText="The amount of days after the calculation method that the payment is due"
+ />
+ <Number
+ name="daysDiscount"
+ label={`Discount Days after ${selectedCalculationMethod}`}
+ min={0}
+ helperText="The amount of days after the calculation method that the cash discount is available"
+ />
+ <Number
+ name="discountPercentage"
+ label="Discount Percent"
+ min={0}
+ max={100}
+ helperText="The percentage of the cash discount. Use 0 for no discount."
+ />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default PaymentTermForm;
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermForm/index.ts b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermForm/index.ts
new file mode 100644
index 0000000000..df19001d81
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermForm/index.ts
@@ -0,0 +1,3 @@
+import PaymentTermsForm from "./PaymentTermForm";
+
+export default PaymentTermsForm;
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx
new file mode 100644
index 0000000000..625d405ea4
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx
@@ -0,0 +1,96 @@
+import { MenuItem } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { PaymentTerm } from "~/modules/accounting";
+
+type PaymentTermsTableProps = {
+ data: PaymentTerm[];
+ count: number;
+};
+
+const PaymentTermsTable = memo(({ data, count }: PaymentTermsTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "daysDue",
+ header: "Days Due",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "daysDiscount",
+ header: "Days Discount",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "discountPercentage",
+ header: "Discount Percentage",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "calculationMethod",
+ header: "Calculation Method",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, []);
+
+ const renderContextMenu = useCallback(
+ (row: typeof data[number]) => {
+ return (
+ <>
+ <MenuItem
+ isDisabled={!permissions.can("update", "accounting")}
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(
+ `/x/accounting/payment-terms/${row.id}?${params.toString()}`
+ );
+ }}
+ >
+ Edit Payment Term
+ </MenuItem>
+ <MenuItem
+ isDisabled={!permissions.can("delete", "accounting")}
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/x/accounting/payment-terms/delete/${
+ row.id
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Delete Payment Term
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<typeof data[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ renderContextMenu={renderContextMenu}
+ />
+ );
+});
+
+PaymentTermsTable.displayName = "PaymentTermsTable";
+export default PaymentTermsTable;
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/index.ts b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/index.ts
new file mode 100644
index 0000000000..56265c576e
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/index.ts
@@ -0,0 +1,3 @@
+import PaymentTermsTable from "./PaymentTermsTable";
+
+export default PaymentTermsTable;
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx
new file mode 100644
index 0000000000..a82b9fa2ef
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx
@@ -0,0 +1,46 @@
+import { useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+
+const PaymentTermsTableFilters = () => {
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
+ const borderColor = useColor("gray.200");
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Filter by name"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "accounting") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Payment Term
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default PaymentTermsTableFilters;
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/index.ts b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/index.ts
new file mode 100644
index 0000000000..cc0cd9abc4
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/index.ts
@@ -0,0 +1,3 @@
+import PaymentTermsTableFilters from "./PaymentTermsTableFilters";
+
+export default PaymentTermsTableFilters;
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/index.ts b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/index.ts
new file mode 100644
index 0000000000..08f3aece14
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/index.ts
@@ -0,0 +1,5 @@
+import PaymentTermForm from "./PaymentTermForm";
+import PaymentTermsTable from "./PaymentTermsTable";
+import PaymentTermsTableFilters from "./PaymentTermsTableFilters";
+
+export { PaymentTermForm, PaymentTermsTable, PaymentTermsTableFilters };
diff --git a/apps/carbon/app/modules/accounting/interfaces/index.ts b/apps/carbon/app/modules/accounting/interfaces/index.ts
new file mode 100644
index 0000000000..40f4971e43
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/index.ts
@@ -0,0 +1,4 @@
+import useAccountingSidebar from "./useAccountingSidebar";
+
+export { useAccountingSidebar };
+export * from "./PaymentTerms";
diff --git a/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsx b/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsx
new file mode 100644
index 0000000000..4ef8a30520
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsx
@@ -0,0 +1,43 @@
+import { usePermissions } from "~/hooks";
+import type { AuthenticatedRouteGroup } from "~/types";
+
+const accountingRoutes: AuthenticatedRouteGroup[] = [
+ {
+ name: "Configure",
+ routes: [
+ {
+ name: "Payment Terms",
+ to: "/x/accounting/payment-terms",
+ role: "employee",
+ },
+ ],
+ },
+];
+
+export default function useAccountingSidebar() {
+ const permissions = usePermissions();
+ return {
+ groups: accountingRoutes
+ .filter((group) => {
+ const filteredRoutes = group.routes.filter((route) => {
+ if (route.role) {
+ return permissions.is(route.role);
+ } else {
+ return true;
+ }
+ });
+
+ return filteredRoutes.length > 0;
+ })
+ .map((group) => ({
+ ...group,
+ routes: group.routes.filter((route) => {
+ if (route.role) {
+ return permissions.is(route.role);
+ } else {
+ return true;
+ }
+ }),
+ })),
+ };
+}
diff --git a/apps/carbon/app/modules/accounting/services/accounting.form.ts b/apps/carbon/app/modules/accounting/services/accounting.form.ts
new file mode 100644
index 0000000000..bb6a6cd9fe
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/services/accounting.form.ts
@@ -0,0 +1,35 @@
+import { withZod } from "@remix-validated-form/with-zod";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const paymentTermValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ daysDue: zfd.numeric(
+ z
+ .number()
+ .min(0, { message: "Days due must be greater than or equal to 0" })
+ ),
+ daysDiscount: zfd.numeric(
+ z
+ .number()
+ .min(0, { message: "Days discount must be greater than or equal to 0" })
+ ),
+ discountPercentage: zfd.numeric(
+ z
+ .number()
+ .min(0, {
+ message: "Discount percent must be greater than or equal to 0",
+ })
+ .max(100, {
+ message: "Discount percent must be less than or equal to 100",
+ })
+ ),
+ calculationMethod: z.enum(["Net", "End of Month", "Day of Month"], {
+ errorMap: (issue, ctx) => ({
+ message: "Calculation method is required",
+ }),
+ }),
+ })
+);
diff --git a/apps/carbon/app/modules/accounting/services/accounting.server.ts b/apps/carbon/app/modules/accounting/services/accounting.server.ts
index 5ad500a6d8..93f3702fb4 100644
--- a/apps/carbon/app/modules/accounting/services/accounting.server.ts
+++ b/apps/carbon/app/modules/accounting/services/accounting.server.ts
@@ -1,5 +1,19 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
+import type { TypeOfValidator } from "~/types/validators";
+import type { GenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters } from "~/utils/query";
+import type { paymentTermValidator } from "./accounting.form";
+
+export async function deletePaymentTerm(
+ client: SupabaseClient<Database>,
+ paymentTermId: string
+) {
+ return client
+ .from("paymentTerm")
+ .update({ active: false })
+ .eq("id", paymentTermId);
+}
export async function getAccountsList(client: SupabaseClient<Database>) {
return client
@@ -15,3 +29,56 @@ export async function getCurrenciesList(client: SupabaseClient<Database>) {
.select("code, name")
.order("name", { ascending: true });
}
+
+export async function getPaymentTerm(
+ client: SupabaseClient<Database>,
+ paymentTermId: string
+) {
+ return client
+ .from("paymentTerm")
+ .select("*")
+ .eq("id", paymentTermId)
+ .single();
+}
+
+export async function getPaymentTerms(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ }
+) {
+ let query = client
+ .from("paymentTerm")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("active", true);
+
+ if (args.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ query = setGenericQueryFilters(query, args, "name");
+ return query;
+}
+
+export async function upsertPaymentTerm(
+ client: SupabaseClient<Database>,
+ paymentTerm:
+ | (Omit<TypeOfValidator<typeof paymentTermValidator>, "id"> & {
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof paymentTermValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in paymentTerm) {
+ return client.from("paymentTerm").insert([paymentTerm]).select("id");
+ }
+ return client
+ .from("paymentTerm")
+ .update(paymentTerm)
+ .eq("id", paymentTerm.id)
+ .select("id");
+}
diff --git a/apps/carbon/app/modules/accounting/services/index.ts b/apps/carbon/app/modules/accounting/services/index.ts
index c5fec51e7e..d9d49eff7e 100644
--- a/apps/carbon/app/modules/accounting/services/index.ts
+++ b/apps/carbon/app/modules/accounting/services/index.ts
@@ -1 +1,2 @@
+export * from "./accounting.form";
export * from "./accounting.server";
diff --git a/apps/carbon/app/modules/accounting/types.ts b/apps/carbon/app/modules/accounting/types.ts
new file mode 100644
index 0000000000..3ebebc68f4
--- /dev/null
+++ b/apps/carbon/app/modules/accounting/types.ts
@@ -0,0 +1,9 @@
+import type { Database } from "@carbon/database";
+import type { getPaymentTerms } from "./services";
+
+export type PaymentTermCalculationMethod =
+ Database["public"]["Enums"]["paymentTermCalculationMethod"];
+
+export type PaymentTerm = NonNullable<
+ Awaited<ReturnType<typeof getPaymentTerms>>["data"]
+>[number];
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsx
index 027914a591..816e346558 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsx
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsx
@@ -45,6 +45,7 @@ const DocumentIcon = ({ fileName }: DocumentIconProps) => {
case "jpeg":
case "gif":
case "svg":
+ case "avif":
return <Icon color="yellow.400" {...iconSize} as={BsFileImageFill} />;
case "mp4":
case "avi":
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/index.ts
new file mode 100644
index 0000000000..666c9a63ea
--- /dev/null
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/index.ts
@@ -0,0 +1,3 @@
+import DocumentIcon from "./DocumentIcon";
+
+export default DocumentIcon;
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx
index 0ec0a1d843..f8fc6e6d84 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx
@@ -1,7 +1,6 @@
import { CreatableSelect } from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
import {
- Box,
HStack,
Icon,
Image,
@@ -34,7 +33,7 @@ import { Avatar, Table } from "~/components";
import { Confirm, ConfirmDelete } from "~/components/Modals";
import { useUrlParams } from "~/hooks";
import type { Document, DocumentLabel } from "~/modules/documents";
-import DocumentIcon from "../DocumentIcon/DocumentIcon";
+import DocumentIcon from "../DocumentIcon";
import { useDocument } from "../useDocument";
type DocumentsTableProps = {
@@ -149,17 +148,14 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {
header: "Name",
cell: ({ row }) => (
<HStack>
- <Box
+ <Icon
color={row.original.favorite ? "yellow.400" : "gray.300"}
cursor="pointer"
- >
- <Icon
- h={4}
- w={4}
- as={row.original.favorite ? BsStarFill : BsStar}
- onClick={() => onFavorite(row.original)}
- />
- </Box>
+ h={4}
+ w={4}
+ as={row.original.favorite ? BsStarFill : BsStar}
+ onClick={() => onFavorite(row.original)}
+ />
<DocumentIcon fileName={row.original.name} />
<Link onClick={() => download(row.original)}>
{row.original.name}
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
index fde41c21dd..288a275652 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
@@ -5,46 +5,30 @@ import { usePermissions, useUrlParams } from "~/hooks";
import type { DocumentLabel } from "~/modules/documents/types";
import { mapRowsToOptions } from "~/utils/form";
import DocumentCreateForm from "../DocumentCreateForm";
+import { capitalize } from "~/utils/string";
type DocumentTableFiltersProps = {
labels: DocumentLabel[];
};
+const documentTypeOptions = [
+ "all",
+ "document",
+ "presentation",
+ "spreadsheet",
+ "image",
+ "video",
+ "audio",
+].map((type) => ({
+ label: capitalize(type),
+ value: type,
+}));
+
const DocumentsTableFilters = ({ labels }: DocumentTableFiltersProps) => {
const [params, setParams] = useUrlParams();
const permissions = usePermissions();
const borderColor = useColor("gray.200");
- const documentTypeOptions = [
- {
- label: "All",
- value: "all",
- },
- {
- label: "Document",
- value: "document",
- },
- {
- label: "Presentation",
- value: "presentation",
- },
- {
- label: "Spreadsheet",
- value: "spreadsheet",
- },
- {
- label: "Image",
- value: "image",
- },
- {
- label: "Video",
- value: "video",
- },
- {
- label: "Audio",
- value: "audio",
- },
- ];
const labelOptions = mapRowsToOptions({
data: labels,
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.ts b/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.ts
index befa47703b..e6226e5f3e 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.ts
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.ts
@@ -109,7 +109,7 @@ export const useDocument = () => {
);
const isImage = useCallback((fileType: string) => {
- return ["png", "jpg", "jpeg", "gif", "svg"].includes(fileType);
+ return ["png", "jpg", "jpeg", "gif", "svg", "avif"].includes(fileType);
}, []);
const label = useCallback(
diff --git a/apps/carbon/app/modules/inventory/index.ts b/apps/carbon/app/modules/inventory/index.ts
new file mode 100644
index 0000000000..490fd762ea
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/index.ts
@@ -0,0 +1,3 @@
+export * from "./interfaces";
+export * from "./services";
+export * from "./types";
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx
new file mode 100644
index 0000000000..80089d10d9
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx
@@ -0,0 +1,113 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import { Hidden, Input, Select, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { shippingMethodValidator } from "~/modules/inventory";
+import type { TypeOfValidator } from "~/types/validators";
+import { mapRowsToOptions } from "~/utils/form";
+
+type ShippingMethodFormProps = {
+ initialValues: TypeOfValidator<typeof shippingMethodValidator>;
+ accounts: {
+ number: string;
+ name: string;
+ }[];
+};
+
+const ShippingMethodForm = ({
+ initialValues,
+ accounts,
+}: ShippingMethodFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "inventory")
+ : !permissions.can("create", "inventory");
+
+ const shippingCarrierOptions = ["UPS", "FedEx", "USPS", "DHL", "Other"].map(
+ (v) => ({
+ label: v,
+ value: v,
+ })
+ );
+
+ const accountOptions = mapRowsToOptions({
+ data: accounts,
+ value: "number",
+ label: "name",
+ });
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={shippingMethodValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/inventory/shipping-methods/${initialValues.id}`
+ : "/x/inventory/shipping-methods/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Shipping Method
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="name" label="Name" />
+ <Select
+ name="carrier"
+ label="Carrier"
+ options={shippingCarrierOptions}
+ />
+ <Select
+ name="carrierAccountId"
+ label="Carrier Account"
+ options={accountOptions}
+ />
+ <Input
+ name="trackingUrl"
+ label="Tracking URL"
+ prefix="https://"
+ />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default ShippingMethodForm;
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/index.ts b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/index.ts
new file mode 100644
index 0000000000..45df5723f5
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/index.ts
@@ -0,0 +1,3 @@
+import ShippingMethodForm from "./ShippingMethodForm";
+
+export default ShippingMethodForm;
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx
new file mode 100644
index 0000000000..8da8f2d730
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx
@@ -0,0 +1,103 @@
+import { MenuItem } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { ShippingMethod } from "~/modules/inventory";
+
+type ShippingMethodsTableProps = {
+ data: ShippingMethod[];
+ count: number;
+};
+
+const ShippingMethodsTable = memo(
+ ({ data, count }: ShippingMethodsTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const hasAccounting =
+ permissions.has("accounting") && permissions.can("view", "accounting");
+
+ const rows = useMemo(() => data, [data]);
+
+ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const result: ColumnDef<typeof rows[number]>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "carrier",
+ header: "Carrier",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "trackingUrl",
+ header: "Tracking URL",
+ cell: (item) => item.getValue(),
+ },
+ ];
+
+ return hasAccounting
+ ? result.concat([
+ {
+ accessorKey: "carrierAccountId",
+ header: "Carrier Account",
+ cell: (item) => item.getValue(),
+ },
+ ])
+ : result;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [permissions]);
+
+ const renderContextMenu = useCallback(
+ (row: typeof data[number]) => {
+ return (
+ <>
+ <MenuItem
+ isDisabled={!permissions.can("update", "inventory")}
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(
+ `/x/inventory/shipping-methods/${row.id}?${params.toString()}`
+ );
+ }}
+ >
+ Edit Shipping Method
+ </MenuItem>
+ <MenuItem
+ isDisabled={!permissions.can("delete", "inventory")}
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/x/inventory/shipping-methods/delete/${
+ row.id
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Delete Shipping Method
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<typeof data[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ renderContextMenu={renderContextMenu}
+ />
+ );
+ }
+);
+
+ShippingMethodsTable.displayName = "ShippingMethodsTable";
+export default ShippingMethodsTable;
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/index.ts b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/index.ts
new file mode 100644
index 0000000000..c807689689
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/index.ts
@@ -0,0 +1,3 @@
+import ShippingMethodsTable from "./ShippingMethodsTable";
+
+export default ShippingMethodsTable;
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx
new file mode 100644
index 0000000000..1b2e82afa1
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx
@@ -0,0 +1,46 @@
+import { useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+
+const ShippingMethodsTableFilters = () => {
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
+ const borderColor = useColor("gray.200");
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Filter by name"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "inventory") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Shipping Method
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default ShippingMethodsTableFilters;
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/index.ts b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/index.ts
new file mode 100644
index 0000000000..2972aec811
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/index.ts
@@ -0,0 +1,3 @@
+import ShippingMethodsTableFilters from "./ShippingMethodsTableFilters";
+
+export default ShippingMethodsTableFilters;
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/index.ts b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/index.ts
new file mode 100644
index 0000000000..85db132cde
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/index.ts
@@ -0,0 +1,9 @@
+import ShippingMethodForm from "./ShippingMethodForm";
+import ShippingMethodsTable from "./ShippingMethodsTable";
+import ShippingMethodsTableFilters from "./ShippingMethodsTableFilters";
+
+export {
+ ShippingMethodForm,
+ ShippingMethodsTable,
+ ShippingMethodsTableFilters,
+};
diff --git a/apps/carbon/app/modules/inventory/interfaces/index.ts b/apps/carbon/app/modules/inventory/interfaces/index.ts
new file mode 100644
index 0000000000..1edad05971
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/index.ts
@@ -0,0 +1,4 @@
+import useInventorySidebar from "./useInventorySidebar";
+
+export { useInventorySidebar };
+export * from "./ShippingMethods";
diff --git a/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx b/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx
new file mode 100644
index 0000000000..fdc626a56c
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx
@@ -0,0 +1,43 @@
+import { usePermissions } from "~/hooks";
+import type { AuthenticatedRouteGroup } from "~/types";
+
+const inventoryRoutes: AuthenticatedRouteGroup[] = [
+ {
+ name: "Configure",
+ routes: [
+ {
+ name: "Shipping Methods",
+ to: "/x/inventory/shipping-methods",
+ role: "employee",
+ },
+ ],
+ },
+];
+
+export default function useAccountingSidebar() {
+ const permissions = usePermissions();
+ return {
+ groups: inventoryRoutes
+ .filter((group) => {
+ const filteredRoutes = group.routes.filter((route) => {
+ if (route.role) {
+ return permissions.is(route.role);
+ } else {
+ return true;
+ }
+ });
+
+ return filteredRoutes.length > 0;
+ })
+ .map((group) => ({
+ ...group,
+ routes: group.routes.filter((route) => {
+ if (route.role) {
+ return permissions.is(route.role);
+ } else {
+ return true;
+ }
+ }),
+ })),
+ };
+}
diff --git a/apps/carbon/app/modules/inventory/services/index.ts b/apps/carbon/app/modules/inventory/services/index.ts
new file mode 100644
index 0000000000..6600d49679
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/services/index.ts
@@ -0,0 +1,2 @@
+export * from "./inventory.form";
+export * from "./inventory.server";
diff --git a/apps/carbon/app/modules/inventory/services/inventory.form.ts b/apps/carbon/app/modules/inventory/services/inventory.form.ts
new file mode 100644
index 0000000000..c8499553f5
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/services/inventory.form.ts
@@ -0,0 +1,17 @@
+import { withZod } from "@remix-validated-form/with-zod";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const shippingMethodValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ carrier: z.enum(["UPS", "FedEx", "USPS", "DHL", "Other"], {
+ errorMap: (issue, ctx) => ({
+ message: "Carrier is required",
+ }),
+ }),
+ carrierAccountId: zfd.text(z.string().optional()),
+ trackingUrl: zfd.text(z.string().optional()),
+ })
+);
diff --git a/apps/carbon/app/modules/inventory/services/inventory.server.ts b/apps/carbon/app/modules/inventory/services/inventory.server.ts
new file mode 100644
index 0000000000..8ae017eca1
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/services/inventory.server.ts
@@ -0,0 +1,69 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { TypeOfValidator } from "~/types/validators";
+import type { GenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters } from "~/utils/query";
+import type { shippingMethodValidator } from "./inventory.form";
+
+export async function deleteShippingMethod(
+ client: SupabaseClient<Database>,
+ shippingMethodId: string
+) {
+ return client
+ .from("shippingMethod")
+ .update({ active: false })
+ .eq("id", shippingMethodId);
+}
+
+export async function getShippingMethod(
+ client: SupabaseClient<Database>,
+ shippingMethodId: string
+) {
+ return client
+ .from("shippingMethod")
+ .select("*")
+ .eq("id", shippingMethodId)
+ .single();
+}
+
+export async function getShippingMethods(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ }
+) {
+ let query = client
+ .from("shippingMethod")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("active", true);
+
+ if (args.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ query = setGenericQueryFilters(query, args, "name");
+ return query;
+}
+
+export async function upsertShippingMethod(
+ client: SupabaseClient<Database>,
+ shippingMethod:
+ | (Omit<TypeOfValidator<typeof shippingMethodValidator>, "id"> & {
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof shippingMethodValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in shippingMethod) {
+ return client.from("shippingMethod").insert([shippingMethod]).select("id");
+ }
+ return client
+ .from("shippingMethod")
+ .update(shippingMethod)
+ .eq("id", shippingMethod.id)
+ .select("id");
+}
diff --git a/apps/carbon/app/modules/inventory/types.ts b/apps/carbon/app/modules/inventory/types.ts
new file mode 100644
index 0000000000..a47d478b6c
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/types.ts
@@ -0,0 +1,8 @@
+import type { Database } from "@carbon/database";
+import type { getShippingMethod } from "./services";
+
+export type ShippingCarrier = Database["public"]["Enums"]["shippingCarrier"];
+
+export type ShippingMethod = NonNullable<
+ Awaited<ReturnType<typeof getShippingMethod>>["data"]
+>[number];
diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx
index f4fa00162a..041d8e0480 100644
--- a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx
@@ -21,10 +21,6 @@ const UnitOfMeasuresTable = memo(
const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
return [
- {
- header: "Component",
- cell: ({ row }) => <p>{row.original.name}</p>,
- },
{
accessorKey: "name",
header: "Name",
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
new file mode 100644
index 0000000000..a39f7ede33
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
@@ -0,0 +1,129 @@
+import {
+ Card,
+ CardBody,
+ CardFooter,
+ CardHeader,
+ Grid,
+ Heading,
+ Text,
+ VStack,
+} from "@chakra-ui/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Boolean,
+ Currency,
+ DatePicker,
+ Input,
+ Select,
+ Submit,
+ Supplier,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import type {
+ PurchaseOrderApprovalStatus,
+ PurchaseOrderType,
+} from "~/modules/purchasing";
+import { purchaseOrderValidator } from "~/modules/purchasing";
+
+type PurchaseOrderFormValues = {
+ id?: string;
+ purchaseOrderId?: string;
+ status: PurchaseOrderApprovalStatus;
+ type: PurchaseOrderType;
+ currencyCode: string;
+};
+
+type PurchaseOrderFormProps = {
+ initialValues: PurchaseOrderFormValues;
+ purchaseOrderApprovalStatuses: PurchaseOrderApprovalStatus[];
+ purchaseOrderTypes: PurchaseOrderType[];
+};
+
+const PurchaseOrderForm = ({
+ initialValues,
+ purchaseOrderApprovalStatuses,
+ purchaseOrderTypes,
+}: PurchaseOrderFormProps) => {
+ const permissions = usePermissions();
+ const isEditing = initialValues.id !== undefined;
+
+ const approvalOptions = purchaseOrderApprovalStatuses.map((approval) => ({
+ label: approval,
+ value: approval,
+ }));
+
+ const typeOptions = purchaseOrderTypes.map((type) => ({
+ label: type,
+ value: type,
+ }));
+
+ return (
+ <ValidatedForm
+ method="post"
+ validator={purchaseOrderValidator}
+ defaultValues={initialValues}
+ >
+ <Card w="full">
+ <CardHeader>
+ <Heading size="md">
+ {isEditing ? "Purchase Order Basics" : "New Purchase Order"}
+ </Heading>
+ {!isEditing && (
+ <Text color="gray.500">
+ A purchase order contains information about the agreement between
+ the company and a specific supplier for parts and services.
+ </Text>
+ )}
+ </CardHeader>
+ <CardBody>
+ <Grid
+ gridTemplateColumns={
+ isEditing ? ["1fr", "1fr", "1fr 1fr 1fr"] : "1fr"
+ }
+ gridColumnGap={8}
+ gridRowGap={2}
+ w="full"
+ >
+ <VStack alignItems="start" spacing={2} w="full">
+ {isEditing && (
+ <Input
+ name="id"
+ label="Purchase Order ID"
+ isReadOnly={isEditing}
+ />
+ )}
+ <Supplier name="supplierId" label="Supplier" />
+ <DatePicker name="orderDate" label="Order Date" />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Select name="type" label="Type" options={typeOptions} />
+ <Select
+ name="status"
+ label="Approval Status"
+ options={approvalOptions}
+ />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Currency name="currencyCode" label="Currency" />
+ <Boolean name="blocked" label="Blocked" />
+ {isEditing && <Boolean name="active" label="Active" />}
+ </VStack>
+ </Grid>
+ </CardBody>
+ <CardFooter>
+ <Submit
+ isDisabled={
+ isEditing
+ ? !permissions.can("update", "purchasing")
+ : !permissions.can("create", "purchasing")
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ );
+};
+
+export default PurchaseOrderForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/index.ts
new file mode 100644
index 0000000000..d66e36545c
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderForm from "./PurchaseOrderForm";
+
+export default PurchaseOrderForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
new file mode 100644
index 0000000000..4febcbf25e
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
@@ -0,0 +1,74 @@
+import {
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ HStack,
+ Stack,
+ Text,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { FaHistory } from "react-icons/fa";
+import { useRouteData } from "~/hooks";
+import type { PurchaseOrder } from "~/modules/purchasing";
+
+const PartPreview = () => {
+ const { orderId } = useParams();
+ if (!orderId) throw new Error("Could not find orderId");
+ const routeData = useRouteData<PurchaseOrder>(`/x/purchase-order/${orderId}`);
+
+ return (
+ <Card w="full">
+ <CardHeader>
+ <HStack justifyContent="space-between" alignItems="start">
+ <Stack direction="column" spacing={2}>
+ <Heading size="md">{routeData?.purchaseOrderId}</Heading>
+ <Text color="gray.500">{routeData?.supplierName}</Text>
+ </Stack>
+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
+ View History
+ </Button>
+ </HStack>
+ </CardHeader>
+ <CardBody>
+ <Stack direction={["column", "column", "row"]} spacing={8}>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Order Date</Text>
+ <Text fontWeight="bold">{routeData?.orderDate}</Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Due Date</Text>
+ <Text fontWeight="bold">{routeData?.orderDueDate}</Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Order Type</Text>
+ <Text fontWeight="bold">{routeData?.type}</Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Order Status</Text>
+ <Text fontWeight="bold">{routeData?.status}</Text>
+ </Stack>
+ </Stack>
+ </CardBody>
+ </Card>
+ );
+};
+
+export default PartPreview;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/index.ts
new file mode 100644
index 0000000000..4be22f10d3
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderHeader from "./PurchaseOrderHeader";
+
+export default PurchaseOrderHeader;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
new file mode 100644
index 0000000000..6bfc7851cf
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
@@ -0,0 +1,50 @@
+import { Button, Box, VStack } from "@chakra-ui/react";
+import { Link, useMatches, useParams } from "@remix-run/react";
+import { usePurchaseOrderSidebar } from "./usePurchaseOrderSidebar";
+
+const PurchaseOrderSidebar = () => {
+ const { orderId } = useParams();
+ if (!orderId)
+ throw new Error(
+ "PurchaseOrderSidebar requires an orderId and could not find orderId in params"
+ );
+
+ const links = usePurchaseOrderSidebar();
+ const matches = useMatches();
+
+ return (
+ <VStack h="full" alignItems="start">
+ <Box overflowY="auto" w="full" h="full">
+ <VStack spacing={2}>
+ <VStack spacing={1} alignItems="start" w="full">
+ {links.map((route) => {
+ const isActive = matches.some(
+ (match) =>
+ (match.pathname.includes(route.to) && route.to !== "") ||
+ (match.id.includes(".index") && route.to === "")
+ );
+
+ return (
+ <Button
+ key={route.name}
+ as={Link}
+ to={route.to}
+ variant={isActive ? "solid" : "ghost"}
+ border="none"
+ fontWeight={isActive ? "bold" : "normal"}
+ justifyContent="start"
+ size="md"
+ w="full"
+ >
+ {route.name}
+ </Button>
+ );
+ })}
+ </VStack>
+ </VStack>
+ </Box>
+ </VStack>
+ );
+};
+
+export default PurchaseOrderSidebar;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/index.ts
new file mode 100644
index 0000000000..7687bb6c04
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderSidebar from "./PurchaseOrderSidebar";
+
+export default PurchaseOrderSidebar;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx
new file mode 100644
index 0000000000..05e418397b
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx
@@ -0,0 +1,46 @@
+import { usePermissions } from "~/hooks";
+import type { Role } from "~/types";
+
+export function usePurchaseOrderSidebar() {
+ const permissions = usePermissions();
+ return [
+ {
+ name: "Header",
+ to: "",
+ },
+ {
+ name: "Line Items",
+ to: "items",
+ role: ["employee", "supplier"],
+ },
+ {
+ name: "Delivery",
+ to: "delivery",
+ role: ["employee", "supplier"],
+ },
+ {
+ name: "Taxes",
+ to: "taxes",
+ role: ["employee"],
+ },
+ {
+ name: "Approvals",
+ to: "approvals",
+ role: ["employee"],
+ },
+ {
+ name: "Internal Attachments",
+ to: "internal-attachments",
+ role: ["employee"],
+ },
+ {
+ name: "External Attachments",
+ to: "external-attachments",
+ role: ["employee", "supplier"],
+ },
+ ].filter(
+ (item) =>
+ item.role === undefined ||
+ item.role.some((role) => permissions.is(role as Role))
+ );
+}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts
new file mode 100644
index 0000000000..07d4c7afc2
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts
@@ -0,0 +1,5 @@
+import PurchaseOrderForm from "./PurchaseOrderForm";
+import PurchaseOrderHeader from "./PurchaseOrderHeader";
+import PurchaseOrderSidebar from "./PurchaseOrderSidebar";
+
+export { PurchaseOrderForm, PurchaseOrderHeader, PurchaseOrderSidebar };
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
new file mode 100644
index 0000000000..d6ba8a727f
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
@@ -0,0 +1,213 @@
+import { HStack, Icon, MenuItem, Text, useDisclosure } from "@chakra-ui/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import { BsPencilSquare, BsStar, BsStarFill } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Avatar, Table } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type { PurchaseOrder } from "~/modules/purchasing";
+import { usePurchaseOrder } from "../usePurchaseOrder";
+
+type PurchaseOrdersTableProps = {
+ data: PurchaseOrder[];
+ count: number;
+};
+
+const PurchaseOrdersTable = memo(
+ ({ data, count }: PurchaseOrdersTableProps) => {
+ const permissions = usePermissions();
+
+ // put rows in state for use with optimistic ui updates
+ const [rows, setRows] = useState<PurchaseOrder[]>(data);
+ // we have to do this useEffect silliness since we're putitng rows
+ // in state for optimistic ui updates
+ useEffect(() => {
+ setRows(data);
+ }, [data]);
+
+ const { edit, favorite } = usePurchaseOrder();
+
+ const [selectedPurchaseOrder, setSelectedPurchaseOrder] =
+ useState<PurchaseOrder | null>(null);
+ const closePurchaseOrderModal = useDisclosure();
+
+ const onFavorite = useCallback(
+ async (row: PurchaseOrder) => {
+ // optimistically update the UI and then make the mutation
+ setRows((prev) => {
+ const index = prev.findIndex((item) => item.id === row.id);
+ const updated = [...prev];
+ updated[index] = {
+ ...updated[index],
+ favorite: !updated[index].favorite,
+ };
+ return updated;
+ });
+ // mutate the database
+ await favorite(row);
+ },
+ [favorite]
+ );
+
+ const columns = useMemo<ColumnDef<PurchaseOrder>[]>(() => {
+ return [
+ {
+ accessorKey: "purchaseOrderId",
+ header: "PO Number",
+ cell: ({ row }) => (
+ <HStack>
+ <Icon
+ color={row.original.favorite ? "yellow.400" : "gray.300"}
+ cursor="pointer"
+ h={4}
+ w={4}
+ as={row.original.favorite ? BsStarFill : BsStar}
+ onClick={() => onFavorite(row.original)}
+ />
+ <span>{row.original.purchaseOrderId}</span>
+ </HStack>
+ ),
+ },
+ {
+ accessorKey: "supplierName",
+ header: "Supplier",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "orderDate",
+ header: "Order Date",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "orderDueDate",
+ header: "Due Date",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "createdByFullName",
+ header: "Created By",
+ cell: ({ row }) => {
+ return (
+ <HStack>
+ <Avatar size="sm" path={row.original.createdByAvatar} />
+ <Text>{row.original.createdByFullName}</Text>
+ </HStack>
+ );
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "updatedByFullName",
+ header: "Updated By",
+ cell: ({ row }) => {
+ return row.original.updatedByFullName ? (
+ <HStack>
+ <Avatar size="sm" path={row.original.updatedByAvatar ?? null} />
+ <Text>{row.original.updatedByFullName}</Text>
+ </HStack>
+ ) : null;
+ },
+ },
+ {
+ accessorKey: "updatedAt",
+ header: "Updated At",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, [onFavorite]);
+
+ const actions = useMemo(() => {
+ return [
+ {
+ label: "Add to Favorites",
+ icon: <BsStar />,
+ onClick: (selected: PurchaseOrder[]) => {
+ console.log("move to favorites", selected);
+ },
+ },
+ ];
+ }, []);
+
+ const defaultColumnVisibility = {
+ createdAt: false,
+ updatedAt: false,
+ };
+
+ const renderContextMenu = useMemo(() => {
+ // eslint-disable-next-line react/display-name
+ return (row: PurchaseOrder) => (
+ <>
+ <MenuItem
+ icon={<BsPencilSquare />}
+ isDisabled={!permissions.can("update", "purchasing")}
+ onClick={() => edit(row)}
+ >
+ Edit
+ </MenuItem>
+ <MenuItem
+ icon={<BsStar />}
+ onClick={() => {
+ onFavorite(row);
+ }}
+ >
+ Favorite
+ </MenuItem>
+ <MenuItem
+ icon={<IoMdTrash />}
+ isDisabled={!permissions.can("delete", "purchasing")}
+ onClick={() => {
+ setSelectedPurchaseOrder(row);
+ closePurchaseOrderModal.onOpen();
+ }}
+ >
+ Close
+ </MenuItem>
+ </>
+ );
+ }, [closePurchaseOrderModal, edit, onFavorite, permissions]);
+
+ return (
+ <>
+ <Table<PurchaseOrder>
+ actions={actions}
+ count={count}
+ columns={columns}
+ data={rows}
+ defaultColumnVisibility={defaultColumnVisibility}
+ withColumnOrdering
+ withFilters
+ withPagination
+ withSimpleSorting
+ withSelectableRows
+ renderContextMenu={renderContextMenu}
+ />
+
+ {selectedPurchaseOrder && (
+ <ConfirmDelete
+ action={`/x/documents/${selectedPurchaseOrder?.id}/close`}
+ isOpen={closePurchaseOrderModal.isOpen}
+ name={selectedPurchaseOrder.purchaseOrderId!}
+ text={`Are you sure you want to move ${selectedPurchaseOrder.purchaseOrderId!} to the trash?`}
+ onCancel={() => {
+ closePurchaseOrderModal.onClose();
+ setSelectedPurchaseOrder(null);
+ }}
+ onSubmit={() => {
+ closePurchaseOrderModal.onClose();
+ setSelectedPurchaseOrder(null);
+ }}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+PurchaseOrdersTable.displayName = "PurchaseOrdersTable";
+
+export default PurchaseOrdersTable;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/index.ts
new file mode 100644
index 0000000000..e1ae2054e9
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrdersTable from "./PurchaseOrdersTable";
+
+export default PurchaseOrdersTable;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
new file mode 100644
index 0000000000..1b9f1527c9
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
@@ -0,0 +1,75 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+
+const purchaseOrderStatusOptions = [
+ "Draft",
+ "In Review",
+ "In External Review",
+ "Approved",
+ "Rejected",
+ "Confirmed",
+].map((type) => ({
+ label: type,
+ value: type,
+}));
+
+const PurchaseOrdersTableFilters = () => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+
+ const borderColor = useColor("gray.200");
+
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="search"
+ size="sm"
+ minW={180}
+ placeholder="Search"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={purchaseOrderStatusOptions.filter(
+ (type) => type.value === params.get("status")
+ )}
+ isClearable
+ options={purchaseOrderStatusOptions}
+ onChange={(selected) => {
+ setParams({ status: selected?.value });
+ }}
+ aria-label="Status"
+ minW={180}
+ placeholder="Status"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "purchasing") && (
+ <Button
+ as={Link}
+ to="/x/purchase-order/new"
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Purchase Order
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default PurchaseOrdersTableFilters;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/index.ts
new file mode 100644
index 0000000000..ed0ac3f694
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrdersTableFilters from "./PurchaseOrdersTableFilters";
+
+export default PurchaseOrdersTableFilters;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/index.ts
new file mode 100644
index 0000000000..e53af4f77e
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/index.ts
@@ -0,0 +1,4 @@
+import PurchaseOrdersTable from "./PurchaseOrdersTable";
+import PurchaseOrdersTableFilters from "./PurchaseOrdersTableFilters";
+
+export { PurchaseOrdersTable, PurchaseOrdersTableFilters };
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts
new file mode 100644
index 0000000000..c7f5ae5dc1
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts
@@ -0,0 +1,58 @@
+import { useNavigate } from "@remix-run/react";
+import { useCallback } from "react";
+import { useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type {
+ PurchaseOrder,
+ PurchaseOrderTransactionType,
+} from "~/modules/purchasing";
+
+export const usePurchaseOrder = () => {
+ const navigate = useNavigate();
+ const { supabase } = useSupabase();
+ const user = useUser();
+
+ const insertTransaction = useCallback(
+ (purchaseOrder: PurchaseOrder, type: PurchaseOrderTransactionType) => {
+ if (user?.id === undefined) throw new Error("User is undefined");
+ if (!purchaseOrder.id) throw new Error("Purchase order ID is undefined");
+ return supabase?.from("purchaseOrderTransaction").insert({
+ purchaseOrderId: purchaseOrder.id,
+ type,
+ userId: user.id,
+ });
+ },
+ [supabase, user?.id]
+ );
+
+ const edit = useCallback(
+ (purchaseOrder: PurchaseOrder) =>
+ navigate(`/x/purchase-order/${purchaseOrder.id}`),
+ [navigate]
+ );
+
+ const favorite = useCallback(
+ async (purchaseOrder: PurchaseOrder) => {
+ if (!purchaseOrder.id) throw new Error("Purchase order ID is undefined");
+ if (purchaseOrder.favorite) {
+ await supabase
+ ?.from("purchaseOrderFavorite")
+ .delete()
+ .eq("purchaseOrderId", purchaseOrder.id)
+ .eq("userId", user?.id);
+ return insertTransaction(purchaseOrder, "Unfavorite");
+ } else {
+ await supabase
+ ?.from("purchaseOrderFavorite")
+ .insert({ purchaseOrderId: purchaseOrder.id, userId: user?.id });
+ return insertTransaction(purchaseOrder, "Favorite");
+ }
+ },
+ [insertTransaction, supabase, user?.id]
+ );
+
+ return {
+ edit,
+ favorite,
+ };
+};
diff --git a/apps/carbon/app/modules/purchasing/interfaces/index.ts b/apps/carbon/app/modules/purchasing/interfaces/index.ts
index 64f6cad37c..a02c6ef3b2 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/index.ts
+++ b/apps/carbon/app/modules/purchasing/interfaces/index.ts
@@ -1,5 +1,7 @@
import usePurchasingSidebar from "./usePurchasingSidebar";
export { usePurchasingSidebar };
+export * from "./PurchaseOrder";
+export * from "./PurchaseOrders";
export * from "./Suppliers";
export * from "./SupplierTypes";
diff --git a/apps/carbon/app/modules/purchasing/interfaces/usePurchasingSidebar.tsx b/apps/carbon/app/modules/purchasing/interfaces/usePurchasingSidebar.tsx
index 54dd1d4a22..7c8da4307b 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/usePurchasingSidebar.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/usePurchasingSidebar.tsx
@@ -5,6 +5,10 @@ const purchasingRoutes: AuthenticatedRouteGroup[] = [
{
name: "Manage",
routes: [
+ {
+ name: "Purchase Orders",
+ to: "/x/purchasing/orders",
+ },
{
name: "Suppliers",
to: "/x/purchasing/suppliers",
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
index 2bd91ec4a1..944d1b9a9c 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
@@ -3,6 +3,46 @@ import { z } from "zod";
import { zfd } from "zod-form-data";
import { address, contact } from "~/types/validators";
+export const purchaseOrderValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ purchaseOrderId: zfd.text(z.string().optional()),
+ orderDate: z.string().min(1, { message: "Order Date is required" }),
+ type: z.enum(["Draft", "Purchase", "Return"], {
+ errorMap: (issue, ctx) => ({
+ message: "Type is required",
+ }),
+ }),
+ status: z.enum(
+ [
+ "Draft",
+ "In Review",
+ "In External Review",
+ "Approved",
+ "Rejected",
+ "Confirmed",
+ ],
+ {
+ errorMap: (issue, ctx) => ({
+ message: "Status is required",
+ }),
+ }
+ ),
+ orderDueDate: zfd.text(z.string().optional()),
+ receivedDate: zfd.text(z.string().optional()),
+ notes: zfd.text(z.string().optional()),
+ supplierId: z.string().min(36, { message: "Supplier is required" }),
+ supplierContactId: zfd.text(z.string().optional()),
+ supplierReference: zfd.text(z.string().optional()),
+ invoiceSupplierId: zfd.text(z.string().optional()),
+ invoiceSupplierLocationId: zfd.text(z.string().optional()),
+ invoiceSupplierContactId: zfd.text(z.string().optional()),
+ paymentTermId: zfd.text(z.string().optional()),
+ shippingMethodId: zfd.text(z.string().optional()),
+ currencyCode: zfd.text(z.string().optional()),
+ })
+);
+
export const supplierValidator = withZod(
z.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
index 8ff0f9f204..dff230e9bb 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
@@ -1,8 +1,26 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getSupabaseServiceRole } from "~/lib/supabase";
+import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import type { purchaseOrderValidator } from "./purchasing.form";
+
+export async function closePurchaseOrder(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string,
+ userId: string
+) {
+ return client
+ .from("purchaseOrder")
+ .update({
+ closed: true,
+ closedAt: new Date().toISOString(),
+ closedBy: userId,
+ })
+ .eq("id", purchaseOrderId)
+ .select("id");
+}
export async function deleteSupplierContact(
client: SupabaseClient<Database>,
@@ -34,7 +52,6 @@ export async function deleteSupplierType(
) {
return client.from("supplierType").delete().eq("id", supplierTypeId);
}
-
export async function getSupplier(
client: SupabaseClient<Database>,
supplierId: string
@@ -48,6 +65,64 @@ export async function getSupplier(
.single();
}
+export async function getPurchaseOrder(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return client
+ .from("purchase_order_view")
+ .select("*")
+ .eq("id", purchaseOrderId)
+ .single();
+}
+
+export async function getPurchaseOrders(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ search: string | null;
+ status: string | null;
+ supplierId: string | null;
+ }
+) {
+ let query = client
+ .from("purchase_order_view")
+ .select("*", { count: "exact" });
+
+ if (args.search) {
+ query = query.ilike("purchaseOrderId", `%${args.search}%`);
+ }
+
+ if (args.status) {
+ if (args.status === "closed") {
+ query = query.eq("closed", true);
+ } else {
+ query = query.eq("status", args.status);
+ }
+ }
+
+ if (args.supplierId) {
+ query = query.eq("supplierId", args.supplierId);
+ }
+
+ query = setGenericQueryFilters(query, args, "purchaseOrderId");
+ return query;
+}
+
+export function getPurchaseOrderApprovalStatuses(): Database["public"]["Enums"]["purchaseOrderApprovalStatus"][] {
+ return [
+ "Draft",
+ "In Review",
+ "In External Review",
+ "Approved",
+ "Rejected",
+ "Confirmed",
+ ];
+}
+
+export function getPurchaseOrderTypes(): Database["public"]["Enums"]["purchaseOrderType"][] {
+ return ["Draft", "Purchase", "Return"];
+}
+
export async function getSupplierLocations(
client: SupabaseClient<Database>,
supplierId: string
@@ -343,6 +418,40 @@ export async function updateSupplierLocation(
.select("id");
}
+export async function upsertPurchaseOrder(
+ client: SupabaseClient<Database>,
+ purchaseOrder:
+ | (Omit<
+ TypeOfValidator<typeof purchaseOrderValidator>,
+ "id" | "purchaseOrderId"
+ > & {
+ purchaseOrderId: string;
+ createdBy: string;
+ })
+ | (Omit<
+ TypeOfValidator<typeof purchaseOrderValidator>,
+ "id" | "purchaseOrderId"
+ > & {
+ id: string;
+ purchaseOrderId: string;
+ updatedBy: string;
+ })
+) {
+ if ("id" in purchaseOrder) {
+ return client
+ .from("purchaseOrder")
+ .update(purchaseOrder)
+ .eq("id", purchaseOrder.id)
+ .select("id, purchaseOrderId");
+ }
+ return client
+ .from("purchaseOrder")
+ .insert([
+ { ...purchaseOrder, currencyCode: purchaseOrder.currencyCode || "USD" },
+ ])
+ .select("id, purchaseOrderId");
+}
+
export async function upsertSupplierType(
client: SupabaseClient<Database>,
supplierType: { id?: string; name: string; color: string | null }
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index 694a1ea4a4..bf53f06e8e 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -1,4 +1,6 @@
+import type { Database } from "@carbon/database";
import type {
+ getPurchaseOrders,
getSupplierContacts,
getSupplierLocations,
getSuppliers,
@@ -6,6 +8,19 @@ import type {
getSupplierTypes,
} from "./services";
+export type PurchaseOrder = NonNullable<
+ Awaited<ReturnType<typeof getPurchaseOrders>>["data"]
+>[number];
+
+export type PurchaseOrderApprovalStatus =
+ Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+
+export type PurchaseOrderType =
+ Database["public"]["Enums"]["purchaseOrderType"];
+
+export type PurchaseOrderTransactionType =
+ Database["public"]["Enums"]["purchaseOrderTransactionType"];
+
export type Supplier = NonNullable<
Awaited<ReturnType<typeof getSuppliers>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/settings/index.ts b/apps/carbon/app/modules/settings/index.ts
new file mode 100644
index 0000000000..684aed031a
--- /dev/null
+++ b/apps/carbon/app/modules/settings/index.ts
@@ -0,0 +1,3 @@
+export * from "./services";
+export * from "./interfaces";
+export * from "./types";
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequenceForm/SequenceForm.tsx b/apps/carbon/app/modules/settings/interfaces/Sequences/SequenceForm/SequenceForm.tsx
new file mode 100644
index 0000000000..3e684bedcc
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequenceForm/SequenceForm.tsx
@@ -0,0 +1,123 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ Heading,
+ HStack,
+ Text,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import { Hidden, Input, Number, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { sequenceValidator } from "~/modules/settings";
+import type { TypeOfValidator } from "~/types/validators";
+import { interpolateDate } from "~/utils/string";
+
+type SequenceFormProps = {
+ initialValues: TypeOfValidator<typeof sequenceValidator> & {
+ name: string;
+ };
+};
+
+const SequenceForm = ({ initialValues }: SequenceFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const [prefix, setPrefix] = useState(initialValues.prefix ?? "");
+ const [suffix, setSuffix] = useState(initialValues.suffix ?? "");
+ const [next, setNext] = useState(initialValues.next ?? "1");
+ const [size, setSize] = useState(initialValues.size ?? 5);
+
+ const makePreview = () => {
+ const p = interpolateDate(prefix);
+ const s = interpolateDate(suffix);
+
+ return `${p}${next.toString().padStart(size, "0")}${s}`;
+ };
+
+ const isDisabled = !permissions.can("update", "settings");
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={sequenceValidator}
+ method="post"
+ action={`/x/settings/sequences/${initialValues.table}`}
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{`${initialValues.name}`} Sequence</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="table" />
+ <VStack spacing={4} alignItems="start">
+ <Heading size="lg">{makePreview()}</Heading>
+
+ <Input
+ name="prefix"
+ label="Prefix"
+ onChange={(e) => setPrefix(e.target.value)}
+ />
+ <Number
+ name="next"
+ min={0}
+ label="Next"
+ onChange={(_, val) => setNext(val)}
+ />
+ <Number
+ name="size"
+ min={0}
+ max={30}
+ label="Size"
+ onChange={(_, val) => setSize(val)}
+ />
+ <Number name="step" min={0} max={10000} label="Step" />
+ <Input
+ name="suffix"
+ label="Suffix"
+ onChange={(e) => setSuffix(e.target.value)}
+ />
+ <VStack spacing={0} alignItems="start">
+ <Text
+ color="gray.500"
+ fontSize="sm"
+ >{`%{yyyy} = Full Year`}</Text>
+ <Text color="gray.500" fontSize="sm">{`%{yy} = Year`}</Text>
+ <Text color="gray.500" fontSize="sm">{`%{mm} = Month`}</Text>
+ <Text color="gray.500" fontSize="sm">{`%{dd} = Day`}</Text>
+ <Text color="gray.500" fontSize="sm">{`%{hh} = Hour`}</Text>
+ <Text color="gray.500" fontSize="sm">{`%{mm} = Minute`}</Text>
+ <Text color="gray.500" fontSize="sm">{`%{ss} = Second`}</Text>
+ </VStack>
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default SequenceForm;
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequenceForm/index.ts b/apps/carbon/app/modules/settings/interfaces/Sequences/SequenceForm/index.ts
new file mode 100644
index 0000000000..2de2d14ff0
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequenceForm/index.ts
@@ -0,0 +1,3 @@
+import SequenceForm from "./SequenceForm";
+
+export default SequenceForm;
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx
new file mode 100644
index 0000000000..8391e3131b
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx
@@ -0,0 +1,87 @@
+import { MenuItem } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Sequence } from "~/modules/settings";
+
+type SequencesTableProps = {
+ data: Sequence[];
+ count: number;
+};
+
+const SequencesTable = memo(({ data, count }: SequencesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "prefix",
+ header: "Prefix",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "next",
+ header: "Next",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "size",
+ header: "Size",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "step",
+ header: "Step",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "suffix",
+ header: "Suffix",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, []);
+
+ const renderContextMenu = useCallback(
+ (row: typeof data[number]) => {
+ return (
+ <>
+ <MenuItem
+ isDisabled={!permissions.can("update", "settings")}
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(
+ `/x/settings/sequences/${row.table}?${params.toString()}`
+ );
+ }}
+ >
+ Edit Sequence
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<typeof data[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ renderContextMenu={renderContextMenu}
+ />
+ );
+});
+
+SequencesTable.displayName = "SequencesTable";
+export default SequencesTable;
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/index.ts b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/index.ts
new file mode 100644
index 0000000000..d9d7b918be
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/index.ts
@@ -0,0 +1,3 @@
+import SequencessTable from "./SequencesTable";
+
+export default SequencessTable;
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx
new file mode 100644
index 0000000000..7a0a526ab0
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx
@@ -0,0 +1,29 @@
+import { useColor } from "@carbon/react";
+import { HStack } from "@chakra-ui/react";
+import { DebouncedInput } from "~/components/Search";
+
+const SequencesTableFilters = () => {
+ const borderColor = useColor("gray.200");
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Filter by name"
+ />
+ </HStack>
+ </HStack>
+ );
+};
+
+export default SequencesTableFilters;
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/index.ts b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/index.ts
new file mode 100644
index 0000000000..e4f6a338e6
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/index.ts
@@ -0,0 +1,3 @@
+import SequencesTableFilters from "./SequencesTableFilters";
+
+export default SequencesTableFilters;
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/index.ts b/apps/carbon/app/modules/settings/interfaces/Sequences/index.ts
new file mode 100644
index 0000000000..23e49d40e6
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/index.ts
@@ -0,0 +1,5 @@
+import SequenceForm from "./SequenceForm";
+import SequencesTable from "./SequencesTable";
+import SequencesTableFilters from "./SequencesTableFilters";
+
+export { SequenceForm, SequencesTable, SequencesTableFilters };
diff --git a/apps/carbon/app/modules/settings/interfaces/index.ts b/apps/carbon/app/modules/settings/interfaces/index.ts
new file mode 100644
index 0000000000..f930f5b8b3
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/index.ts
@@ -0,0 +1,4 @@
+import useSettingsSidebar from "./useSettingsSidebar";
+
+export { useSettingsSidebar };
+export * from "./Sequences";
diff --git a/apps/carbon/app/modules/settings/interfaces/useSettingsSidebar.tsx b/apps/carbon/app/modules/settings/interfaces/useSettingsSidebar.tsx
new file mode 100644
index 0000000000..526ff0948f
--- /dev/null
+++ b/apps/carbon/app/modules/settings/interfaces/useSettingsSidebar.tsx
@@ -0,0 +1,43 @@
+import { usePermissions } from "~/hooks";
+import type { AuthenticatedRouteGroup } from "~/types";
+
+const settingsRoutes: AuthenticatedRouteGroup[] = [
+ {
+ name: "Configure",
+ routes: [
+ {
+ name: "Sequences",
+ to: "/x/settings/sequences",
+ role: "employee",
+ },
+ ],
+ },
+];
+
+export default function usePurchasingSidebar() {
+ const permissions = usePermissions();
+ return {
+ groups: settingsRoutes
+ .filter((group) => {
+ const filteredRoutes = group.routes.filter((route) => {
+ if (route.role) {
+ return permissions.is(route.role);
+ } else {
+ return true;
+ }
+ });
+
+ return filteredRoutes.length > 0;
+ })
+ .map((group) => ({
+ ...group,
+ routes: group.routes.filter((route) => {
+ if (route.role) {
+ return permissions.is(route.role);
+ } else {
+ return true;
+ }
+ }),
+ })),
+ };
+}
diff --git a/apps/carbon/app/modules/settings/services/index.ts b/apps/carbon/app/modules/settings/services/index.ts
new file mode 100644
index 0000000000..7e5c33ed01
--- /dev/null
+++ b/apps/carbon/app/modules/settings/services/index.ts
@@ -0,0 +1,2 @@
+export * from "./settings.form";
+export * from "./settings.server";
diff --git a/apps/carbon/app/modules/settings/services/settings.form.ts b/apps/carbon/app/modules/settings/services/settings.form.ts
new file mode 100644
index 0000000000..4599f70d7c
--- /dev/null
+++ b/apps/carbon/app/modules/settings/services/settings.form.ts
@@ -0,0 +1,14 @@
+import { withZod } from "@remix-validated-form/with-zod";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const sequenceValidator = withZod(
+ z.object({
+ table: z.string().min(1, { message: "Table is required" }),
+ prefix: zfd.text(z.string().optional()),
+ suffix: zfd.text(z.string().optional()),
+ next: zfd.numeric(z.number().min(1)),
+ step: zfd.numeric(z.number().min(1)),
+ size: zfd.numeric(z.number().min(1).max(20)),
+ })
+);
diff --git a/apps/carbon/app/modules/settings/services/settings.server.ts b/apps/carbon/app/modules/settings/services/settings.server.ts
new file mode 100644
index 0000000000..c2f0c1b971
--- /dev/null
+++ b/apps/carbon/app/modules/settings/services/settings.server.ts
@@ -0,0 +1,73 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { TypeOfValidator } from "~/types/validators";
+import type { GenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters } from "~/utils/query";
+import { interpolateDate } from "~/utils/string";
+import type { sequenceValidator } from "./settings.form";
+
+export async function getNextSequence(
+ client: SupabaseClient<Database>,
+ table: string,
+ userId: string
+) {
+ // TODO: add transaction through stored procedure: https://www.postgresql.org/docs/current/plpgsql-transactions.html
+ const sequence = await getSequence(client, table);
+ if (sequence.error) {
+ return sequence;
+ }
+
+ const { prefix, suffix, next, size, step } = sequence.data;
+
+ const nextValue = next + step;
+ const nextSequence = nextValue.toString().padStart(size, "0");
+ const derivedPrefix = interpolateDate(prefix);
+ const derivedSuffix = interpolateDate(suffix);
+
+ const update = await updateSequence(client, table, {
+ next: nextValue,
+ updatedBy: userId,
+ });
+
+ if (update.error) {
+ return update;
+ }
+
+ return {
+ data: `${derivedPrefix}${nextSequence}${derivedSuffix}`,
+ error: null,
+ };
+}
+
+export async function getSequence(
+ client: SupabaseClient<Database>,
+ table: string
+) {
+ return client.from("sequence").select("*").eq("table", table).single();
+}
+
+export async function getSequences(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ }
+) {
+ let query = client.from("sequence").select("*");
+
+ if (args.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ query = setGenericQueryFilters(query, args);
+ return query;
+}
+
+export async function updateSequence(
+ client: SupabaseClient<Database>,
+ table: string,
+ sequence: Partial<TypeOfValidator<typeof sequenceValidator>> & {
+ updatedBy: string;
+ }
+) {
+ return client.from("sequence").update(sequence).eq("table", table);
+}
diff --git a/apps/carbon/app/modules/settings/types.ts b/apps/carbon/app/modules/settings/types.ts
new file mode 100644
index 0000000000..c3a2d7c63c
--- /dev/null
+++ b/apps/carbon/app/modules/settings/types.ts
@@ -0,0 +1,5 @@
+import type { getSequences } from "./services";
+
+export type Sequence = NonNullable<
+ Awaited<ReturnType<typeof getSequences>>["data"]
+>[number];
diff --git a/apps/carbon/app/routes/x+/accounting+/_layout.tsx b/apps/carbon/app/routes/x+/accounting+/_layout.tsx
new file mode 100644
index 0000000000..01b0029cfb
--- /dev/null
+++ b/apps/carbon/app/routes/x+/accounting+/_layout.tsx
@@ -0,0 +1,22 @@
+import { Grid, VStack } from "@chakra-ui/react";
+import type { MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
+import { useAccountingSidebar } from "~/modules/accounting";
+
+export const meta: MetaFunction = () => ({
+ title: "Carbon | Accounting",
+});
+
+export default function UsersRoute() {
+ const { groups } = useAccountingSidebar();
+
+ return (
+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
+ <GroupedContentSidebar groups={groups} />
+ <VStack w="full" h="full" spacing={0}>
+ <Outlet />
+ </VStack>
+ </Grid>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/accounting+/index.tsx b/apps/carbon/app/routes/x+/accounting+/index.tsx
new file mode 100644
index 0000000000..cbc3904f5d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/accounting+/index.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "@remix-run/node";
+
+export async function loader() {
+ return redirect("/x/accounting/payment-terms");
+}
diff --git a/apps/carbon/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsx b/apps/carbon/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsx
new file mode 100644
index 0000000000..e0a61f5979
--- /dev/null
+++ b/apps/carbon/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsx
@@ -0,0 +1,87 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import type { PaymentTermCalculationMethod } from "~/modules/accounting";
+import {
+ PaymentTermForm,
+ paymentTermValidator,
+ getPaymentTerm,
+ upsertPaymentTerm,
+} from "~/modules/accounting";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee",
+ });
+
+ const { paymentTermId } = params;
+ if (!paymentTermId) throw notFound("paymentTermId not found");
+
+ const paymentTerm = await getPaymentTerm(client, paymentTermId);
+
+ return json({
+ paymentTerm: paymentTerm?.data ?? null,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "accounting",
+ });
+
+ const validation = await paymentTermValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updatePaymentTerm = await upsertPaymentTerm(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+
+ if (updatePaymentTerm.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updatePaymentTerm.error, "Failed to update payment term")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/accounting/payment-terms",
+ await flash(request, success("Updated payment term"))
+ );
+}
+
+export default function EditPaymentTermsRoute() {
+ const { paymentTerm } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: paymentTerm?.id ?? undefined,
+ name: paymentTerm?.name ?? "",
+ daysDue: paymentTerm?.daysDue ?? 0,
+ daysDiscount: paymentTerm?.daysDiscount ?? 0,
+ discountPercentage: paymentTerm?.discountPercentage ?? 0,
+ calculationMethod:
+ paymentTerm?.calculationMethod ?? ("Net" as PaymentTermCalculationMethod),
+ };
+
+ return <PaymentTermForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsx b/apps/carbon/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsx
new file mode 100644
index 0000000000..bdff0ff431
--- /dev/null
+++ b/apps/carbon/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsx
@@ -0,0 +1,82 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { deletePaymentTerm, getPaymentTerm } from "~/modules/accounting";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "accounting",
+ });
+ const { paymentTermId } = params;
+ if (!paymentTermId) throw notFound("paymentTermId not found");
+
+ const paymentTerm = await getPaymentTerm(client, paymentTermId);
+ if (paymentTerm.error) {
+ return redirect(
+ "/x/accounting/payment-terms",
+ await flash(
+ request,
+ error(paymentTerm.error, "Failed to get payment term")
+ )
+ );
+ }
+
+ return json({ paymentTerm: paymentTerm.data });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "accounting",
+ });
+
+ const { paymentTermId } = params;
+ if (!paymentTermId) {
+ return redirect(
+ "/x/accounting/payment-terms",
+ await flash(request, error(params, "Failed to get an payment term id"))
+ );
+ }
+
+ const { error: deleteTypeError } = await deletePaymentTerm(
+ client,
+ paymentTermId
+ );
+ if (deleteTypeError) {
+ return redirect(
+ "/x/accounting/payment-terms",
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete payment term")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/accounting/payment-terms",
+ await flash(request, success("Successfully deleted payment term"))
+ );
+}
+
+export default function DeletePaymentTermRoute() {
+ const { paymentTermId } = useParams();
+ const { paymentTerm } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!paymentTermId || !paymentTerm) return null; // TODO - handle this better (404?)
+
+ const onCancel = () => navigate("/x/accounting/payment-terms");
+
+ return (
+ <ConfirmDelete
+ action={`/x/accounting/payment-terms/delete/${paymentTermId}`}
+ name={paymentTerm.name}
+ text={`Are you sure you want to delete the payment term: ${paymentTerm.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx b/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx
new file mode 100644
index 0000000000..02163df660
--- /dev/null
+++ b/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx
@@ -0,0 +1,86 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import type { PaymentTermCalculationMethod } from "~/modules/accounting";
+import {
+ PaymentTermForm,
+ paymentTermValidator,
+ upsertPaymentTerm,
+} from "~/modules/accounting";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ await requirePermissions(request, {
+ create: "accounting",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "accounting",
+ });
+
+ const validation = await paymentTermValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { name, daysDue, daysDiscount, discountPercentage, calculationMethod } =
+ validation.data;
+
+ const insertPaymentTerm = await upsertPaymentTerm(client, {
+ name,
+ daysDue,
+ daysDiscount,
+ discountPercentage,
+ calculationMethod,
+ createdBy: userId,
+ });
+ if (insertPaymentTerm.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertPaymentTerm.error, "Failed to insert payment term")
+ )
+ );
+ }
+
+ const paymentTermId = insertPaymentTerm.data[0]?.id;
+ if (!paymentTermId) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertPaymentTerm, "Failed to insert payment term")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/accounting/payment-terms",
+ await flash(request, success("Payment term created"))
+ );
+}
+
+export default function NewPaymentTermsRoute() {
+ const initialValues = {
+ name: "",
+ daysDue: 0,
+ daysDiscount: 0,
+ discountPercentage: 0,
+ calculationMethod: "Net" as PaymentTermCalculationMethod,
+ };
+
+ return <PaymentTermForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/accounting+/payment-terms.tsx b/apps/carbon/app/routes/x+/accounting+/payment-terms.tsx
new file mode 100644
index 0000000000..2a9a3798cf
--- /dev/null
+++ b/apps/carbon/app/routes/x+/accounting+/payment-terms.tsx
@@ -0,0 +1,37 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ PaymentTermsTable,
+ PaymentTermsTableFilters,
+ getPaymentTerms,
+} from "~/modules/accounting";
+import { requirePermissions } from "~/services/auth";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ return json(await getPaymentTerms(client, { name, limit, offset, sorts }));
+}
+
+export default function PaymentTermsRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <PaymentTermsTableFilters />
+ <PaymentTermsTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/_layout.tsx b/apps/carbon/app/routes/x+/inventory+/_layout.tsx
new file mode 100644
index 0000000000..15e15337f4
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/_layout.tsx
@@ -0,0 +1,22 @@
+import { Grid, VStack } from "@chakra-ui/react";
+import type { MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
+import { useInventorySidebar } from "~/modules/inventory";
+
+export const meta: MetaFunction = () => ({
+ title: "Carbon | Inventory",
+});
+
+export default function UsersRoute() {
+ const { groups } = useInventorySidebar();
+
+ return (
+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
+ <GroupedContentSidebar groups={groups} />
+ <VStack w="full" h="full" spacing={0}>
+ <Outlet />
+ </VStack>
+ </Grid>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/index.tsx b/apps/carbon/app/routes/x+/inventory+/index.tsx
new file mode 100644
index 0000000000..061034bc98
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/index.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "@remix-run/node";
+
+export async function loader() {
+ return redirect("/x/inventory/shipping-methods");
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
new file mode 100644
index 0000000000..98b3ffffda
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
@@ -0,0 +1,96 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { useRouteData } from "~/hooks";
+import type { ShippingCarrier } from "~/modules/inventory";
+import {
+ ShippingMethodForm,
+ shippingMethodValidator,
+ getShippingMethod,
+ upsertShippingMethod,
+} from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ role: "employee",
+ });
+
+ const { shippingMethodId } = params;
+ if (!shippingMethodId) throw notFound("shippingMethodId not found");
+
+ const shippingMethod = await getShippingMethod(client, shippingMethodId);
+
+ return json({
+ shippingMethod: shippingMethod?.data ?? null,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const validation = await shippingMethodValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updateShippingMethod = await upsertShippingMethod(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+
+ if (updateShippingMethod.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateShippingMethod.error, "Failed to update shipping method")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/inventory/shipping-methods",
+ await flash(request, success("Updated shipping method"))
+ );
+}
+
+export default function EditShippingMethodsRoute() {
+ const { shippingMethod } = useLoaderData<typeof loader>();
+ const routeData = useRouteData<{
+ accounts: { name: string; number: string }[];
+ }>("/x/inventory/shipping-methods");
+
+ console.log(shippingMethod);
+
+ const initialValues = {
+ id: shippingMethod?.id ?? undefined,
+ name: shippingMethod?.name ?? "",
+ carrier: (shippingMethod?.carrier ?? "") as ShippingCarrier,
+ carrierAccountId: shippingMethod?.carrierAccountId ?? "",
+ trackingUrl: shippingMethod?.trackingUrl ?? "",
+ };
+
+ return (
+ <ShippingMethodForm
+ initialValues={initialValues}
+ accounts={routeData?.accounts ?? []}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsx
new file mode 100644
index 0000000000..42765c5bac
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsx
@@ -0,0 +1,82 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteShippingMethod, getShippingMethod } from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ });
+ const { shippingMethodId } = params;
+ if (!shippingMethodId) throw notFound("shippingMethodId not found");
+
+ const shippingMethod = await getShippingMethod(client, shippingMethodId);
+ if (shippingMethod.error) {
+ return redirect(
+ "/x/inventory/shipping-methods",
+ await flash(
+ request,
+ error(shippingMethod.error, "Failed to get shipping method")
+ )
+ );
+ }
+
+ return json({ shippingMethod: shippingMethod.data });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "inventory",
+ });
+
+ const { shippingMethodId } = params;
+ if (!shippingMethodId) {
+ return redirect(
+ "/x/inventory/shipping-methods",
+ await flash(request, error(params, "Failed to get an shipping method id"))
+ );
+ }
+
+ const { error: deleteTypeError } = await deleteShippingMethod(
+ client,
+ shippingMethodId
+ );
+ if (deleteTypeError) {
+ return redirect(
+ "/x/inventory/shipping-methods",
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete shipping method")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/inventory/shipping-methods",
+ await flash(request, success("Successfully deleted shipping method"))
+ );
+}
+
+export default function DeleteShippingMethodRoute() {
+ const { shippingMethodId } = useParams();
+ const { shippingMethod } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!shippingMethodId || !shippingMethod) return null; // TODO - handle this better (404?)
+
+ const onCancel = () => navigate("/x/inventory/shipping-methods");
+
+ return (
+ <ConfirmDelete
+ action={`/x/inventory/shipping-methods/delete/${shippingMethodId}`}
+ name={shippingMethod.name}
+ text={`Are you sure you want to delete the shipping method: ${shippingMethod.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx
new file mode 100644
index 0000000000..cfce790209
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx
@@ -0,0 +1,91 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { useRouteData } from "~/hooks";
+import type { ShippingCarrier } from "~/modules/inventory";
+import {
+ ShippingMethodForm,
+ shippingMethodValidator,
+ upsertShippingMethod,
+} from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const validation = await shippingMethodValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { name, carrier, carrierAccountId, trackingUrl } = validation.data;
+
+ const insertShippingMethod = await upsertShippingMethod(client, {
+ name,
+ carrier,
+ carrierAccountId,
+ trackingUrl,
+ createdBy: userId,
+ });
+ if (insertShippingMethod.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertShippingMethod.error, "Failed to insert shipping method")
+ )
+ );
+ }
+
+ const shippingMethodId = insertShippingMethod.data[0]?.id;
+ if (!shippingMethodId) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertShippingMethod, "Failed to insert shipping method")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/inventory/shipping-methods",
+ await flash(request, success("Shipping method created"))
+ );
+}
+
+export default function NewShippingMethodsRoute() {
+ const routeData = useRouteData<{
+ accounts: { name: string; number: string }[];
+ }>("/x/inventory/shipping-methods");
+
+ const initialValues = {
+ name: "",
+ carrier: "" as ShippingCarrier,
+ };
+
+ return (
+ <ShippingMethodForm
+ initialValues={initialValues}
+ accounts={routeData?.accounts ?? []}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx
new file mode 100644
index 0000000000..5e54c86298
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx
@@ -0,0 +1,69 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { getAccountsList } from "~/modules/accounting";
+import {
+ ShippingMethodsTable,
+ ShippingMethodsTableFilters,
+ getShippingMethods,
+} from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ const [shippingMethods, accounts] = await Promise.all([
+ getShippingMethods(client, {
+ name,
+ limit,
+ offset,
+ sorts,
+ }),
+ getAccountsList(client),
+ ]);
+
+ if (shippingMethods.error) {
+ return redirect(
+ "/x/inventory",
+ await flash(request, error(null, "Error loading part groups"))
+ );
+ }
+
+ if (accounts.error) {
+ return redirect(
+ "/x/inventory",
+ await flash(request, error(accounts.error, "Error loading accounts"))
+ );
+ }
+
+ return json({
+ shippingMethods: shippingMethods.data ?? [],
+ count: shippingMethods.count ?? 0,
+ accounts: accounts.data ?? [],
+ });
+}
+
+export default function ShippingMethodsRoute() {
+ const { shippingMethods, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <ShippingMethodsTableFilters />
+ <ShippingMethodsTable data={shippingMethods ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.tsx b/apps/carbon/app/routes/x+/part+/$partId.tsx
index c8ced84830..2b1d8564a8 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.tsx
@@ -29,7 +29,7 @@ export async function loader({ request, params }: LoaderArgs) {
return json(partSummary.data);
}
-export default function PartsNewRoute() {
+export default function PartRoute() {
return (
<>
<PartPreview />
diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsx
index fad01cef3f..07a0ab4900 100644
--- a/apps/carbon/app/routes/x+/part+/new.tsx
+++ b/apps/carbon/app/routes/x+/part+/new.tsx
@@ -1,4 +1,4 @@
-import { Grid } from "@chakra-ui/react";
+import { Box } from "@chakra-ui/react";
import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
@@ -61,12 +61,7 @@ export default function PartsNewRoute() {
};
return (
- <Grid
- gridTemplateColumns={["1fr", "1fr", "2fr 4fr 2fr"]}
- gridColumnGap={8}
- w="full"
- >
- <div></div>
+ <Box w="50%" maxW={720} minW={420}>
<PartForm
initialValues={initialValues}
partGroups={routeData?.partGroups ?? []}
@@ -74,6 +69,6 @@ export default function PartsNewRoute() {
partReplenishmentSystems={routeData?.partReplenishmentSystems ?? []}
unitOfMeasures={routeData?.unitOfMeasures ?? []}
/>
- </Grid>
+ </Box>
);
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
new file mode 100644
index 0000000000..f87e59aea6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
@@ -0,0 +1,3 @@
+export default function PurchaseOrderHeaderRoute() {
+ return null;
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
new file mode 100644
index 0000000000..df34bda5d3
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
@@ -0,0 +1,50 @@
+import { Grid } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import {
+ getPurchaseOrder,
+ PurchaseOrderHeader,
+ PurchaseOrderSidebar,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const purchaseOrder = await getPurchaseOrder(client, orderId);
+ if (purchaseOrder.error) {
+ return redirect(
+ "/x/purchasing/orders",
+ await flash(
+ request,
+ error(purchaseOrder.error, "Failed to load purchase order summary")
+ )
+ );
+ }
+
+ return json(purchaseOrder.data);
+}
+
+export default function PurchaseOrderRoute() {
+ return (
+ <>
+ <PurchaseOrderHeader />
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "2fr 8fr"]}
+ gridColumnGap={8}
+ w="full"
+ >
+ <PurchaseOrderSidebar />
+ <Outlet />
+ </Grid>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
new file mode 100644
index 0000000000..8b18a460cf
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
@@ -0,0 +1,33 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs, MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import {
+ getPurchaseOrderApprovalStatuses,
+ getPurchaseOrderTypes,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+
+export const meta: MetaFunction = () => ({
+ title: "Carbon | Purchasing",
+});
+
+export async function loader({ request }: LoaderArgs) {
+ await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ // const [] = await Promise.all([]);
+
+ return {
+ purchaseOrderApprovalStatuses: getPurchaseOrderApprovalStatuses(),
+ purchaseOrderTypes: getPurchaseOrderTypes(),
+ };
+}
+
+export default function PurchaseOrderRoute() {
+ return (
+ <VStack w="full" h="full" spacing={4} p={4}>
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
new file mode 100644
index 0000000000..faf1280c05
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
@@ -0,0 +1,96 @@
+import { Box } from "@chakra-ui/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { useRouteData } from "~/hooks";
+import type {
+ PurchaseOrderApprovalStatus,
+ PurchaseOrderType,
+} from "~/modules/purchasing";
+import {
+ PurchaseOrderForm,
+ purchaseOrderValidator,
+ upsertPurchaseOrder,
+} from "~/modules/purchasing";
+import { getNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const validation = await purchaseOrderValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const nextSequence = await getNextSequence(client, "purchaseOrder", userId);
+ if (nextSequence.error) {
+ return redirect(
+ "/x/purchase-order/new",
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ const createPurchaseOrder = await upsertPurchaseOrder(client, {
+ ...validation.data,
+ purchaseOrderId: nextSequence.data,
+ createdBy: userId,
+ });
+ if (createPurchaseOrder.error) {
+ return redirect(
+ "/x/purchasing/orders",
+ await flash(
+ request,
+ error(createPurchaseOrder.error, "Failed to insert purchase order")
+ )
+ );
+ }
+
+ const { id, purchaseOrderId } = createPurchaseOrder.data[0];
+
+ return redirect(
+ `/x/purchase-order/${id}`,
+ await flash(request, success(`Created purchase order ${purchaseOrderId}`))
+ );
+}
+
+export default function PurchaseOrderNewRoute() {
+ const routeData = useRouteData<{
+ purchaseOrderApprovalStatuses: PurchaseOrderApprovalStatus[];
+ purchaseOrderTypes: PurchaseOrderType[];
+ }>("/x/purchase-order");
+
+ const initialValues = {
+ id: undefined,
+ purchaseOrderId: undefined,
+ orderDate: today(getLocalTimeZone()).toString(),
+ status: "Draft" as PurchaseOrderApprovalStatus,
+ type: "Purchase" as PurchaseOrderType,
+ currencyCode: "USD",
+ };
+
+ return (
+ <Box w="50%" maxW={720} minW={420}>
+ <PurchaseOrderForm
+ initialValues={initialValues}
+ purchaseOrderApprovalStatuses={
+ routeData?.purchaseOrderApprovalStatuses ?? []
+ }
+ purchaseOrderTypes={routeData?.purchaseOrderTypes ?? []}
+ />
+ </Box>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchasing+/index.tsx b/apps/carbon/app/routes/x+/purchasing+/index.tsx
index 4332709353..204111b785 100644
--- a/apps/carbon/app/routes/x+/purchasing+/index.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/index.tsx
@@ -1,5 +1,5 @@
import { redirect } from "@remix-run/node";
export async function loader() {
- return redirect("/x/purchasing/suppliers");
+ return redirect("/x/purchasing/orders");
}
diff --git a/apps/carbon/app/routes/x+/purchasing+/orders.tsx b/apps/carbon/app/routes/x+/purchasing+/orders.tsx
new file mode 100644
index 0000000000..e5d2286ab8
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchasing+/orders.tsx
@@ -0,0 +1,68 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ PurchaseOrdersTable,
+ PurchaseOrdersTableFilters,
+ getPurchaseOrders,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const status = searchParams.get("status");
+ const supplierId = searchParams.get("supplierId");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [purchasOrders] = await Promise.all([
+ getPurchaseOrders(client, {
+ search,
+ status,
+ supplierId,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ ]);
+
+ if (purchasOrders.error) {
+ redirect(
+ "/x",
+ await flash(
+ request,
+ error(purchasOrders.error, "Failed to fetch purchas orders")
+ )
+ );
+ }
+
+ return json({
+ count: purchasOrders.count ?? 0,
+ purchasOrders: purchasOrders.data ?? [],
+ });
+}
+
+export default function PurchaseOrdersSearchRoute() {
+ const { count, purchasOrders } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <PurchaseOrdersTableFilters />
+ <PurchaseOrdersTable data={purchasOrders} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/settings+/_layout.tsx b/apps/carbon/app/routes/x+/settings+/_layout.tsx
new file mode 100644
index 0000000000..a84132e373
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/_layout.tsx
@@ -0,0 +1,22 @@
+import { Grid, VStack } from "@chakra-ui/react";
+import type { MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
+import { useSettingsSidebar } from "~/modules/settings";
+
+export const meta: MetaFunction = () => ({
+ title: "Carbon | Settings",
+});
+
+export default function SettingsRoute() {
+ const { groups } = useSettingsSidebar();
+
+ return (
+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
+ <GroupedContentSidebar groups={groups} />
+ <VStack w="full" h="full" spacing={0}>
+ <Outlet />
+ </VStack>
+ </Grid>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/settings+/index.tsx b/apps/carbon/app/routes/x+/settings+/index.tsx
new file mode 100644
index 0000000000..d4794ba0d2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/index.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "@remix-run/node";
+
+export async function loader() {
+ return redirect("/x/settings/sequences");
+}
diff --git a/apps/carbon/app/routes/x+/settings+/sequences.$tableId.tsx b/apps/carbon/app/routes/x+/settings+/sequences.$tableId.tsx
new file mode 100644
index 0000000000..41d419810e
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/sequences.$tableId.tsx
@@ -0,0 +1,85 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ SequenceForm,
+ sequenceValidator,
+ getSequence,
+ updateSequence,
+} from "~/modules/settings";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee",
+ });
+
+ const { tableId } = params;
+ if (!tableId) throw notFound("tableId not found");
+
+ const sequence = await getSequence(client, tableId);
+ if (sequence.error) {
+ return redirect(
+ "/x/settings/sequences",
+ await flash(request, error(sequence.error, "Failed to get sequence"))
+ );
+ }
+
+ return json({
+ sequence: sequence?.data ?? null,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const validation = await sequenceValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { table, ...data } = validation.data;
+
+ const update = await updateSequence(client, table, {
+ ...data,
+ updatedBy: userId,
+ });
+
+ if (update.error) {
+ return json(
+ {},
+ await flash(request, error(update.error, "Failed to update sequence"))
+ );
+ }
+
+ return redirect(
+ "/x/settings/sequences",
+ await flash(request, success("Updated sequence"))
+ );
+}
+
+export default function EditSequenceRoute() {
+ const { sequence } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ table: sequence?.table ?? "",
+ name: sequence?.name ?? "",
+ prefix: sequence?.prefix ?? "",
+ next: sequence?.next ?? 1,
+ size: sequence?.size ?? 5,
+ step: sequence?.step ?? 1,
+ suffix: sequence?.suffix ?? "",
+ };
+
+ return <SequenceForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/settings+/sequences.tsx b/apps/carbon/app/routes/x+/settings+/sequences.tsx
new file mode 100644
index 0000000000..df52997e8c
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/sequences.tsx
@@ -0,0 +1,37 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ SequencesTable,
+ SequencesTableFilters,
+ getSequences,
+} from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ return json(await getSequences(client, { name, limit, offset, sorts }));
+}
+
+export default function SequencesRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <SequencesTableFilters />
+ <SequencesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/utils/string.ts b/apps/carbon/app/utils/string.ts
index 56c86577f9..473b1d0360 100644
--- a/apps/carbon/app/utils/string.ts
+++ b/apps/carbon/app/utils/string.ts
@@ -2,3 +2,28 @@ export const capitalize = (words: string) => {
const [first, ...otherLetters] = words;
return [first.toLocaleUpperCase(), ...otherLetters].join("");
};
+
+// used to generate sequences
+export const interpolateDate = (value: string | null) => {
+ // replace all instances of %{year} with the current year
+ if (!value) return "";
+ let result = value;
+
+ if (result.includes("%{")) {
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = date.getMonth() + 1;
+ const day = date.getDate();
+ const hours = date.getHours();
+ const seconds = date.getSeconds();
+
+ result = result.replace(/%{yyyy}/g, year.toString());
+ result = result.replace(/%{yy}/g, year.toString().slice(-2));
+ result = result.replace(/%{mm}/g, month.toString().padStart(2, "0"));
+ result = result.replace(/%{dd}/g, day.toString().padStart(2, "0"));
+ result = result.replace(/%{hh}/g, hours.toString().padStart(2, "0"));
+ result = result.replace(/%{ss}/g, seconds.toString().padStart(2, "0"));
+ }
+
+ return result;
+};
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index 9c9cf945c9..a02413ff1c 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -1482,6 +1482,179 @@ export interface Database {
createdAt?: string;
};
};
+ paymentTerm: {
+ Row: {
+ name: string;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ id: string;
+ daysDue: number;
+ daysDiscount: number;
+ discountPercentage: number;
+ calculationMethod: Database["public"]["Enums"]["paymentTermCalculationMethod"];
+ active: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ name: string;
+ createdBy: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ daysDue?: number;
+ daysDiscount?: number;
+ discountPercentage?: number;
+ calculationMethod?: Database["public"]["Enums"]["paymentTermCalculationMethod"];
+ active?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ name?: string;
+ createdBy?: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ daysDue?: number;
+ daysDiscount?: number;
+ discountPercentage?: number;
+ calculationMethod?: Database["public"]["Enums"]["paymentTermCalculationMethod"];
+ active?: boolean;
+ createdAt?: string;
+ };
+ };
+ purchaseOrder: {
+ Row: {
+ purchaseOrderId: string;
+ type: Database["public"]["Enums"]["purchaseOrderType"];
+ status: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+ orderDueDate: string | null;
+ receivedDate: string | null;
+ notes: string | null;
+ supplierId: string;
+ supplierContactId: string | null;
+ supplierReference: string | null;
+ invoiceSupplierId: string | null;
+ invoiceSupplierLocationId: string | null;
+ invoiceSupplierContactId: string | null;
+ paymentTermId: string | null;
+ shippingMethodId: string | null;
+ currencyCode: string;
+ closedAt: string | null;
+ closedBy: string | null;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ id: string;
+ orderDate: string;
+ orderSubTotal: number;
+ orderTax: number;
+ orderDiscount: number;
+ orderShipping: number;
+ orderTotal: number;
+ closed: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ purchaseOrderId: string;
+ type: Database["public"]["Enums"]["purchaseOrderType"];
+ status: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+ orderDueDate?: string | null;
+ receivedDate?: string | null;
+ notes?: string | null;
+ supplierId: string;
+ supplierContactId?: string | null;
+ supplierReference?: string | null;
+ invoiceSupplierId?: string | null;
+ invoiceSupplierLocationId?: string | null;
+ invoiceSupplierContactId?: string | null;
+ paymentTermId?: string | null;
+ shippingMethodId?: string | null;
+ currencyCode: string;
+ closedAt?: string | null;
+ closedBy?: string | null;
+ createdBy: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ orderDate?: string;
+ orderSubTotal?: number;
+ orderTax?: number;
+ orderDiscount?: number;
+ orderShipping?: number;
+ orderTotal?: number;
+ closed?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ purchaseOrderId?: string;
+ type?: Database["public"]["Enums"]["purchaseOrderType"];
+ status?: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+ orderDueDate?: string | null;
+ receivedDate?: string | null;
+ notes?: string | null;
+ supplierId?: string;
+ supplierContactId?: string | null;
+ supplierReference?: string | null;
+ invoiceSupplierId?: string | null;
+ invoiceSupplierLocationId?: string | null;
+ invoiceSupplierContactId?: string | null;
+ paymentTermId?: string | null;
+ shippingMethodId?: string | null;
+ currencyCode?: string;
+ closedAt?: string | null;
+ closedBy?: string | null;
+ createdBy?: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ orderDate?: string;
+ orderSubTotal?: number;
+ orderTax?: number;
+ orderDiscount?: number;
+ orderShipping?: number;
+ orderTotal?: number;
+ closed?: boolean;
+ createdAt?: string;
+ };
+ };
+ purchaseOrderFavorite: {
+ Row: {
+ purchaseOrderId: string;
+ userId: string;
+ };
+ Insert: {
+ purchaseOrderId: string;
+ userId: string;
+ };
+ Update: {
+ purchaseOrderId?: string;
+ userId?: string;
+ };
+ };
+ purchaseOrderTransaction: {
+ Row: {
+ purchaseOrderId: string;
+ type: Database["public"]["Enums"]["purchaseOrderTransactionType"];
+ userId: string;
+ id: string;
+ createdAt: string;
+ };
+ Insert: {
+ purchaseOrderId: string;
+ type: Database["public"]["Enums"]["purchaseOrderTransactionType"];
+ userId: string;
+ id?: string;
+ createdAt?: string;
+ };
+ Update: {
+ purchaseOrderId?: string;
+ type?: Database["public"]["Enums"]["purchaseOrderTransactionType"];
+ userId?: string;
+ id?: string;
+ createdAt?: string;
+ };
+ };
search: {
Row: {
id: number;
@@ -1511,6 +1684,41 @@ export interface Database {
fts?: unknown | null;
};
};
+ sequence: {
+ Row: {
+ table: string;
+ name: string;
+ prefix: string | null;
+ suffix: string | null;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ next: number;
+ size: number;
+ step: number;
+ };
+ Insert: {
+ table: string;
+ name: string;
+ prefix?: string | null;
+ suffix?: string | null;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ next?: number;
+ size?: number;
+ step?: number;
+ };
+ Update: {
+ table?: string;
+ name?: string;
+ prefix?: string | null;
+ suffix?: string | null;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ next?: number;
+ size?: number;
+ step?: number;
+ };
+ };
shelf: {
Row: {
id: string;
@@ -1587,6 +1795,44 @@ export interface Database {
active?: boolean;
};
};
+ shippingMethod: {
+ Row: {
+ name: string;
+ carrierAccountId: string | null;
+ trackingUrl: string | null;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ id: string;
+ carrier: Database["public"]["Enums"]["shippingCarrier"];
+ active: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ name: string;
+ carrierAccountId?: string | null;
+ trackingUrl?: string | null;
+ createdBy: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ carrier?: Database["public"]["Enums"]["shippingCarrier"];
+ active?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ name?: string;
+ carrierAccountId?: string | null;
+ trackingUrl?: string | null;
+ createdBy?: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ carrier?: Database["public"]["Enums"]["shippingCarrier"];
+ active?: boolean;
+ createdAt?: string;
+ };
+ };
supplier: {
Row: {
name: string;
@@ -2149,6 +2395,32 @@ export interface Database {
abilityIds: string[] | null;
};
};
+ purchase_order_view: {
+ Row: {
+ id: string | null;
+ purchaseOrderId: string | null;
+ status:
+ | Database["public"]["Enums"]["purchaseOrderApprovalStatus"]
+ | null;
+ type: Database["public"]["Enums"]["purchaseOrderType"] | null;
+ orderDate: string | null;
+ orderDueDate: string | null;
+ createdBy: string | null;
+ supplierName: string | null;
+ createdByAvatar: string | null;
+ createdByFullName: string | null;
+ createdAt: string | null;
+ updatedBy: string | null;
+ updatedByAvatar: string | null;
+ updatedByFullName: string | null;
+ updatedAt: string | null;
+ closed: boolean | null;
+ closedAt: string | null;
+ closedByAvatar: string | null;
+ closedByFullName: string | null;
+ favorite: boolean | null;
+ };
+ };
};
Functions: {
_xid_machine_id: {
@@ -2285,6 +2557,22 @@ export interface Database {
| "Maximum Quantity";
partReplenishmentSystem: "Buy" | "Make" | "Buy and Make";
partType: "Inventory" | "Non-Inventory" | "Service";
+ paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month";
+ purchaseOrderApprovalStatus:
+ | "Draft"
+ | "In Review"
+ | "In External Review"
+ | "Approved"
+ | "Rejected"
+ | "Confirmed";
+ purchaseOrderTransactionType:
+ | "Edit"
+ | "Favorite"
+ | "Unfavorite"
+ | "Approved"
+ | "Reject"
+ | "Request Approval";
+ purchaseOrderType: "Draft" | "Purchase" | "Return";
searchEntity:
| "Resource"
| "Person"
@@ -2295,6 +2583,7 @@ export interface Database {
| "Purchase Order"
| "Sales Order"
| "Document";
+ shippingCarrier: "UPS" | "FedEx" | "USPS" | "DHL" | "Other";
};
};
}
diff --git a/packages/carbon-database/supabase/migrations/20230423023136_documents.sql b/packages/carbon-database/supabase/migrations/20230423023136_documents.sql
index e051a8e810..fe7b947471 100644
--- a/packages/carbon-database/supabase/migrations/20230423023136_documents.sql
+++ b/packages/carbon-database/supabase/migrations/20230423023136_documents.sql
@@ -115,13 +115,13 @@ CREATE TABLE "documentTransaction" (
"userId" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- CONSTRAINT "documentActivity_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "documentActivity_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
- CONSTRAINT "documentActivity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+ CONSTRAINT "documentTransaction_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "documentTransaction_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
+ CONSTRAINT "documentTransaction_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
);
-CREATE INDEX "documentActivity_documentId_idx" ON "documentTransaction" ("documentId");
-CREATE INDEX "documentActivity_userId_idx" ON "documentTransaction" ("userId");
+CREATE INDEX "documentTransaction_documentId_idx" ON "documentTransaction" ("documentId");
+CREATE INDEX "documentTransaction_userId_idx" ON "documentTransaction" ("userId");
CREATE TABLE "documentFavorite" (
"documentId" TEXT NOT NULL,
@@ -137,17 +137,17 @@ CREATE INDEX "documentFavorites_documentId_idx" ON "documentFavorite" ("document
ALTER TABLE "documentFavorite" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Users can view their own favorites" ON "documentFavorite"
+CREATE POLICY "Users can view their own document favorites" ON "documentFavorite"
FOR SELECT USING (
auth.uid()::text = "userId"
);
-CREATE POLICY "Users can create their own favorites" ON "documentFavorite"
+CREATE POLICY "Users can create their own document favorites" ON "documentFavorite"
FOR INSERT WITH CHECK (
auth.uid()::text = "userId"
);
-CREATE POLICY "Users can delete their own favorites" ON "documentFavorite"
+CREATE POLICY "Users can delete their own document favorites" ON "documentFavorite"
FOR DELETE USING (
auth.uid()::text = "userId"
);
diff --git a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
new file mode 100644
index 0000000000..24275a7357
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
@@ -0,0 +1,222 @@
+CREATE TYPE "paymentTermCalculationMethod" AS ENUM (
+ 'Net',
+ 'End of Month',
+ 'Day of Month'
+);
+
+CREATE TABLE "paymentTerm" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "daysDue" INTEGER NOT NULL DEFAULT 0,
+ "daysDiscount" INTEGER NOT NULL DEFAULT 0,
+ "discountPercentage" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "calculationMethod" "paymentTermCalculationMethod" NOT NULL DEFAULT 'Net',
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "paymentTerm_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "paymentTerm_name_key" UNIQUE ("name", "active"),
+ CONSTRAINT "paymentTerm_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "paymentTerm_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+INSERT INTO "paymentTerm" ("name", "daysDue", "calculationMethod", "daysDiscount", "discountPercentage", "createdBy")
+VALUES
+ ('Net 15', 15, 'Net', 0, 0, 'system'),
+ ('Net 30', 30, 'Net', 0, 0, 'system'),
+ ('Net 50', 50, 'Net', 0, 0, 'system'),
+ ('Net 60', 60, 'Net', 0, 0, 'system'),
+ ('Net 90', 90, 'Net', 0, 0, 'system'),
+ ('1% 10 Net 30', 30, 'Net', 10, 1, 'system'),
+ ('2% 10 Net 30', 30, 'Net', 10, 2, 'system'),
+ ('Due on Receipt', 0, 'Net', 0, 0, 'system'),
+ ('Net EOM 10', 10, 'End of Month', 0, 0, 'system');
+
+
+CREATE TYPE "shippingCarrier" AS ENUM (
+ 'UPS',
+ 'FedEx',
+ 'USPS',
+ 'DHL',
+ 'Other'
+);
+
+CREATE TABLE "shippingMethod" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "carrier" "shippingCarrier" NOT NULL DEFAULT 'Other',
+ "carrierAccountId" TEXT,
+ "trackingUrl" TEXT,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "shippingMethod_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "shippingMethod_name_key" UNIQUE ("name"),
+ CONSTRAINT "shippingMethod_carrierAccountId_fkey" FOREIGN KEY ("carrierAccountId") REFERENCES "account" ("number") ON DELETE CASCADE,
+ CONSTRAINT "shippingMethod_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "shippingMethod_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "shippingMethod_name_idx" ON "shippingMethod" ("name");
+
+CREATE TYPE "purchaseOrderType" AS ENUM (
+ 'Draft',
+ 'Purchase',
+ 'Return'
+);
+
+CREATE TYPE "purchaseOrderApprovalStatus" AS ENUM (
+ 'Draft',
+ 'In Review',
+ 'In External Review',
+ 'Approved',
+ 'Rejected',
+ 'Confirmed'
+);
+
+CREATE TABLE "purchaseOrder" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT NOT NULL,
+ "type" "purchaseOrderType" NOT NULL,
+ "status" "purchaseOrderApprovalStatus" NOT NULL,
+ "orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
+ "orderDueDate" DATE,
+ "receivedDate" DATE,
+ "orderSubTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderTax" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderDiscount" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderShipping" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "orderTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
+ "notes" TEXT,
+ "supplierId" TEXT NOT NULL,
+ "supplierContactId" TEXT,
+ "supplierReference" TEXT,
+ "invoiceSupplierId" TEXT,
+ "invoiceSupplierLocationId" TEXT,
+ "invoiceSupplierContactId" TEXT,
+ "paymentTermId" TEXT,
+ "shippingMethodId" TEXT,
+ "currencyCode" TEXT NOT NULL,
+ -- "approvalRequestDate" DATE,
+ -- "approvalDecisionDate" DATE,
+ -- "approvalDecisionUserId" TEXT,
+ -- "approvalDecisionNotes" TEXT,
+ "closed" BOOLEAN NOT NULL DEFAULT FALSE,
+ "closedAt" DATE,
+ "closedBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "purchaseOrder_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrder_purchaseOrderId_key" UNIQUE ("purchaseOrderId"),
+ CONSTRAINT "purchaseOrder_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_supplierContactId_fkey" FOREIGN KEY ("supplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_invoiceSupplierLocationId_fkey" FOREIGN KEY ("invoiceSupplierLocationId") REFERENCES "supplierLocation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_invoiceSupplierContactId_fkey" FOREIGN KEY ("invoiceSupplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE,
+ -- CONSTRAINT "purchaseOrder_approvalDecisionUserId_fkey" FOREIGN KEY ("approvalDecisionUserId") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_closedBy_fkey" FOREIGN KEY ("closedBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrder_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrder_purchaseOrderId_idx" ON "purchaseOrder" ("purchaseOrderId");
+CREATE INDEX "purchaseOrder_supplierId_idx" ON "purchaseOrder" ("supplierId");
+CREATE INDEX "purchaseOrder_supplierContactId_idx" ON "purchaseOrder" ("supplierContactId");
+CREATE INDEX "purchaseOrder_invoiceSupplierId_idx" ON "purchaseOrder" ("invoiceSupplierId");
+CREATE INDEX "purchaseOrder_invoiceSupplierLocationId_idx" ON "purchaseOrder" ("invoiceSupplierLocationId");
+CREATE INDEX "purchaseOrder_invoiceSupplierContactId_idx" ON "purchaseOrder" ("invoiceSupplierContactId");
+-- CREATE INDEX "purchaseOrder_approvalDecisionUserId_idx" ON "purchaseOrder" ("approvalDecisionUserId");
+
+CREATE TYPE "purchaseOrderTransactionType" AS ENUM (
+ 'Edit',
+ 'Favorite',
+ 'Unfavorite',
+ 'Approved',
+ 'Reject',
+ 'Request Approval'
+);
+
+CREATE TABLE "purchaseOrderTransaction" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT NOT NULL,
+ "type" "purchaseOrderTransactionType" NOT NULL,
+ "userId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "purchaseOrderTransaction_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderTransaction_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder"("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderTransaction_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrderTransaction_purchaseOrderId_idx" ON "purchaseOrderTransaction" ("purchaseOrderId");
+CREATE INDEX "purchaseOrderTransaction_userId_idx" ON "purchaseOrderTransaction" ("userId");
+
+CREATE TABLE "purchaseOrderFavorite" (
+ "purchaseOrderId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+
+ CONSTRAINT "purchaseOrderFavorites_pkey" PRIMARY KEY ("purchaseOrderId", "userId"),
+ CONSTRAINT "purchaseOrderFavorites_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder"("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrderFavorites_userId_idx" ON "purchaseOrderFavorite" ("userId");
+CREATE INDEX "purchaseOrderFavorites_purchaseOrderId_idx" ON "purchaseOrderFavorite" ("purchaseOrderId");
+
+ALTER TABLE "purchaseOrderFavorite" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Users can view their own purchase order favorites" ON "purchaseOrderFavorite"
+ FOR SELECT USING (
+ auth.uid()::text = "userId"
+ );
+
+CREATE POLICY "Users can create their own purchase order favorites" ON "purchaseOrderFavorite"
+ FOR INSERT WITH CHECK (
+ auth.uid()::text = "userId"
+ );
+
+CREATE POLICY "Users can delete their own purchase order favorites" ON "purchaseOrderFavorite"
+ FOR DELETE USING (
+ auth.uid()::text = "userId"
+ );
+
+CREATE VIEW "purchase_order_view" AS
+ SELECT
+ p."id",
+ p."purchaseOrderId",
+ p."status",
+ p."type",
+ p."orderDate",
+ p."orderDueDate",
+ p."createdBy",
+ s."name" AS "supplierName",
+ u."avatarUrl" AS "createdByAvatar",
+ u."fullName" AS "createdByFullName",
+ p."createdAt",
+ p."updatedBy",
+ u2."avatarUrl" AS "updatedByAvatar",
+ u2."fullName" AS "updatedByFullName",
+ p."updatedAt",
+ p."closed",
+ p."closedAt",
+ u3."avatarUrl" AS "closedByAvatar",
+ u3."fullName" AS "closedByFullName",
+ EXISTS(SELECT 1 FROM "purchaseOrderFavorite" pf WHERE pf."purchaseOrderId" = p.id AND pf."userId" = auth.uid()::text) AS favorite
+ FROM "purchaseOrder" p
+ LEFT JOIN "supplier" s ON s."id" = p."supplierId"
+ LEFT JOIN "user" u ON u."id" = p."createdBy"
+ LEFT JOIN "user" u2 ON u2."id" = p."updatedBy"
+ LEFT JOIN "user" u3 ON u3."id" = p."closedBy";
+
diff --git a/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql b/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
new file mode 100644
index 0000000000..6a08670886
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
@@ -0,0 +1,21 @@
+CREATE TABLE "sequence" (
+ "table" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "prefix" TEXT,
+ "suffix" TEXT,
+ "next" BIGINT NOT NULL DEFAULT 1,
+ "size" INTEGER NOT NULL DEFAULT 5,
+ "step" INTEGER NOT NULL DEFAULT 1,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "sequence_pkey" PRIMARY KEY ("table"),
+ CONSTRAINT "sequence_next_check" CHECK ("next" >= 1),
+ CONSTRAINT "sequence_size_check" CHECK ("size" >= 1),
+ CONSTRAINT "sequence_step_check" CHECK ("step" >= 1),
+ CONSTRAINT "sequence_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
+VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 1, 5, 1);
+
diff --git a/packages/carbon-react/src/Inputs/Date/DatePicker.tsx b/packages/carbon-react/src/Inputs/Date/DatePicker.tsx
index 87fea2e1c3..ae96dfc5d8 100644
--- a/packages/carbon-react/src/Inputs/Date/DatePicker.tsx
+++ b/packages/carbon-react/src/Inputs/Date/DatePicker.tsx
@@ -22,8 +22,19 @@ const DatePicker = (props: DatePickerProps<CalendarDate>) => {
useDatePicker(props, state, ref);
return (
- <Box position="relative" display="inline-flex" flexDirection="column">
- <InputGroup {...groupProps} ref={ref} width="auto" display="inline-flex">
+ <Box
+ position="relative"
+ display="inline-flex"
+ flexDirection="column"
+ w="full"
+ >
+ <InputGroup
+ {...groupProps}
+ ref={ref}
+ width="auto"
+ display="inline-flex"
+ w="full"
+ >
<StyledField pr="4.5rem">
<DateField {...fieldProps} />
{state.validationState === "invalid" && (
diff --git a/packages/carbon-react/src/Inputs/Date/components/CalendarCell.tsx b/packages/carbon-react/src/Inputs/Date/components/CalendarCell.tsx
index c5adf0fce6..2f2adae93b 100644
--- a/packages/carbon-react/src/Inputs/Date/components/CalendarCell.tsx
+++ b/packages/carbon-react/src/Inputs/Date/components/CalendarCell.tsx
@@ -30,7 +30,7 @@ export const CalendarCell = ({
ref={ref}
hidden={isOutsideMonth}
size="sm"
- colorScheme={isInvalid ? "red" : "blackAlpha"}
+ colorScheme={isInvalid ? "red" : "brand"}
variant={isSelected ? "solid" : "ghost"}
width="100%"
>
diff --git a/packages/carbon-react/src/Inputs/Date/components/StyledField.tsx b/packages/carbon-react/src/Inputs/Date/components/StyledField.tsx
index 4d864626a8..c049410b3b 100644
--- a/packages/carbon-react/src/Inputs/Date/components/StyledField.tsx
+++ b/packages/carbon-react/src/Inputs/Date/components/StyledField.tsx
@@ -26,6 +26,7 @@ export const StyledField = forwardRef<HTMLDivElement, StyledFieldProps>(
alignItems="center"
px="1"
py=".4rem"
+ w="full"
_hover={{
borderColor: "gray.400",
}}
diff --git a/packages/carbon-react/src/Theme/palette.ts b/packages/carbon-react/src/Theme/palette.ts
index b6c3be724d..e77c083cc3 100644
--- a/packages/carbon-react/src/Theme/palette.ts
+++ b/packages/carbon-react/src/Theme/palette.ts
@@ -12,16 +12,16 @@ export const colors = {
900: "#01770a",
},
gray: {
- 50: "#fafafa",
- 100: "#f5f5f5",
- 200: "#e5e5e5",
- 300: "#d4d4d4",
- 400: "#a3a3a3",
- 500: "#737373",
- 600: "#525252",
- 700: "#404040",
- 800: "#262626",
- 900: "#171717",
+ 50: "#F8FAFB",
+ 100: "#F2F4F7",
+ 200: "#EAECF0",
+ 300: "#D0D5DD",
+ 400: "#98A2B3",
+ 500: "#667085",
+ 600: "#475467",
+ 700: "#344054",
+ 800: "#1D2939",
+ 900: "#101828",
},
purple: {
50: "#faebff",